Vous êtes sur la page 1sur 46

CGV Lab Manual

What Is OpenGL?
OpenGL is a software interface to graphics hardware. This interface consists
of about 150 distinct commands that you use to specify the objects and
operations needed to produce interactive three-dimensional applications.
OpenGL is designed as a streamlined, hardware-independent interface to be
implemented on many different hardware platforms. To achieve these
qualities, no commands for performing windowing tasks or obtaining user
input are included in OpenGL; instead, you must work through whatever
windowing system controls the particular hardware you're using. Similarly,
OpenGL doesn't provide high-level commands for describing models of threedimensional objects. Such commands might allow you to specify relatively
complicated shapes such as automobiles, parts of the body, airplanes, or
molecules. With OpenGL, you must build up your desired model from a small
set of geometric primitives - points, lines, and polygons.
A sophisticated library that provides these features could certainly be built on
top of OpenGL. The OpenGL Utility Library (GLU) provides many of the
modeling features, such as quadric surfaces and NURBS (Non-Uniform
Rational B-Splines) curves and surfaces. GLU is a standard part of every
OpenGL implementation. Also, there is a higher-level, object-oriented toolkit,
Open Inventor, which is built atop OpenGL, and is available separately for
many implementations of OpenGL.
OpenGL-Related Libraries
OpenGL provides a powerful but primitive set of rendering commands, and
all higher-level drawing must be done in terms of these commands. Also,
OpenGL programs have to use the underlying mechanisms of the windowing
system. A number of libraries exist to allow you to simplify your
programming tasks, including the following:

The OpenGL Utility Library (GLU) contains several routines that use
lower-level OpenGL commands to perform such tasks as setting up
matrices for specific viewing orientations and projections, performing
polygon tessellation, and rendering surfaces. This library is provided as
part of every OpenGL implementation. GLU routines use the prefix
glu.

For every window system, there is a library that extends the


functionality of that window system to support OpenGL rendering. For
machines that use the X Window System, the OpenGL Extension to the
X Window System (GLX) is provided as an adjunct to OpenGL. GLX
routines use the prefix glX. For Microsoft Windows, the WGL routines
provide the Windows to OpenGL interface. All WGL routines use the
prefix wgl. For IBM OS/2, the PGL is the Presentation Manager to
OpenGL interface, and its routines use the prefix pgl.

Dept. of CSE, BIT

CGV Lab Manual

The OpenGL Utility Toolkit (GLUT) is a window system-independent


toolkit, written by Mark Kilgard, to hide the complexities of differing
window system APIs. GLUT routines use the prefix glut.

Open Inventor is an object-oriented toolkit based on OpenGL which


provides objects and methods for creating interactive three-dimensional
graphics applications. Open Inventor, which is written in C++, provides
prebuilt objects and a built-in event model for user interaction, highlevel application components for creating and editing three-dimensional
scenes, and the ability to print objects and exchange data in other
graphics formats. Open Inventor is separate from OpenGL.

Include Files
For all OpenGL applications, you want to include the gl.h header file in every
file. Almost all OpenGL applications use GLU, the aforementioned OpenGL
Utility Library, which requires inclusion of the glu.h header file. So almost
every OpenGL source file begins with
#include <GL/gl.h>
#include <GL/glu.h>
If you are directly accessing a window interface library to support OpenGL,
such as GLX, AGL, PGL, or WGL, you must include additional header files.
For example, if you are calling GLX, you may need to add these lines to your
code
#include <X11/Xlib.h>
#include <GL/glx.h>
If you are using GLUT for managing your window manager tasks, you should
include
#include <GL/glut.h>
Note that glut.h includes gl.h, glu.h, and glx.h automatically, so including all
three files is redundant. GLUT for Microsoft Windows includes the
appropriate header file to access WGL.
GLUT, the OpenGL Utility Toolkit
As you know, OpenGL contains rendering commands but is designed to be
independent of any window system or operating system. Consequently, it
contains no commands for opening windows or reading events from the
keyboard or mouse. Unfortunately, it's impossible to write a complete
graphics program without at least opening a window, and most interesting

Dept. of CSE, BIT

CGV Lab Manual

programs require a bit of user input or other services from the operating
system or window system.
In addition, since OpenGL drawing commands are limited to those that
generate simple geometric primitives (points, lines, and polygons), GLUT
includes several routines that create more complicated three-dimensional
objects such as a sphere, a torus, and a teapot. This way, snapshots of program
output can be interesting to look at. (Note that the OpenGL Utility Library,
GLU, also has quadrics routines that create some of the same threedimensional objects as GLUT, such as a sphere, cylinder, or cone.)
Important features of OpenGL Utility Toolkit (GLUT)

Provides functionality common to all window systems.


Open a window.
Get input from mouse and keyboard.
Menus.
Event-driven.
Code is portable but GLUT lacks the functionality of a good toolkit for
a specific platform.
No slide bars.
OpenGL is not object oriented so that there are multiple functions for a
given logical function :
glVertex3f
o glVertex2i
o glVertex3dv
Underlying storage mode is the same easy to create overloaded
functions in C++ but issue is efficiency.
OpenGL Interface
o GL (OpenGL in Windows)
o GLU (graphics utility library)
uses only GL functions, creates common objects (such as
spheres)
o GLUT (GL Utility Toolkit)
interfaces with the window system
o GLX: glue between OpenGL and Xwindow, used by GLUT
Window Management
Five routines perform tasks necessary to initialize a window.

glutInit(int *argc, char **argv) initializes GLUT and processes any


command line arguments (for X, this would be options like -display and
-geometry). glutInit() should be called before any other GLUT routine.

Dept. of CSE, BIT

CGV Lab Manual

glutInitDisplayMode(unsigned int mode) specifies whether to use an


RGBA or color-index color model. You can also specify whether you
want a single- or double-buffered window. (If you're working in colorindex mode, you'll want to load certain colors into the color map; use
glutSetColor() to do this.) Finally, you can use this routine to indicate
that you want the window to have an associated depth, stencil, and/or
accumulation buffer. For example, if you want a window with double
buffering, the RGBA color model, and a depth buffer, you might call
glutInitDisplayMode(GLUT_DOUBLE
|
GLUT_RGB
|
GLUT_DEPTH).

glutInitWindowPosition(int x, int y) specifies the screen location for


the upper-left corner of your window.

glutInitWindowSize(int width, int size) specifies the size, in pixels, of


your window.

int glutCreateWindow(char *string) creates a window with an


OpenGL context. It returns a unique identifier for the new window. Be
warned: Until glutMainLoop() is called (see next section), the window
is not yet displayed.

The Display Callback


glutDisplayFunc(void (*func)(void)) is the first and most important event
callback function you will see. Whenever GLUT determines the contents of
the window need to be redisplayed, the callback function registered by
glutDisplayFunc() is executed. Therefore, you should put all the routines you
need to redraw the scene in the display callback function.
If your program changes the contents of the window, sometimes you will have
to call glutPostRedisplay(void), which gives glutMainLoop() a nudge to call
the registered display callback at its next opportunity.
Running the Program
The very last thing you must do is call glutMainLoop(void). All windows
that have been created are now shown, and rendering to those windows is now
effective. Event processing begins, and the registered display callback is
triggered. Once this loop is entered, it is never exited!
Example: Simple OpenGL Program Using GLUT: hello.c
#include <GL/gl.h>
#include <GL/glut.h>
void display(void)
{
/* clear all pixels */
Dept. of CSE, BIT

CGV Lab Manual

glClear (GL_COLOR_BUFFER_BIT);
/* draw white polygon (rectangle) with corners at
* (0.25, 0.25, 0.0) and (0.75, 0.75, 0.0)
*/
glColor3f (1.0, 1.0, 1.0);
glBegin(GL_POLYGON);
glVertex3f (0.25, 0.25, 0.0);
glVertex3f (0.75, 0.25, 0.0);
glVertex3f (0.75, 0.75, 0.0);
glVertex3f (0.25, 0.75, 0.0);
glEnd();
/* don't wait!
* start processing buffered OpenGL routines
*/
glFlush ();
}
void init (void)
{
/* select clearing (background) color
glClearColor (0.0, 0.0, 0.0, 0.0);

*/

/* initialize viewing values */


glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}
/*
* Declare initial window size, position, and display mode
* (single buffer and RGBA). Open window with "hello"
* in its title bar. Call initialization routines.
* Register callback function to display graphics.
* Enter main loop and process events.
*/

int main(int argc, char** argv)


{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (250, 250);
Dept. of CSE, BIT

CGV Lab Manual

glutInitWindowPosition (100, 100);


glutCreateWindow ("hello");
init ();
glutDisplayFunc(display);
glutMainLoop();
return 0; /* ISO C requires main to return int. */
}

Instructions for using OpenGL and GLUT for Windows XP machines


with Microsoft Visual Studio.Net 2003
If you are using OpenGL on your computer at home:
All Windows systems since Windows 98 have OpenGL preinstalled.
Download GLUT. Go to the CSCI 4250 pages web site
(http://www.mtsu.edu/~csjudy/4250) and visit the Links to OpenGL
sites. You will find a site for downloading GLUT.
When you down load it, it will be a zip file. You will have to unzip it.
Then place the glut32.dll file in the windows\system32 directory.
If your system is configured like the ones at MTSU, you will need to
place the glut.h file in the \Program Files\Microsoft Visual Studio
.Net 2003\vc7\PlatformSDK\Include\ GL folder and the glut32.lib
file in the Program Files\Microsoft Visual Studio .Net
2003\vc7\PlatformSDK\Lib folder.
To use Microsoft Visual Studio.Net 2003:
Start Microsoft Visual C++ -- click on Start, Programs, Microsoft
Visual Studio .Net 2003, Microsoft Visual Studio .Net 2003
Create a new project by selecting File
Give your project a name (use your last
name followed by the number of the project for the name of the
project), select the appropriate disk or hard drive, and click on OK. On
the subsequent window, select Application Settings. In the next
window, select Empty Project and Console Application then click on
Finish.
To create the files that should be placed in the project, you should
select Project, Add New Item, and then select the type of files that you
are creating.
To create an executable, compile Build
Rebuild Solution (Compiles and Links.)

Dept. of CSE, BIT

CGV Lab Manual

You can then run your executable by typing (CTRL + F5) or selecting

Graphics Programming Using OpenGL in Visual C++


Opengl32.dll and glu32.dll should be in the system folder.
Opengl32.lib and glu32.lib should be in the lib folder for VC++.
gl.h and glu.h should be in a folder called GL under the include folder
for VC++.
Get glut32.lib, glut32.dll and glut.h from the course homepage and put
them in the same places as the other files.
Fire up visual studio.
Create a new project as the following :
File
(workspace) with the same name will be built)

In the workspace click on File View to access (expand) the source


code tree.
In Source Files, add in the source code (*.cpp files).

Opengl32.lib glu32.lib glut32.lib.


Press F7 to build your_project.exe.
Basic OpenGL Elements - Programming 2D Applications
A vertex is a location in space
glVertex*
* is in the form of nt or ntv
n is the number of dimensions

Dept. of CSE, BIT

CGV Lab Manual

t denotes the data type:


integer (i), float (f), or double (d);
pointer to an array (v)
Examples :
glVertex2i(GLint xi, GLint yi)
glVertex3f(GLfloat x, GLfloat y, GLfloat z)
GLfloat vertex[3]
glVertex3fv(vertex)

OpenGL Object Examples


glBegin (mode);
glVertex2f (x1, y1);
glVertex2f (x2, y2);
glVertex2f (x3, y3);
glVertex2f (x4, y4);
glEnd ();
where mode = GL_POINTS, GL_LINES, GL_LINE_STRIP,
GL_POLYGON, GL_LINE_LOOP, etc.
Lines of zero length are not visible.
A vertex is considered to be just a location with zero mass.
Only 10 of the OpenGL functions are legal for use between glBegin
and glEnd.
Examples : glBegin(GL_LINES);
glVertex2f(x1, y1);
glVertex2f(x2, y2);
glEnd();
glBegin(GL_POINTS);
glVertex2f(x1, y1);
glVertex2f(x2, y2);
glEnd();

Dept. of CSE, BIT

CGV Lab Manual

Graphics Functions
Primitive functions:
points, line segments, polygons, pixels, text, curves, surfaces
Attributes functions:
color, pattern, typeface
Some Primitive Attributes
glClearColor (red, green, blue, alpha); - Default = (0.0, 0.0, 0.0, 0.0)
glColor3f (red, green, blue); - Default = (1.0, 1.0, 1.0)
glLineWidth (width); - Default = (1.0)
glLineStipple (factor, pattern) - Default = (1, 0xffff)
glEnable (GL_LINE_STIPPLE);
glPolygonMode (face, mode) - Default = (GL_FRONT_AND_BACK,
GL_FILL)
glPointSize (size); - Default = (1.0)

Viewing functions:
position, orientation, clipping
Transformation functions:
rotation, translation, scaling
Input functions:
keyboards, mice, data tablets
Control functions:
communicate with windows, initialization, error handling
Inquiry functions: number of colors, camera parameters/values
Matrix Mode
There are two matrices in OpenGL:
Model-view: defines COP and orientation
Projection: defines the projection matrix

Dept. of CSE, BIT

CGV Lab Manual

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 500.0, 0.0, 500.0);
glMatrixMode(GL_MODELVIEW);
Control Functions
OpenGL assumes origin is bottom left
glutInit(int *argcp, char **argv);
glutCreateWindow(char *title);
glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH |
GLUT_DOUBLE);
glutInitWindowSize(480,640);
glutInitWindowPosition(0,0);
OpenGL default: RGB color, no hidden-surface removal, single
buffering
Obtaining Values of OpenGL State Variables
glGetBooleanv (paramname, *paramlist);
glGetDoublev (paramname, *paramlist);
glGetFloatv (paramname, *paramlist);
glGetIntegerv (paramname, *paramlist);
Saving and Restoring Attributes
glPushAttrib (group);
glPopAttrib ( );
where group = GL_CURRENT_BIT, GL_ENABLE_BIT,
GL_LINE_BIT, GL_POLYGON_BIT, etc.
Projection Transformations
glMatrixMode (GL_PROJECTION);
glLoadIdentity ( );
glFrustum (left, right, bottom, top, near, far);
gluPerspective (fov, aspect, near, far);
glOrtho (left, right, bottom, top, near, far);
Dept. of CSE, BIT

10

CGV Lab Manual

- Default = (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)


gluOrtho2D (left, right, bottom, top);
Modelview Transformations
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ( );
gluLookAt (eye_x, eye_y, eye_z, at_x, at_y, at_z, up_x, up_y, up_z);
glTranslatef (dx, dy, dz);
glScalef (sx, sy, sz);
glRotatef (angle, axisx, axisy, axisz);
Writing Bitmapped Text
glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
glColor3f (red, green, blue);
glRasterPos2f (x, y);
glutBitmapCharacter (font, character);
where font = GLUT_BITMAP_8_BY_13,
GLUT_BITMAP_HELVETICA_10, etc.
Managing the Frame Buffer
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_RGB | mode);
glutInitWindowSize (width, height);
glutInitWindowPosition (x, y);
glutCreateWindow (label);
glClear (GL_COLOR_BUFFER_BIT);
glutSwapBuffers ( );
where mode = GLUT_SINGLE or GLUT_DOUBLE.

Dept. of CSE, BIT

11

CGV Lab Manual

Registering Callbacks
glutDisplayFunc (callback);
glutReshapeFunc (callback);
glutDisplayFunc (callback);
glutMotionFunc (callback);
glutPassiveMotionFunc (callback);
glutMouseFunc (callback);
glutKeyboardFunc (callback);
id = glutCreateMenu (callback);
glutMainLoop ( );
Display Lists
glNewList (number, GL_COMPILE);
glEndList ( );
glCallList (number);
glDeleteLists (number, 1);
Managing Menus
id = glutCreateMenu (callback);
glutDestroyMenu (id);
glutAddMenuEntry (label, number);
glutAttachMenu (button);
glutDetachMenu (button);
where button = GLUT_RIGHT_BUTTON or GLUT_LEFT_BUTTON.

Dept. of CSE, BIT

12

CGV Lab Manual

1. Program to recursively subdivided 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 */
#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
typedef GLfloat point[3];
point v[]={{-1.0,-0.5,0.0},{1.0,-0.5,0.0},{0.0,1.0,0.0}, {0.0,0.0,1.0}};
GLfloat colors[4][3]={{1.0,0.0,0.0},{0.0,1.0,0.0},{0.0,0.0,1.0},{1.0,1.0,0.0}};
int n;
void triangle(point a,point b,point c)
{
glBegin(GL_POLYGON);
glVertex3fv(a);
glVertex3fv(b);
glVertex3fv(c);
glEnd();
}
void tetra(point a,point b,point c,point 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);
}
void divide_tetra(point a,point b,point c,point d,int m)
{
point mid[6];
int j;
if(m>0)
{
for(j=0;j<3;j++)
{
mid[0][j]=(a[j]+b[j])/2.0;
mid[1][j]=(a[j]+c[j])/2.0;
mid[2][j]=(a[j]+d[j])/2.0;
mid[3][j]=(b[j]+c[j])/2.0;
mid[4][j]=(c[j]+d[j])/2.0;
mid[5][j]=(b[j]+d[j])/2.0;
}
divide_tetra(a,mid[0],mid[1],mid[2],m-1);
divide_tetra(mid[0],b,mid[3],mid[5],m-1);
Dept. of CSE, BIT

13

CGV Lab Manual

divide_tetra(mid[1],mid[3],c,mid[4],m-1);
divide_tetra(mid[2],mid[5],mid[4],d,m-1);
}
else
tetra(a,b,c,d);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glClearColor(1.0,1.0,1.0,1.0);
divide_tetra(v[0],v[1],v[2],v[3],n);
glFlush();
}
void myReshape(int w,int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w<=h)
glOrtho(-1.0,1.0,-1.0*((GLfloat)h/(GLfloat)w), 1.0*((GLfloat)h/(GLfloat)w),-1.0,1.0);
else
glOrtho(-1.0*((GLfloat)w/(GLfloat)h),1.0*((GLfloat)w/(GLfloat)h),-1.0,1.0,-1.0,1.0);
glMatrixMode(GL_MODELVIEW);
glutPostRedisplay();
}
void main(int argc,char ** argv)
{
printf( "No of Division?: ");
scanf("%d",&n);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(500,500);
glutCreateWindow( "3D gasket" );
glutDisplayFunc(display);
glutReshapeFunc(myReshape);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
}

Dept. of CSE, BIT

14

CGV Lab Manual

**** Output ***


No. of Divisions ? 2

No. of Divisions ? 3

Dept. of CSE, BIT

15

CGV Lab Manual

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>
#include<stdbool.h>
double xmin=50,ymin=50, xmax=100,ymax=100; // Window boundaries
double xvmin=200,yvmin=200,xvmax=300,yvmax=300; // Viewport boundaries
double x[50],y[50];
int n;
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 edge
if(cliptest(dx,xmax-x0,&te,&tl)) // inside test wrt right edge
if(cliptest(-dy,y0-ymin,&te,&tl)) // inside test wrt bottom edge
if(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;
}
Dept. of CSE, BIT

16

CGV Lab Manual


// Window to viewport mappings
double sx=(xvmax-xvmin)/(xmax-xmin); // Scale parameters
double sy=(yvmax-yvmin)/(ymax-ymin);
double vx0=xvmin+(x0-xmin)*sx;
double vy0=yvmin+(y0-ymin)*sy;
double vx1=xvmin+(x1-xmin)*sx;
double vy1=yvmin+(y1-ymin)*sy;
glColor3f(1.0, 0.0, 0.0); //draw a red colored viewport
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 line
glBegin(GL_LINES);
glVertex2d (vx0, vy0);
glVertex2d (vx1, vy1);
glEnd();
}
}
void display()
{
int i;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINES);
for(i=0;i<n;i++)
{ glVertex2d (x[2*i], y[2*i]);
glVertex2d (x[(2*i)+1], y[(2*i)+1]);
}
glEnd();
glColor3f(0.0, 0.0, 1.0); //draw a blue colored window
glBegin(GL_LINE_LOOP);
glVertex2f(xmin, ymin);
glVertex2f(xmax, ymin);
glVertex2f(xmax, ymax);
glVertex2f(xmin, ymax);
glEnd();
for(i=0;i<n;i++)
LiangBarskyLineClipAndDraw(x[2*i],y[2*i],x[2*i+1],y[2*i+1]);
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, BIT

17

CGV Lab Manual


void main(int argc, char** argv)
{
int i;
printf( "enter no of lines");
scanf(" %d ",&n);
printf("enter the x & y co-ordinates of the line segments");
for(i=0;i<(2*n);i++)
scanf("%lf %lf",&x[i],&y[i]);
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, BIT

18

CGV Lab Manual

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 of Interactive Computer Graphics by Edward Angle*/
/*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);
Dept. of CSE, BIT

19

CGV Lab Manual


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);
}
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);
}
void main(int argc, char **argv)
{
Dept. of CSE, BIT

20

CGV Lab Manual

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, BIT

21

CGV Lab Manual

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

#define BLACK 0
#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 rotatemat[3][3]={{0},{0},{0}};
GLfloat result[3][9]={{0},{0},{0}};
GLfloat arbitrary_x=100.0;
GLfloat arbitrary_y=100.0;
GLfloat rotation_angle;
void multiply()
{
int i,j,k;
for(i=0;i<3;i++)
for(j=0;j<9;j++)
{
result[i][j]=0;
for(k=0;k<3;k++)
result[i][j]=result[i][j]+rotatemat[i][k]*house[k][j];
}
}
void rotate()
{
GLfloat m,n;
m=-arbitrary_x*(cos(rotation_angle) -1) + arbitrary_y * (sin(rotation_angle));
n=-arbitrary_y * (cos(rotation_angle) - 1) -arbitrary_x * (sin(rotation_angle));
rotatemat[0][0]=cos(rotation_angle);
rotatemat[0][1]=-sin(rotation_angle);
rotatemat[0][2]=m;
rotatemat[1][0]=sin(rotation_angle);
rotatemat[1][1]=cos(rotation_angle);
rotatemat[1][2]=n;
rotatemat[2][0]=0;
rotatemat[2][1]=0;
rotatemat[2][2]=1;
//multiply the two matrices
multiply();
}
void drawhouse()
{
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_LINE_LOOP);
Dept. of CSE, BIT

22

CGV Lab Manual


glVertex2f(house[0][0],house[1][0]);
glVertex2f(house[0][1],house[1][1]);
glVertex2f(house[0][3],house[1][3]);
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(house);
rotate();
drawrotatedhouse();
Dept. of CSE, BIT

23

CGV Lab Manual


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)
{
printf("Enter the rotation angle in degree :");
scanf("%f", &rotation_angle);
rotation_angle= (3.14 * rotation_angle) / 180;
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("house rotation");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}

*** Output ***


Enter the rotation angle in degree : 30

Dept. of CSE, BIT

24

CGV Lab Manual

5.Make provision to specify the input line, window for clipping and view port
for displaying the clipped image.
// Cohen-Suderland Line Clipping Algorithm with Window to viewport
Mapping */
#include <stdio.h>
#include <GL/glut.h>
#include<stdbool.h>
double xmin=50,ymin=50, xmax=100,ymax=100; // Window boundaries
double xvmin=200,yvmin=200,xvmax=300,yvmax=300; // Viewport boundaries
//bit codes for the right, left, top, & bottom
const int TOP = 8;
const int BOTTOM = 4;
const int RIGHT= 2;
const int LEFT = 1;
//used to compute bit codes of a poin
int 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 rectangle
int outcode0, outcode1, outcodeOut;
bool accept = false, done = false;
//compute outcodes
outcode0 = ComputeOutCode (x0, y0);
outcode1 = ComputeOutCode (x1, y1);
do{
if ((outcode0 |outcode1)==0) //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 edge
double x, y;
//At least one endpoint is outside the clip rectangle; pick it.
outcodeOut = outcode0? outcode0: outcode1;
float slope=(y1-y0)/(x1-x0);
//Now find the intersection point;
//use formulas y = y0 + slope * (x - x0), x = x0 + (1/slope)* (y - y0)
if (outcodeOut & TOP) //point is above the clip rectangle
Dept. of CSE, BIT

25

CGV Lab Manual


{
x = x0 + (1/slope) * (ymax - y0);
y = ymax;
}
else if (outcodeOut & BOTTOM) //point is below the clip rectangle
{
x = x0 + (1/slope) * (ymin - y0);
y = ymin;
}
else if (outcodeOut & RIGHT) //point is to the right of clip rectangle
{
y = y0 + slope * (xmax - x0);
x = xmax;
}
else //point is to the left of clip rectangle
{
y = y0 + slope* (xmin - 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 parameters
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 a red colored viewport
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xvmin, yvmin);
glVertex2f(xvmax, yvmin);
glVertex2f(xvmax, yvmax);
glVertex2f(xvmin, yvmax);
glEnd();
Dept. of CSE, BIT

26

CGV Lab Manual


glColor3f(0.0,0.0,1.0); // draw blue colored clipped line
glBegin(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)
int ComputeOutCode (double x, double y)
{
int 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 color
glColor3f(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 window
glColor3f(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();
}
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, BIT

27

CGV Lab Manual


}
void main(int argc, char** argv)
{
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, BIT

28

CGV Lab Manual

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.
#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);
}
// Midpoint Circle Drawing Algorithm
void Circle_draw(GLint h, GLint k, GLint r) {
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);
}
}
void parallelepiped(int x1, int x2,int y1, int y2, int y3, int y4)
Dept. of CSE, BIT

29

CGV Lab Manual


{
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 white
glMatrixMode(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 cylinder
parallelepiped_draw();// call parallelepiped
glFlush(); // 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 mode
glutInitWindowPosition(50,50); // Set top left window position
glutInitWindowSize(400,300); // Set Display window width and height
glutCreateWindow("Cylinder and parallelePiped Display by Extruding Circle and
Quadrilaterl "); // Create Display Window
init();
glutDisplayFunc(display); // Send the graphics to Display Window
glutMainLoop();
}

Dept. of CSE, BIT

30

CGV Lab Manual

*** Output ***

Dept. of CSE, BIT

31

CGV Lab Manual

7. Program using OpenGL functions, 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 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>
#include<stdio.h>
void displaySolid(void)
{
double winht;
GLfloat mat_ambient[]={0.7,0.7,0.7,1.0};
GLfloat mat_diffuse[]={0.5,0.5,0.5,1.0};
GLfloat mat_specular[]={1.0,1.0,1.0,1.0};
GLfloat mat_shininess[]={50.0};
GLfloat lightintensity[]={0.7,0.7,0.7,1.0};
GLfloat lightposition[]={2.0,6.0,3.0,0.0};
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);
glLightfv(GL_LIGHT0, GL_POSITION, lightposition);
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightintensity);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-2.0,2.0,-2.0,2.0,-10.0,10.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(2.0,1.0,2.0,0.0,0.2,0.2,0.0,1.0,0.0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glPushMatrix();//teapot
glTranslated(0.4,0.0,0.4);
glRotated(30,0,1,0);
glutSolidTeapot(0.2);
glPopMatrix();
glPushMatrix();//tabletop
glTranslated(0.0,-0.3,0.0);
glScaled(7.0,0.5,7.0);
glutSolidCube(0.2);
glPopMatrix();
glPushMatrix();// front leg
glTranslated(0.5,-0.7,0.5);
glScaled(0.5,7.0,0.5);
glutSolidCube(0.1);
glPopMatrix();
glPushMatrix();// left leg
glTranslated(-0.5,-0.7,0.5);
glScaled(0.5,7.0,0.5);
Dept. of CSE, BIT

32

CGV Lab Manual


glutSolidCube(0.1);
glPopMatrix();
glPushMatrix();// right leg
glTranslated(0.5,-0.7,-0.5);
glScaled(0.5,7.0,0.5);
glutSolidCube(0.1);
glPopMatrix();
glPushMatrix();// back leg
glTranslated(-0.5,-0.7,-0.5);
glScaled(0.5,7.0,0.5);
glutSolidCube(0.1);
glPopMatrix();
glPushMatrix();//left wall
glTranslated(-1.0,0.0,0.0);
glScaled(0.1,10.0,10.0);
glutSolidCube(0.2);
glPopMatrix();
glPushMatrix();//bottom floor
glTranslated(0.0,-1.0,0.0);
glScaled(10.0,0.1,10.0);
glutSolidCube(0.2);
glPopMatrix();
glPushMatrix();//right wall
glTranslated(0.0,0.0,-1.0);
glScaled(10.0,10.0,0.1);
glutSolidCube(0.2);
glPopMatrix();
glFlush();
}
void main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowPosition(50,50);
glutInitWindowSize(400,300);
glutCreateWindow("Shaded Scene");
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();
}

Dept. of CSE, BIT

33

CGV Lab Manual

*** Output ***

Dept. of CSE, BIT

34

CGV Lab Manual

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 point
the 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);
}
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 */
Dept. of CSE, BIT

35

CGV Lab Manual


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();
}
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);
Dept. of CSE, BIT

36

CGV Lab Manual


glutInitWindowSize(500, 500);
glutCreateWindow("Colorcube Viewer");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutKeyboardFunc(keys);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
}

*** Output ***

Dept. of CSE, BIT

37

CGV Lab Manual

9 (a) Program to fill any given polygon using scan-line area filling algorithm.

// 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);
Dept. of CSE, BIT

38

CGV Lab Manual


edgedetect(x2,y2,x3,y3,le,re);
edgedetect(x3,y3,x4,y4,le,re);
edgedetect(x4,y4,x1,y1,le,re);
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();
}

Dept. of CSE, BIT

39

CGV Lab Manual

*** Output ***

Dept. of CSE, BIT

40

CGV Lab Manual

9 (b) Program to fill any given polygon using scan-line area filling algorithm.
(Use appropriate data structures).
#include <GL/glut.h>
#include <stdio.h>
#include<stdbool.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
//Global Edge table
// et contains information as ymin , xmin, ymax,1/m
float et[4][4]={{100,250,200,-1}, //ab
{100,250,200,1},// ad
{200,150,300,1},//bc
{200,350,300,-1}};// dc
int np=4;// number of points
float ae[4][3];
//js is scan line
// find minimum value of scan
float js=et[0][0];
int iaet=0;
int ymax=0;//max val of scan
//add to a e t
void addaet()
{
int i;
for(i=0; i<np;i++)
{
printf("scan line =%f & iate=%d\n",js,iaet);
if(js==et[i][0])
{
ae[iaet][0]=et[i][1];//x min
ae[iaet][1]=et[i][2];//ymax
ae[iaet][2]=et[i][3];//1/m
if(ae[iaet][1]>ymax) ymax=ae[iaet][1];//update ymax value
iaet++;
}
}
}
// update aet
void upaet()
{
int i;
for(i=0;i<np;i++)
ae[i][0]=ae[i][0]+ae[i][2];//x=x+1/m
}
void draw_pixel(float x1,float x2)
{ int i;
float n;
Dept. of CSE, BIT

41

CGV Lab Manual


for(i=0;i<1000;i++)
for(n=x1;n<x2;n++)// fill from x1 to x2
{
glColor3f(1.0,1.0,0.0);
glBegin(GL_POINTS);
glVertex2f(n,js);
glEnd();
glFlush();
}
//glutPostRedisplay();
printf(" x1=%f x2= %f\n",x1,x2);
}
void fill_tri()
{
float x[3]={0,0,0};
int i=0;
bool done=false;
do
{
i=0;
addaet();
printf(" 1=%f 2= %f %f\n",ae[0][1],ae[1][1],js);
if(ae[0][1]>js){x[i]=ae[0][0]; i++;
printf(" 1=%f ae=%f \n ",ae[0][0],x[0]);}
if(ae[1][1]>js){x[i]=ae[1][0]; i++;
printf(" 1=%f ae=%f \n",ae[0][0],x[0]);}
if(ae[2][1]>js){x[i]=ae[2][0]; i++;}
if(ae[3][1]>js){x[i]=ae[3][0]; i++;}
draw_pixel(x[0],x[1]);
upaet();
js++;
}
while(js<=ymax);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0.0,0.0,0.0,1.0);
fill_tri();
glFlush();
}
void myinit()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,499.0,0.0,499.0);
glMatrixMode(GL_MODELVIEW);
// glFlush();
}
void main(int argc, char** argv)
{
glutInit(&argc,argv);
Dept. of CSE, BIT

42

CGV Lab Manual


glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(400,400);
glutInitWindowPosition(100,100);
glutCreateWindow("polygon filling algorithm");
myinit();
glutDisplayFunc(display);
glutMainLoop();
}

*** Output ***

Dept. of CSE, BIT

43

CGV Lab Manual

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


// 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, y
GLint 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, BIT

44

CGV Lab Manual


}
void main(int argc, char** argv)
{
glutInit(&argc, argv); // OpenGL initializations
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // single buffering and RGB
glutInitWindowSize(500, 400); // create a 500x400 window
glutInitWindowPosition(0, 0); // ...in the upper left
glutCreateWindow("Rectangular Mesh"); // create the window
glutDisplayFunc(display); // setup callbacks
init();
glutMainLoop(); // start it running
}

*** Output ***

Dept. of CSE, BIT

45

CGV Lab Manual

Dept. of CSE, BIT

46

Vous aimerez peut-être aussi