Download as pdf or txt
Download as pdf or txt
You are on page 1of 74

15CSL68 COMPUTER GRAPHICS AND VISUALIZATION

LABOROTORY WITH MINI PROJECT

SYLLABUS

Subject Code : 15CSL67 IA Marks : 20

No. of Practical Hrs. / Week : 01I + 02P Exam Hours : 03

Total No. of Practical Hours : 40 Exam Marks : 80

COMPUTER GRAPHICS LABORATORY WITH MINI PROJECT


SEMESTER – VI
Subject Code: 15CSL68
Lab Experiments:
PART A

Design, develop, and implement the following programs using OpenGL API

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


2. Create and rotate a triangle about the origin and a fixed point.
3. Draw a color cube and spin it using OpenGL transformation matrices.
4. Draw a color cube and allow the user to move the camera suitably to experiment with perspective
viewing.
5. Clip a lines using Cohen-Sutherland algorithm.
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.
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.
8. Develop a menu driven program to animate a flag using Bezier Curve algorithm
9. . Develop a menu driven program to fill the polygon using scan line algorithm.

PART –B ( MINI-PROJECT)

10. Student should develop mini project on the topics mentioned below or similar applications using
Open GL API. Consider all types of attributes like color, thickness, styles, font, background,
speed etc., while doing mini project. (During the practical exam: the students should demonstrate
and answer Viva-Voce)

Dept. Of CSE ,BTLITM Page 1


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

SAMPLE PROGRAMS

This section covers simple programs to draw points, lines, triangles, and polygons. The aim of
these programs is to introduce the basic functions and structure of OpenGL programs.

Program to draw points

Source Code:
#include <GL/glut.h>

void display()

/* Clear the display window */

glClear(GL_COLOR_BUFFER_BIT);

/* Draw points */

glBegin(GL_POINTS);

glVertex2f(0.0,0.0);

glVertex2f(100.0,100.0);

glVertex2f(110.0,10.0);

glVertex2f(400.0,500.0);

glVertex2f(500.0,500.0);

glVertex2f(550.0,550.0);

glEnd();

/* Clear buffers */

glFlush();

Dept. Of CSE ,BTLITM Page 2


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
}

void myinit()

/* Set background color */

glClearColor(1.0,1.0,1.0,1.0);

/* Set foreground color */

glColor3f(1.0,0.0,0.0);

/* Set point size */

glPointSize(5.0);

/* Set 2D orthogonal viewing window */

gluOrtho2D(0.0,550.0,0.0,550.0);

void main(int argc, char** argv)

/* Standard GLUT intialization */

glutInit(&argc,argv);

/* Set single buffer and RGB color mode */

glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);

/* Set intial window size to 500 by 500 pixels */

glutInitWindowSize(500,500);

Dept. Of CSE ,BTLITM Page 3


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

/* Sets the inital window position */

glutInitWindowPosition(0,0);

/* Create a display window */

glutCreateWindow("Points");

/* Register display callback */

glutDisplayFunc(display);

/* Set the programs attributes */

myinit();

/* Enter event processing loop */

glutMainLoop();

Output:

Dept. Of CSE ,BTLITM Page 4


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

Exercise:
1. Change the color of each point (set yellow color for origin & green for dagonally opposite point)
2. Change the backgorund color
3. Change the size of the window
4. What happens if glutMainLoop () function is not specified?
Program to draw lines

Source Code:
#include <GL/glut.h>

void display(void)

Dept. Of CSE ,BTLITM Page 5


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
/* Clear the display window */

glClear(GL_COLOR_BUFFER_BIT);

/* Set foreground color to red */

glColor3f(1.0,0.0,0.0);

/* Draw line segment */

glBegin(GL_LINES);

glVertex2i(50,50);

glVertex2i(400,400);

glEnd();

/* Set the text color */

glColor3f(0.0,0.0,0.0);

/* Set the location to print text */

glRasterPos2i(190, 200);

/* Set the bitmap character to be displayed */

glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12,'L');

/* Clear buffers */

glFlush();

void myinit()

Dept. Of CSE ,BTLITM Page 6


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
/* Set background color to white */

glClearColor(1.0,1.0,1.0,1.0);

/* Set matrix to projection matrix */

glMatrixMode(GL_PROJECTION);

/* Set 2D orthogonal viewing window */

gluOrtho2D(0.0,500.0,0.0,500.0);

void main(int argc, char** argv)

/* Standard GLUT intialization */

glutInit(&argc,argv);

/* Set single buffer and RGB color mode */

glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);

/* Set intial window size to 500 by 500 pixels */

glutInitWindowSize(500,500);

/* Sets the inital window position */

glutInitWindowPosition(0,0);

/* Create a display window names 'Points' */

glutCreateWindow("Lines");

Dept. Of CSE ,BTLITM Page 7


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

/* Register display callback */

glutDisplayFunc(display);

/* Set the programs attributes */

myinit();

/* Enter event processing loop */

glutMainLoop();

Output:

Dept. Of CSE ,BTLITM Page 8


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

Exercise:
1. Add two or more line segments in different colors
2. What happens when negative coordinates are given for lines?
3. Print the word ‘LINE A’, LINE ‘B’,… along each line
4. What happens if glutInitWindowSize and glutCreateWindow functions are not included?
Program to draw triangle

Source Code:
#include <GL/glut.h>

void display(void)

Dept. Of CSE ,BTLITM Page 9


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
{

/* Clear the display window */

glClear(GL_COLOR_BUFFER_BIT);

/* Draw triangle */

glBegin(GL_TRIANGLES);

glVertex2f(-0.5, -0.5);

glVertex2f(-0.5, 0.5);

glVertex2f(0.5, 0.5);

glEnd();

/* Clear buffers */

glFlush();

void myinit()

/* Set background color */

glClearColor (0.0, 0.0, 0.0, 0.0);

/* Set foreground color to white */

glColor3f(1.0, 1.0, 1.0);

/* Set matrix to projection matrix */

glMatrixMode (GL_PROJECTION);

Dept. Of CSE ,BTLITM Page 10


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
glLoadIdentity ();

/* Set Orthogonal view with clipping cube with

sides of 2 unit length centered around the origin */

glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

void main(int argc, char** argv)

/* Standard GLUT intialization */

glutInit(&argc,argv);

/* Set single buffer and RGB color mode */

glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);

/* Set intial window size to 500 by 500 pixels */

glutInitWindowSize(500,500);

/* Sets the inital window position */

glutInitWindowPosition(0,0);

/* Create a display window names 'Triangles' */

glutCreateWindow("Triangles");

/* Register display callback */

glutDisplayFunc(display);

Dept. Of CSE ,BTLITM Page 11


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
/* Set the programs attributes */

myinit();

/* Enter event processing loop */

glutMainLoop();

Output:

Dept. Of CSE ,BTLITM Page 12


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

Exercise:
1. Add two or more triangles in different colors
2. Draw triangles using macros for lines and line loops
3. What is the difference in the triangles formed using three different macros
4. What happens if glutDisplayFunc function is not included?

Program to draw polygons

Source Code:
#include <GL/glut.h>

void display(void)

/* Clear the display window */

glClear(GL_COLOR_BUFFER_BIT);

/* Draw Polygon */

glBegin(GL_POLYGON);

glVertex2f(-0.5, -0.5);

glVertex2f(-0.5, 0.5);

glVertex2f(0.5, 0.5);

glVertex2f(0.5, -0.5);

glEnd();

/* Clear buffers */

glFlush();

Dept. Of CSE ,BTLITM Page 13


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

void myinit()

/* Set background color to black */

glClearColor (0.0, 0.0, 0.0, 0.0);

/* Set foreground color to yellow color */

glColor3f(1.0, 1.0, 0.0);

/* Set matrix to projection matrix */

glMatrixMode (GL_PROJECTION);

glLoadIdentity ();

/* Set orthoginal view with a clipping window of

size 2 centered at origin */

glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

void main(int argc, char** argv)

/* Standard GLUT intialization */

glutInit(&argc,argv);

/* Set single buffer and RGB color mode */

glutInitDisplayMode (GLUT_SINGLE|GLUT_RGB);

/* Set intial window size to 500 by 500 pixels */

Dept. Of CSE ,BTLITM Page 14


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
glutInitWindowSize(500,500);

/* Sets the inital window position */

glutInitWindowPosition(0,0);

/* Create a display window names 'Polygons' */ glutCreateWindow("Polygons");

/* Register display callback */

glutDisplayFunc(display);

myinit();

/* Enter event processing loop */

glutMainLoop();

Output:

Dept. Of CSE ,BTLITM Page 15


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

Exercise:
1. Add two or more rectangles in different colors
2. Draw rectangles using macros for lines and line loops
3. Change the size of the clipping window and redraw the rectangles
4. What happens if macros in glutInitDisplayMode are entered wrong?

Dept. Of CSE ,BTLITM Page 16


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

PROGRAM 1
Question 1.

Implement Brenham’s line drawing algorithm for all types of slope.

#include <GL/glut.h>
#include <math.h>
int ww = 600, wh = 400;
int first = 0;
int xi, yi, xf, yf;
void putPixel (int x, int y)
{
glColor3f (0.3, 0.2, 0.0); // activate the pixel by setting the point color to white
glBegin (GL_POINTS);
glVertex2i (x, y); // set the point
glEnd ();
glFlush (); // process all openGL routines as quickly as possible
}
void display()
{
glClearColor(0.4, 0.7, 0.5, 1.0);
glColor3f(0.2, 0.3, 0.3);
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
void bresenhamAlg (int x0, int y0, int x1, int y1)
{
int dx = abs (x1 - x0);
int dy = abs (y1 - y0);
int x, y;
if (dx >= dy)
{
int d = 2*dy-dx;
int ds = 2*dy;
int dt = 2*(dy-dx);

Dept. Of CSE ,BTLITM Page 17


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

if (x0 < x1)


{
x = x0;
y = y0;
}
else
{
x = x1;
y = y1;
x1 = x0;
y1 = y0;
}
putPixel (x, y);
while (x < x1)
{
if (d < 0)
d += ds;
else {
if (y < y1) {
y++;
d += dt;
}
else {
y--;
d += dt;
}
}
x++;
putPixel (x, y);
}
}
else {
int d = 2*dx-dy;
int ds = 2*dx;
int dt = 2*(dx-dy);

Dept. Of CSE ,BTLITM Page 18


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

if (y0 < y1) {


x = x0;
y = y0;
}
else {
x = x1;
y = y1;
y1 = y0;
x1 = x0;
}
putPixel (x, y);
while (y < y1)
{
if (d < 0)
d += ds;
else {
if (x > x1){
x--;
d += dt;
} else {
x++;
d += dt;
}
}
y++;
putPixel (x, y);
}
}
}
void mouse(int btn, int state, int x, int y)
{
if(btn==GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
switch(first)
{

Dept. Of CSE ,BTLITM Page 19


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

case 0:
xi = x;
yi = (wh-y);
first = 1;
break;
case 1:
xf = x;
yf = (wh-y);
bresenhamAlg ( xi, yi, xf, yf);
first = 0;
break;
}
}
}
void myinit()
{
glViewport(0,0,ww,wh);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,(GLdouble)ww,0.0,(GLdouble)wh);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(ww,wh);
glutCreateWindow("Bresenham Line Algorithm");
glutDisplayFunc(display);
myinit();
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}

Dept. Of CSE ,BTLITM Page 20


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

Question 2

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

PROGRAM:
#include<GL/glut.h>
#include<stdio.h>
int x,y; int rFlag=0;
void draw_pixel(float x1,float y1)
{
glColor3f(0.0,0.0,1.0);
glPointSize(5.0);
glBegin(GL_POINTS);
glVertex2f(x1,y1);
glEnd();
}
void triangle()
{ glColor3f(1.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2f(100,100);
glVertex2f(250,400);
glVertex2f(400,100);
glEnd(); }
float th=0.0;
float trX=0.0,trY=0.0;
void display()
{ glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
if(rFlag==1) //Rotate Around origin
{ trX=0.0; trY=0.0; th+=0.1; draw_pixel(0.0,0.0); }
if(rFlag==2) //Rotate Around Fixed Point
{ trX=x; trY=y; th+=0.1; draw_pixel(x,y);
} glTranslatef(trX,trY,0.0);
glRotatef(th,0.0,0.0,1.0);

Dept. Of CSE ,BTLITM Page 21


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

glTranslatef(-trX,-trY,0.0);
triangle();
glutPostRedisplay();
glutSwapBuffers();
}
void myInit()
{ glClearColor(0.0,0.0,0.0,1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-500.0, 500.0, -500.0, 500.0);
glMatrixMode(GL_MODELVIEW);
}
void rotateMenu (int option)
{ if(option==1)
rFlag=1; if(option==2)
rFlag=2; if(option==3)
rFlag=3;
}
void main(int argc, char **argv)
{
printf( "Enter Fixed Points (x,y) for Roration: \n");
scanf("%d %d", &x, &y);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(0, 0);
glutCreateWindow("Create and Rotate Triangle");
myInit();
glutDisplayFunc(display);
glutCreateMenu(rotateMenu);
glutAddMenuEntry("Rotate around ORIGIN",1);
glutAddMenuEntry("Rotate around FIXED POINT",2);
glutAddMenuEntry("Stop Rotation",3);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutMainLoop();
}

Dept. Of CSE ,BTLITM Page 22


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

Sample Output:

Dept. Of CSE ,BTLITM Page 23


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

PROGRAM 3
Question 3.

Program to draw a color cube and spin it using OpenGL transformation matrices.

The cube is drawn based on the diagram below:

Y – Axis

(-1, 1,-1) 3 2 (1, 1,-1)


7 (-1,1,1)
6 (1, 1, 1)

(-1,-1,-1) 0 1 (1,-1,-1)
5 (1,-1, 1)
(-1,-1, 1) 4

X – Axis

Z – Axis
The cube is rotated around the x-axis, y-axis, and z-axis when the left button, middle button, or right
button is clicked on the mouse respectively. The cube is rotated by an angle of 0.05º around the selected

Dept. Of CSE ,BTLITM Page 24


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

axis. The angle of rotation around a given axis is stored in a static variable. Assume that the cube was
rotated by 30º around x – axis first. If it is then starts rotating about y – axis, then it will remain at 30º
with respect to x – axis. The angle of rotation about y – axis is incremented.

The faces of the cube are based on the right hand thumb rule. The rule states that if the right hand
thumb points outwards, the direction in which the fingers are encircled gives the sequence for the outward
face of the cube.

Each vertex of the cube is assigned a color. A given face of the cube is colored by bilinear
interpolation of the colors of each vertex of that face of the cube.

Source Code:

/* This is a program to rotate a cube using OpenGL functions */

#include <stdlib.h>

#include <GL/glut.h>

/* Initialize vertices for a cube of length 2 centered around the origin */

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}};

GLfloat normals[][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}};

GLfloat colors[][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}};

/* Declare static variables to store the rotation angle around each axis */

Dept. Of CSE ,BTLITM Page 25


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
static GLfloat theta[] = {0.0,0.0,0.0};

static GLint axis = 2;

void polygon(int a, int b, int c , int d)

/* Draw a face of the cube */

glBegin(GL_POLYGON);

glColor3fv(colors[a]);

glNormal3fv(normals[a]);

glVertex3fv(vertices[a]);

glColor3fv(colors[b]);

glNormal3fv(normals[b]);

glVertex3fv(vertices[b]);

glColor3fv(colors[c]);

glNormal3fv(normals[c]);

glVertex3fv(vertices[c]);

glColor3fv(colors[d]);

glNormal3fv(normals[d]);

glVertex3fv(vertices[d]);

glEnd();

void colorcube(void)

/* Define the faces of the cube using right-hand thumb rule */

polygon(0,3,2,1);

polygon(2,3,7,6);

Dept. Of CSE ,BTLITM Page 26


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
polygon(0,4,7,3);

polygon(1,2,6,5);

polygon(4,5,6,7);

polygon(0,1,5,4);

void display(void)

/* Clear color buffer and depth buffer */

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

/* Load rotation matrix */

glLoadIdentity();

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);

/* Draw cube */

colorcube();

/* Clear buffers */

glFlush();

/* Swap buffers */

glutSwapBuffers();

Dept. Of CSE ,BTLITM Page 27


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
/* Define idle callback function */

void spinCube()

/* Rotate the cube around the choosen axis by 0.05 degrees*/

theta[axis] += 0.05;

/* If the rotation angle has reached 360 degrees, then restart from 0 degrees */

if( theta[axis] > 360.0 ) theta[axis] -= 360.0;

/* Redisplay the cube after the rotation */

glutPostRedisplay();

/* Define mouse callback function */

void mouse(int btn, int state, int x, int y)

/* Select the axis based on the clicked mouse button */

/* Choose x - axis */

if(btn==GLUT_LEFT_BUTTON && state == GLUT_DOWN) axis = 0;

/* Choose y - axis */

if(btn==GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) axis = 1;

/* Choose z - axis */

if(btn==GLUT_RIGHT_BUTTON && state == GLUT_DOWN) axis = 2;

Dept. Of CSE ,BTLITM Page 28


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
/* Define reshape callback function */

void myReshape(int w, int h)

/* Define new viewport */

glViewport(0, 0, w, h);

/* Set matrix to projection matrix */

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);

/* Set matrix to modelview matrix */

glMatrixMode(GL_MODELVIEW);

void main(int argc, char **argv)

/* Standard GLUT intialization */

glutInit(&argc, argv);

Dept. Of CSE ,BTLITM Page 29


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
/* Set double buffer, RGB color mode, and enable depth buffer */

glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);

/* Set intial window size to 500 by 500 pixels */

glutInitWindowSize(500,500);

/* Create display window */

glutCreateWindow("Rotating a Color Cube");

/* Register reshape callback function */

glutReshapeFunc(myReshape);

/* Register display callback function */

glutDisplayFunc(display);

/* Register idle callback function */

glutIdleFunc(spinCube);

/* Register mouse callback function */

glutMouseFunc(mouse);

/* Enable depth test */

glEnable(GL_DEPTH_TEST);

/* Enter event processing loop */

glutMainLoop();

Dept. Of CSE ,BTLITM Page 30


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

Output:

Exercise:
1. Which algorithm is used for depth test?
2. What happens if the matrix mode is not set to modelview?
3. What happens if the faces of the polygon are not defined properly?
4. How is the depth buffer clearly? What happens if depth buffer is not cleared?

PROGRAM 4

Dept. Of CSE ,BTLITM Page 31


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

Question 4.

Program to draw a color cube and allow the user to move the camera suitably to experiment
with perspective viewing. Use OpenGL functions.

The color cube drawn in this program uses the same fundamental as in program 3. Here, the cube
is moved only when the user clicks the mouse button or presses specified keys on the keyboard. Left
button, rmiddle button, and right button move the cube about x-axis, y-axis, and z-axis respectively. The
movement of the cube along each of these axes is stored in three different static variables.

Additionally, viewer can be moved about by pressing the keys on the keyboard. ‘x’ and ‘X’ move
the viewer in negative direction and positive direction along the x-axis respectively. ‘y’ and ‘Y’ move the
viewer in negative direction and positive direction along the y-axis. ‘z’ and ‘Z’ move the viewer in
negative and positive direction along the z-axis.

Source Code:

/* This is a program to view a color cube in perspective view */

#include <GL/glut.h>

/* Initialize vertices for a cube of length 2 centered around the origin */

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}};

GLfloat normals[][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}};

GLfloat colors[][3] = {{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0},{1.0,1.0,-1.0},

Dept. Of CSE ,BTLITM Page 32


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
{-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}};

/* Define static variables for angles of roatation, axis, and the viewer position */

static GLfloat theta[] = {0.0,0.0,0.0};

static GLint axis = 2;

static GLdouble viewer[]= {0.0, 0.0, 5.0};

/* Draw a face of the color cube */

void polygon(int a, int b, int c , int d)

glBegin(GL_POLYGON);

glColor3fv(colors[a]);

glNormal3fv(normals[a]);

glVertex3fv(vertices[a]);

glColor3fv(colors[b]);

glNormal3fv(normals[b]);

glVertex3fv(vertices[b]);

glColor3fv(colors[c]);

glNormal3fv(normals[c]);

glVertex3fv(vertices[c]);

glColor3fv(colors[d]);

glNormal3fv(normals[d]);

glVertex3fv(vertices[d]);

glEnd();

Dept. Of CSE ,BTLITM Page 33


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
/* Draw color cube by drawing the different faces */

void colorcube()

polygon(0,3,2,1);

polygon(2,3,7,6);

polygon(0,4,7,3);

polygon(1,2,6,5);

polygon(4,5,6,7);

polygon(0,1,5,4);

/* initial viewer location */

void display(void)

/* Clear color buffer and depth buffer */

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

/* Set the viewer position */

glLoadIdentity();

gluLookAt(viewer[0],viewer[1],viewer[2], 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);

/* Load rotation matrix */

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);

Dept. Of CSE ,BTLITM Page 34


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

/* Draw cube */

colorcube();

/* Clear buffers */

glFlush();

/* Swap buffers */

glutSwapBuffers();

/* Define mouse callback function */

void mouse(int btn, int state, int x, int y)

/* Select the axis based on the clicked mouse button */

/* Choose x - axis */

if(btn==GLUT_LEFT_BUTTON && state == GLUT_DOWN) axis = 0;

/* Choose y - axis */

if(btn==GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) axis = 1;

/* Choose z - axis */

if(btn==GLUT_RIGHT_BUTTON && state == GLUT_DOWN) axis = 2;

/* Rotate the cube around the choosen axis by 2 degrees */

theta[axis] += 2.0;

Dept. Of CSE ,BTLITM Page 35


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
/* If the rotation angle has reached 360 degrees, then restart from 0 degree */

if( theta[axis] > 360.0 ) theta[axis] -= 360.0;

/* Redisplay the cube after the rotation */

glutPostRedisplay();

/* Define keyboard callback function */

void keys(unsigned char key, int x, int y)

/* Move the viewer position */

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;

if(key == 'Z') viewer[2]+= 1.0;

/* Redisplay the cube after the rotation */

glutPostRedisplay();

void myReshape(int w, int h)

/* Redefine viewport based on new window size */

glViewport(0, 0, w, h);

Dept. Of CSE ,BTLITM Page 36


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
/* Set metrix to projection mode */

glMatrixMode(GL_PROJECTION);

glLoadIdentity();

/* Use function to create perspective view */

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);

/* Set matrix to modelview matrix */

glMatrixMode(GL_MODELVIEW);

void main(int argc, char **argv)

/* Standard GLUT intialization */

glutInit(&argc, argv);

/* Set double buffer, RGB color mode, and enable depth buffer */

glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);

/* Set intial window size to 500 by 500 pixels */

glutInitWindowSize(500, 500);

/* Create display window */

glutCreateWindow("Perspective colorcube viewer");

Dept. Of CSE ,BTLITM Page 37


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

/* Register reshape callback function */

glutReshapeFunc(myReshape);

/* Register display callback function */

glutDisplayFunc(display);

/* Register mouse callback function */

glutMouseFunc(mouse);

/* Register keyboard callback function */

glutKeyboardFunc(keys);

/* Enable depth test */

glEnable(GL_DEPTH_TEST);

/* Enter event processing loop */

glutMainLoop();}

Output:

Dept. Of CSE ,BTLITM Page 38


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

Dept. Of CSE ,BTLITM Page 39


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

PROGRAM 5

Question 5.

Program to implement Cohen-Sutherland line-clipping algorithm

Source Code:

/* Program to clip a line using cohen sutherland line clipping algorithm */

#include <stdio.h>

#include <GL/glut.h>

#define outcode int

/* Initialize clipping window */

double xmin=50,ymin=50, xmax=100,ymax=100;

/* Initialize viewport window */

double xvmin=200,yvmin=200,xvmax=300,yvmax=300;

double x0,y0,x1,y1;

/* Bit codes for right, left, top, & bottom boundaries of clipping window */

const int RIGHT = 8;

Dept. Of CSE ,BTLITM Page 40


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
const int LEFT = 2;

const int TOP = 4;

const int BOTTOM = 1;

/* Function to calculate outcode of a given point */

outcode ComputeOutCode (double x, double y);

/* Function to implement Cohen Sutherland line clipping algorithm and to draw the clipped line */

void CohenSutherlandLineClipAndDraw (double x0, double y0,double x1, double y1)

outcode outcode0, outcode1, outcodeOut;

bool accept = false, done = false;

/* Find outcodes for the two endpoints of a given line */

outcode0 = ComputeOutCode (x0, y0);

outcode1 = ComputeOutCode (x1, y1);

do{

/* Trivially accept the line if the bitwise OR is zero */

if (!(outcode0 | outcode1))

accept = true;

done = true;

/* Trivially reject the line if the bitwise AND is zero */

else if (outcode0 & outcode1)

done = true;

Dept. Of CSE ,BTLITM Page 41


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
else

/* If the line is not trivially accepted or trivially rejected, then it intersects the clippping
window on some boundary. The following procedure finds the clipped window */

double x, y;

/* Choose the outcode for the point that lies outside the boundary */

outcodeOut = outcode0? outcode0: outcode1;

/* Check if the line intersects with the top boundary */

if (outcodeOut & TOP)

/* Find the clipped coordinates */

x = x0 + (x1 - x0) * (ymax - y0)/(y1 - y0);

y = ymax;

/* Check if the line intersects with the bottom boundary */

else if (outcodeOut & BOTTOM)

/* Find the clipped coordinates */

x = x0 + (x1 - x0) * (ymin - y0)/(y1 - y0);

y = ymin;

/* Check if the line intersects with the right boundary */

else if (outcodeOut & RIGHT)

/* Find the clipped coordinates */

Dept. Of CSE ,BTLITM Page 42


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
y = y0 + (y1 - y0) * (xmax - x0)/(x1 - x0);

x = xmax;

else

/* Check if the line intersects with the left boundary */

/* Find the clipped coordinates */

y = y0 + (y1 - y0) * (xmin - x0)/(x1 - x0);

x = xmin;

/* Claculate the new outcode for the clipped coordinate */

if (outcodeOut == outcode0)

x0 = x;

y0 = y;

outcode0 = ComputeOutCode (x0, y0);

else

x1 = x;

y1 = y;

outcode1 = ComputeOutCode (x1, y1);

}while (!done);

Dept. Of CSE ,BTLITM Page 43


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
if (accept)

/* Map the window to the viewport */

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;

/* Draw the viewport */

glColor3f(0.0,0.0,0.0);

glBegin(GL_LINE_LOOP);

glVertex2f(xvmin,yvmin);

glVertex2f(xvmax,yvmin);

glVertex2f(xvmax,yvmax);

glVertex2f(xvmin,yvmax);

glEnd();

/* Draw the original line in blue color */

glColor3f(0.0,0.0,1.0);

glBegin(GL_LINES);

glVertex2d (vx0, vy0);

glVertex2d (vx1, vy1);

glEnd();

Dept. Of CSE ,BTLITM Page 44


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

outcode ComputeOutCode (double x, double y)

outcode code = 0;

/* Set TOP bit if point is above top boundary of the clipping window */

if (y > ymax)

code |= TOP;

/* Set BOTTOM bit if point is below bottom boundary of the clipping window */

else if (y < ymin)

code |= BOTTOM;

/* Set RIGHT bit if point lies beyond right boundary of the clipping window */

if (x > xmax)

code |= RIGHT;

/* Set LEFT bit if point lies before left boundary of the clipping window */

else if (x < xmin)

code |= LEFT;

return code;

void display()

/* Clear display window */

glClear(GL_COLOR_BUFFER_BIT);

/* Draw clipped line in red color */

glColor3f(1.0,0.0,0.0);

glBegin(GL_LINES);

Dept. Of CSE ,BTLITM Page 45


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
glVertex2d (x0, y0);

glVertex2d (x1, y1);

glEnd();

/* Draw clipping window in black color */

glColor3f(0.0, 0.0, 1.0);

glBegin(GL_LINE_LOOP);

glVertex2f(xmin, ymin);

glVertex2f(xmax, ymin);

glVertex2f(xmax, ymax);

glVertex2f(xmin, ymax);

glEnd();

/* Clip line using cohen sutherland line clipping algorithm */

CohenSutherlandLineClipAndDraw(x0,y0,x1,y1);

/* Clear buffers */

glFlush();

void myinit()

/* Set background color to white */

glClearColor(1.0,1.0,1.0,1.0);

/* Set matrix mode to projection matrix */

glMatrixMode(GL_PROJECTION);

Dept. Of CSE ,BTLITM Page 46


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
glLoadIdentity();

/* Set view port to 499 by 499 pixels */

gluOrtho2D(0.0,499.0,0.0,499.0);

void main(int argc, char** argv)

/* Read point (x0, y0) */

printf("Enter point (x0, y0): ");

scanf("%lf %lf", &x0,&y0);

/* Read point (x1, y1) */

printf ("Enter point (x1, y1): ");

scanf("%lf %lf", &x1, &y1);

/* Standard GLUT intialization */

glutInit(&argc,argv);

/* Set single buffer and RGB color mode */

glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);

/* Set intial window size to 500 by 500 pixels */

glutInitWindowSize(500,500);

/* Create a display window */

Dept. Of CSE ,BTLITM Page 47


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
glutCreateWindow("Cohen Suderland Line Clipping Algorithm");

/* Register display callback function */

glutDisplayFunc(display);

myinit();

/* Enter event processing loop */

glutMainLoop();

Output:
Enter point (x0, y0): 10 40

Enter point (x1, y1): 150 100

Dept. Of CSE ,BTLITM Page 48


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

PROGRAM 6

Question 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.

This program uses the built in functions to create teapot and cubes. Cube is scaled and translated to form
wall, table top, and table legs. Light 0 is enabled.

Dept. Of CSE ,BTLITM Page 49


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

Source Code:
/* A program to draw a simple shaded scene consisting of a teapot on a table in a room */

#include <GL/glut.h>

/* Draw wall in xz plane */

void wall (double thickness)

glPushMatrix();

glTranslated (0.5, 0.5 * thickness, 0.5);

glScaled (1.0, thickness, 1.0);

glutSolidCube (1.0);

glPopMatrix();

/* Draw table leg */

void tableLeg (double thick, double len)

glPushMatrix();

glTranslated (0, len/2, 0);

glScaled (thick, len, thick);

glutSolidCube (1.0);

glPopMatrix();

void table (double topWid, double topThick, double legThick, double legLen)

Dept. Of CSE ,BTLITM Page 50


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
/* Draw table top */

glPushMatrix();

glTranslated (0, legLen, 0);

glScaled(topWid, topThick, topWid);

glutSolidCube (1.0);

glPopMatrix();

/* Draw table leg */

double dist = 0.95 * topWid/2.0 - legThick/2.0;

glPushMatrix();

glTranslated (dist, 0, dist);

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();

void displaySolid (void)

/* Set properties of the surface material */

Dept. Of CSE ,BTLITM Page 51


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
GLfloat mat_ambient[] = {0.7f,0.7f,0.7f,1.0f};

GLfloat mat_diffuse[] = {.5f,.5f,.5f,1.0f};

GLfloat mat_specular[] = {1.0f,1.0f,1.0f,1.0f};

GLfloat mat_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 ligth properties */

GLfloat lightIntensity[] = {0.7f,0.7f,0.7f,1.0f};

GLfloat light_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 position */

glMatrixMode(GL_PROJECTION);

glLoadIdentity();

double winHt = 1.0;

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);

/* Clear color buffer and depth buffer */

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

Dept. Of CSE ,BTLITM Page 52


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
/* Draw teapot */

glPushMatrix();

glTranslated (0.5,0.40,0.5);

glRotated (50,0,1,0);

glutSolidTeapot(0.08);

glPopMatrix();

/* Draw table */

glPushMatrix();

glTranslated(0.4,0,0.4);

table (0.6,0.02,0.02,0.3);

glPopMatrix();

/* Draw floor */

wall(0.02);

/* Draw side wall */

glPushMatrix();

glRotated(90.0,0.0,0.0,1.0);

wall(0.02);

glPopMatrix();

/* Draw opposite side wall */

glPushMatrix();

Dept. Of CSE ,BTLITM Page 53


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
glRotated(-90.0, 1.0, 0.0, 0.0);

wall(0.02);

glPopMatrix();

/* Clear buffers */

glFlush();

void main (int argc, char ** argv)

/* Standard GLUT intialization */

glutInit(&argc,argv);

/* Set single buffer, RGB color mode, and enable depth buffer */

glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);

/* Set intial window size to 640 by 480 pixels */

glutInitWindowSize(640,480);

/* Create a display window */

glutCreateWindow("simple shaded scene consisting of a tea pot on a table");

/* Register display callback */

glutDisplayFunc(displaySolid);

/* Enable lighting */

glEnable(GL_LIGHTING);

Dept. Of CSE ,BTLITM Page 54


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

/* Enable light 0 */

glEnable(GL_LIGHT0);

glShadeModel(GL_SMOOTH);

/* Enable depth test */

glEnable(GL_DEPTH_TEST);

/* Makes all normals unit length to prevent undesirable lighting problems */

glEnable(GL_NORMALIZE);

/* Enter event processing loop */

glutMainLoop();

Output:

Dept. Of CSE ,BTLITM Page 55


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

Exercise:

1. What happens if other light sources are enabled and light 0 is disabled?
2. Rotate the teapot by 180º.
3. Rotate the table by 90º.
4. Add a stool to the scene

Dept. Of CSE ,BTLITM Page 56


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

PROGRAM 7

Question 7.

Program to recursively subdivide a tetrahedron to form 3D Sierpinski gasket. The number


of recursive steps must be specified by the user.

Tetrahedron is composed of four triangular faces. Three faces meet at each vertex. A tetrahedron
is recursively subdivided to form a three dimensional Sierpinski gasket.

The below diagram shows the way the vertices are named in the program.

mid3 mid0
mid4

a
mid1
mid2

c d
mid5

Figure 1 Tetrahedron

The steps in forming a 3D Sierpinski gasket are as below:

1. Read the number of subdivisions, n

Dept. Of CSE ,BTLITM Page 57


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

2. If n > 0,
a. Find the midpoint for each edge of the tetrahedron
b. Call ‘divide_tetra’ function to define new tetrahedra. The vertices used for the same
are as below
i. Tetrahedron 1 – a, mid0, mid1, mid2
ii. Tetrahedron 2 – mid0, b, mid3, mid4
iii. Tetrahedron 3 – mid1, mid3, c, mid5
iv. Tetrahedron 4 – mid2, mid4, mid5, d
3. Else if n = 0,
a. Draw the tetrahedrons
b. Exit when all tetrahedra are drawn
4. Reduce the number of subdivisions by 1
5. Repeat step 2

Each tetrahedron is divided into five smaller tetrahedra. One tetrahedron at each vertex and
another tetrahedron formed by connecting the midpoints. The tetrahedron formed by midpoints is ignored.
For additional levels of recursion, the tetrahedra formed at the vertices are considered as separate
tetrahedron and the same procedure is repeated for each additional level.

Source Code:
/* This is a program to recursively subdivide a tetrahedron to form a 3D Sierpinski Gasket. The number of recursive
steps is specified by the user */

#include <stdio.h>

#include <GL/glut.h>

/* Initial tetrahedron */

GLfloat vertices[4][3] = {{0.0,0.0,1.0,},{0.0,0.94,-0.33},

{-0.82,-0.47,-0.33},{0.82,-0.47,-0.33}};

/* Initialize colors for each face of tetrahedron */

GLfloat colors[4][3] = {{1.0,0.0,0.0},{0.0,1.0,0.0},

{0.0,0.0,1.0},{0.0,0.0,0.0}};

Dept. Of CSE ,BTLITM Page 58


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

/* n - Number of recursive steps */

int n;

/* Function to draw triangle */

void triangle(GLfloat *va,GLfloat *vb,GLfloat *vc)

glVertex3fv(va);

glVertex3fv(vb);

glVertex3fv(vc);

/* Function to draw tetrahedron */

void tetra(GLfloat *a,GLfloat *b,GLfloat *c,GLfloat *d)

glColor3fv(colors[0]);

triangle(a,b,c);

glColor3fv(colors[1]);

triangle(a,c,d);

glColor3fv(colors[2]);

triangle(a,d,b);

glColor3fv(colors[3]);

triangle(b,d,c);

/* Function to subdivide tetrahedron recursively */

void divide_tetra(GLfloat *a,GLfloat *b,GLfloat *c,GLfloat *d,int m)

Dept. Of CSE ,BTLITM Page 59


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
{

GLfloat mid[6][3];

int j;

if (m > 0)

for (j = 0;j < 3;j++) mid[0][j] = (a[j] + b[j]) / 2;

for (j = 0;j < 3;j++) mid[1][j] = (a[j] + c[j]) / 2;

for (j = 0;j < 3;j++) mid[2][j] = (a[j] + d[j]) / 2;

for (j = 0;j < 3;j++) mid[3][j] = (b[j] + c[j]) / 2;

for (j = 0;j < 3;j++) mid[4][j] = (b[j] + d[j]) / 2;

for (j = 0;j < 3;j++) mid[5][j] = (c[j] + d[j]) / 2;

/* Create four tetrahedrons by subdivision */

divide_tetra(a,mid[0],mid[1],mid[2],m-1);

divide_tetra(mid[0],b,mid[3],mid[4],m-1);

divide_tetra(mid[1],mid[3],c,mid[5],m-1);

divide_tetra(mid[2],mid[4],mid[5],d,m-1);

else

tetra(a,b,c,d);

void display(void)

/* Clear display window and depth buffer */

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

Dept. Of CSE ,BTLITM Page 60


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

/* Draw subdivided tetrahedron */

glBegin(GL_TRIANGLES);

divide_tetra(vertices[0],vertices[1],vertices[2],vertices[3],n);

glEnd();

/* Clear buffers */

glFlush();

void myReshape(int w,int h)

/* Define new view port on reshaping */

glViewport(0,0,w,h);

/* Set matrix to projection mode */

glMatrixMode(GL_PROJECTION);

glLoadIdentity();

/* Set orthoginal view with a clipping window whose size is based

on the width and height of viewport */

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)h / (GLfloat)w,

2.0 * (GLfloat)h / (GLfloat)w,

Dept. Of CSE ,BTLITM Page 61


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
-2.0,2.0,-10.0,10.0);

glMatrixMode(GL_MODELVIEW);

glutPostRedisplay();

void main(int argc, char** argv)

//n = 3;

printf("Enter number of recursive steps to divide tetrahedron: ");

scanf("%d",&n);

/* Standard GLUT intialization */

glutInit(&argc,argv);

/* Set single buffer, RGB color mode, and enable depth buffer */

glutInitDisplayMode (GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);

/* Set intial window size to 500 by 500 pixels */

glutInitWindowSize(500,500);

/* Create a display window names 'Polygons' */

glutCreateWindow("3D Sierpinski Gasket");

/* Register reshape function */

glutReshapeFunc(myReshape);

Dept. Of CSE ,BTLITM Page 62


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
/* Register display callback */

glutDisplayFunc(display);

/* Enable depth test */

glEnable(GL_DEPTH_TEST);

/* Set background color to white */

glClearColor(1.0,1.0,1.0,1.0);

/* Enter event processing loop */

glutMainLoop();

Output:
Enter number of recursive steps to divide tetrahedron: 2

Dept. Of CSE ,BTLITM Page 63


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

Exercise:
1. What happens if depth buffer is not initialized or if depth test is not enabled?
2. What is the purpose of myReshape function?
3. glOrtho function is defined in myReshape function. What is the default viewport size?
4. What happens if macros in glutInitDisplayMode are entered wrong?
PROGRAM 8
Question 8.

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

#include<GL/glut.h>
#include<stdio.h>
#include<math.h>
#define PI 3.1416
GLsizei winWidth = 600, winHeight = 600;
GLfloat xwcMin = 0.0, xwcMax = 130.0;
GLfloat ywcMin = 0.0, ywcMax = 130.0;
typedef struct wcPt3D
{
GLfloat x, y, z;

Dept. Of CSE ,BTLITM Page 64


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

};
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(GLfloat u, wcPt3D *bezPt, GLint nCtrlPts, wcPt3D *ctrlPts, GLint
*C)
{
GLint k, n=nCtrlPts-1;
GLfloat bezBlendFcn;
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(wcPt3D *ctrlPts, GLint nCtrlPts, GLint nBezCurvePts)
{
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;

Dept. Of CSE ,BTLITM Page 65


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

}
void displayFcn()
{
GLint nCtrlPts = 4, nBezCurvePts =20;
static float theta = 0;
wcPt3D ctrlPts[4] = {
{20, 100, 0},
{30, 110, 0},
{50, 90, 0},
{60, 100, 0}};
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);
glPushMatrix();
glLineWidth(5);
glColor3f(255/255, 153/255.0, 51/255.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(19/255.0, 136/255.0, 8/255.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);

Dept. Of CSE ,BTLITM Page 66


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

glBegin(GL_LINES);
glVertex2f(20,100);
glVertex2f(20,40);
glEnd();
glFlush();
glutPostRedisplay();
glutSwapBuffers();
}
void winReshapeFun(GLint newWidth, GLint newHeight)
{
glViewport(0, 0, newWidth, newHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(xwcMin, xwcMax, ywcMin, ywcMax);
glClear(GL_COLOR_BUFFER_BIT);
}
void main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition(50, 50);
glutInitWindowSize(winWidth, winHeight);
glutCreateWindow("Bezier Curve");
glutDisplayFunc(displayFcn);
glutReshapeFunc(winReshapeFun);
glutMainLoop();
}

PROGRAM 9
Question 9.

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

This program can be used to fill convex polygons of upto ten sides. Each line in the display window
is scanned to check if any of the edges intersect that line. If the edges do intersect that line, the points
between the first edge and the second edge that intersect are colored.

Source Code:

Dept. Of CSE ,BTLITM Page 67


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

/* Program to fill a polygon using scanline algorithm polygon filling algorithm */

#include <stdio.h>

#include <GL/glut.h>

float x[10],y[10];

int n;

/* Function to detect the edges of the given polygon */

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

float mx,x,temp;

int i;

/* Swap coordinates if y2 < y1 */

if((y2-y1)<0)

temp=y1; y1=y2; y2=temp;

temp=x1; x1=x2; x2=temp;

/* Find slope m if y2 <> y1, else mx = dx */

if((y2-y1)!=0)

mx=(x2-x1)/(y2-y1);

else

mx=x2-x1;

Dept. Of CSE ,BTLITM Page 68


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
x=x1;

/* Store x-coordinate of all the points on the given edge in le or re array */

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;

/* Draw the given pixel */

void draw_pixel(int x,int y)

glBegin(GL_POINTS);

glVertex2i(x,y);

glEnd();

/* Function to scan fill a given polygon */

void scanfill(float x[], float y[], int n)

int le[500],re[500];

GLint i,j;

Dept. Of CSE ,BTLITM Page 69


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
for(i=0;i<500;i++)

/* Initialize the left edge of view port to 500 */

le[i]=500;

/* Initialize the right edge of view port to 0 */

re[i]=0;

/* Call function to detect the points on each edge */

glBegin(GL_LINE_LOOP);

for (i = 0;i < n;i++)

edgedetect(x[i],y[i],x[(i+1)%n],y[(i+1)%n],le,re);

glEnd();

/* For every line, color pixels that lie between left and right edge */

glColor3f(1.0,0.0,1.0);

for(j=0;j<500;j++)

if(le[j]<=re[j])

for(i=(int)le[j];i<=(int)re[j];i++)

draw_pixel(i,j);

glFlush();

Dept. Of CSE ,BTLITM Page 70


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
void display()

/* Clear display window */

glClear(GL_COLOR_BUFFER_BIT);

/* Set foreground to blue */

glColor3f(0.0,0.0,1.0);

/* Draw the given polygon */

glBegin(GL_LINE_LOOP);

for (GLint i = 0;i < n;i++)

glVertex2f(x[i],y[i]);

glEnd();

/* Call function to fill polygon using scan line algorithm */

scanfill(x,y,n);

/* Clear buffers */

glFlush();

void myinit()

/* Set background color to white */

glClearColor(1.0,1.0,1.0,1.0);

/* Set matrix mode to projection matrix */

glMatrixMode(GL_PROJECTION);

Dept. Of CSE ,BTLITM Page 71


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
glLoadIdentity();

/* Set view port to 499 by 499 pixels */

gluOrtho2D(0.0,499.0,0.0,499.0);

void main(int argc, char** argv)

/* Read the number of sides for polygon */

printf("Enter number of vertices(n<=10) for polygon: ");

scanf("%d",&n);

if (n > 10) n = 10;

/* Read coordinates for each vertex */

for (GLint i = 0;i < n;i++)

printf("Enter coordinates for vertex %d: ", i);

scanf("%f %f",&x[i],&y[i]);

/* Standard GLUT intialization */

glutInit(&argc,argv);

/* Set single buffer and RGB color mode */

glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);

Dept. Of CSE ,BTLITM Page 72


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT
/* Set intial window size to 500 by 500 pixels */

glutInitWindowSize(500,500);

/* Create a display window */

glutCreateWindow("Polygon fill using Scan-line Algorithm");

/* Register display callback */

glutDisplayFunc(display);

/* Set the programs attributes */

myinit();

/* Enter event processing loop */

glutMainLoop();

Output:
Enter number of vertices(n<=10) for polygon: 5

Enter coordinates for vertex 0: 100 100

Enter coordinates for vertex 1: 300 100

Enter coordinates for vertex 2: 350 250

Enter coordinates for vertex 3: 200 400

Enter coordinates for vertex 4: 50 250

Dept. Of CSE ,BTLITM Page 73


15CSL68 COMPUTER GRAPHICS AND VISUALIZATION
LABOROTORY WITH MINI PROJECT

Exercise:

1. Change the program to stop animating scan line filling.


2. Explain how the edgedetect function works by tracing an example.
3. Change the program to use double buffer for smoother display.
4. Instead of a solid fill color, change the program to use interpolated color as fill color

Dept. Of CSE ,BTLITM Page 74

You might also like