0% found this document useful (0 votes)
76 views51 pages

CG - MANUAL (18 Scheme) bmk2021

This document is a lab manual for a computer graphics and visualization course. It provides an introduction and overview of OpenGL, including that it is a hardware-independent interface consisting of around 150 commands. It also describes related libraries like GLU and GLUT that build upon OpenGL to provide additional functionality. The manual outlines the course objectives, outcomes, and lists programming assignments that students will complete to apply concepts of computer graphics and implement applications using OpenGL.

Uploaded by

Manasa Krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views51 pages

CG - MANUAL (18 Scheme) bmk2021

This document is a lab manual for a computer graphics and visualization course. It provides an introduction and overview of OpenGL, including that it is a hardware-independent interface consisting of around 150 commands. It also describes related libraries like GLU and GLUT that build upon OpenGL to provide additional functionality. The manual outlines the course objectives, outcomes, and lists programming assignments that students will complete to apply concepts of computer graphics and implement applications using OpenGL.

Uploaded by

Manasa Krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

LAB MANUAL

Computer Graphics and Visualization


Laboratory
[18CSL68]
Department of CSE,SJBIT
Prepared By,
Mrs. Dr.Bindiya M K, Asso. Professor
Mrs.Pavithra G S, Asso. Professor
Mrs. Manasa B S, Assistant Professor

Department of Computer Science and Engineering


SJBIT
(NAAC Accredited and an ISO 9001:2015 Certified Institution)
(Affiliated to Visvesvaraya Technological University Belgaum and approved by AICTE, New Delhi)
18CSL68 Computer Graphics and Mini Project Laboratory

SYLLABUS

COMPUTER GRAPHICS LABORATORY WITH MINI PROJECT


[As per Choice Based Credit System (CBCS) scheme]
(Effective from the academic year 2016 -2017)

Course Objectives: This course will enable students to


• Demonstrate simple algorithms using OpenGL Graphics Primitives and
attributes.
• Implementation of line drawing and clipping algorithms using OpenGL
functions.
• Design and implementation of algorithms Geometric transformations on
both 2D and 3D objects.

Course outcome: This course will enable students to


• Apply the concepts of computer graphics
• Implement computer graphics applications using OpenGL
• Animate real world problems using OpenGL

Part A

SL NO PROGRAMS

01 Implement Brenham‟s line drawing algorithm for all types of slope

02 Create and rotate a triangle about the origin and a fixed point

03 Draw a color cube and spin it using OpenGL transformation matrices

04 Draw a color cube and allow the user to move the camera suitably to experiment with
perspective viewing

05 Clip a lines using Cohen-Sutherland algorithm

06 To draw a simple shaded scene consisting of a tea pot on a table. Define suitably the
position and properties of the light source along with the properties of the surfaces of the
solid object used in the scene

07 Design, develop and implement recursively subdivide a tetrahedron to form 3D sierpinski


gasket. The number of recursive steps is to be specified by the user

08 Develop a menu driven program to animate a flag using Bezier Curve algorithm

09 Develop a menu driven program to fill the polygon using scan line algorithm

S.J.B.I.T Dept of CSE Page 2


18CSL68 Computer Graphics and Mini Project Laboratory

Introduction to Computer Graphics


Introduction to Open GL
OpenGL is a software interface to graphics hardware. This interface consists of about
150 distinct commands that you use to specify the objects and operations needed to produce
interactive three-dimensional applications. OpenGL is designed as a streamlined,
hardwareindependent interface to be implemented on many different hardware platforms.
With OpenGL, you can build up your desired model from a small set of geometric primitives
- points, lines, and polygons. A sophisticated library that provides these features could
certainly be built on top of OpenGL. The OpenGL Utility Library (GLU) provides many of
the modeling features. GLU is a standard part of every OpenGL implementation.
OpenGL as a State Machine
OpenGL is a state machine. It is called a state machine because it can be put into various
states until you change them. As you've already seen, the current color is a state variable.
You can set the current color to white, red, or any other color, and thereafter every object is
drawn with that color until you set the current color to something else.
The current color is only one of many state variables that OpenGL maintains. Others control
such things as the current viewing and projection transformations; line and polygon stipple
patterns, polygon drawing modes, pixel-packing conventions, positions and characteristics of
lights, and material properties of the objects being drawn. Many state variables refer to
modes that are enabled or disabled with the command glEnable() or glDisable(). Each state
variable or mode has a default value, and at any point you can query the system for each
variable's current value.
OpenGL-Related Libraries
OpenGL provides apowerful but primitive set of rendering commands, and all higher-level
drawing must be done in terms of these commands. Also, OpenGL programs have to use the
underlying mechanisms of the windowing system. A number of libraries exist to allow you to
simplify your programming tasks, including the following:
• The OpenGL Utility Library (GLU) contains several routines that use lower-level
OpenGL commands to perform such tasks as setting up matrices for specific viewing
orientations and projections, performing polygon tessellation, and rendering surfaces.
This library is provided as part of every OpenGL implementation. GLU routines use
the prefix glu.

S.J.B.I.T Dept of CSE Page 3


18CSL68 Computer Graphics and Mini Project Laboratory

• The OpenGL Utility Toolkit (GLUT) is a window system-independent toolkit. It


contains rendering commands but is designed to be independent of any window
system or operating system. Consequently, it contains no commands for opening
windows or reading events from the keyboard or mouse. Since OpenGL drawing
commands are limited to those that generate simple geometric primitives (points,
lines, and polygons), GLUT includes several routines that create more complicated
three-dimensional objects such as a sphere, a torus, and a teapot. GLUT may not be
satisfactory for full-featured OpenGL applications, but you may find it a useful
starting point for learning OpenGL.
Include Files
For all OpenGL applications, you want to include the gl.h header file in every file. Almost
all OpenGL applications use GLU, the aforementioned OpenGL Utility Library, which
requires inclusion of the glu.h header file. So almost every OpenGL source file begins with
#include <GL/gl.h>
#include <GL/glu.h>
If you are using GLUT for managing your window manager tasks, you should include
#include <GL/glut.h>
Note that glut.h includes gl.h, glu.h automatically, so including all three files is redundant.
Associated utility libraries
Several libraries are built on top of or beside OpenGL to provide features not available in
OpenGL itself. Libraries such asGLUcan be found with most OpenGL implementations, and
others such asGLUTandSDLhave grown over time and provide rudimentary cross-platform
windowing and mouse functionality, and if unavailable can easily be downloaded and added
to a development environment. Simplegraphical userinterfacefunctionality can be found in
libraries likeGLUIorFLTK. Still other libraries like GLAux (OpenGL Auxiliary Library) are
deprecated and have been superseded by functionality commonly available in more popular
libraries.
Other libraries have been created to provide OpenGL application developers a simple means
of managing OpenGL extensions and versioning. Examples of these libraries
includeGLEW(the OpenGL Extension Wrangler Library) and GLEE(the OpenGL
EasyExtension Library). In addition to the aforementioned simple libraries, other higher-level
object-oriented scene graph retained mode libraries exist such
asPLIB,OpenSG,OpenSceneGraph, andOpenGL Performer. These are available as

S.J.B.I.T Dept of CSE Page 4


18CSL68 Computer Graphics and Mini Project Laboratory

crossplatform free/open source orproprietaryprogramming interfaces written on top of


OpenGL and systems libraries to enable the creation ofreal-timevisual simulation
applications.
Comprises several libraries with varying levels of abstraction: GL, GLU, and GLUT
• Software Interface to Graphics Hardware
• Consists of about 150 Distinct Commands
• Hardware-independent Interface
• no command for windows or user input handling
• does not include low-level I/O management
• Mid-level, device-independent, portable graphics subroutine package
• Developed primarily by SGI
• 2D/3D graphics, lower-level primitives (polygons)
• Basis for higher-level libraries/toolkits
OpenGL Hierarchy
• Several levels of abstraction are provided
• GL
 Lowest level: vertex, matrix manipulation
 glVertex3f(point.x, point.y, point.z)
• GLU
 Helper functions for shapes, transformations
 gluPerspective( fovy, aspect, near, far )
 gluLookAt(0, 0, 10, 0, 0, 0, 0, 1, 0);
• GLUT
 Highest level: Window and interface management
 glutSwapBuffers()
 glutInitWindowSize (500, 500);
OpenGL Implementations
• OpenGL IS an API (think of as collection of .h files):
 #include <GL/gl.h>
 #include <GL/glu.h>
 #include <GL/glut.h>
• Windows, Linux, UNIX, etc. all provide a platform specific implementation.
• Windows: opengl32.lib glu32.lib glut32.lib

S.J.B.I.T Dept of CSE Page 5


18CSL68 Computer Graphics and Mini Project Laboratory

• Linux: -l GL -l GLU –l GLUT


OpenGL API
• As a programmer, you need to do the following things:
 Specify the location/parameters of camera.
 Specify the geometry (and appearance).
 Specify the lights (optional).
• OpenGL will compute the resulting 2D image
OpenGL: Camera
Two things to specify:
Physical location of camera in the scene (MODELVIEW matrix in OpenGL).
Projection properties of the camera (PROJECTION matrix in OpenGL):

voi
d glFrustum(GLdouble left, GLdouble right, GLdoublebottom,GLdouble top, GLdouble near,
GLdouble far);

void
glOrtho(GLdouble left, GLdouble right, GLdouble bottom,
GLdouble top, GLdouble near, GLdouble far);

OpenGL Conventions
• Many functions have multiple forms:
 glVertex2f, glVertex3i, glVertex4dv, etc.

S.J.B.I.T Dept of CSE Page 6


18CSL68 Computer Graphics and Mini Project Laboratory

• Number indicates number of arguments


• Letters indicate type
 f: float, d: double, ub: unsigned byte, etc.
• „v‟ (if present) indicates a single pointer argument
Required files for Windows
• In the System Directory
– glu32.dll
– opengl32.dll
– glut32.dll

• In the C++ Include Directory


– gl\gl.h
– l\glu.h
– gl\glaux.h (probably won't need it)
– gl\glut.h (includes both gl.h and glu.h)
• In the C++ Library Directory
– gl\glu32.lib
– l\opengl32.lib
– gl\glaux.lib (probably won't need it)
– gl\glut32.lib
Event Loop
• OpenGL programs often run in an event loop:
– Start the program
– Run some initialization code
– Run an infinite loop and wait for events such as
• Key press
• Mouse move, click
• Reshape window
• Expose event
OpenGL Command Syntax (1)
• OpenGL commands start with “gl”
• OpenGL constants start with “GL_”
• Some commands end in a number and one, two or three letters at the end
(indicating number and type of arguments)

S.J.B.I.T Dept of CSE Page 7


18CSL68 Computer Graphics and Mini Project Laboratory

• A Number indicates number of arguments


• Characters indicate type of argument
OpenGL Command Syntax (2)

OpenGL Command Syntax (3)


 glClearColor() – Specifies the background color
 glClear() – Erases the output with background color
 glMatrixMode() – Chooses projection/modelview matrix
 glBegin()/glEnd() – Model data pumped within this block
 glVertex() – Pumps vertex data into OpenGL
 glViewport() – Resizes the OpenGL viewport
 glOrtho() – Specifies orthogonal view volume
 glPolygonMode() – Specifies whether to draw filled polygons or wire-frame
polygons

OpenGL Primitives

S.J.B.I.T Dept of CSE Page 8


18CSL68 Computer Graphics and Mini Project Laboratory

OpenGL Program Organization


• main:
– find GL visual and create window
– initialize GL states (e.g. viewing, color, lighting)
– initialize display lists
– loop
• check for events (and process them)
• if window event (window moved, exposed,
etc.)
• modify viewport, if needed
• redraw
• else if mouse or keyboard
• do something, e.g., change states and
redraw • redraw:
– clear screen (to background color)
– change state(s), if needed
– render some graphics
– change more states
– render some more graphics

glMatrixMode
• glMatrixMode
– - specify which matrix is the current matrix
• C Specification
– void glMatrixMode( GLenummode )
• Parameters
– mode Specifies which matrix stack is the
target for subsequent matrix operations. Three values are accepted:
GL_MODELVIEW, GL_PROJECTION, and GL_TEXTURE. The
default value is GL_MODELVIEW.
• Description
– glMatrixMode sets the current matrix mode. mode can assume one of
three values: GL_MODELVIEW Applies subsequent matrix operations to

S.J.B.I.T Dept of CSE Page 9


18CSL68 Computer Graphics and Mini Project Laboratory

the modelview matrix stack. GL_PROJECTION Applies subsequent


matrix operations to the projection matrix stack.

General 3D Viewing Pipeline

• Modeling coordinates (MC)


• World coordinates (WC)
• Viewing coordinates (VC)
• Projection coordinates (PC)
• Normalized coordinates (NC)
• Device coordinates (DC)

OpenGL 3D Viewing Functions


• Viewing-transformation function
– glMatrixMode(GL_MODELVIEW);
– gluLookAt(x0,y0,z0,xref,yref,zref,vx,vy,vz);
– Default: gluLookAt(0,0,0, 0,0,-1, 0,1,0);
– OpenGL orthogonal-projection function
– glMatrixMode(GL_PROJECTION);
– gluOrtho(xwmin,xwmax, ywmin,ywmax, dnear,dfar);
– Default: gluOrtho(-1,1, -1,1, -1,1);
– Note that
• dnear and dfar must be assigned positive values
• znear=-dnear and zfar=-dfar
• The near clipping plane is the view plane

S.J.B.I.T Dept of CSE Page 10


18CSL68 Computer Graphics and Mini Project Laboratory

Open GL program installation and execution steps


Open GL libraries path
File Location

C:\WINDOWS\System\
glut32.dll

glut32.lib C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib

glut.h C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\include\gl

If you plan on giving your program to friends to run using Windows, you must also

include the glut32.dll file. If they don't have this file in the same directory as your

application or in their C:\WINDOWS\system folder, the program will not run.

S.J.B.I.T Dept of CSE Page 11


18CSL68 Computer Graphics and Mini Project Laboratory

Step 1: Create a Visual Studio 2017 Project


To create an empty console project in Visual Studio, do the following:
1. Create a new project (File ---> New ---> --->Project)
2. In the Project Types: pane, select Visual C++, Win32. Then select Win 32 Console
Application in the Templates: pane. Name your project, select the location for the project
and click OK.
3. Click the Application Settings tab on the left, and check the Empty Project box. Then
click Finish button

Step 2: Add Source Code


1. Select Project, Add New Item
2. In the Categories pane, select Visual C++, Code. Then select C++ File ( .cpp) in the
Templates: pane. Name your file, and then click Add.
Step 3: Compile and Run the project
a. Compile the Program
From the Visual Studio's menu Build option (Build ---> Build Solution) b.
Execute the program
From the Visual Studio's menu Debug option (Debug ---> Start Without Debugging)

S.J.B.I.T Dept of CSE Page 12


18CSL68 Computer Graphics and Mini Project Laboratory

Experiment 1: Implement Brenham’s line drawing algorithm for all types of slope

AIM:
Write a program to implement Bresenham’s line drawing algorithm withal values of
slopes

ALGORITHM:

Bresenham's Line-DrawingAlgorithm.

Step 1 - Input the two end-points of line, storing the left end-point in (x0,y0).

Step 2 - Plot the point (x0,y0).

Step 3 - Calculate the constants dx, dy, 2dy, and (2dy – 2dx) and get the first value for the
decision parameter as -

p0=2dy-dx

Step 4 - At each Xk along the line, starting at k = 0, perform the following test -

If pk< 0, the next point to plot is (xk+1,yk) and pk+1=pk+2dy

Otherwise, (xk,yk+1)

pk+1=pk+2dy-2dx

Step 5 - Repeat step 4 (dx – 1) times.

For m > 1, find out whether you need to increment x while incrementing y each time.

After solving, the equation for decision parameter Pk will be very


similar, just the x and y in the equation gets interchanged.

S.J.B.I.T Dept of CSE Page 13


18CSL68 Computer Graphics and Mini Project Laboratory

PROGRAM:

#include<math.h>
#include<stdio.h>
#include<stdlib.h>
#include<GL/glut.h>

GLintxi,yi,xk,yk;
void plot_point(GLintx,GLint y){
glColor3f(1.0,0.0,0.0);
glPointSize(4);
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
glFlush();
}

void BresenhamlineDrawing()
{
GLint pk;
GLintdy=yk-yi;
GLint dx=xk-xi;
float m;
if(xi!=xk&&yi!=yk)
{
printf("Next pk\t\t Next xi\t Next yi\n");
m=(float)dy/(float)dx;
if(m>0)
{
plot_point(xi,yi);
if(abs(m)<=1)
{
pk=2*dy-dx;
while(xi<xk)
{
if(pk<=0)
{
pk=pk+2*dy;
xi++;
printf("%2d\t\t %2d\t\t %2d\n",pk,xi,yi);
plot_point(xi,yi);
}
if(pk > 0){
pk=pk+2*(dy-dx);
xi++;
yi++;

S.J.B.I.T Dept of CSE Page 14


18CSL68 Computer Graphics and Mini Project Laboratory

printf("%2d\t\t %2d\t\t %2d\n",pk,xi,yi);


plot_point(xi,yi);
}
}
}
if(abs(m)>1){
pk=dy-2*dx;
while(yi<yk)
{
if(pk<=0)
{
pk=pk+2*(dy-dx);
xi++;
yi++;
printf("%3d\t\t %3d\t\t %3d\n",pk,xi,yi);
plot_point(xi,yi);
}
if(pk>0)
{
pk=pk-2*dx;
yi++;
printf("%3d\t\t %3d\t\t %3d\n",pk,xi,yi);
plot_point(xi,yi);
}
}
}
}
else if(m<0){
plot_point(xk,yk);
if(abs(m)<=1)
{
pk=-2*dy-dx;
while(xk>xi)
{
if(pk<=0)
{
pk=pk+(-2*dy);
xk--;
printf("%2d\t\t %2d\t\t %2d\n",pk,xk,yk);
plot_point(xk,yk);
}
if(pk>0){
pk=pk+2*(-dy-dx);
xk--;
yk++;
printf("%2d\t\t %2d\t\t %2d\n",pk,xk,yk);

S.J.B.I.T Dept of CSE Page 15


18CSL68 Computer Graphics and Mini Project Laboratory

plot_point(xk,yk);
}
}
}
if(abs(m)>1){
pk=-dy-2*dx;
while(yk<yi)
{
if(pk>0)
{
pk=pk+(-2*dx);
yk++;
printf("%3d\t\t %3d\t\t %3d\n",pk,xk,yk);
plot_point(xk,yk);
}
if(pk<=0){
pk=pk+2*(-dy-dx);
xk--;
yk++;
printf("%3d\t\t %3d\t\t %3d\n",pk,xk,yk);
plot_point(xk,yk);
}
}
}
}
}
else if(xi==xk){
while(yi<yk){
yi++;
printf("Next xi\t\t Next yi\n");
printf("%3d\t\t %3d\n",xi,yi);
plot_point(xi,yi);
}
}
else if(yi==yk)
{
while(xi<xk)
{
xi++;
printf("Next xi\t\t Next yi\n");
printf("%3d\t\t %3d\n",xi,yi);
plot_point(xi,yi);
}
}
}

S.J.B.I.T Dept of CSE Page 16


18CSL68 Computer Graphics and Mini Project Laboratory

void display(void){
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-50.0,50.0,-50.0,50.0);
BresenhamlineDrawing();
}

int main(int argc,char** argv){


printf("Enter the values of (x0,y0) and (xk,yk)\n");
scanf("%d%d%d%d",&xi,&yi,&xk,&yk);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowPosition(50,50);
glutInitWindowSize(400,300);
glutCreateWindow("Bresenham's Line Drawing Algorithm");
glClearColor(1.0,1.0,1.0,1.0);
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

Sample Output:

S.J.B.I.T Dept of CSE Page 17


18CSL68 Computer Graphics and Mini Project Laboratory

Experiment 2:Create and rotate a triangle about the origin and a fixed point

AIM:
Write a program to Create and rotate a triangle about the origin and a fixed point.

PROGRAM:

#include<stdio.h>
#include<math.h>
#include<GL/glut.h>

GLfloatt[3][3]={{10.0,30.0,20.0},{20.0,20.0,40.0},{1.0,1.0,1.0}};
GLfloatrotatemat[3][3]={{0},{0},{0}};
GLfloatresult[3][9]={{0},{0},{0}};

GLfloatxr=10.0;
GLfloatyr=20.0;

GLfloat theta;
GLintch;

void multiply(){
int i,j,k;
for(i=0;i<3;i++)
for(j=0;j<9;j++){
result[i][j]=0;
for(k=0;k<3;k++)
result[i][j]=result[i][j]+rotatemat[i][k]*t[k][j];
}
}

void rotate_about_origin(){
rotatemat[0][0]=cos(theta);
rotatemat[0][1]=-sin(theta);
rotatemat[0][2]=0;
rotatemat[1][0]=sin(theta);
rotatemat[1][1]=cos(theta);
rotatemat[1][2]=0;
rotatemat[2][0]=0;
rotatemat[2][1]=0;
rotatemat[2][2]=1;
multiply();
}

void rotate_about_fixed_point(){

S.J.B.I.T Dept of CSE Page 18


18CSL68 Computer Graphics and Mini Project Laboratory

GLfloatm,n;
m=xr*(1-cos(theta))+yr*sin(theta);
n=yr*(1-cos(theta))-xr*sin(theta);
rotatemat[0][0]=cos(theta);
rotatemat[0][1]=-sin(theta);
rotatemat[0][2]=m;
rotatemat[1][0]=sin(theta);
rotatemat[1][1]=cos(theta);
rotatemat[1][2]=n;
rotatemat[2][0]=0;
rotatemat[2][1]=0;
rotatemat[2][2]=1;
multiply();
}

void draw_triangle(){
glLineWidth(10);
glBegin(GL_LINE_LOOP);
glColor3f(1.0,0.0,0.0);
glVertex2f(t[0][0],t[1][0]);
glColor3f(0.0,1.0,0.0);
glVertex2f(t[0][1],t[1][1]);
glColor3f(0.0,0.0,1.0);
glVertex2f(t[0][2],t[1][2]);
glEnd();
glFlush();
}

void draw_rotated_triangle(){
glLineWidth(10);
glBegin(GL_LINE_LOOP);
glColor3f(1.0,0.0,0.0);
glVertex2f(result[0][0],result[1][0]);
glColor3f(0.0,1.0,0.0);
glVertex2f(result[0][1],result[1][1]);
glColor3f(0.0,0.0,1.0);
glVertex2f(result[0][2],result[1][2]);
glEnd();
glFlush();
}

void display(){
glClear(GL_COLOR_BUFFER_BIT);
if(ch==1){
draw_triangle();
rotate_about_origin();

S.J.B.I.T Dept of CSE Page 19


18CSL68 Computer Graphics and Mini Project Laboratory

draw_rotated_triangle();
glFlush();
}
if(ch==2){
draw_triangle();
rotate_about_fixed_point();
draw_rotated_triangle();
glFlush();
}
}

void myinit(){
glClearColor(1.0,1.0,1.0,1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-50.0,50.0,-50.0,50.0);
}

int main(int argc,char** argv){


printf("***Rotation***\n1.Rotation about origin\n2.Rotation about a fixed point (xr,yr)\n");
printf("Enter choice\n");
scanf("%d",&ch);
printf("Enter the rotation angle\n");
scanf("%f",&theta);
theta=theta*(3.14/180);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("Triangle Rotation\n");
glutDisplayFunc(display);
myinit();
glutMainLoop();
return 0;
}

S.J.B.I.T Dept of CSE Page 20


18CSL68 Computer Graphics and Mini Project Laboratory

Sample Output :

S.J.B.I.T Dept of CSE Page 21


18CSL68 Computer Graphics and Mini Project Laboratory

Experiment 3:
Draw a color cube and spin it using OpenGL transformation matrices

AIM:
Write a program to Draw a color cube and spin it using OpenGL transformation
matrices

PROGRAM:

#include<stdio.h>
#include<GL/glut.h>

GLfloat vertices[][3]={{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0},{1.0,1.0,-1.0},{-1.0,1.0,-1.0},{-1.0,-1.0,1.0},{1.0,-
1.0,1.0},{1.0,1.0,1.0},{-1.0,1.0,1.0}};

GLfloatcolors[][3]={{0.0,0.0,0.0},{1.0,0.0,0.0},{1.0,1.0,-
1.0},{0.0,1.0,0.0},{0.0,0.0,1.0},{1.0,0.0,1.0},{1.0,1.0,1.0},{0.0,1.0,1.0}};

void polygon(int a,intb,intc,int d){


glBegin(GL_POLYGON);
glColor3fv(colors[a]);
glVertex3fv(vertices[a]);
glColor3fv(colors[b]);
glVertex3fv(vertices[b]);
glColor3fv(colors[c]);
glVertex3fv(vertices[c]);
glColor3fv(colors[d]);
glVertex3fv(vertices[d]);
glEnd();
}

void colorcube(void){
polygon(0,1,2,3);
polygon(0,4,7,3);
polygon(0,1,5,4);
polygon(1,5,6,2);
polygon(3,2,6,7);
polygon(4,5,6,7);
}

static GLfloattheta[] = {0.0,0.0,0.0};


static GLint axis=2;

void display(void)
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glL
S.J.B.I.T Dept of CSE Page 22
18CSL68 Computer Graphics and Mini Project Laboratory

glRotatef(theta[0],1.0,0.0,0.0);
glRotatef(theta[1],0.0,1.0,0.0);
glRotatef(theta[2],0.0,0.0,1.0);
colorcube();
glFlush();
glutSwapBuffers();
}

void spinCube(){
theta[axis]+=0.1;
if(theta[axis>360.0]) theta[axis]-=360.0;
glutPostRedisplay();
}

void mouse(int btn,intstate,intx,int y){


if(btn==GLUT_LEFT_BUTTON && state == GLUT_DOWN) axis=0;
if(btn==GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) axis=1;
if(btn==GLUT_RIGHT_BUTTON && state == GLUT_DOWN) axis=2;
}

void myReshape(int w,int h){


glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w<=h)
glOrtho(-2.0,2.0,-2.0*(GLfloat)h/(GLfloat)w,2.0*(GLfloat)h/(GLfloat)w,-10.0,10.0);
else
glOrtho(-2.0*(GLfloat)w/(GLfloat)h,2.0*(GLfloat)w/(GLfloat)h,-2.0,2.0,-10.0,10.0);
glMatrixMode(GL_MODELVIEW);
}

void main(int argc,char** argv){


glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(500,500);
glutCreateWindow("ColorCube");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutIdleFunc(spinCube);
glutMouseFunc(mouse);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
}
Sample Output:

S.J.B.I.T Dept of CSE Page 23


18CSL68 Computer Graphics and Mini Project Laboratory

S.J.B.I.T Dept of CSE Page 24


18CSL68 Computer Graphics and Mini Project Laboratory

Experiment 4:
Draw a color cube and allow the user to move the camera suitably to experiment
with perspective viewing.

AIM:
Write a program to Draw a color cube and allow the user to move the camera
suitably to experiment with perspective viewing.

PROGRAM:

#include<stdio.h>
#include<GL/glut.h>

GLfloat vertices[][3]={{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0},{1.0,1.0,-1.0},{-1.0,1.0,-1.0},{-1.0,-1.0,1.0},{1.0,-
1.0,1.0},{1.0,1.0,1.0},{-1.0,1.0,1.0}};
GLfloatcolors[][3]={{0.0,0.0,0.0},{1.0,0.0,0.0},{1.0,1.0,-
1.0},{0.0,1.0,0.0},{0.0,0.0,1.0},{1.0,0.0,1.0},{1.0,1.0,1.0},{0.0,1.0,1.0}};
void polygon(int a,intb,intc,int d){
glBegin(GL_POLYGON);
glColor3fv(colors[a]);
glVertex3fv(vertices[a]);
glColor3fv(colors[b]);
glVertex3fv(vertices[b]);
glColor3fv(colors[c]);
glVertex3fv(vertices[c]);
glColor3fv(colors[d]);
glVertex3fv(vertices[d]);
glEnd();
}
void colorcube(void){
polygon(0,1,2,3);
polygon(0,4,7,3);
polygon(0,1,5,4);
polygon(1,5,6,2);
polygon(3,2,6,7);

S.J.B.I.T Dept of CSE Page 25


18CSL68 Computer Graphics and Mini Project Laboratory

polygon(4,5,6,7);
polygon(0,1,5,4);
}
static GLfloattheta[] = {0.0,0.0,0.0};
static GLint axis=2;
static GLdoubleviewer[] = {0.0,0.0,0.5};
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt(viewer[0],viewer[1],viewer[2],0.0,0.0,0.0,0.0,1.0,0.0);
glRotatef(theta[0],1.0,0.0,0.0);
glRotatef(theta[1],0.0,1.0,0.0);
glRotatef(theta[2],0.0,0.0,1.0);
colorcube();
glFlush();
glutSwapBuffers();
}
void mouse(int btn,intstate,intx,int y){
if(btn==GLUT_LEFT_BUTTON && state == GLUT_DOWN) axis=0;
if(btn==GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) axis=1;
if(btn==GLUT_RIGHT_BUTTON && state == GLUT_DOWN) axis=2;
theta[axis]+=2.0;
if(theta[axis]>360.0) theta[axis]-=360.0;
display();
}
void keys(unsigned char key,intx,int y){
if(key=='x') viewer[0]-=1.0;
if(key=='X') viewer[0]+=1.0;
if(key=='y') viewer[1]-=1.0;
if(key=='Y') viewer[1]+=1.0;
if(key=='z') viewer[2]-=1.0;

S.J.B.I.T Dept of CSE Page 26


18CSL68 Computer Graphics and Mini Project Laboratory

if(key=='Z') viewer[3]+=1.0;
display();
}
void myReshape(int w,int h){
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w<=h)
glFrustum(-2.0,2.0,-2.0*(GLfloat)h/(GLfloat)w,2.0*(GLfloat)h/(GLfloat)w,2.0,20.0);
else
glFrustum(-2.0,2.0,-2.0*(GLfloat)w/(GLfloat)h,2.0*(GLfloat)w/(GLfloat)h,2.0,20.0);
glMatrixMode(GL_MODELVIEW);
}
void main(int argc,char** argv){
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(500,500);
glutCreateWindow("ColorCube");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutKeyboardFunc(keys);
glutMouseFunc(mouse);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
} Sample Output:

S.J.B.I.T Dept of CSE Page 27


18CSL68 Computer Graphics and Mini Project Laboratory

Experiment 5:
Clip a lines using Cohen-Sutherland algorithm.

AIM:
Write a program to Clip a lines using Cohen-Sutherland algorithm.

ALGORITHM:
Cohen-sutherland line clipping Algorithm
To perform the trivial acceptance and rejection tests, we extend the edges of the window to
divide the plane of the window into the nine regions. Each end point of the line segment is
then assigned the code of the region in which it lies.
and
1. Given a line segment with endpoint
2. Compute the 4-bit codes for each endpoint.
If both codes are 0000,(bitwise OR of the codes yields 0000 ) line lies completely
inside the window: pass the endpoints to the draw routine.
If both codes have a 1 in the same bit position (bitwise AND of the codes is not 0000),
the line lies outside the window. It can be trivially rejected.
3. If a line cannot be trivially accepted or rejected, at least one of the two endpoints must
lie outside the window and the line segment crosses a window edge. This line must be
clipped at the window edge before being passed to the drawing routine.
4. Examine one of the endpoints, say . Read 's 4-bit code in order: Left-
to-Right, Bottom-to-Top.
5. When a set bit (1) is found, compute theintersectionI of the corresponding window
edge with the line from to . Replace with I and repeat the algorithm.

S.J.B.I.T Dept of CSE Page 28


18CSL68 Computer Graphics and Mini Project Laboratory

PROGRAM:

#include<windows.h>
#include <stdio.h>
#include <GL/glut.h>
#define outcode int
GLfloatxmin,ymin,xmax,ymax;
GLfloatxvmin,yvmin,xvmax,yvmax;
GLfloat x0,y0,x1,y1;
const int LEFT = 1;
const int RIGHT = 2;
const int BOTTOM = 4;
const int TOP = 8;
outcodeComputeOutCode (double x, double y);

void CohenSutherlandLineClipAndDraw ()
{

outcode outcode0, outcode1, outcodeOut;


bool accept = false, done = false;
outcode0 = ComputeOutCode (x0, y0);
outcode1 = ComputeOutCode (x1, y1);
do{
if (!(outcode0 | outcode1))
{
accept = true;
done = true;
}
else if (outcode0 & outcode1)
done = true;
else
{

double x, y;
outcodeOut = outcode0? outcode0: outcode1;

if (outcodeOut& TOP)
{
x = x0 + (x1 - x0) * (ymax - y0)/(y1 - y0);
y = ymax;
}
else if (outcodeOut& BOTTOM)
{
x = x0 + (x1 - x0) * (ymin - y0)/(y1 - y0);
y = ymin;
}
S.J.B.I.T Dept of CSE Page 29
18CSL68 Computer Graphics and Mini Project Laboratory

else if (outcodeOut& RIGHT)


{
y = y0 + (y1 - y0) * (xmax - x0)/(x1 - x0);
x = xmax;
}
else
{
y = y0 + (y1 - y0) * (xmin - x0)/(x1 - x0);
x = xmin;
}
if (outcodeOut == outcode0)
{
x0 = x;
y0 = y;
outcode0 = ComputeOutCode (x0, y0);
}
else
{
x1 = x;
y1 = y;
outcode1 = ComputeOutCode (x1, y1);
}
}
}while (!done);
if (accept)
{
double sx=(xvmax-xvmin)/(xmax-xmin);
double sy=(yvmax-yvmin)/(ymax-ymin);
double vx0=xvmin+(x0-xmin)*sx;
double vy0=yvmin+(y0-ymin)*sy;
double vx1=xvmin+(x1-xmin)*sx;
double vy1=yvmin+(y1-ymin)*sy;
glColor3f(0.0, 1.0, 0.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xvmin, yvmin);
glVertex2f(xvmax, yvmin);
glVertex2f(xvmax, yvmax);
glVertex2f(xvmin, yvmax);
glEnd();
glFlush();
glColor3f(0.0,1.0,0.0);
glBegin(GL_LINES);
glVertex2d (vx0, vy0);
glVertex2d (vx1, vy1);
glEnd();
glFlush();
}
S.J.B.I.T Dept of CSE Page 30
18CSL68 Computer Graphics and Mini Project Laboratory

outcodeComputeOutCode (double x, double y)


{
outcode code = 0;
if (y >ymax)
code |= TOP;
else if (y <ymin)
code |= BOTTOM;
if (x >xmax)
code |= RIGHT;
else if (x <xmin)
code |= LEFT;
return code;
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINES);
glVertex2d (x0, y0);
glVertex2d (x1, y1);
glEnd();
glFlush();
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xmin, ymin);
glVertex2f(xmax, ymin);
glVertex2f(xmax, ymax);
glVertex2f(xmin, ymax);
glEnd();
glFlush();
CohenSutherlandLineClipAndDraw();

void myinit()
{
glClearColor(1.0,1.0,1.0,1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-1000.0,1000.0,-1000.0,1000.0);
}

int main(int argc, char** argv)


{

S.J.B.I.T Dept of CSE Page 31


18CSL68 Computer Graphics and Mini Project Laboratory

printf("Enter xmin, ymin, xmax, ymax for the clipping window\n");


scanf("%f%f%f%f", &xmin,&ymin,&xmax,&ymax);
printf("Enter xmin, ymin, xmax, ymax for the viewport for the output display\n");
scanf("%f%f%f%f", &xvmin,&yvmin,&xvmax,&yvmax);
printf("Enter the points for the line\n");
scanf("%f%f%f%f", &x0,&y0,&x1,&y1);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,300);
glutInitWindowPosition(0,0);
glutCreateWindow("Cohen Suderland Line Clipping Algorithm");
glutDisplayFunc(display);
myinit();
glutMainLoop();
return 0;}}
Sample Output:

S.J.B.I.T Dept of CSE Page 32


18CSL68 Computer Graphics and Mini Project Laboratory

Experiment 6:
To draw a simple shaded scene consisting of a tea pot on a table. Define suitably the
position and properties of the light source along with the properties of the surfaces
of the solid object used in the scene.

AIM:
Write a program to draw a simple shaded scene consisting of a tea pot on a table.
Define suitably the position and properties of the light source along with the
properties of the surfaces of the solid object used in the scene.

PROGRAM

#include <GL/glut.h>

void wall (double thickness)


{
//draw thin wall with top = xz-plane, corner at origin
glPushMatrix();
glTranslated (0.5, 0.5 * thickness, 0.5);
glScaled (1.0, thickness, 1.0);
glutSolidCube (1.0);
glPopMatrix();
}

//draw one table leg


voidtableLeg (double thick, doublelen)
{
glPushMatrix();
glTranslated (0, len/2, 0);
glScaled (thick, len, thick);
glutSolidCube (1.0);
glPopMatrix();
}

void table (doubletopWid, doubletopThick, doublelegThick, doublelegLen) {


//draw the table - a top and four legs
//draw the top firs
tglPushMatrix();
glTranslated (0, legLen, 0);
glScaled(topWid, topThick, topWid);
glutSolidCube (1.0);
glPopMatrix();
doubledist = 0.95 * topWid/2.0 - legThick/2.0;
glPushMatrix();
glTranslated (dist, 0, dist);

S.J.B.I.T Dept of CSE Page 33


18CSL68 Computer Graphics and Mini Project Laboratory

tableLeg (legThick, legLen);


glTranslated (0.0, 0.0, -2 * dist);
tableLeg (legThick, legLen);
glTranslated (-2*dist, 0, 2 *dist);
tableLeg (legThick, legLen);
glTranslated(0, 0, -2*dist);
tableLeg (legThick, legLen);
glPopMatrix();
}

voiddisplaySolid (void)
{
//set properties of the surface material
GLfloatmat_ambient[] = {0.7f, 0.7f, 0.7f, 1.0f}; // gray
GLfloatmat_diffuse[] = {.5f, .5f, .5f, 1.0f};
GLfloatmat_specular[] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloatmat_shininess[] = {50.0f};
glMaterialfv (GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv (GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv (GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);

//set the light source properties


GLfloatlightIntensity[] = {0.7f, 0.7f, 0.7f, 1.0f};
GLfloatlight_position[] = {2.0f, 6.0f, 3.0f, 0.0f};
glLightfv (GL_LIGHT0, GL_POSITION, light_position);
glLightfv (GL_LIGHT0, GL_DIFFUSE, lightIntensity);

//set the camera


glMatrixMode (GL_PROJECTION);
glLoadIdentity();
doublewinHt = 1.0; //half-height of window
glOrtho (-winHt * 64/48.0, winHt*64/48.0, -winHt, winHt, 0.1, 100.0);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity();
gluLookAt (2.3, 1.3, 2.0, 0.0, 0.25, 0.0, 0.0, 1.0, 0.0);

//start drawing
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslated (0.4, 0.4, 0.6);
glRotated (45, 0, 0, 1);
glScaled (0.08, 0.08, 0.08);
glPopMatrix();
glPushMatrix();
glTranslated (0.6, 0.38, 0.5);
glRotated (30, 0, 1, 0);

S.J.B.I.T Dept of CSE Page 34


18CSL68 Computer Graphics and Mini Project Laboratory

glutSolidTeapot (0.08);
glPopMatrix ();
glPushMatrix();
glTranslated (0.25, 0.42, 0.35); //glutSolidSphere (0.1, 15, 15);
glPopMatrix();
glPushMatrix();
glTranslated (0.4, 0, 0.4);
table (0.6, 0.02, 0.02, 0.3);
glPopMatrix();
wall (0.02);
glPushMatrix();
glRotated (90.0, 0.0, 0.0, 1.0);
wall (0.02);
glPopMatrix();
glPushMatrix();
glRotated (-90.0, 1.0, 0.0, 0.0);
wall (0.02);
glPopMatrix();

glFlush();
}

void main (intargc, char ** argv)


{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize (640, 480);
glutInitWindowPosition (100, 100);
glutCreateWindow ("simple shaded scene consisting of a tea pot on a table");
glutDisplayFunc (displaySolid);
glEnable (GL_LIGHTING);
glEnable (GL_LIGHT0);
glShadeModel (GL_SMOOTH);
glEnable (GL_DEPTH_TEST);
glEnable (GL_NORMALIZE);
glClearColor (0.1, 0.1, 0.1, 0.0);
glViewport (0, 0, 640, 480);
glutMainLoop();
}

OR
#include<gl/glut.h>
void obj(double tx,doublety,doubletz,doublesx,doublesy,doublesz)
{
glRotated(50,0,1,0); glRotated(10,-1,0,0);
glRotated(11.7,0,0,-1);

S.J.B.I.T Dept of CSE Page 35


18CSL68 Computer Graphics and Mini Project Laboratory

glTranslated(tx,ty,tz); glScaled(sx,sy,sz);
glutSolidCube(1);
glLoadIdentity();
}
void display()
{
glViewport(0,0,700,700);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

obj(0,0,0.5,1,1,0.04); // three walls


obj(0,-0.5,0,1,0.04,1);
obj(-0.5,0,0,0.04,1,1);
obj(0,-0.3,0,0.02,0.2,0.02); // four table legs
obj(0,-0.3,-0.4,0.02,0.2,0.02);
obj(0.4,-0.3,0,0.02,0.2,0.02);
obj(0.4,-0.3,-0.4,0.02,0.2,0.02);
obj(0.2,-0.18,-0.2,0.6,0.02,0.6); // table top
glRotated(50,0,1,0);
glRotated(10,-1,0,0);
glRotated(11.7,0,0,-1);
glTranslated(0.3,-0.1,-0.3);
glutSolidTeapot(0.09); glFlush();
glLoadIdentity();
}
void main()
{
float ambient[]={1,1,1,1}; float
light_pos[]={27,80,2,3};
glutInitWindowSize(700,700);
glutCreateWindow("scene");
glutDisplayFunc(display);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glMaterialfv(GL_FRONT,GL_AMBIENT,ambient);
glLightfv(GL_LIGHT0,GL_POSITION,light_pos);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
}
Output:

S.J.B.I.T Dept of CSE Page 36


18CSL68 Computer Graphics and Mini Project Laboratory

Experiment 7:
Design, develop and implement recursively subdivide a tetrahedron to form 3D
sierpinski gasket. The number of recursive steps is to be specified by the user.

AIM:
Write a program to Design, develop and implement recursively subdivide a
tetrahedron to form 3D sierpinski gasket. The number of recursive steps is to be
specified by the user..

PROGRAM

#include<stdio.h>
#include<GL/glut.h>

typedef float point[3];

point v[] = {{0.0,0.0,1.0},{0.0,1.0,-1.0},{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0}};


int n;

void triangle(point a,pointb,point c)


{

S.J.B.I.T Dept of CSE Page 37


18CSL68 Computer Graphics and Mini Project Laboratory

glBegin(GL_POLYGON);
glVertex3fv(a);
glVertex3fv(b);
glVertex3fv(c);
glEnd();
}

void divide_triangle(point a,pointb,pointc,int m)


{
point v1,v2,v3;
int j;
if(m>0)
{
for(j=0;j<3;j++) v1[j]=(a[j]+b[j])/2;
for(j=0;j<3;j++) v2[j]=(a[j]+c[j])/2;
for(j=0;j<3;j++) v3[j]=(b[j]+c[j])/2;
divide_triangle(a,v1,v2,m-1);
divide_triangle(c,v2,v3,m-1);
divide_triangle(b,v3,v1,m-1);
}
else(triangle(a,b,c));
}

void tetrahedron(int m)
{
glColor3f(1.0,0.0,0.0);
divide_triangle(v[0],v[1],v[2],m);
glColor3f(0.3,0.3,0.3);
divide_triangle(v[3],v[2],v[1],m);
glColor3f(0.0,0.0,1.0);
divide_triangle(v[0],v[3],v[1],m);
glColor3f(0.0,1.0,0.0);
divide_triangle(v[0],v[2],v[3],m);
glFlush();
}

void display(void)
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
tetrahedron(n);
}
void myReshape(int w,int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);

S.J.B.I.T Dept of CSE Page 38


18CSL68 Computer Graphics and Mini Project Laboratory

glLoadIdentity();
if(w<=h)
glOrtho(-2.0,2.0,-2.0*(GLfloat)h/(GLfloat)w,2.0*(GLfloat)h/(GLfloat)w,-10.0,10.0);
else
glOrtho(-2.0*(GLfloat)w/(GLfloat)h,2.0*(GLfloat)w/(GLfloat)h,-2.0,2.0,-10.0,10.0);
glMatrixMode(GL_MODELVIEW);
glutPostRedisplay();
}
int main(int argc,char** argv)
{
printf("Enter the number of division:");
scanf("%d",&n);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(640,480);
glutCreateWindow("3D Gasket");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glEnable(GL_DEPTH_TEST);
glClearColor(1.0,1.0,1.0,1.0);
glutMainLoop();
return 0;
}
Sample Output:

S.J.B.I.T Dept of CSE Page 39


18CSL68 Computer Graphics and Mini Project Laboratory

Experiment 8:
Develop a menu driven program to animate a flag using Bezier Curve algorithm.

AIM:
Write a program to develop a menu driven program to animate a flag using Bezier
Curve algorithm

PROGRAM

#include<GL/glut.h>
#include<stdio.h>
#include<math.h>
#define PI 3.1416

static int win,val=0,CMenu;

void CreateMenu(void);
void Menu(int value);

struct wcPt3D
{
GLfloat x, y, z;
};

S.J.B.I.T Dept of CSE Page 40


18CSL68 Computer Graphics and Mini Project Laboratory

GLsizeiwinWidth = 600, winHeight = 600;


GLfloatxwcMin = 0.0, xwcMax = 130.0;
GLfloatywcMin = 0.0, ywcMax = 130.0; void
bino(GLint n, GLint *C)
{
GLint k, j;
for(k=0;k<=n;k++)
{
C[k]=1;
for(j=n;j>=k+1; j--) C[k]*=j;
for(j=n-k;j>=2;j--)
C[k]/=j;
}}
void computeBezPt(GLfloatu,struct wcPt3D *bezPt, GLintnCtrlPts,struct wcPt3D *ctrlPts,
GLint *C)
{
GLint k, n=nCtrlPts-1;
GLfloatbezBlendFcn;
bezPt ->x =bezPt ->y = bezPt->z=0.0; for(k=0;
k<nCtrlPts; k++)
{
bezBlendFcn = C[k] * pow(u, k) * pow( 1-u, n-k);
bezPt ->x += ctrlPts[k].x * bezBlendFcn; bezPt -
>y += ctrlPts[k].y * bezBlendFcn;
bezPt ->z += ctrlPts[k].z * bezBlendFcn;
}}
void bezier(struct wcPt3D *ctrlPts, GLintnCtrlPts, GLintnBezCurvePts)
{
struct wcPt3D bezCurvePt;
GLfloat u;
GLint *C, k;
C= new GLint[nCtrlPts]; bino(nCtrlPts-1,
C); glBegin(GL_LINE_STRIP);
for(k=0; k<=nBezCurvePts; k++)
{
u=GLfloat(k)/GLfloat(nBezCurvePts); computeBezPt(u,
&bezCurvePt, nCtrlPts, ctrlPts, C);
glVertex2f(bezCurvePt.x, bezCurvePt.y);
} glEnd();
delete[]C;
}
void displayFcn()
{
GLintnCtrlPts = 4, nBezCurvePts =20;
static float theta = 0;
struct wcPt3D ctrlPts[4] = {{20, 100, 0},{30, 110, 0},{50, 90, 0},{60, 100, 0}};

S.J.B.I.T Dept of CSE Page 41


18CSL68 Computer Graphics and Mini Project Laboratory

ctrlPts[1].x +=10*sin(theta * PI/180.0); ctrlPts[1].y +=5*sin(theta * PI/180.0);


ctrlPts[2].x -= 10*sin((theta+30) * PI/180.0); ctrlPts[2].y -= 10*sin((theta+30)
* PI/180.0); ctrlPts[3].x-= 4*sin((theta) *PI/180.0); ctrlPts[3].y += sin((theta-
30) * PI/180.0); theta+=0.1;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glPointSize(5); //Indian
Flag if(val==1){
glPushMatrix();
glLineWidth(5);
glColor3f(1.0,0.5,0); //Indian flag: Orange color code for(int
i=0;i<8;i++)
{
glTranslatef(0, -0.8, 0);
bezier(ctrlPts, nCtrlPts, nBezCurvePts);
}
glColor3f(1,1,1); //Indian flag: white color code for(int
i=0;i<8;i++)
{
glTranslatef(0, -0.8, 0);
bezier(ctrlPts, nCtrlPts, nBezCurvePts);
}
glColor3f(0,1.0,0); //Indian flag: green color code for(int
i=0;i<8;i++)
{
glTranslatef(0, -0.8, 0);
bezier(ctrlPts, nCtrlPts, nBezCurvePts);
} glPopMatrix();
glColor3f(0.7, 0.5,0.3);
glLineWidth(5);
glBegin(GL_LINES);
glVertex2f(20,100);
glVertex2f(20,40);
glEnd(); glFlush(); }
//Karnataka Flag
if(val==2){glPushMatrix();
glLineWidth(5);
glColor3f(1.0, 1.0, 0.0); //Karnataka flag: Yellow color code for(int
i=0;i<12;i++)
{
glTranslatef(0, -0.8, 0);
bezier(ctrlPts, nCtrlPts, nBezCurvePts);
}
glColor3f(1, 0.0, 0.0); //Karnataka flag: Red color code for(int
i=0;i<12;i++)
{
glTranslatef(0, -0.8, 0);

S.J.B.I.T Dept of CSE Page 42


18CSL68 Computer Graphics and Mini Project Laboratory

bezier(ctrlPts, nCtrlPts, nBezCurvePts);


}
glPopMatrix();
glColor3f(0.7, 0.5,0.3);
glLineWidth(5);
glBegin(GL_LINES);
glVertex2f(20,100);
glVertex2f(20,40);
glEnd(); glFlush(); }
glutPostRedisplay();
glutSwapBuffers();
}

void winReshapeFun(GLintnewWidth, GLintnewHeight)


{
glViewport(0, 0, newWidth, newHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(xwcMin, xwcMax, ywcMin, ywcMax);
glClear(GL_COLOR_BUFFER_BIT);
}

void CreateMenu(void)
{
CMenu= glutCreateMenu(Menu);//Creaate Menu Option
glutAddMenuEntry("Indian Flag",1);
glutAddMenuEntry("Karnataka Flag",2);
glutAddMenuEntry("Exit",0);
glutAttachMenu(GLUT_RIGHT_BUTTON);

void Menu(int value)


{
if(value==0)
{
glutDestroyWindow(win);
exit(0); }
else {
val=value;
}
}
int main(int argc, char **argv)
{ glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition(50, 50);

S.J.B.I.T Dept of CSE Page 43


18CSL68 Computer Graphics and Mini Project Laboratory

glutInitWindowSize(winWidth, winHeight);
glutCreateWindow("Prg. 8 Bezier Curve");
CreateMenu(); glutDisplayFunc(displayFcn);
glutReshapeFunc(winReshapeFun); glutMainLoop();
}
Sample Output:

Experiment 9:
Develop a menu driven program to fill the polygon using scan line algorithm.

AIM:
Write a program to Develop a menu driven program to fill the polygon using scan
line algorithm.

ALGORITHM:

Step 1 − Find out the Ymin and Ymax from the given polygon.
Step 2 − ScanLine intersects with each edge of the polygon from Ymin to Ymax. Name
each intersection point of the polygon. As per the figure shown above, they are named as
p0, p1, p2, p3.
Step 3 − Sort the intersection point in the increasing order of X coordinate i.e. (p0, p1), (p1,
p2), and (p2, p3).
Step 4 − Fill all those pair of coordinates that are inside polygons and ignore the alternate pairs.

PROGRAM

S.J.B.I.T Dept of CSE Page 44


18CSL68 Computer Graphics and Mini Project Laboratory

#include<stdlib.h>
#include<stdio.h>
#include<GL/glut.h>

float x1=200.0,y1=200.0,x2=100.0,y2=300.0,x3=200.0,y3=400.0,x4=300.0,y4=300.0;

void edgedetect(float x1,float y1,float x2,float y2,int *le,int *re){


float mx,x,temp;
int i;
if((y2-y1)<0){
temp=y1;y1=y2;y2=temp;
temp=x1;x1=x2;x2=temp;
}
if((y2-y1)!= 0)
mx=(x2-x1)/(y2-y1);
else
mx=(x2-x1);
x=x1;
for(i=y1;i<=y2;i++){
if(x<(float)le[i])
le[i]=(int)x;
if(x>(float)re[i]){
re[i]=(int)x;
}
x+=mx;
}
}

void drawpixel(int x,int y){


glColor3f(1,0,0);
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
}

void scanfill(float x1,float y1,float x2,float y2,float x3,float y3,float x4,float y4){
int le[500],re[500];
int i,y;
for(i=0;i<500;i++){
le[i]=500;
re[i]=0;
}
edgedetect(x1,y1,x2,y2,le,re);
edgedetect(x2,y2,x3,y3,le,re);
edgedetect(x3,y3,x4,y4,le,re);
edgedetect(x4,y4,x1,y1,le,re);

S.J.B.I.T Dept of CSE Page 45


18CSL68 Computer Graphics and Mini Project Laboratory

for(y=0;y<500;y++){
if(le[y]<=re[y])
for(i=(int)le[y];i<(int)re[y];i++)
drawpixel(i,y);
}
}

void drawpoly(){
glColor3f(0,0,1);
glBegin(GL_LINE_LOOP);
glVertex2f(x1,y1);
glVertex2f(x2,y2);
glVertex2f(x3,y3);
glVertex2f(x4,y4);
glEnd();
glFlush();
}

void display(){
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,499,0,499);
}

void menu(int id){


switch(id){
case 1:drawpoly();
break;
case 2:scanfill(x1,y1,x2,y2,x3,y3,x4,y4);
drawpoly();
break;
}
}
int main(int argc,char **argv){
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(300,300);
glutInitWindowPosition(50,50);
glutCreateWindow("ScanFill");
glutDisplayFunc(display);
glClearColor(1,1,1,1);
glFlush();
glutCreateMenu(menu);
glutAddMenuEntry("display Polygon",1);
glutAddMenuEntry("fill polygon",2);

S.J.B.I.T Dept of CSE Page 46


18CSL68 Computer Graphics and Mini Project Laboratory

glutAttachMenu(GLUT_RIGHT_BUTTON);
glutMainLoop();
return 0;
}
Sample Output:

Viva questions
1. What is scan conversion?
A major task of the display processor is digitizing a picture definition given in an application program into a
set of pixel-intensity values for storage in the frame buffer. This digitization process is called scan
conversion.

2. Write the properties of video display devices?


Properties of video display devices are persistence,resolution, and aspect ratio.

3. What is rasterization?
The process of determining the appropriate pixels for representing picture or graphics object is known as
rasterization.

4. Define Computer graphics.


Computer graphics remains one of the most existing andrapidly growing computer fields. Computer
graphics maybe defined as a pictorial representation or graphicalrepresentation of objects in a computer.

5. Name any four input devices?


Four input devices are keyboard, mouse, image scanners,and trackball.

6. Write the two techniques for producing color displays with a CRT?
Beam penetration method, shadow mask method.

7. What is vertical retrace of the electron beam?


In raster
S.J.B.I.T Dept of CSE Page 47
18CSL68 Computer Graphics and Mini Project Laboratory

scan display, at the end of one frame, the electron beam returns to the left top corner of the screen to start the
next frame.

8. Short notes on video controller?


Video controller is used to control the operation of the display device. A fixed area of the system is reserved
for the frame buffer, and the video controller is given direct access to the frame buffer memory.

9. What is bitmap?
Some system has only one bit per pixel; the frame buffer is often referred to as bitmap.

10. Differentiate plasma panel display and thin film electro luminescent display?
In plasma panel display, the region between two glass plates is filled with neon gas. In thin film electro
luminescent display, the region between two glasses plates are filled with phosphor, such as zinc sulphide
doped with manganese.

11. What is resolution?


The maximum number of points that can be displayed without overlap on a CRT is referred to as the
resolution.

12. What is horizontal retrace of the electron beam?


In raster scan display, the electron beam return to the left of the screen after refreshing each scan line, is
called horizontal retrace of the electron beam.

13. What is filament?


In the CRT, heat is applied to the cathode by directing a current through a coil of wire, is called filament.

14. What is pixel map?


Some system has multiple bits per pixel, the frame buffer is often referred to as pixel map.

15. Write the types of clipping?


Point clipping, line clipping, area clipping, text clipping and curve clipping.

16. What is meant by scan code?


When a key is pressed on the keyboard, the keyboard controller places a code carry to the key pressed into a
part of the memory called as the keyboard buffer. This code is called as the scan code.

17. List out the merits and demerits of Penetration techniques?


The merits and demerits of the Penetration techniques areas follows. It is an inexpensive technique. It has
only four colors. The quality of the picture is not good when it is compared to other techniques. It can
display color scans in monitors. Poor limitation etc.

18. List out the merits and demerits of DVST?


The merits and demerits of direct view storage tubes[DVST] are as follows. It has a flat screen. Refreshing
of screen is not required. Selective or part erasing of screen is not possible. It has poor contrast Performance
is inferior to the refresh CRT.

19. What
S.J.B.I.T Dept of CSE Page 48
18CSL68 Computer Graphics and Mini Project Laboratory

do you mean by emissive and non-emissivedisplays?


The emissive display converts electrical energy into lightenergy. The plasma panels, thin film electro-
luminescent displays are the examples.The Non-emissive are optical effects to convert the sunlightor light
from any other source to graphic form. Liquid crystal display is an example

20. List out the merits and demerits of Plasma paneldisplay?


Merits. Refreshing is not required. Produce a very steady image free of Flicker. Less bulky than a
CRT.Demerits. Poor resolution of up to 60 d.p.i. It requires complex addressing and wiring. It is costlier
than CRT.

21. What is persistence?


The time it takes the emitted light from the screen to decay one tenth of its original intensity is called as
persistence.

22. What is Aspect ratio?


The ratio of vertical points to the horizontal points necessary to produce length of lines in both directions of
the screen is called the Aspect ratio. Usually the aspect ratio is ¾.

23. What is the difference between impact and non-impactprinters?


Impact printer press formed character faces against an inked ribbon on to the paper. A line printer and dot-
matrix printer are examples.Non-impact printer and plotters use Laser techniques,inkjet sprays, Xerographic
process, electrostatic method sand electrothermal methods to get images onto the papers. Examples are:
Inkjet/Laser printers.

24. Define pixel?


Pixel is shortened forms of picture element. Each screen point is referred to as pixel or pixel.

25. What is frame buffer?


Picture definition is stored in a memory area called frame buffer or refresh buffer.

26. Where the video controller is used?


A special purpose processor, which is used to control the operation of the display device, is known as video
controller or display controller.

27. What is run length encoding?


Run length encoding is a compression technique used to store the intensity values in the frame buffer, which
store search scan line as a set of integer pairs. One number each pair indicates an intensity value, and second
number specifies the number of adjacent pixels on the scan line that are to have that intensity value.

28. What is point in the computer graphics system?


The point is a most basic graphical element & is completely defined by a pair of user coordinates (x, y).

29. Write short notes on lines?


A line is of infinite extent can be defined by an angle of slope q and one point on the line P=P(x,y). This can
also be defined as y=mx+C where C is the Y intercept.

30. Define
S.J.B.I.T Dept of CSE Page 49
18CSL68 Computer Graphics and Mini Project Laboratory

Circle?
Circle is defined by its center xc, yc and its radius in user coordinate units. The equation of the circle is (x-
xc) + (yyc)= r2.

31. What are the various attributes of a line?


The line type, width and color are the attributes of the line.The line type include solid line, dashed lines, and
dotted lines.

32. What is anti aliasing?


The process of adjusting intensities of the pixels along the line to minimize the effect of aliasing is called
anti aliasing.

33. What is Transformation?


Transformation is the process of introducing changes in the shape size and orientation of the object using
scaling rotation reflection shearing & translation etc.

34. What is translation?


Translation is the process of changing the position of an object in a straight-line path from one coordinate
location to another. Every point (x , y) in the object must under go a displacement to (x|,y|). the
transformation is:x| = x + tx ; y| = y+ty

35. What is rotation?


A 2-D rotation is done by re positioning the coordinates along a circular path, in the x-y plane by making an
angle with the axes. The transformation is given by:X| = r cos (q + f) and Y| = r sin (q + f).

36. What is scaling?


A 2-D rotation is done by re positioning the coordinates along a circular path, in the x-y plane by making an
angle with the axes. The transformation is given by:X| = r cos (q + f) and Y| = r sin (q + f).

37. What is shearing?


The shearing transformation actually slants the object along the X direction or the Y direction as required.
ie; this transformation slants the shape of an object along a required plane.

38. What is reflection?


The reflection is actually the transformation that produces a mirror image of an object. For this use some
angles and lines of reflection.

39. What are the two classifications of shear transformation?


X shear, y shear

40. A point (4,3) is rotated counterclockwise by an angle of 45°. Find the rotation matrix and the
resultant
point

41. Name any three font editing tools.


ResEdit, FONTo grapher

S.J.B.I.T Dept of CSE Page 50


18CSL68 Computer Graphics and Mini Project Laboratory

42. Differentiate serif and sans serif fonts.


Give one example Serif fonts has a little decoration at the end of the letter,but serif font has not. Times, new
century schoolbook is the examples of serif fonts. Arial, optima are examples for sanserif fonts.

43. Distinguish between window port & view port?


A portion of a picture that is to be displayed by a window is known as window port. The display area of the
part selected or the form in which the selected part is viewed is known as view port.

44. Define clipping?


Clipping is the method of cutting a graphics display to neatly fit a predefined graphics region or the view
port.

45. What is the need of homogeneous coordinates?


To perform more than one transformation at a time, use homogeneous coordinates or matrixes. They reduce
unwanted calculations intermediate steps saves time and memory and produce a sequence of
transformations.

S.J.B.I.T Dept of CSE Page 51

You might also like