CG Lab Manual
CG Lab Manual
CONTENTS
SL No.
Page No.
Introduction to OpenGL
01-07
08-10
Sample programs
11-14
15-17
18-20
3. 3D - Color Cube
21-22
4. 2D House
23-25
5. Cohen-Sutherland line-clipping
26-29
30-32
7. 3D Tea pot
32-33
34-36
37-39
40-41
REFERENCE
42
Annexure
43-47
Viva Questions
48-51
VI Sem. CSE
Introduction to OpenGL
OpenGL is a low-level graphics library specification. It makes available to the programmer a
small set of geometric primitives - points, lines, polygons, images, and bitmaps. OpenGL
provides a set of commands that allow the specification of geometric objects in two or three
dimensions, using the provided primitives, together with commands that control how these
objects are rendered (drawn).
Since OpenGL drawing commands are limited to those that generate simple geometric primitives
(points, lines, and polygons), the OpenGL Utility Toolkit (GLUT) has been created to aid in the
development of more complicated three-dimensional objects such as a sphere, a torus, and even a
teapot. GLUT may not be satisfactory for full-featured OpenGL applications, but it is a useful
starting point for learning OpenGL.
GLUT is designed to fill the need for a window system independent programming interface for
OpenGL programs. The interface is designed to be simple yet still meet the needs of useful
OpenGL programs. Removing window system operations from OpenGL is a sound decision
because it allows the OpenGL graphics system to be retargeted to various systems including
powerful but expensive graphics workstations as well as mass-production graphics systems like
video games, set-top boxes for interactive television, and PCs.
GLUT simplifies the implementation of programs using OpenGL rendering. The GLUT
application programming interface (API) requires very few routines to display a graphics scene
rendered using OpenGL. The GLUT routines also take relatively few parameters.
VI Sem. CSE
Display Lists: All data, whether it describes geometry or pixels, can be saved in a display list for
current or later use. (The alternative to retaining data in a display list is processing the data
immediately-known as immediate mode.) When a display list is executed, the retained data is
sent from the display list just as if it were sent by the application in immediate mode.
Evaluators: All geometric primitives are eventually described by vertices. Evaluators provide a
method for deriving the vertices used to represent the surface from the control points. The
method is a polynomial mapping, which can produce surface normal, colors, and spatial
coordinate values from the control points.
VI Sem. CSE
Per-Vertex and Primitive Assembly: For vertex data, the next step converts the vertices into
primitives. Some types of vertex data are transformed by 4x4 floating-point matrices. Spatial
coordinates are projected from a position in the 3D world to a position on your screen. In some
cases, this is followed by perspective division, which makes distant geometric objects appear
smaller than closer objects. Then view port and depth operations are applied. The results at this
point are geometric primitives, which are transformed with related color and depth values and
guidelines for the rasterization step.
Pixel Operations: While geometric data takes one path through the OpenGL rendering pipeline,
pixel data takes a different route. Pixels from an array in system memory are first unpacked form
one of a variety of formats into the proper number of components. Next the data is scaled, biased,
processed by a pixel map, and sent to the rasterization step.
Rasterization: Rasterization is the conversion of both geometric and pixel data into fragments.
Each fragment square corresponds to a pixel in the frame buffer. Line width, point size, shading
model, and coverage calculations to support antialiasing are taken it to consideration as vertices
are connected into lines or the interior pixels are calculated for a filled polygon. Color and depth
values are assigned for each fragment square. The processed fragment is then drawn into the
appropriate buffer, where it has finally advanced to be a pixel and achieved its final resting place.
1.2 Libraries
OpenGL provides a powerful but primitive set of rendering command, and all higher-level
drawing must be done in terms of these commands. There are several libraries that allow you to
simplify your programming tasks, including the following:
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 and rendering surfaces.
VI Sem. CSE
#include<GL/gl.h>
#include <GL/glu.h>
If you are using the OpenGL Utility Toolkit (GLUT) for managing your window manager tasks,
you should include:
#include <GL/glut.h>
Note that glut.h guarantees that gl.h and glu.h are properly included for you so including these
three files is redundant. To make your GLUT programs portable, include glut.h and do not
include gl.h or glu.h explicitly.
opengl32.lib
glu32.lib
glut32.lib
gl.h
glu.h
glut.h
opengl32.dll
glu32.dll
glut32.dll
VI Sem. CSE
1.5 Initialization
The first thing we need to do is call the glutInit() procedure. It should be called before any
other GLUT routine because it initializes the GLUT library. The parameters to glutInit() should
be the same as those to main(), specifically main(int argc, char** argv) and glutInit(&argc, argv),
where argcp is a pointer to the program's unmodified argc variable from main. Upon return, the
value pointed to by argcp will be updated, and argv is the program's unmodified argv variable
from main. Like argcp, the data for argv will be updated.
The next thing we need to do is call the glutInitDisplayMode() procedure to specify the
display mode for a window. You must first decide whether you want to use an RGBA
(GLUT_RGBA) or color-index (GLUT_INDEX) color model. The RGBA mode stores its color
buffers as red, green, blue, and alpha color components. The forth color component, alpha,
corresponds to the notion of opacity. An alpha value of 1.0 implies complete opacity, and an
alpha value of 0.0 complete transparancy. Color-index mode, in contrast, stores color buffers in
indices. Your decision on color mode should be based on hardware availability and what you
application requires. More colors can usually be simultaneously represented with RGBA mode
than with color-index mode. And for special effects, such as shading, lighting, and fog, RGBA
mode provides more flexibility. In general, use RGBA mode whenever possible. RGBA mode is
the default.
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
Another decision you need to make when setting up the display mode is whether you
want to use single buffering (GLUT_SINGLE) or double buffering (GLUT_DOUBLE).
Applications that use both front and back color buffers are double-buffered. Smooth animation is
accomplished by rendering into only the back buffer (which isn't displayed), then causing the
front and back buffers to be swapped. If you aren't using animation, stick with single buffering,
which is the default.
Finally, you must decide if you want to use a depth buffer (GLUT_DEPTH), a stencil
buffer (GLUT_STENCIL) and/or an accumulation buffer (GLUT_ACCUM). The depth buffer
stores a depth value for each pixel. By using a "depth test", the depth buffer can be used to
display objects with a smaller depth value in front of objects with a larger depth value. The
second buffer, the stencil buffer is used to restrict drawing to certain portions of the screen, just
as a cardboard stencil can be used with a can of spray paint to make a printed image. Finally, the
accumulation buffer is used for accumulating a series of images into a final composed image.
None of these are default buffers.
We need to create the characteristics of our window. A call to glutInitWindowSize() will
be used to specify the size, in pixels, of your initial window. The arguments indicate the height
and width (in pixels) of the requested window. Similarly, glutInitWindowPosition() is used to
specify the screen location for the upper-left corner of your initial window. The arguments, x and
y, indicate the location of the window relative to the entire display.
VI Sem. CSE
the window needs to be redisplayed. Therefore, you should put all the routines that you need to
draw a scene in this display callback function.
VI Sem. CSE
vertex
is
ignored.
GL_LINE_STRIP: Draws a line segment from the first vertex to the last. Lines can intersect
arbitrarily.
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
GL_LINE_LOOP: Same as GL_STRIP, except that a final line segment is drawn from the last
vertex back to the first.
With OpenGL, the description of the shape of an object being drawn is independent of the
description of its color. When a particular geometric object is drawn, it's drawn using the
currently specified coloring scheme. In general, an OpenGL programmer first sets the color,
using glColor*() and then draws the objects. Until the color is changed, all objects are drawn in
that color or using that color scheme.
Polygons: Polygons are the areas enclosed by single closed loops of line segments, where the
line segments are specified by the vertices at their endpoints. Polygons are typically drawn with
the pixels in the interior filled in, but you can also draw them as outlines or a set of points. In
OpenGL, there are a few restrictions on what constitutes a primitive polygon. For example, the
edges of a polygon cannot intersect and they must be convex (no indentations). There are special
commands
for
three-sided
(triangle)
and
four-sided
(quadrilateral)
polygons,
2.3 Transformations
A modeling transformation is used to position and orient the model. For example, you can
rotate, translate, or scale the model - or some combination of these operations. To make an object
appear further away from the viewer, two options are available - the viewer can move closer to
the object or the object can be moved further away from the viewer. Moving the viewer will be
discussed later when we talk about viewing transformations. For right now, we will keep the
default "camera" location at the origin, pointing toward the negative z-axis, which goes into the
screen perpendicular to the viewing plane.
VI Sem. CSE
When transformations are performed, a series of matrix multiplications are actually performed to
affect the position, orientation, and scaling of the model. You must, however, think of these
matrix multiplications occuring in the opposite order from how they appear in the code. The
order of transformations is critical. If you perform transformation A and then perform
transformation B, you almost always get something different than if you do them in the opposite
order.
Scaling: The scaling command glScale() multiplies the current matrix by a matrix that stretches,
shrinks, or reflects an object along the axes. Each x-, y-, and z-coordinate of every point in the
object is multiplied by the corresponding argument x, y, or z. The glScale*() is the only one of
the three modeling transformations that changes the apparent size of an object: scaling with
values greater than 1.0 stretches an object, and using values less than 1.0 shrinks it. Scaling with
a -1.0 value reflects an object across an axis.
Translation: The translation command glTranslate() multiplies the current matrix by a matrix
that moves (translates) an object by the given x-, y-, and z-values.
Rotation: The rotation command glRotate() multiplies the current matrix that rotates an object in
a counterclockwise direction about the ray from the origin through the point (x,y,z). The angle
parameter specifies the angle of rotation in degrees. An object that lies farther from the axis of
rotation is more dramatically rotated (has a larger orbit) than an object drawn near the axis.
VI Sem. CSE
Sample Programs
Sample Program: 01
/* A basic Open GL window*/
#include<GL/glut.h>
void display (void)
{
glClearColor (0.0,0.0,0.0,1.0);
glClear (GL_COLOR_BUFFER_BIT);
glLoadIdentity ();
gluLookAt (0.0,0.0,5.0,0.0,0.0,0.0,0.0,1.0,0.0);
glFlush ();
}
int main (int argc,char **argv)
{
glutInit (&argc,argv);
glutInitDisplayMode (GLUT_SINGLE);
glutInitWindowSize (500,500);
glutInitWindowPosition (100,100);
glutCreateWindow ("A basic open GL window");
glutDisplayFunc (display);
glutMainLoop ();
return 0;
}
Sample Program: 02
/*Program to create a teapot*/
#include<GL/glut.h>
void cube(void)
{
glutWireTeapot(2);
}
void display(void)
{
glClearColor(0.0,0.0,0.0,1.0);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
gluLookAt(0.0,0.0,5.0,0.0,0.0,0.0,0.0,1.0,0.0);
cube();
glFlush();
}
void reshape(int w,int h)
{
glViewport(0,0,(GLsizei)w,(GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60,(GLfloat)w/(GLfloat)h,1.0,100.0);
glMatrixMode(GL_MODELVIEW);
}
int main(int agrc,char**agrv)
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
{
glutInit(&agrc,agrv);
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowSize(500,500);
glutInitWindowPosition(100,100);
glutCreateWindow("A basic OpenGL Window");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
Sample Program: 03
/* Program to create a cube*/
#include<GL/glut.h>
void cube(void)
{
glutWireCube(2);
}
void display(void)
{
glClearColor(0.0,0.0,0.0,1.0);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
gluLookAt(0.0,0.0,5.0,0.0,0.0,0.0,0.0,1.0,0.0);
cube();
glFlush();
}
void reshape(int w,int h)
{
glViewport(0,0,(GLsizei)w,(GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60,(GLfloat)w/(GLfloat)h,1.0,100.0);
glMatrixMode(GL_MODELVIEW);
}
int main(int agrc,char** agrv)
{
glutInit(&agrc,agrv);
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowSize(500,500);
glutInitWindowPosition(100,100);
glutCreateWindow("A basic OpenGL Window");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
VI Sem. CSE
Sample Program: 04
/*point.c
/* Program to draw/display points */
#include<GL/glut.h>
#include<stdlib.h>
void myInit(void)
{
glClearColor(2.0,2.0,2.0,4.0);
glColor3f(0.0f,0.0f,0.0f);
glPointSize(4.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,640.0,0.0,480.0);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POINTS);
glVertex2i(100,200);
glVertex2i(400,200);
glVertex2i(200,100);
glVertex2i(200,400);
glEnd();
glFlush();
}
void main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(100,150);
glutCreateWindow("My First Attempt");
glutDisplayFunc(display);
myInit();
glutMainLoop();
}
Sample Program: 05
/*program to implement horizontal and vertical lines*/
#include<GL/glut.h>
#include<stdlib.h>
void myInit(void)
{
glClearColor(2.0,2.0,2.0,4.0);
glColor3f(0.0f,0.0f,0.0f);
glLineWidth(4.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,640.0,0.0,480.0);
}
void drawLineInt(GLint x1,GLint y1,GLint x2,GLint y2)
{
glBegin(GL_LINES);
glVertex2i(x1,y1);
glVertex2i(x2,y2);
glEnd();
}
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINES);
glVertex2i(100,200);
glVertex2i(400,200);
glVertex2i(200,100);
glVertex2i(200,400);
glEnd();
glFlush();
}
void main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(100,150);
glutCreateWindow("My First Attempt");
glutDisplayFunc(display);
myInit();
drawLineInt(100,200,40,60);
glutMainLoop();
}
VI Sem. CSE
LAB PROGRAMS:
Program No: 01
Date:
v1[j]=(a[j]+b[j])/2;
v2[j]=(a[j]+c[j])/2;
v3[j]=(b[j]+c[j])/2;
v1, v2, m-1);
v2, v3, m-1);
v3, v1, m-1);
/* draw triangle at end of recursion */
}
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
v[2], m);
v[1], m);
v[1], m);
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);
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);
glutCreateWindow("3D Gasket");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glEnable(GL_DEPTH_TEST);
glClearColor (1.0, 1.0, 1.0, 1.0);
glutMainLoop();
}
VI Sem. CSE
Output:-
Date:
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
Program No: 02
Date:
Algorithm
1. Set
and
2. Calculate the values of tL, tR, tT, and tB (tvalues).
if
or
ignore it and go to the next edge
otherwise classify the tvalue as entering or exiting value (using inner product to
classify)
if t is entering value set
3. If
then draw a line from (x1 + dx*tmin, y1 + dy*tmin) to (x1 + dx*tmax, y1
+ dy*tmax)
4. If the line crosses over the window, you will see (x1 + dx*tmin, y1 + dy*tmin) and (x1 +
dx*tmax, y1 + dy*tmax) are intersection between line and edge.
Program
// 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 boundaries
double 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);
}
VI Sem. CSE
VI Sem. CSE
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("Liang Barsky Line Clipping Algorithm");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
Output:-
Date:
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
Program No: 03
Date:
3D - Color Cube
AIM: - Program to draw a color cube and spin it using OpenGL transformation
matrices
/* Rotating cube with color interpolation */
#include <stdlib.h>
#include <GL/glut.h>
GLfloat vertices[] = {-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[] = {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};
GLubyte cubeIndices[]={0,3,2,1,2,3,7,6,0,4,7,3,1,2,6,5,4,5,6,7,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);
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, cubeIndices);
/*glBegin(GL_LINES);
glVertex3f(0.0,0.0,0.0);
glVertex3f(1.0,1.0,1.0);
glEnd(); */
glFlush();
glutSwapBuffers();
}
void spinCube()
{
/* Idle callback, spin cube 2 degrees about selected axis */
theta[axis] += 2.0;
if( theta[axis] > 360.0 ) theta[axis] -= 360.0;
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;
}
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
Output:-
Date:
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
Program No: 04
Date:
2D - House
AIM: - 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>
#define PI 3.1425
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 matrix
m=-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]);
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]);
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
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();
}
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");
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
scanf("%f", &theta);
theta= theta*PI/180;
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("house rotation");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
Output:In command prompt enter the rotation angle=45 result look as below
Date:
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
Program No: 05
Date:
Cohen-Sutherland line-clipping
AIM: - Program to implement the Cohen-Sutherland line-clipping algorithm. 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>
#define outcode int
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 INSIDE = 0;
//0000
const int LEFT = 1;
//0001
const int RIGHT = 2;
//0010
const int BOTTOM = 4;
//0100
const int TOP = 8;
//1000
/*used to compute bit codes of a point*/
outcode 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*/
outcode outcode0, outcode1, outcodeOut;
bool accept = false, done = false;
/*compute outcodes*/
outcode0 = ComputeOutCode (x0, y0);
outcode1 = ComputeOutCode (x1, y1);
do{
if (!(outcode0 | outcode1))
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;
//Now find the intersection point;
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
VI Sem. CSE
VI Sem. CSE
//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:-
Date:
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
Program No: 06
Date:
VI Sem. CSE
Output:-
Date:
Program No: 07
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
3D Tea pot
AIM: - 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>
void obj(double tx,double ty,double tz,double sx,double sy,double sz)
{
glRotated(50,0,1,0);
glRotated(10,-1,0,0);
glRotated(11.7,0,0,-1);
glTranslated(tx,ty,tz);
glScaled(sx,sy,sz);
glutSolidCube(1);
glLoadIdentity();
}
void display()
{
glViewport(0,0,700,700);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
obj(0,0,0.5,1,1,0.04); // three walls
obj(0,-0.5,0,1,0.04,1);
obj(-0.5,0,0,0.04,1,1);
obj(0,-0.3,0,0.02,0.2,0.02);
// four table legs
obj(0,-0.3,-0.4,0.02,0.2,0.02);
obj(0.4,-0.3,0,0.02,0.2,0.02);
obj(0.4,-0.3,-0.4,0.02,0.2,0.02);
obj(0.2,-0.18,-0.2,0.6,0.02,0.6);
// table top
glRotated(50,0,1,0);
glRotated(10,-1,0,0);
glRotated(11.7,0,0,-1);
glTranslated(0.3,-0.1,-0.3);
glutSolidTeapot(0.09);
glFlush();
glLoadIdentity();
}
void main()
{
float ambient[]={1,1,1,1};
float light_pos[]={27,80,2,3};
glutInitWindowSize(700,700);
glutCreateWindow("scene");
glutDisplayFunc(display);
glEnable(GL_LIGHTING);
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
glEnable(GL_LIGHT0);
glMaterialfv(GL_FRONT,GL_AMBIENT,ambient);
glLightfv(GL_LIGHT0,GL_POSITION,light_pos);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
}
Output:-
Date:
Program No: 08
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
VI Sem. CSE
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)
{
if(key == 'x')
if(key == 'X')
if(key == 'y')
if(key == 'Y')
if(key == 'z')
if(key == 'Z')
display();
viewer[0]-=
viewer[0]+=
viewer[1]-=
viewer[1]+=
viewer[2]-=
viewer[2]+=
1.0;
1.0;
1.0;
1.0;
1.0;
1.0;
}
void myReshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w<=h) glFrustum(-2.0, 2.0, -2.0 * (GLfloat) h/ (GLfloat) w,
2.0* (GLfloat) h / (GLfloat) w, 2.0, 20.0);
glMatrixMode(GL_MODELVIEW);
}
void
{
Date:
VI Sem. CSE
Program No: 09
VI Sem. CSE
Date:
VI Sem. CSE
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();
}
VI Sem. CSE
Output:-
Date:
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
Program No: 10
Date:
Rectangular mesh
AIM: - 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, 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, CIT,Gubbi -572 216.
VI Sem. CSE
Output:-
Date:
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
References
1. Edward Angel: Interactive Computer Graphics A Top-Down Approach with OpenGL, 5th
Edition, Addison-Wesley, 2008.
2. F.S. Hill,Jr.: Computer Graphics Using OpenGL, 2nd Edition, Pearson education, 2001.
3. James D Foley, Andries Van Dam, Steven K Feiner, John F Hughes, Computer Graphics,
Addison-wesley 1997.
4. Donald Hearn and Pauline Baker: Computer Graphics- OpenGL Version, 2nd Edition,
Pearson Education, 2003.
VI Sem. CSE
Annexures
Basic 2D Drawing
glBegin (mode);
glBegin delimit the vertices of a primitive or a group of like primitives
Mode
Specifies the primitive or primitives that will be created from vertices presented
between glBegin and
the
subsequent glEnd.
Ten
symbolic
constants
are
VI Sem. CSE
Projection Transformations
glMatrixMode (mode);
glMatrixMode specify which matrix is the current matrix
Mode - Specifies which matrix stack is the target for subsequent matrix operations. Three
values are accepted: GL_MODELVIEW, GL_PROJECTION, and GL_TEXTURE. The
initial value is GL_MODELVIEW. Additionally, if the GL_ARB_imaging extension is
supported, GL_COLOR is also accepted.
glLoadIdentity ( );
VI Sem. CSE
zNear
Specifies the distance from the viewer to the near clipping plane (always positive).
zFar
Specifies the distance from the viewer to the far clipping plane (always positive).
glOrtho( ) - multiply the current matrix with an orthographic matrix.
glOrtho (left, right, bottom, top, near, far); - Default = (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)
gluOrtho2D - define a 2D orthographic projection matrix.
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);
This
is
the
default
if
GLUT_RGB
An alias for GLUT_RGBA.
GLUT_INDEX
Bit mask to select a color index mode window. This overrides GLUT_RGBA if it is also
specified.
Dept. of CSE, CIT,Gubbi -572 216.
GLUT_SINGLE
Bit mask to select a single buffered window. This
neither GLUT_DOUBLE or GLUT_SINGLE are specified.
VI Sem. CSE
is
the
default
if
GLUT_DOUBLE
Bit mask to select a double buffered window. This overrides GLUT_SINGLE if it is also
specified.
GLUT_ACCUM
Bit mask to request a window with an accumulation buffer.
GLUT_ALPHA
Bit mask to request a window with an alpha component to the color buffer(s).
GLUT_DEPTH
Bit mask to request a window with a depth buffer.
GLUT_STENCIL
Bit mask to request a window with a stencil buffer.
glutInitWindowSize (width, height);
glutInitWindowPosition (x, y);
glutCreateWindow (label);
glClear (GL_COLOR_BUFFER_BIT);
Registering Callbacks
glutDisplayFunc (callback);
glutReshapeFunc (callback);
glutDisplayFunc (callback);
glutMotionFunc (callback);
glutPassiveMotionFunc (callback);
glutMouseFunc (callback);
glutKeyboardFunc (callback);
id = glutCreateMenu (callback);
glutMainLoop ( );
VI Sem. CSE
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.
VI Sem. CSE
VI Sem. CSE
camera, where the camera aperture is described as a point and no lenses are used to focus
light.
13. Define digital image?
A digital image is a representation of a two-dimensional image using ones and zeros
(binary). Without qualifications, the term "digital image" usually refers to raster images.
14. Define Grayscale?
A grayscale or greyscale digital image is an image in which the value of each pixel is a
single sample, that is, it carries only intensity information.
15. Define Pinhole Camera?
A pinhole camera is a very simple camera with no lens and a single very small aperture.
Simply explained, it is a light-proof box with a small hole in one side.
16. Define CCD?
A charge-coupled device (CCD) is an analog shift register that enables the transportation
of analog signals (electric charges) through successive stages (capacitors), controlled by a
clock signa.
17. Define Image Resolution?
Image resolution describes the detail an image holds. The term applies equally to digital
images, film images, and other types of images. Higher resolution means more image
detail.
18. Define Wavelength?
Wavelength is the distance between repeating units of a propagating wave of a given
frequency.
19. What is an Electromagnetic Spectrum?
The electromagnetic (EM) spectrum is the range of all possible electromagnetic
radiation frequencies. The "electromagnetic spectrum" (usually just spectrum) of an
object is the characteristic distribution of electromagnetic radiation from that particular
object.
20. Define Halftone?
Halftone is the reprographic technique that simulates continuous tone imagery through
the use of dots, varying either in size or in spacing. 'Halftone' can also be used to refer
specifically to the image that is produced by this process.
21. Define WCS?
World Coordinate Systems. While every point in the FITS data array can be located in
the coordinate system determined by the array axes. World Coordinate Systems (WCS)
are any coordinate systems that describe the physical coordinate associated with a data
array, such as sky coordinates.
22. What is OpenGL?
OpenGL(R) is the software interface for graphics hardware that allows graphics
programmers to produce high-quality color images of 3D objects. OpenGL is a rendering
only, vendor neutral API providing 2D and 3D graphics functions, including modeling,
transformations, color, lighting, smooth shading, as well as advanced features like texture
Dept. of CSE, CIT,Gubbi -572 216.
VI Sem. CSE
mapping, NURBS, fog, alpha blending and motion blur. OpenGL works in both
immediate and retained (display list) graphics modes.
OpenGL is window system and operating system independent. OpenGL has been
integrated with Windows NT and with the X Window System under UNIX. Also,
OpenGL is network transparent. A defined common extension to the X Window System
allows an OpenGL client on one vendor's platform to run across a network to another
vendor's OpenGL server
23. What hardware supports the OpenGL API?
Many vendors have developed or are developing implementations of the OpenGL API for
a variety of embedded hardware devices including aircraft avionics, PDAs (personal
digital assistants such as PalmTM), cellular phones, game consoles (Sony Playstation 2),
television set-top boxes, and display devices (X-Terms and network computers). The
small size of the OpenGL API, its open nature, and now free use of the sample
implementation make the OpenGL API an ideal graphics library for these types of
applications.
24. What are the benefits of OpenGL for hardware and software developers?
Industry standard
Evolving.
Scalable.
Easy to use.
Well-documented.
VI Sem. CSE
A simple method for zooming is to use a uniform scale on the ModelView matrix.
However, this often results in clipping by the zNear and zFar clipping planes if the model
is scaled too large. A better method is to restrict the width and height of the view volume
in the Projection matrix. For example, your program might maintain a zoom factor based
on user input, which is a floating-point number. When set to a value of 1.0, no zooming
takes place. Larger values result in greater zooming or a more restricted field of view,
while smaller values cause the opposite to occur.
28. How do I get a specified point (XYZ) to appear at the center of the scene?
gluLookAt() is the easiest way to do this. Simply set the X, Y, and Z values of your point
as the fourth, fifth, and sixth parameters to gluLookAt ().
29. Define Instruction Pipeline?
An instruction pipeline is a technique used in the design of computers and other digital
electronic devices to increase their instruction throughput (the number of instructions that
can be executed in a unit of time).
30. Define Geometric Pipeline?
Geometric manipulation of modeling primitives, such as that performed by a Geometry
Pipeline, is the first stage in computer graphics systems which perform image generation
based on geometric models.
31. Define Perspective Projection?
Perspective (from Latin perspicere, to see through) in the graphic arts, such as drawing,
is an approximate representation, on a flat surface (such as paper), of an image as it is
perceived by the eye. The two most characteristic features of perspective are that objects
are drawn.