Top Banner
COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67) REVA INSTITUTE OF TECHNOLOGY AND MANAGEMENT DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING VI SEMESTER B.E. COMPUTER GRAPHICS AND VISUALIZATION LABORATORY Subject Code: 06CSL67 LABORATORY MANUAL Prepared By: Prepared By: Mr. Ashwin Kumar U M Mr. Ashwin Kumar U M Dept. of CSE, REVA ITM 1
52
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

REVA INSTITUTE OF TECHNOLOGY AND MANAGEMENT

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

VI SEMESTER B.E.

COMPUTER GRAPHICS AND VISUALIZATION LABORATORY

Subject Code: 06CSL67

LABORATORY MANUAL

Prepared By:Prepared By:

Mr. Ashwin Kumar U MMr. Ashwin Kumar U M Mrs. Nirmala S GupthaMrs. Nirmala S Guptha

Mrs. Shantala PatilMrs. Shantala PatilMiss. Shobha BiradarMiss. Shobha Biradar

Dept. of CSE, REVA ITM 1

Page 2: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

IntroductionComputer graphics

Computer graphics is a sub-field of computer science which studies methods for digitally synthesizing and manipulating visual content. Although the term often refers to the study of three-dimensional computer graphics, it also encompasses two-dimensional graphics and image processing.

Computer graphics studies the manipulation of visual and geometric information using computational techniques. It focuses on the mathematical and computational foundations of image generation and processing rather than purely aesthetic issues. Computer graphics is often differentiated from the field of visualization, although the two fields have many similarities.

Subfields in computer graphics

A broad classification of major subfields in computer graphics might be:

1. Geometry: studies ways to represent and process surfaces2. Animation: studies with ways to represent and manipulate motion3. Rendering: studies algorithms to reproduce light transport

Imaging: studies image acquisition or image editing

Applications of computer graphics include:

Special effects Visual effects Video games Digital art

Connected studies include:

Scientific visualization Information visualization Computer vision Image processing Computational Geometry Computational Topology Applied mathematics

OpenGLOpenGL (Open Graphics Library) is a standard specification defining a cross-language

cross-platform API for writing applications that produce 2D and 3D computer graphics. The interface consists of over 250 different function calls which can be used to draw complex three-dimensional scenes from simple primitives. OpenGL was developed by Silicon Graphics Inc. (SGI) in 1992 and is widely used in CAD, virtual reality, scientific visualization, information visualization, and flight simulation. It is also used in video games, where it competes with Direct3D on Microsoft Windows platforms (see Direct3D vs. OpenGL). OpenGL is managed by the non-profit technology consortium, the Khronos Group, Inc.

Dept. of CSE, REVA ITM 2

Page 3: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

OpenGL serves two main purposes: To hide the complexities of interfacing with different 3D accelerators, by presenting the

programmer with a single, uniform API. To hide the differing capabilities of hardware platforms, by requiring that all

implementations support the full OpenGL feature set (using software emulation if necessary).

OpenGL's basic operation is to accept primitives such as points, lines and polygons, and convert them into pixels. This is done by a graphics pipeline known as the OpenGL state machine. Most OpenGL commands either issue primitives to the graphics pipeline, or configure how the pipeline processes these primitives. Prior to the introduction of OpenGL 2.0, each stage of the pipeline performed a fixed function and was configurable only within tight limits. OpenGL 2.0 offers several stages that are fully programmable using GLSL.

OpenGL is a low-level, procedural API, requiring the programmer to dictate the exact steps required to render a scene. This contrasts with descriptive (scene graph or retained mode) APIs, where a programmer only needs to describe a scene and can let the library manage the details of rendering it. OpenGL's low-level design requires programmers to have a good knowledge of the graphics pipeline, but also gives a certain amount of freedom to implement novel rendering algorithms.

OpenGL has historically been influential on the development of 3D accelerators, promoting a base level of functionality that is now common in consumer-level hardware:

Rasterized points, lines and polygons as basic primitives A transform and lighting pipeline Z-buffering Texture mapping Alpha blending

Dept. of CSE, REVA ITM 3

Block Diagram of Open GL

Page 4: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

A brief description of the process in the graphics pipeline could be: Evaluation, if necessary, of the polynomial functions which define certain inputs, like NURBS surfaces, approximating curves and the surface geometry. Vertex operations, transforming and lighting them depends on their material, also clipping the non visible parts of the scene in order to produce the viewing volume. Rasterization is conversion of the previous information into pixels. The polygons are represented by the appropriate colors by means of interpolation algorithms. Per-fragment operations like updating values depending on incoming and previously stored depth values, or color combinations, among others. At last, fragments are inserted into the Frame buffer.

Many modern 3D accelerators provide functionality far above this baseline, but these new features are generally enhancements of this basic pipeline rather than radical reinventions of it.

RUNNING OpenGL on VISUAL STUDIO 2005

GLUT Installation (only needs to be done once)   

Windows comes with OpenGL, and Visual Studio comes with the OpenGL libraries, but neither of them comes with GLUT. Get the newest version of GLUT here: GLUT 3.7.6 for Windows.

Put the following files in the following locations:

File Location

glut32.dll

Windows XP | Server 2003:

C:\WINDOWS\system\

Windows 2000: C:\WINNT\system\

glut32.lib C:\Program Files\Microsoft Visual Studio NET 2003\Vc7\PlatformSDK\Lib

glut.h C:\Program Files\Microsoft Visual Studio NET 2003\Vc7\PlatformSDK\Include\gl

Note: 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.

Dept. of CSE, REVA ITM 4

Page 5: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

Dept. of CSE, REVA ITM 5

Step 1: Create a Visual Studio 2005 Project

To create an empty console project in Visual Studio, do the following:1.Create a new project (File --->  New --->  --->Project

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.

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 selectC++ File (.cpp) in the Templates: pane. Name your file, and then

click Add.

3. Type the code into the file and save.

Step 3: Modify the project properties

1. Use Visual Studio's menu Project options (Project --> Draw Properties)

2. The Draw Property Page dialog will open. Once it appears, do the following:

a. Select the Configuration combo box, select all Configuration

b. In the left pane, select the linker subtree and then click the Input option. Add the following code to the Additional Dependencies text in the right pane. Copy and Paste:  opengl32.lib glu32.lib glut32.lib

Now Visual Studio knows where to find GLUT. Click OK button

Step 4: Compile and Run the projecta. Compile 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)

Page 6: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

1. Program to recursively subdivide a tetrahedron to from 3D Sierpinski gasket. The number of recursive steps is to be specified by the user.

/* Recursive subdivision of tetrahedron to form 3D Sierpinski gasket *///tetra_vtu.cpp

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

typedef float point[3];/* initial tetrahedron */

point v[]={{0.0, 0.0, 1.0}, {0.0, 0.942809, -0.33333}, {-0.816497, -0.471405, -0.333333}, {0.816497, -0.471405, -0.333333}};

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

int n;

void triangle( point a, point b, point c)

/* display one triangle using a line loop for wire frame, a singlenormal for constant shading, or three normals for interpolative shading */{ glBegin(GL_POLYGON); glNormal3fv(a); glVertex3fv(a); glVertex3fv(b); glVertex3fv(c); glEnd();}

void divide_triangle(point a, point b, point c, int m){

/* triangle subdivision using vertex numbersrighthand rule applied to create outward pointing faces */

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)); /* draw triangle at end of recursion */

Dept. of CSE, REVA ITM 6

Page 7: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

}void tetrahedron( int m){

/* Apply triangle subdivision to faces of tetrahedron */

glColor3f(1.0,0.0,0.0); divide_triangle(v[0], v[1], v[2], m);

glColor3f(0.0,1.0,0.0); 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,0.0,0.0); divide_triangle(v[0], v[2], v[3], m);}

void display(void){

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity();

tetrahedron(n); glFlush();}

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

void main(int argc, char **argv){ //n=atoi(argv[1]);

printf(" No. of Divisions ? ");scanf("%d",&n);

glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(500, 500);

Dept. of CSE, REVA ITM 7

Page 8: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

glutCreateWindow("3D Gasket"); glutReshapeFunc(myReshape); glutDisplayFunc(display);

glEnable(GL_DEPTH_TEST); glClearColor (1.0, 1.0, 1.0, 1.0); glutMainLoop();}

Output:

No of divisions 3

Dept. of CSE, REVA ITM 8

Page 9: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

2. Program to implement Liang-Barsky line clipping algorithm.

// Liang-Barsky Line Clipping Algorithm with Window to viewport Mapping */#include <stdio.h>#include <GL/glut.h>

double xmin=50,ymin=50, xmax=100,ymax=100; // Window boundariesdouble xvmin=200,yvmin=200,xvmax=300,yvmax=300; // Viewport boundaries

int cliptest(double p, double q, double *t1, double *t2){ double t=q/p; if(p < 0.0) // potentially enry point, update te {

if( t > *t1) *t1=t; if( t > *t2) return(false); // line portion is outside

} else if(p > 0.0) // Potentially leaving point, update tl {

if( t < *t2) *t2=t; if( t < *t1) return(false); // line portion is outside

} else

if(p == 0.0) {

if( q < 0.0) return(false); // line parallel to edge but outside }

return(true);}

void LiangBarskyLineClipAndDraw (double x0, double y0,double x1, double y1){

double dx=x1-x0, dy=y1-y0, te=0.0, tl=1.0;if(cliptest(-dx,x0-xmin,&te,&tl)) // inside test wrt left edgeif(cliptest(dx,xmax-x0,&te,&tl)) // inside test wrt right edgeif(cliptest(-dy,y0-ymin,&te,&tl)) // inside test wrt bottom edgeif(cliptest(dy,ymax-y0,&te,&tl)) // inside test wrt top edge{

if( tl < 1.0 ){

x1 = x0 + tl*dx;y1 = y0 + tl*dy;

}if( te > 0.0 ) { x0 = x0 + te*dx;

y0 = y0 + te*dy;}

// Window to viewport mappingsdouble sx=(xvmax-xvmin)/(xmax-xmin); // Scale parametersdouble sy=(yvmax-yvmin)/(ymax-ymin);

Dept. of CSE, REVA ITM 9

Page 10: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

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 a red colored viewportglColor3f(1.0, 0.0, 0.0);glBegin(GL_LINE_LOOP);

glVertex2f(xvmin, yvmin);glVertex2f(xvmax, yvmin);glVertex2f(xvmax, yvmax);glVertex2f(xvmin, yvmax);

glEnd();glColor3f(0.0,0.0,1.0); // draw blue colored clipped lineglBegin(GL_LINES);

glVertex2d (vx0, vy0);glVertex2d (vx1, vy1);

glEnd();}}// end of line clipping

void display(){double x0=60,y0=20,x1=80,y1=120;glClear(GL_COLOR_BUFFER_BIT);//draw the line with red colorglColor3f(1.0,0.0,0.0);//bres(120,20,340,250);glBegin(GL_LINES);

glVertex2d (x0, y0);glVertex2d (x1, y1);

glEnd();//draw a blue colored windowglColor3f(0.0, 0.0, 1.0);

glBegin(GL_LINE_LOOP); glVertex2f(xmin, ymin); glVertex2f(xmax, ymin); glVertex2f(xmax, ymax); glVertex2f(xmin, ymax);glEnd();LiangBarskyLineClipAndDraw(x0,y0,x1,y1);glFlush();}void myinit(){

glClearColor(1.0,1.0,1.0,1.0);glColor3f(1.0,0.0,0.0);glPointSize(1.0);glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D(0.0,499.0,0.0,499.0);

Dept. of CSE, REVA ITM 10

Page 11: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

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

//int x1, x2, y1, y2;//printf("Enter End points:");//scanf("%d%d%d%d", &x1,&x2,&y1,&y2);

glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutInitWindowSize(500,500);glutInitWindowPosition(0,0);glutCreateWindow("Liang Barsky Line Clipping Algorithm");glutDisplayFunc(display);myinit();glutMainLoop();

}

Output:

Dept. of CSE, REVA ITM 11

Page 12: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

3. Program to draw a color cube and spin it using OpenGL transformation matrices.* Rotating cube with color interpolation *//* Demonstration of use of homogeneous coordinate transformations and simple data structure for representing cube from Chapter 4 *//*Both normals and colors are assigned to the vertices *//*Cube is centered at origin so (unnormalized) normals are the same as the vertex values */#include <stdlib.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}};

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] = {{0.0,0.0,0.0},{1.0,0.0,0.0},{1.0,1.0,0.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, int b, int c , int d){/* draw a polygon via list of vertices */ 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){

/* map vertices to faces */

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

Dept. of CSE, REVA ITM 12

Page 13: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

}static GLfloat theta[] = {0.0,0.0,0.0};static GLint axis = 2;

void display(void){/* display callback, clear frame buffer and z buffer, rotate cube and draw, swap buffers */

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);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);

colorcube();

glFlush();glutSwapBuffers();

}void spinCube(){

/* Idle callback, spin cube 2 degrees about selected axis */

theta[axis] += 1.0;if( theta[axis] > 360.0 ) theta[axis] -= 360.0;/* display(); */glutPostRedisplay();

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

/* mouse callback, selects an axis about which to rotate */

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

Dept. of CSE, REVA ITM 13

Page 14: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

}voidmain(int argc, char **argv){ glutInit(&argc, argv);

/* need both double buffering and z buffer */

glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(500, 500); glutCreateWindow("Rotating a Color Cube"); glutReshapeFunc(myReshape); glutDisplayFunc(display);

glutIdleFunc(spinCube); glutMouseFunc(mouse); glEnable(GL_DEPTH_TEST); /* Enable hidden--surface--removal */

glutMainLoop();}

Output:

Dept. of CSE, REVA ITM 14

Page 15: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

4. Program to create a house like figure and rotate it about a given fixed point using OpenGL functions.

// Progam to draw a house and rotate about the pivot point#include <stdio.h>#include <math.h>#include <GL/glut.h>

GLfloat house[3][9]={{100.0,100.0,175.0,250.0,250.0,150.0,150.0,200.0,200.0}, {100.0,300.0,400.0,300.0,100.0,100.0,150.0,150.0,100.0}, {1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0}};

GLfloat rot_mat[3][3]={{0},{0},{0}};GLfloat result[3][9]={{0}, {0}, {0}};GLfloat h=100.0; // Pivot point GLfloat k=100.0;GLfloat theta;void multiply(){ // Rotation MATRIX and Object Matrix => Resultant Transformed House

int i,j,l;for(i=0;i<3;i++)

for(j=0;j<9;j++){

result[i][j]=0;for(l=0;l<3;l++)

result[i][j]=result[i][j]+rot_mat[i][l]*house[l][j];}

}void rotate(){

GLfloat m,n; // Build the rotation matrixm=-h*(cos(theta)-1)+k*(sin(theta));n=-k*(cos(theta)-1)-h*(sin(theta));rot_mat[0][0]=cos(theta);rot_mat[0][1]=-sin(theta);rot_mat[0][2]=m;rot_mat[1][0]=sin(theta);rot_mat[1][1]=cos(theta);rot_mat[1][2]=n;rot_mat[2][0]=0;rot_mat[2][1]=0;rot_mat[2][2]=1;//multiply the two matrices: Rotation Matrix * Objet Matrix(house)multiply();

}

void drawhouse(){glColor3f(0.0, 0.0, 1.0);glBegin(GL_LINE_LOOP); glVertex2f(house[0][0],house[1][0]); glVertex2f(house[0][1],house[1][1]); glVertex2f(house[0][3],house[1][3]);

Dept. of CSE, REVA ITM 15

Page 16: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

glVertex2f(house[0][4],house[1][4]); glEnd();glColor3f(1.0,0.0,0.0); glBegin(GL_LINE_LOOP); glVertex2f(house[0][5],house[1][5]); glVertex2f(house[0][6],house[1][6]); glVertex2f(house[0][7],house[1][7]); glVertex2f(house[0][8],house[1][8]); glEnd();glColor3f(0.0, 0.0, 1.0); glBegin(GL_LINE_LOOP); glVertex2f(house[0][1],house[1][1]); glVertex2f(house[0][2],house[1][2]); glVertex2f(house[0][3],house[1][3]); glEnd();}void drawrotatedhouse(){glColor3f(0.0, 0.0, 1.0);

glBegin(GL_LINE_LOOP); glVertex2f(result[0][0],result[1][0]); glVertex2f(result[0][1],result[1][1]); glVertex2f(result[0][3],result[1][3]); glVertex2f(result[0][4],result[1][4]); glEnd();glColor3f(1.0,0.0,0.0); glBegin(GL_LINE_LOOP); glVertex2f(result[0][5],result[1][5]); glVertex2f(result[0][6],result[1][6]); glVertex2f(result[0][7],result[1][7]); glVertex2f(result[0][8],result[1][8]); glEnd();glColor3f(0.0, 0.0, 1.0); glBegin(GL_LINE_LOOP); glVertex2f(result[0][1],result[1][1]); glVertex2f(result[0][2],result[1][2]); glVertex2f(result[0][3],result[1][3]); glEnd();

}

void display(){

glClear(GL_COLOR_BUFFER_BIT);drawhouse();rotate();drawrotatedhouse();glFlush();}

Dept. of CSE, REVA ITM 16

Page 17: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

void myinit(){

glClearColor(1.0,1.0,1.0,1.0);glColor3f(1.0,0.0,0.0);glPointSize(1.0);glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D(0.0,499.0,0.0,499.0);

}

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

printf("Enter the rotation angle\n");scanf("%f", &theta);glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutInitWindowSize(500,500);glutInitWindowPosition(0,0);glutCreateWindow("house rotation");glutDisplayFunc(display);myinit();glutMainLoop();

}

Output:

Enter the Theta value45

Dept. of CSE, REVA ITM 17

Page 18: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

5. Program to implement the Cohen-Sutherland line-clipping algorithm. Make provision to specify the input line, window for clipping and viewport for displaying the clipped image.

// Cohen-Suderland Line Clipping Algorithm with Window to viewport Mapping */#include <stdio.h>#include <GL/glut.h>

#define outcode intdouble xmin=50,ymin=50, xmax=100,ymax=100; // Window boundariesdouble xvmin=200,yvmin=200,xvmax=300,yvmax=300; // Viewport boundaries//bit codes for the right, left, top, & bottomconst int RIGHT = 8;const int LEFT = 2;const int TOP = 4;const int BOTTOM = 1;

//used to compute bit codes of a pointoutcode ComputeOutCode (double x, double y);

//Cohen-Sutherland clipping algorithm clips a line from//P0 = (x0, y0) to P1 = (x1, y1) against a rectangle with //diagonal from (xmin, ymin) to (xmax, ymax).void CohenSutherlandLineClipAndDraw (double x0, double y0,double x1, double y1){

//Outcodes for P0, P1, and whatever point lies outside the clip rectangleoutcode outcode0, outcode1, outcodeOut;bool accept = false, done = false;

//compute outcodesoutcode0 = ComputeOutCode (x0, y0);outcode1 = ComputeOutCode (x1, y1);

do{if (!(outcode0 | outcode1)) //logical or is 0 Trivially accept & exit{

accept = true;done = true;

}else if (outcode0 & outcode1) //logical and is not 0. Trivially reject and exit

done = true;else{

//failed both tests, so calculate the line segment to clip//from an outside point to an intersection with clip edgedouble x, y;

//At least one endpoint is outside the clip rectangle; pick it.outcodeOut = outcode0? outcode0: outcode1;

//Now find the intersection point;//use formulas y = y0 + slope * (x - x0), x = x0 + (1/slope)* (y - y0)

Dept. of CSE, REVA ITM 18

Page 19: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

if (outcodeOut & TOP) //point is above the clip rectangle{

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

}else if (outcodeOut & BOTTOM) //point is below the clip rectangle{

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

}else if (outcodeOut & RIGHT) //point is to the right of clip rectangle{

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

}else //point is to the left of clip rectangle{

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

}

//Now we move outside point to intersection point to clip//and get ready for next pass.if (outcodeOut == outcode0){

x0 = x;y0 = y;outcode0 = ComputeOutCode (x0, y0);

}else {

x1 = x;y1 = y;outcode1 = ComputeOutCode (x1, y1);

}}

}while (!done);

if (accept){ // Window to viewport mappings

double sx=(xvmax-xvmin)/(xmax-xmin); // Scale parametersdouble 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 a red colored viewportglColor3f(1.0, 0.0, 0.0);glBegin(GL_LINE_LOOP);

glVertex2f(xvmin, yvmin);glVertex2f(xvmax, yvmin);glVertex2f(xvmax, yvmax);

Dept. of CSE, REVA ITM 19

Page 20: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

glVertex2f(xvmin, yvmax);glEnd();glColor3f(0.0,0.0,1.0); // draw blue colored clipped lineglBegin(GL_LINES);

glVertex2d (vx0, vy0);glVertex2d (vx1, vy1);

glEnd();}

}

//Compute the bit code for a point (x, y) using the clip rectangle//bounded diagonally by (xmin, ymin), and (xmax, ymax)outcode ComputeOutCode (double x, double y){

outcode code = 0;if (y > ymax) //above the clip window

code |= TOP;else if (y < ymin) //below the clip window

code |= BOTTOM;if (x > xmax) //to the right of clip window

code |= RIGHT;else if (x < xmin) //to the left of clip window

code |= LEFT;return code;

}

void display(){

double x0=60,y0=20,x1=80,y1=120;glClear(GL_COLOR_BUFFER_BIT);//draw the line with red colorglColor3f(1.0,0.0,0.0);//bres(120,20,340,250);glBegin(GL_LINES);

glVertex2d (x0, y0);glVertex2d (x1, y1);

glEnd();

//draw a blue colored windowglColor3f(0.0, 0.0, 1.0);

glBegin(GL_LINE_LOOP); glVertex2f(xmin, ymin); glVertex2f(xmax, ymin); glVertex2f(xmax, ymax); glVertex2f(xmin, ymax);glEnd();CohenSutherlandLineClipAndDraw(x0,y0,x1,y1);glFlush();}

Dept. of CSE, REVA ITM 20

Page 21: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

void myinit(){

glClearColor(1.0,1.0,1.0,1.0);glColor3f(1.0,0.0,0.0);glPointSize(1.0);glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D(0.0,499.0,0.0,499.0);

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

//int x1, x2, y1, y2;//printf("Enter End points:");//scanf("%d%d%d%d", &x1,&x2,&y1,&y2);

glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutInitWindowSize(500,500);glutInitWindowPosition(0,0);glutCreateWindow("Cohen Suderland Line Clipping Algorithm");glutDisplayFunc(display);myinit();glutMainLoop(); }

Output:

Dept. of CSE, REVA ITM 21

Page 22: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

6. Program to create a cylinder and a parallelepiped by extruding a circle and quadrilateral respectively. Allow the user to specify the circle and the quadrilateral.

//Cylinder and Parallelepiped by extruding Circle and Quadrilateral//cyl_pp_vtu.cpp#include <GL/glut.h>#include <math.h>#include <stdio.h>

void draw_pixel(GLint cx, GLint cy){ glColor3f(1.0,0.0,0.0);

glBegin(GL_POINTS); glVertex2i(cx,cy); glEnd();

}

void plotpixels(GLint h, GLint k, GLint x, GLint y){

draw_pixel(x+h,y+k);draw_pixel(-x+h,y+k);draw_pixel(x+h,-y+k);draw_pixel(-x+h,-y+k);draw_pixel(y+h,x+k);draw_pixel(-y+h,x+k);draw_pixel(y+h,-x+k);draw_pixel(-y+h,-x+k);

}void Circle_draw(GLint h, GLint k, GLint r) // Midpoint Circle Drawing Algorithm{

GLint d = 1-r, x=0, y=r; while(y > x) {

plotpixels(h,k,x,y); if(d < 0) d+=2*x+3; else {d+=2*(x-y)+5; --y; } ++x;

} plotpixels(h,k,x,y);

}

void Cylinder_draw(){

GLint xc=100, yc=100, r=50;GLint i,n=50;for(i=0;i<n;i+=3){Circle_draw(xc,yc+i,r);}

}

Dept. of CSE, REVA ITM 22

Page 23: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

void parallelepiped(int x1, int x2,int y1, int y2, int y3, int y4){

glColor3f(0.0, 0.0, 1.0);glPointSize(2.0);glBegin(GL_LINE_LOOP); glVertex2i(x1,y1); glVertex2i(x2,y3); glVertex2i(x2,y4); glVertex2i(x1,y2); glEnd();}

void parallelepiped_draw(){

int x1=200,x2=300,y1=100,y2=175,y3=100,y4=175; GLint i,n=40;

for(i=0;i<n;i+=2) { parallelepiped(x1+i,x2+i,y1+i,y2+i,y3+i,y4+i); }

}

void init(void){

glClearColor(1.0,1.0,1.0,0.0); // Set display window color to whiteglMatrixMode(GL_PROJECTION); // Set Projection parameters gluOrtho2D(0.0,400.0,0.0,300.0);

}

void display(void){ glClear(GL_COLOR_BUFFER_BIT); // Clear Display Window

glColor3f(1.0,0.0,0.0); // Set circle color to red (R G B)glPointSize(2.0);Cylinder_draw(); // Call cylinderparallelepiped_draw();// call parallelepipedglFlush(); // Process all OpenGL routines as quickly as possible

}

void main(int argc, char **argv){ glutInit(&argc,argv); // Initialize GLUT

glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // Set Display modeglutInitWindowPosition(50,50); // Set top left window positionglutInitWindowSize(400,300); // Set Display window width and height glutCreateWindow("Cylinder and parallelePiped Display by Extruding Circle and

Quadrilaterl "); // Create Display Windowinit();glutDisplayFunc(display); // Send the graphics to Display WindowglutMainLoop();

}

Dept. of CSE, REVA ITM 23

Page 24: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

Output:

Dept. of CSE, REVA ITM 24

Page 25: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

7. Program, using OpenGL functions, to draw a simple shaded scene consisting of a teapot on a table. Define suitably the position and properties of the light source along with the properties of the properties of the surfaces of the solid object used in the scene.

/* simple shaded scene consisting of a tea pot on a table */ #include <GL/glut.h>

void wall (double thickness){

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

}

//draw one table legvoid 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){

//draw the table - a top and four legs//draw the top firstglPushMatrix();glTranslated (0, legLen, 0);glScaled(topWid, topThick, topWid);glutSolidCube (1.0);glPopMatrix();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();

}

Dept. of CSE, REVA ITM 25

Page 26: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

void displaySolid (void){

//set properties of the surface materialGLfloat mat_ambient[] = {0.7f, 0.7f, 0.7f, 1.0f}; // grayGLfloat 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 light source propertiesGLfloat 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 cameraglMatrixMode (GL_PROJECTION);glLoadIdentity();double winHt = 1.0; //half-height of windowglOrtho (-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 drawingglClear (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);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);

Dept. of CSE, REVA ITM 26

Page 27: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

wall (0.02);glPopMatrix();glPushMatrix();glRotated (-90.0, 1.0, 0.0, 0.0);wall (0.02);glPopMatrix();glFlush();

}

void main (int argc, 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();

}

Output:

Dept. of CSE, REVA ITM 27

Page 28: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

8. Program to draw a color cube and allow the user to move the camera suitably to experiment with perspective viewing. Use OpenGL functions./* Rotating cube with viewer movement */

/* We use the Lookat function in the display callback to pointthe viewer, whose position can be altered by the x,X,y,Y,z, and Z keys.The perspective view is set in the reshape callback */

#include <stdlib.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}};

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] = {{0.0,0.0,0.0},{1.0,0.0,0.0},{1.0,1.0,0.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, 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();

}

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

}

Dept. of CSE, REVA ITM 28

Page 29: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

static GLfloat theta[] = {0.0,0.0,0.0};static GLint axis = 2;static GLdouble viewer[]= {0.0, 0.0, 5.0}; /* initial viewer location */

void display(void){

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

/* Update viewer position in modelview matrix */

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

/* rotate cube */

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, int state, int x, 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, int x, int y){

/* Use x, X, y, Y, z, and Z keys to move viewer */

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

Dept. of CSE, REVA ITM 29

Page 30: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

void myReshape(int w, int h){ glViewport(0, 0, w, h);

/* Use a perspective view */

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

/* Or we can use gluPerspective */

/* gluPerspective(45.0, w/h, -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 Viewer"); glutReshapeFunc(myReshape); glutDisplayFunc(display);

glutMouseFunc(mouse);glutKeyboardFunc(keys);glEnable(GL_DEPTH_TEST);

glutMainLoop();}

Output:

Dept. of CSE, REVA ITM 30

Page 31: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

9. Program to fill any given polygon using scan-line area filling algorithm. (Use appropriate data structures.)

// Scan-Line algorithm for filling a polygon#define BLACK 0#include <stdlib.h>#include <stdio.h>#include <GL/glut.h>float x1,x2,x3,x4,y1,y2,y3,y4;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 draw_pixel(int x,int y,int value){

glColor3f(1.0,1.0,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);

Dept. of CSE, REVA ITM 31

Page 32: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

for(y=0;y<500;y++){

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

draw_pixel(i,y,BLACK);} }

void display(){x1=200.0;y1=200.0;x2=100.0;y2=300.0;x3=200.0;y3=400.0;x4=300.0;y4=300.0;

glClear(GL_COLOR_BUFFER_BIT);glColor3f(0.0, 0.0, 1.0);glBegin(GL_LINE_LOOP); glVertex2f(x1,y1); glVertex2f(x2,y2); glVertex2f(x3,y3); glVertex2f(x4,y4); glEnd(); scanfill(x1,y1,x2,y2,x3,y3,x4,y4);glFlush();}void myinit(){

glClearColor(1.0,1.0,1.0,1.0);glColor3f(1.0,0.0,0.0);glPointSize(1.0);glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D(0.0,499.0,0.0,499.0);

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

glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutInitWindowSize(500,500);glutInitWindowPosition(0,0);glutCreateWindow("Filling a Polygon using Scan-line Algorithm");glutDisplayFunc(display);myinit();glutMainLoop();

}Output:

Dept. of CSE, REVA ITM 32

Page 33: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

10. Program to display a set of values {fij} as a rectangular mesh.

// rect_mesh_vtu.cpp// Rectangular Mesh using set of points f(i,j)=f(xi,yi) where xi=x0+i*dx, yi=y0+j*dy #include <stdlib.h> // standard definitions#include <GL/glut.h> // GLUT#define maxx 20#define maxy 25#define dx 15#define dy 10

GLfloat x[maxx]={0.0},y[maxy]={0.0};GLfloat x0=50,y0=50; // initial values for x, yGLint i,j;void init(){ glClearColor(1.0,1.0,1.0,1.0);

glColor3f(1.0,0.0,0.0);glPointSize(5.0);glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D(0.0,499.0,0.0,499.0);glutPostRedisplay(); // request redisplay

}

void display(void){/* clear window */

glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.0, 0.0, 1.0); // set color to blue

/* draw rectangles */ for(i=0;i<maxx;i++)

x[i]=x0+i*dx; // compute x[i]for(j=0;j<maxy;j++)

y[j]=y0+j*dy; // compute y[i]

glColor3f(0.0, 0.0, 1.0);for(i=0;i<maxx-1;i++)for(j=0;j<maxy-1;j++){

glColor3f(0.0, 0.0, 1.0);glBegin(GL_LINE_LOOP);glVertex2f(x[i],y[j]);glVertex2f(x[i],y[j+1]);glVertex2f(x[i+1],y[j+1]);glVertex2f(x[i+1],y[j]);

glEnd();glFlush(); }

glFlush();

}

Dept. of CSE, REVA ITM 33

Page 34: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

void main(int argc, char** argv){glutInit(&argc, argv); // OpenGL initializationsglutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);// single buffering and RGBglutInitWindowSize(500, 400); // create a 500x400 windowglutInitWindowPosition(0, 0); // ...in the upper leftglutCreateWindow("Rectangular Mesh"); // create the windowglutDisplayFunc(display); // setup callbacksinit();glutMainLoop(); // start it running}

Output:

Dept. of CSE, REVA ITM 34

Page 35: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

PART – B

Develop a suitable Graphics package to implement the skills learnt in the theory and the exercises indicated in Part A. Use the OpenGL.

Dept. of CSE, REVA ITM

COMPUTER

GRAPHICS AND

VISUALIZATION

LABORATORY

35

Page 36: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

Viva questions

Alpha A fourth color value added to provide a degree of transparency to the color of an object. An alpha value of 0.0 would mean complete transparency: 1.0 denotes no transparency (opaque).

Ambient light Light in a scene that doesn’t come from any specific point source or direction. Ambient light illuminates all surfaces evenly and on all sides.

Anti-aliasing A rendering method used to smooth lines and curves. This technique averages the color of pixels adjacent to the line. It has the visual effect of softening the transition from the pixels on the line and those adjacent to the line, thus providing a smoother appearance.

Aspect ratio The ratio of the width of a window to the height of the window specifically, the width of the window in pixels divided by the height of the window in pixels.

AUX library A window system, independent utility library. Useful for quick and portable OpenGL demonstration programs.

Bézier curve A curve whose shape is defined by control points near the curve rather than by the precise set of points that define the curve itself.

Bitplane An array of bits mapped directly to screen pixels.

Buffer An area of memory used to store image information. This may be color, depth, or blending information. The red, green, blue, and alpha buffers are often collectively referred to as the color buffers.

Cartesian A coordinate system based on three directional axes placed at a 90º orientation to one another. These coordinates are labeled x, y, and z.

Clipping The elimination of a portion of a single primitive or group of primitives. The points that would be rendered outside the clipping region or volume are not drawn. The clipping volume is generally specified by the projection matrix.

Color index mode A color mode in which colors in a scene are selected from a fixed number of colors available in a palette. These entries are referenced by an index into the palette.

Convex Refers to the shape of a polygon. A convex polygon has no indentations; and no straight line can be drawn through the polygon that will intersect it more than twice (once entering, once leaving).

Dept. of CSE, REVA ITM 36

Page 37: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

Culling Elimination of the front or back face of a primitive so that the face isn’t drawn.

Display list A compiled list of OpenGL functions and commands. When called, a display list executes faster than would a manually called list of single commands.

Dithering A method used to simulate a wider range of color depth by placing different-colored pixels together in patterns that give the illusion of shading between the two colors. Double buffered A drawing technique used by OpenGL. The image to be displayed is assembled in memory and then placed on the screen in a single update operation, as opposed to building the image primitive-by-primitive on the screen. Double buffering is a much faster and smoother update operation and can produce animations.

Extruded The process of taking a 2D image or shape and adding a third dimension uniformly across the surface. This can transform 2D fonts into 3D lettering.

Eye coordinates The coordinate system based on the position of the viewer. The viewer’s position is placed along the positive z-axis, looking down the negative z-axis. Frustum A pyramid-shaped viewing volume that creates a perspective view (near objects are large, far objects are small).

Immediate mode A graphics rendering mode in which commands and functions have an immediate effect on the state of the rendering engine.

Literal A value, not a variable name. A specific string or numeric constant embedded directly in source code.

Matrix A 2D array of numbers. Matrices may be operated on mathematically and are used to perform coordinate transformations.

Modelview matrix The OpenGL matrix that transforms primitives to eye coordinates from object coordinates.

Normal A directional vector that points perpendicularly to a plane or surface. When used, normals must be specified for each vertex in a primitive. Normalize Refers to the reduction of a normal to a unit normal. A unit normal is a vector that has a length of exactly 1.0.

Dept. of CSE, REVA ITM 37

Page 38: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

NURBS An acronym for Non-Uniform Rational B-Spline. This is a method of specifying parametric curves and surfaces.

Open Inventor A C++ class library and toolkit for building interactive 3D applications. Open Inventor is built on OpenGL.

Orthographic A drawing mode in which no perspective or foreshortening takes place. Also called parallel projection, the lengths and dimensions of all primitives are undistorted regardless of orientation or distance from the viewer.

Palette A set of colors available for drawing operations. For 8-bit Windows color modes, the palette contains 256 color entries, and all pixels in the scene may only be colored from this set.

Parametric curve A curve whose shape is determined by one (for a curve) or two (for a surface) parameters. These parameters are used in separate equations that yield the individual x, y, and z values of the points along the curve.

Perspective A drawing mode in which objects farther from the viewer appear smaller than nearby objects.

Pixel Condensed from the words picture element. This is the smallest visual division available on the computer screen. Pixels are arranged in rows and columns and are individually set to the appropriate color to render any given image.

Polygon A 2D shape drawn with any number of sides (must be at least three sides).

Primitive A 2D polygonal shape defined by OpenGL. All objects and scenes are composed of various combinations of primitives.

Projection The transformation of lines, points, and polygons from eye coordinates to clipping coordinates on the screen.

Quadrilateral A polygon with exactly four sides.

Rasterize The process of converting projected primitives and bitmaps into pixel fragments in the framebuffer.

Render The conversion of primitives in object coordinates to an image in the framebuffer. The rendering pipeline is the process by which OpenGL commands and statements become pixels on the screen.

Dept. of CSE, REVA ITM 38

Page 39: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

Spline A general term used to describe any curve created by placing control points near the curve, which have a pulling effect on the curve’s shape. This is similar to the reaction of a piece of flexible material when pressure is applied at various points along its length.

Stipple A binary bit pattern used to mask out pixel generation in the framebuffer. This is similar to a monochrome bitmap, but one-dimensional patterns are used for lines, and two-dimensional patterns are used for polygons.

Tessellation The process of breaking down a complex polygon or analytic surface into a mesh of convex polygons. This can also be applied to separate a complex curve into a series of less complex lines.

Texel Similar to pixel (picture element), a texel is a texture element. A texel represents a color from a texture that will be applied to a pixel fragment in the framebuffer.

Texture An image pattern of colors applied to the surface of a primitive.

Texture mapping The process of applying a texture image to a surface. The surface does not have to be planar (flat). Texture mapping is often used to wrap an image around a curved object or to produce patterned surfaces such as wood or marble.

Transformation The manipulation of a coordinate system. This can include rotation, translation, scaling (both uniform and nonuniform), and perspective division. Translucence A degree of transparency of an object. In OpenGL, this is represented by an alpha value ranging from 1.0 (opaque) to 0.0 (transparent).

Vertex A single point in space. Except when used for point and line primitives, it also defines the point at which two edges of a polygon meet. Viewport The area within a window that is used to display an OpenGL image. Usually, this encompasses the entire client area. Stretched viewports can produce enlarged or shrunken output within the physical window.

Viewing volume The area in 3D space that can be viewed in the window. Objects and points outside the viewing volume will be clipped (cannot be seen). Wireframe

Dept. of CSE, REVA ITM 39

Page 40: CG-manual-5-2-12

COMPUTER GRAPHICS &VISUALIZATION LAB-(06CSL67)

The representation of a solid object by a mesh of lines rather than solid shaded polygons. Wireframe models are usually rendered faster and can be used to view both the front and back of an object at the same time.

Dept. of CSE, REVA ITM 40