You are on page 1of 61

SRI VENKATESWARA COLLEGE OF ENGINEERING

PENNALUR, SRIPERUMBUDUR.

LAB MANUAL
CS2405 - COMPUTER GRAPHICS LABORATORY
YEAR : IV CSE
SEMESTER : 7

Prepared by

Approved by

Mr.K.Srinivasan ,
Ms. G.Janakasudha, Ms.U.Abirami,
AP/CS

Dr.R.Nedunchelian
HOD/CS

Signature

Name

Date

LAB MANUAL

LM-CS2405
LM Rev. No:00
Date: 30/0/2015

Sub Code & Name: CS2405 - COMPUTER


GRAPHICS LABORATORY
Branch: CS

Semester: 7

LIST OF EXPERIMENTS
1. Implementation of Bresenhams Algorithm Line, Circle, Ellipse.
2. Implementation of Line, Circle and ellipse attributes.
3. Two Dimensional transformations - Translation, Rotation, Scaling, Reflection, Shear.
4. Composite 2D Transformations.
5. Cohen Sutherland 2D line clipping and Windowing
6. Sutherland Hodgeman Polygon clipping Algorithm.
7. Three dimensional transformations - Translation, Rotation, Scaling.
8. Composite 3D transformations.
9. Drawing three dimensional objects and Scenes.
10. Generating Fractal images.

TOTAL: 60 PERIODS

LP: CS2405
Department of Computer Science and Engineering
B.E/B.Tech/M.E/M.Tech :

PG Specialisation

Computer Science and Engineering

Regulation:2008

Rev. No: 00
Date: 30.06.2015

:--

Sub. Code / Sub. Name : CS2405/Computer Graphics Lab

Session No*

List of Experiments
CYCLE-I

Introduction to Graphics functions

Implementation of Line, Circle and Ellipse attributes

Implementation of DDA algorithm

Implementation of Bresenhams Line drawing algorithm

Implementation of Midpoint Circle drawing Algorithm

Implementation of Midpoint Ellipse drawing Algorithm

Implementation of Cohen Sutherland line clipping algorithm

Implementation of Sutherland Hodgman Polygon clipping algorithm


CYCLE-II

Two Dimensional Transformation - Translation, Rotation,

10

Two Dimensional Transformation - Scaling, Reflection, Shear

11

Composite 2D transformations

12

Three Dimensional Transformation - Translation, Rotation,

13

Three Dimensional Transformation - Scaling, Reflection, Shear

14

Introduction to OPENGL Basic programs

15

Three dimensional transformations - Translation, Rotation, Scaling using OpenGL

16

Composite 3D transformations using OpenGL

17

Drawing three dimensional Objects

18

Drawing three dimensional Scenes

19

Generating Fractal images

20

Model Lab Exam

Content beyond syllabus (if any):Implementation of DDA algorithm


* Session Duration: 150 minutes

Sub. Code / Sub. Name: CS2405 / COMPUTER GRAPHICS LAB

Course Outcomes:
Course Outcome 1: The student will know the basic concepts of computer graphics
Course Outcome 2: The student will be able to implement scan conversion and clipping algorithms using C
programming
Course Outcome 3: The student will know the different type of geometric transformation of objects like
rotation, translation, scaling in 2D and 3D
Course Outcome 4: The student will be able to implement modeling, rendering, viewing of objects and scenes
in 3D using OpenGL
Course Outcome 5: The student will be able to Identify and Generate Fractal images

Mapping CO PO :
PO1

PO2

PO3

CO1

CO2

CO3

CO4

CO5

PO4

PO5

PO6

PO7

PO8

A
C

PO9

PO10

PO11

A Excellent ; B Good; C - Average

Sub. Code / Sub. Name: CS2405 / COMPUTER GRAPHICS LAB

Prepared by

Approved by

Signature

Name
Designation
Date
Remarks* :

K.Srinivasan
G.Janakasudha
U.Abirami
Assistant Professor/CS
30/06/2015

Dr.R.Nedunchelian
Professor & HOD/CS

Remarks* :

* If the same lab plan is followed in the subsequent semester/year it should be mentioned and
signed by the Faculty and the HOD

EX.NO:1

INTRODUCTION TO GRAPHICS FUNCTIONS

AIM:
To introduce various graphics functions.
DESCRIPTION:

graphics.h
The 'graphics.h' header file is used to declare graphics functions. It declares prototypes for the
graphics functins. Some of the standard member functions of graphics.h header files are as
follows,

Function Name

Description

Syntax

initgraph()

initializes the graphics system by loading a

Void initgraph(int *graphdriver, int


*graphmode, char *pathtodriver);

graphics driver from disk then putting the


system in graphics mode.
closegraph()

void closegraph(int

closegraph deallocates all memory allocated by wid=ALL_WINDOWS);


the graphics system, then restores the screen to
the mode it was in before you called initgraph

line()

line draws a line in the current color, using the

void line(int x1, int y1, int x2, int


y2);

current line style and thickness between the

bar()

circle()

cleardevice()

two points specified, (x1,y1) and (x2,y2)


bar draws a filled-in, rectangular, twodimensional bar. The bar is filled using the
current fill pattern and fill color. bar does not
outline the bar; to draw an outlined twodimensional bar, use bar3d with depth equal to
0.
circle draws a circle in the current drawing
color with its center at (x,y) and the radius
given by radius.
cleardevice erases (that is, fills with the current
background color) the entire graphics screen
and moves the CP (current position) to home
(0,0).
6

void bar(int left, int top, int right,


int bottom);

void circle(int x, int y, int radius);

void cleardevice(void);

rectangle draws a rectangle in the current line


style, thickness, and drawing color. (left,top) is
the upper left corner of the rectangle, and
(right,bottom) is its lower right corner.

void rectangle(int left, int top, int


right, int bottom);

setcolor sets the current drawing color to color,


which can range from 0 to getmaxcolor. The
current drawing color is the value to which
pixels are set when lines, and so on are drawn.
The drawing colors shown below are available
for the CGA and EGA, respectively
ellipse draws an elliptical arc in the current
drawing color with its center at (x,y) and the
horizontal and vertical axes given by xradius
and yradius, respectively. The ellipse travels
from stangle to endangle. If stangle equals 0
and endangle equals 360, the call to ellipse
draws a complete ellipse.
Draws an ellipse using (x,y) as a center point
and xradius and yradius as the horizontal and
vertical axes, and fills it with the current fill
color and fill pattern
setbkcolor sets the background to the color
specified.

void setcolor(int color);

moveto()

moveto moves the current position (CP) to


viewport position (x,y).

void moveto(int x, int y);

outtext()

outtext displays a text string in the viewport,


using the current font, direction, and size.

void outtext(char *textstring);

rectangle()

setcolor()

ellipse()

fillellipse()

setbkcolor()

void ellipse(int x, int y, int stangle,


int endangle, int xradius, int
yradius);

void fillellipse(int x, int y, int


xradius, int yradius);

void setbkcolor(int color);

EX.NO:2

IMPLEMENTATION OF LINE, CIRCLE AND ELLIPSE


ATTRIBUTES

AIM:
To introduce various graphics functions and implement basic functions and line, circle , ellipse
attributes.
Creating Day & night effects
Aim :
To create day and night effects for a house using inbuilt functions in C.
Procedure:
1.
2.
3.
4.
5.
6.
7.
8.

Include all necessary header files


Initialize the graphics driver using initgraph()
Draw house using rectangle() and line() functions
Set background colors using setbkcolor()
Use putpixel() to display stars randomly using random()
Use delay() function to see the changes gradually.
Use outtext() and moveto() functions display the necessary text.
Using closegraph() close the driver.

SAMPLE OUTPUT:

EX.NO:3

LINE GENERATION USING DIGITAL DIFFERENTIAL ALGORITHM

AIM:
To implement Digital Differential Analyser line drawing algorithm.
ALGORITHM:
1. Get the coordinates (x1,y1) & (x2,y2) from the user.
2. Use the initgraph() function to go to the graph mode.
3. Calculate dx and dy as the difference in x-coordinates and y-coordinates respectively.
4. Check if abs(dx) is greater than abs(dy). If true, then assign abs(dx) as steps. Else assign
abs(dy) as steps.
5. Calculate dx/steps. Let that value be x_increment.
6. Calculate dy/steps. Let that value be y_increment.
7. Set x1 as x and y1 as y.
8. Use putpixel function to color the first pixel.
9. Increment x by x_increment and y by y_increment.
10. Use putpixel function to color the other pixels.
11. Repeat steps 9 and 10 for values of k from 1 to steps.
12. Stop.
SAMPLE OUTPUT:
Enter the coordinates x1,y1,x2,y2: 20 40 50 70

Press 1 to continue. 1
Enter the coordinates x1,y1,x2,y2: 70 20 30 50

Press 1 to continue. 1
Enter the coordinates x1,y1,x2,y2: 40 60 20 10

Press 1 to continue. 1
Enter the coordinates x1,y1,x2,y2:20 20 10 50

Press 1 to continue. 2

10

EX. NO: 4

LINE GENERATION USING BRESENHAMS ALGORITHM

AIM:
To implement Bresenhams line generation algorithm.
ALGORITHM:
1. Get the coordinates (x1,y1) & (x2,y2) from the user.
2. Calculate dx and dy as the absolute difference in x and y coordinates respectively.
Calculate the slope, m=dy/dx.
3. Check if dx is greater than dy. If true, then it is a Gentle Case. Else it is a Steep Case.
4. If m<1 and m>0, it is a Gentle Positive Case or m>-1 and m<0, it is a Gentle Negative
Case, then do the following,
a) Calculate the constants p,c1,c2 as follows:
P=2*dy-dx
C1=2*dy
C2=2*(dy-dx)
b) If x1 is greater than x2 then make the starting coordinates as(x2,y2) and x1 will be
the end of x-coordinate.Else the starting coordinates will be (x1,y1) and x2 will be
the end of x- coordinate.
c) Colour the first pixel using putpixel function.
d) Do the following steps till end of x coordinate is reached.
i)
Increment x by 1.
ii)
Check if p is negative. If so, then add c1 to p.
iii)
Else check if y2 is greater than y1. If so then increment y by 1. Else
decrement y by1. Add c2 to p.
iv)
Use putpixel function to color the pixels.
5. If m>1 it is a Steep Positive Case or if m<-1, it is a Steep Negative Case, then do the
following,
a) Calculate the constants p,c1,c2 as follows:
P=2*dx-dy
C1=2*dx
C2=2*(dx-dy)
b) If y1 is greater than y2 then make the starting coordinates as(x2,y2) and y1 will
be the end of y-coordinate. Else the starting coordinates will be (x1,y1) and y2
will be the end of y-coordinate.
c) Colour the first pixel using putpixel function.
d) Do the following steps till end of x coordinate is reached.
v)
Increment y by 1.
vi)
Check if p is negative. If so, then add c1 to p.
vii)
Else check if x2 is greater than x1. If so then increment x by 1. Else
decrement x by1. Add c2 to p.
11

viii) Use putpixel function to color the pixels.


6. As special cases, we also check if slope=0,slope=infinity,slope=1.
7. If slope=0, then we get a horizontal line.
8. If slope=infinity, then we get a vertical line.
9. If slope=1, then we get a diagonal line.
10. Stop
SAMPLE OUTPUT:
Enter the coordinates x1, y1, x2, y2: 20 40 50 70
This is Gentle Positive Case!

Do u want to continue??1-yes 2-No 1


Enter the coordinates x1, y1, x2, y2: 70 20 30 50
This is Gentle Negative Case!

Do u want to continue??1-yes 2-No 1


Enter the coordinates x1, y1, x2, y2: 40 60 20 10
This is Steep Positive Case!

Do u want to continue??1-yes 2-No 1


Enter the coordinates x1, y1, x2, y2:20 20 10 50
This is Steep Negative Case!

12

Do u want to continue??1-yes 2-No 1


Enter the coordinates x1,y1,x2,y2: 40 30 40 50
Special Case !

Do u want to continue??1-yes 2-No 1


Enter the coordinates x1,y1,x2,y2: 20 40 50 40
Special Case !

Do u want to continue??1-yes 2-No

13

EX. NO: 5

CIRCLE GENERATION USING MID POINT ALGORITHM

AIM:
To draw a circle using mid point algorithm.
ALGORITHM:
1. Use initgraph function to initialize the graphics mode.
2. Get the radius and the centre coordinates of the circle as input.
3. Initialize xi=0,yi=radius.
4. Calculate pi=1-radius (the initial decision parameter).
5. Check if xi<=yi. If true, repeat steps 6 & 7. Else go to step 8.
6. Check if pi is less than zero.
a. If true, then the next coordinate will be (xi+1,yi) and
set pi (the decision parameter) as pi=pi+(2*xi)+1.
Plot the point (xi+1,yi) using putpixel function.
b) Else the next coordinate will be (xi+1,yi-1) and
set pi (the decision parameter) as pi=pi+(2*xi)+1-(2*yi).
Plot the point (xi+1,yi-1) using putpixel function.
7. Plot the other points by symmetry in the other seven octants (by the property of the
circle) using putpixel function.
8.

Stop.

SAMPLE OUTPUT:
Enter the radius: 40
Enter the centre coordinates: 0 0

14

EX.NO:6

ELLIPSE GENERATING ALGORITHM

AIM:
To implement the ellipse generating algorithm.
ALGORITHM:
1. Get the center co-ordinates.
2. Get the major and minor axis radii,say ry and rx.
3. Use initgraph() function to initialize graphics mode.
4. Initialise x to 0 and y to ry.
5. Region 1 is obtained by following manipulations
a)calculate p as (ry*ry)-(rx*rx*ry)+(1/4)(rx*rx)
b)if p<0,then calculate the following
x=x+1
y remains same
p=p+(2*ry*ry*x)+(2*ry*ry)-(2*rx*rx*y)+(2*rx*rx)+(ry*ry)
c)else,
x=x+1
y=y-1
p=p+(2*ry*ry*x)+(2*ry*ry)-(2*rx*rx*y)+(2*rx*rx)+(ry*ry)
d)repeat steps b) and c) until (2*ry*ry*x)>=(2*rx*rx*y)
6. Region 2 is obtained by following manipulations
a) calculate p as (ry*ry)*pow((x+0.5),2)+(rx*rx)*pow((y-1),2)-(rx*rx*ry*ry)
where x and y are points where we move to region2.
b)if (p>0)
p=p+((rx*rx)-(2*rx*rx*y)+(2*ry*ry*x)+(2*ry*ry))
y=y-1
x =x+1.
c)else,
x remains same.
p=p+((2*ry*ry*x)-(2*rx*rx*y)+(rx*rx)
y=y-1
d)repeat steps b) and c) until (2*ry*ry*x)>=(2*rx*rx*y)
7. Use putpixel() function to colour the pixels.

15

SAMPLE OUTPUT:

16

EX. NO: 7

COHEN SUTHERLAND LINE CLIPPING ALGORITHM

AIM:
To implement Cohen Sutherland line clipping algorithm.
ALGORITHM:
1.
2.
3.
4.

Declare all the required variables.


Call the initgraph function to go to the graph mode.
Get the coordinates of the line as well as that of the window (xmin,ymin,xmax,ymax).
Use an encode function to find the codes of the end points of the line.
Encode function:

Let code1 and code2 be two integer arrays each of size 4 that represent the codes
of the end points of the line.
Check if x is lesser than xmin. If true then set code[0] as true. Else set it as false.
Check if x is greater than xmax. If true then set code[1] as true. Else set it as false.
Check if y is lesser than ymin. If true then set code[2] as true. Else set it as false.
Check if y is greater than ymax. If true then set code[3] as true. Else set it as false.
5. Check if the line is within the boundary of the window using accept function.
Accept function:
Perform bitwise or operation of code1 and code2. If true, then return value is 1.
Else it is zero.
6. Check if the line lies completely outside the boundary of the window using reject
function.
Reject function:
Perform bitwise and operation of code1 and code2. If true, then return value is
1. Else it is zero.
7. If conditions 5 and 6 are not satisfied, then it means the line cuts the boundary of the
window and we should find the interesting points. Do the following steps: Call the swap function where x1,y1 is set as the point outside the window and
code1 to contain its code.
Find slope(m) of the line.
If code1[0] is set as 1 then
Y1=y1+(xmin-x1)*m;
X1=xmin;
If code1[1] is set as 1 then
Y1=y1+(xmax-x1)*m;
X1=xmax;
If code1[2] is set as 1 then
x1=x1+(ymin-y1)/m;
y1=ymin;
If code1[0] is set as 1 then
17

x1=x1+(ymax-y1)/m;
y1=xmax;
8. Do steps 4 to 7 until the line is completely accepted or rejected.
9. Stop.

SAMPLE OUTPUT:
Enter the Line coordinates : 10 10 10 50
Enter xmin,xmax,ymin,ymax:20 20 60 60

Line is Rejected..!!!
Enter the Line coordinates : 30 30 30 50
Enter xmin,xmax,ymin,ymax:20 20 60 60

Line is Accepted..!!
Enter the Line coordinates : 10 70 70 50
Enter xmin,xmax,ymin,ymax:20 20 60 60

18

The line clipping is depicted below:

X1:40.000 Y1:60.000
X2:60.000 Y2:53.333

19

EX.NO: 8

SUTHERLAND HODGEMAN POLYGON CLIPPING ALGORITHM

AIM:
To perform polygon clipping algorithm using Sutherland- Hodgeman polygon clipping
algorithm.
ALGORITHM:
1.
2.
3.
4.
5.
6.

Declare all the required variables.


Call the initgraph function to go to the graph mode.
Get the coordinates of the line as well as that of the window (xmin,ymin,xmax,ymax).
Get the coordinates of the polygon to be clipped.
Consider the following 4 conditions
a) If both the vertices of a particular edge of a polygon is lying outside save none of the
points.
b) If the first vertex is inside and the second vertex of an edge is outside, then save the
intersection point of the polygon edge with the window boundary and added to the output
list.
c) If the first vertex is outside and the second vertex is inside, then save both the
intersection point of the polygon edge with the window boundary and the second vertex
are saved and added to the output list.
d) If both the vertices of an edge are inside the window boundary, then save only the
second vertex to the output list.
7. Display the vertices that are saved in the output list to view the clipped polygon with
respect to the given window boundary coordinates.
SAMPLE OUTPUT:
Enter xmin,xmax,ymin,ymax:20 20 60 60

20

EX NO : 9 & 10

2D TRANSFORMATIONS

AIM :
To perform translation, scaling, reflection, rotation and scaling transformations on the
given 2d object
ALGORITHM:
The 2d object is first drawn using the given coordinates.
The transformations are performed as follows
Translation:
The values of tx,ty and tz are obtained from the user.
The translation vector tx,ty and tz are added to the original coordinates to get the new
coordinates.
Rotation:
Get .Obtain the new coordinates as:
x=xcos-ysin
y=xsin+ycos
Scaling:
Get sx,sy .
Transform each original point to (x.Sx,y.Sy).
Reflection:
For reflection about x-axis :
Retain x coordinates and flip the y coordinates
For reflection about y-axis :
Retain y coordinates and flip the y coordinates
Shearing
For x direction shear:
Get shx
The new values are:
x=x+shxy
y=y
For y direction shear:
Get shy
21

The transformed points are:


y=y+shyx
x=x
SAMPLE OUTPUT:
Enter the choice for the object
1.Rectangle
2 Triangle
1
Enter the choice
1.Translation
2.Scaling
3.Rotation
4.Reflection
5.Shearing
6.Exit
1
Translation
Enter the first vertex:
100
200
Enter the second vertex
150
210
Enter the transition co-ordinates
10
20
before

after

Scaling
Enter the choice for the object
1.Rectangle
22

2 Triangle
1
Enter the choice
1.Translation
2.Scaling
3.Rotation
4.Reflection
5.Shearing
6.Exit
2
Enter the first vertex:
70 60
Enter the second vertex:
80 60
Enter the third vertex:
80 120
Enter the fouth vertex:
70 120
Enter the scaling factor:
10 20
before

after

Rotation
Enter the choice for the object
1.Rectangle
2 Triangle
2
Enter the choice
1.Translation
2.Scaling
23

3.Rotation
4.Reflection
5.Shearing
6.Exit
3
Enter the first vertex
70 0
Enter the second vertex
80 0
Enter the third vertex
90 0
Enter rotation angle
90
before

after

Reflection
Enter the choice for the object
1.Rectangle
2 Triangle
2
Enter the choice
1.Translation
2.Scaling
3.Rotation
4.Reflection
5.Shearing
6.Exit
24

4
Enter the first vertex
70 0
Enter the second vertex
80 0
Enter the third vertex
90 0
before

after

Shearing
Enter the choice for the object
1.Rectangle
2 Triangle
1
Enter the choice
1.Translation
2.Scaling
3.Rotation
4.Reflection
5.Shearing
6.Exit
5
Enter the first vertex:
70 60
Enter the second vertex:
80 60
Enter the third vertex:
80 120
Enter the fouth vertex:
70 120
25

Enter the hear factor 10


20
before

after

26

EX. NO: 11

COMPOSITE 2D TRANSFORAMTIONS

AIM:
To write a C program to implement 2D composite transformation.
ALGORITHM:
1.
2.
3.
4.

Get the types of transformation to be performed from the user.


Display the object with the calculated position as the reference.
Display the object using the origin as the reference point.
Perform the required transformations on the object and display it using the origin as the reference
point.
5. Display the transformed object in the original location

SAMPLE OUTPUT:

27

EX.NO: 12 & 13

THREE DIMENSIONAL TRANSFORMATIONS

AIM:
To perform 3D transformations such as Translation, Rotation, Scaling, Reflection, Shear.

ALGORITHM:

1: Create a class cube with function draw cube.


2: Use the function draw cube to draw a cube using eight points by means of
functions line.
3: Declare the variables x1, y1, x2, y2, x3, y3, in array type which of data type int.
4: Declare the variables theta,op,ch,tx,ty,sx,sy,sz,lz+xy,zf,i,x,y,z.
5: Initialize graphics functions.
6: Input the first point in the cube.
7: Input the size of the edge.
8: Create an object to call the function.
9: Using switch operation selects the operation to perform translation, rotation,
scaling.
10: Translation
a) Input the translation vectortx,ty,tz.
b) Calculate points using formula
x3[i]=x1[i]+tx.
y3[i]=y1[i]+ty
z3[i]=z1[i]+tz.
x4[i]=x3[i]+z3[i]/2
y4[i]=y3[i]+z3[i]/2
c) Using the function line, display the object before and after translation.
11: Rotation:
a) Input the rotation angle
b) Using formula theta=(theta*3.14)/180
c) Input the direction in x,y,z axis
d) If the direction is along x axis,
x3[i]=x1[i].
y3[i]=y1[i]*cos(theta)-z1[i]*sin(theta),
y3[i]=y1[i]*sin(theta)-z1[i]*cos(theta),
If the direction is along yaxis,
y3[i]=y1[i].
z3[i]=z1[i]*cos(theta)-x1[i]*sin(theta),
x3[i]=z1[i]*sin(theta)-x1[i]*cos(theta),
If the direction is along z axis,
z3[i]=z1[i].
x3[i]=x1[i]*cos(theta)-y1[i]*sin(theta),
y3[i]=x1[i]*sin(theta)-y1[i]*cos(theta),

e) Calculate the points using the formula

28

x4[i]=x3[i]+z3[i]/2
y4[i]=y3[i]+z3[i]/2
f) Using the function line,display the object before and after rotation.
12: Scaling:
a) Input the scaling factor and reference point
b) Calculate coordinates point using formula
x3[i]=xf+(x1[i]*sx+xf*(1-sx),
y3 [i] =yf+ (y1[i]*sy+yf*(1-sy)
z3 [i] =zf+ (z1[i]*sz+zf*(1-sz)
c) Calculate the points using the formula
x4[i]=x3[i]+z3[i]/2
y4[i]=y3[i]+z3[i]/2
d) Using the function line, display the object before and after scaling.
13: Stop.

SAMPLE OUTPUT:
Enter the point in the cube: 100 100 100
Enter the size of the edge: 30
Enter the translation vector: 120 140 160
Before translation

After translation

Enter the rotation angle:90


Enter the direction
1.Rotation about x axis
2.Rotation about y axis
3.Rotation about z axis1

29

Enter the scaling factor:5 5 5


Enter the reference point:140 140 140

30

EX.NO: 14

INTRODUCTION TO OPENGL BASIC PROGRAMS

INTRODUCTION TO OPENGL
A basic library of functions is provided in OpenGL for specifying graphics primitives,
attributes, geometric transformations, viewing transformations, and many other operations.
OpenGL is designed to be hardware independent, therefore many operations, such as input and
output routines, are not included in the basic library. However, input and output routines and
many additional functions are available in auxiliary libraries that have been developed for
OpenGL programs.
Basic OpenGL Syntax
Function names in the OpenGL basic library (also called the OpenGL core library) are
prefixed with gL, and each component word within a function name has its first letter
capitalized. The following examples illustrate this naming convention.
glBegin,
glClear,
glCopyPixels, glPolygonMode
Certain functions require that one (or more) of their arguments be assigned a symbolic
constant specifying, for instance, a parameter name, a value for a parameter, or a particular
mode. All such constants begin with the uppercase letters GL. In addition, component words
within a constant name are written in capital letters, and the underscore (_) is used as a separator
between all component words in the name. Following are a few examples of the several hundred
symbolic constants available for use with OpenGL functions.
GL_2D, GL_RGB, GL_CCW,
GL_POLYGON,
GL_AMBIENT_AND_DIFFUSE
The OpenGL functions also expect specific data types. For example, an OpenGL function
parameter might expect a value that is specified as a 32-bit integer. But the size of an integer
specification can be different on different machines. To indicate a specific data type, OpenGL
uses special built-in, data-type names, such as
GLbyte,
GLshort,
Glint,
GLfloat,
GLdouble, GLboolean
Each data-type name begins with the capital letters GL and the remainder of the name is a
standard data-type designation, written in lower-case letters.
Some arguments of OpenGL functions can be assigned values using an array that lists a set of
data values. This is an option for specifying a list of values as a pointer to an array, rather than
specifying each element of the list explicitly as a parameter argument. A typical example of the
use of this option is in specifying xyz coordinate values.
Related Libraries
In addition to the OpenGL basic (core) library, there are a number of associated libraries
for handling special operations. The OpenGL Utility (GLU) provides routines for setting up
viewing and projection matrices, describing complex objects with line and polygon
approximations, displaying quadrics and B-splines using linear approximations, processing the
surface-rendering operations, and other complex tasks. Every OpenGL implementation includes
the GLU library, and all GLU function names start with the prefix glu. There is also an objectoriented toolkit based on OpenGL, called Open Inventor, which provides routines and predefined
object shapes for interactive three-dimensional applications. This toolkit is written in C++.

31

To create a graphics display using OpenGL, we first need to set up a display window on our
video screen. This is simply the rectangular area of the screen in which our picture will be
displayed. We cannot create the display window directly with the basic OpenGL functions, since
this library contains only device independent graphics functions, and window-management
operations depend on the computer we are using. However, there are several window-system
libraries that support OpenGL functions for a variety of machines. The OpenGL Extension to the
X Window System (GLX) provides a set of routines that are prefixed with the letters glx. Apple
systems can use the Apple GL (AGL) interface for window-management operations. Function
names for this library are prefixed with agl. For Microsoft Windows systems, the WGL routines
provide a Windows-to-OpenGL interface. These routines are prefixed with the letters wgl. The
Presentation Manager to OpenGL (PGL) is an interface for the IBM OS/2, which uses the prefix
pgl for the library routines. And the OpenGL Utility Toolkit (GLUT) provides a library of
functions for interacting with any screen-windowing system. The GLUT library functions are
prefixed with glut, and this library also contains methods for describing and rendering quadric
curves and surfaces.
Since GLUT is an interface to other device-specific window systems, we can use GLUT
so that our programs will be device independent. Information regarding the latest version of
GLUT and download procedures for the source code are available at the Web site:
http://reality.sgi.com/opengl/glut3/glut3.html
Header Files
In all our graphics programs, we will need to include the header file for the OpenGL core library.
For most applications we will also need GLU. And we need to include the header file for the
window system. For instance, with Microsoft Windows, the header file that accesses the WGL
routines is windows.h. This header file must be listed before the OpenGL and GLU header files
because it contains macros needed by the Microsoft Windows version of the OpenGL libraries.
So the source file in this case would begin with
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
However, if we use GLUT to handle the window-managing operations, we do not need to
include gl.h and glu.h because GLUT ensures that these will be included correctly. Thus, we can
replace the header files for OpenGL and GLU with
#include <GL/glut.h>
We could include gl.h and glu.h as well, but doing so would be redundant and could affect
program portability.
In addition, we will often need to include header files that are required by the C++ code.
For example,
#include <stdio.h>
32

#include <stdlib.h>
#include <math.h>
With the new ISO/ANSI standard for C++, these header files are called cstdio, cstdlib, and
cmath.
Display-Window Management Using GLUT
To get started, we can consider a simplified, minimal number of operations for displaying a
picture. Since we are using the OpenGL Utility Toolkit, our first step is to initialize GLUT. This
initialization function could also process any commandline arguments, but we will not need to
use these parameters for our first example programs. We perform the GLUT initialization with
the statement
glutInit (&argc, argv);
Next, we can state that a display window is to be created on the screen with a given
caption for the title bar. This is accomplished with the function
glutCreateWindow (An Example OpenGL Program);
where the single argument for this function can be any character string we want to use fot the
display-window title.
Then we need to specify what the display window is to contain. For this, we create a
picture using OpenGL functions and pass the picture definition to the GLUT routine
glutDisplayFunc, which assigns our picture to the display window. As an example, suppose we
have the OpenGL code for describing a line segment in a procedure called lineSegment. Then the
following function call passes the line-segment description to the display window.
glutDisplayFunc (lineSegment);
But the display window is not yet on the screen. We need one more GLUT function to
complete the window-processing operations. After execution of the following statement, all
display windows that we have created, including their graphic content, are now activated.
glutMainLoop ( );
This function must be the last one in our program. It displays the initial graphics and puts the
program into an infinite loop that checks for input from devices such as a mouse or keyboard.
Our first example will not be interactive, so the program will just continue to display our picture
until we close the display window. In later chapters, we consider how we can modify our
OpenGL programs to handle interactive input.
Although the display window that we created will be in some default location and size,
we can set these parameters using additional GLUT functions. We use the
glutInitWindowPosition function to give an initial location for the top-left corner of the display
window. This position is specified in integer screen coordinates, whose origin is at the upper-left
corner of the screen. For instance, the following statement specifies that the top-left corner of the
33

display window should be placed 50 pixels to the right of the left edge of the screen and 100
pixels down from the top edge of the screen.
glutInitWindowPosition (50, 100);

VIEWING
A series of three computer operations convert an objects three-dimensional coordinates to pixel
positions on the screen.

Transformations, which are represented by matrix multiplication, include modeling,


viewing, and projection operations. Such operations include rotation, translation, scaling,
reflecting, orthographic projection, and perspective projection. Generally, you use a
combination of several transformations to draw a scene.
Since the scene is rendered on a rectangular window, objects (or parts of objects) that lie
outside the window must be clipped. In three-dimensional computer graphics, clipping
occurs by throwing out objects on one side of a clipping plane.
Finally, a correspondence must be established between the transformed coordinates and
screen pixels. This is known as a viewport transformation.
The viewing transformations must precede the modeling transformations in your code, but you
can specify the projection and viewport transformations at any point before drawing occurs.

Stages of vertex transformation


vertex

Model view
matrix

Projection
matrix

Perspective
projection

Viewport
transformation

y
Eye coordinates
clip coordinates
normalized device window
z
coordinates coordinates
w
Object coordinates
The above figure shows the order in which these operations occur on your computer.

THE VIEWING TRANFORMATION


The viewing transformation is analogous to positioning and aiming a camera. Before the
viewing transformation can be specified, the current matrix is set to the identity matrix with
glLoadIdentity(), which is necessary since most of the transformations commands multiply the
current matrix by the specified matrix and then set the result to be the current matrix. If you
34

dont clear the current matrix by loading it with the identity matrix, you continue to combine
previous transformation matrices with the new one you supply.
After the matrix is initialized, the viewing transformation is specified with gluLookAt().
The arguments for this command indicate where the camera (or eye position) is placed, where it
is aimed, and which way is up.
If gluLookAt() was not called the camera has a default position and orientation. By
default, the camera is situated at the origin, points down the negative z-axis, and has an up-vector
of (0, 1, 0).
THE MODELING TRANSFORMATION
The modeling transformation is used to position and orient the model.
You can rotate, translate, or scale the model or perform combination of these operations.
glScalef() is a modeling transformation function. Here instead of moving the camera the object is
moved away. The effect of viewing and modeling transformations has to be considered
simultaneously. The modeling and viewing transformations are combined into the modelview
matrix before the transformation is applied.
The gluWireCube() is used to draw a wired cube. You need to load identity matrix
before performing the viewing and modeling transformations.
THE PROJECTION TRANSFORMATION
Specifying the projection transformation is like choosing a lens for a camera. You can
think of this transformation as determining what the field of view or viewing volume is and
therefore what objects are inside it and to some extent how they look. This is equivalent to
choosing among wide-angle, normal, and telephoto lenses. With a wide-angle lens, you can
include a wider scene in the final photograph than with a telephoto lens, but a telephoto lens
allows you to photograph objects as though they are closer to you than they actually are.
In addition to the field-of-view considerations, the projected transformation determines
how objects are projected onto the screen. There are two basic types of projections provided
OpenGL. One type is the perspective projection, which matches how you see things in daily life.
Perspective makes objects that are farther away appear smaller; for example it makes realistic
tracks appear to converge in the distance. glFrustum() is used to make the realistic pictures.
The other type of projection is orthographic, which maps objects directly onto the screen
without affecting their relative size. Orthographic projection is used in architectural and
computer-aided design applications where the final image needs to reflect the measurements of
objects rather than how they might look. Architects create perspective drawings to show how
particular buildings or interior spaces look when viewed from various vantage points; the need
for orthographic projection arises when blueprint plans or elevations are generated, which are
used in the construction of buildings.
Before the glFrustum() can be called to set projection transformation, the command
called glMatrixMode() is used first. If its argument is GL_PROJECTION then the current
matrix specifies the projection transformation; the following transformation calls then affect the
projection matrix. When it is passed with GL_MODELVIEW as the argument, it indicates that
succeeding transformations now affect the modelview matrix instead of projection matrix.
The function glLoadIdentity() is used to initialize the current projection matrix so that
only the specified projection transformation has an effect. Now glFrustum() can be called, with
35

arguments that define the parameters of the projection transformation. Both the projection and
the viewport relate directly to the scene, and specifically to the size or aspect ratio of the window
on the screen.
THE VIEWPORT TRANSFORMATION
Together, the projection transformation and the viewport transformation determine how a
scene gets mapped onto the computer screen. The projection transformation specifies the
mechanics of how the mapping should occur, and the viewport indicates the shape of the
available screen area into which the scene is mapped. Since the viewport specifies the region the
image occupies on the computer screen, you can think of the viewport transformation as defining
the size and location of the final processed photograph-for example, where the photograph
should be enlarged or shrunk.
The arguments to glViewport() describe the origin of the available screen space within
window. If the window changes size the viewport need to change accordingly.
DRAWING THE SCENE
Once all the necessary transformations have been specified, you can draw the scene. As
the scene is drawn, OpenGL transforms each vertex of every object in the scene by the modeling
and viewing transformations. Each vertex is then transformed as specified by the projection
transformation and clipped if it lies outside the viewing volume described by the projection
transformation. Finally, the remaining transformed vertices are divided by w and mapped onto
the viewport.
DRAWING A CUBE
The program draws a cube thats scaled by modeling transformation. The viewing
transformation, gluLookAt(), positions and aims the camera towards where the cube is drawn. A
projection transformation and a viewport are also specified.

Transformed Cube

36

BUILDING A SOLAR SYSTEM


The program described in this section draws a simple solar system with a planet and a
sun, both using the sphere drawing routine. To write this program, you need to use glRotate() for
the revolution of the planet around the sun and for the rotation of the planet around its own axis.
You also need glTranslate() to move the planet out to its orbit, away from the origin of the solar
system. Remember that you can specify the desired size of the two spheres by supplying the
appropriate arguments for the glutWireSphere() routine.
To draw the solar system, you first want to set up a projection and a viewing
transformation. For this example, gluPerspective() and gluLookAt() are used.
Drawing the sun is straightforward, since it should be located at the origin of the grand,
fixed coordinate system, which is where the sphere routine places it. Thus, drawing the sun
doesnt require translation; you can use glRotate() to make the sun rotate about an arbitrary axis.
To draw a planet rotating around the sun it requires several modeling transformations. The planet
need to rotate about its own axis once a day. And once a year, the planet completes one
revolution around the sun.
To determine the order of modeling transformationa, visualize what happens to the local
coordinate system. An initial glRotate() rotates the local coordinate system that initially
coincides with the grand coordinate system. Next, glTranslate() moves the local coordinate
system to a position on the planets orbit; the distance moved should equal the radius of the orbit.
Thus, the initial glRotate() actually determines where along the orbit the planet is (or what time
of year it is).
A second glRotate() rotates the local coordinate system around the local axes, thus
determining the time if day for the planet. Once you have issued all these transformation
commands, the planet can be drawn.
OPENGL FUNCTIONS:
GL FUNCTIONS
glClearColor ( )

Syntax:
Void glClearColor(GLclampf red ,GLclampf green,GLclampf blue ,GLclampf alpha);

Description:
It sets the background color and alpha values. It specifies the red, green, blue, and
alpha values used by glClear to clear the color buffers. Values specified by glClearColor
are clamped to the range [0, 1].

glClear( )
Syntax:
37

Void glClear(GLbitfield mask);

Description:
The glClear function clears buffers to preset values. The glClear function takes a
single argument (mask) that is the bitwise OR of several values indicating which buffer is
to be cleared. The values of mask can be any one of the following:-GL_COLOR_BUFFER_BIT-- Indicates the buffers currently enabled for color writing.
GL_DEPTH_BUFFER_BIT-- Indicates the depth buffer.
GL_ACCUM_BUFFER_BIT--Indicates the accumulation buffer.
GL_STENCIL_BUFFER_BIT--Indicates the stencil buffer.
glMatrixMode( )
Syntax:
Void glMatrixMode(GLenum mode);

Description:
It sets the current matrix mode. mode can assume one of four values:
GL_MODELVIEW Applies subsequent matrix operations to the
model view matrix stack.
GL_PROJECTION Applies subsequent matrix operations to the
projection matrix stack.
GL_TEXTURE
Applies subsequent matrix operations to the
texture matrix stack.
GL_COLOR
matrix stack.

Applies subsequent matrix operations to the color

glColor3f( )
Syntax:
Void glColor3f (GLfloat red, GLfloat green, GLfloat blue);

Description:
It is used to specify the color of the object. glColor3f specify new red, green, and
blue values explicitly and set the current alpha value to 1.0 (full intensity) implicitly.
Current color values are stored in floating-point format
38

glVertex2i( )
Syntax:
void glVertex2i(GLint x, GLint y );

Description:
The glVertex function commands are used within glBegin/glEnd pairs to specify
point, line, and polygon vertices. Here x and y indicate the corresponding x co-ordinates
and y-co-ordinates.

glBegin( ), glEnd( )
Syntax:
void glBegin(GLenum mode );
void glEnd(

);

Description:
glBegin and glEnd delimit the vertices that define a primitive or a group of like
primitives. glBegin accepts a single argument.There are 10 possible values for mode:GL_LINES treats each pair of vertices as an independent line segment

glFlush( )
Syntax:
void glFlush( );

Description:
It force execution of GL commands in finite time

glShadeModel( )

39

Syntax:
void glShadeModel(GLenum mode);

Description:
Specifies a symbolic value representing a shading technique. Accepted values are
GL_FLAT and GL_SMOOTH

glLoadIdentity( )
Syntax:
void glLoadIdentity( );

Description:
It replaces the current matrix with the identity matrix

glScalef( )
Syntax:
void glScalef(GLfloat x , GLfloat y , GLfloat z );

Description:
It multiplies the current matrix by a general scaling matrix. It produces a
nonuniform scaling along the x,y and z axes.

glViewport( )
Syntax:
void glViewport (GLint x , GLint y, GLsizei width , GLsizei height );

Description:

40

The glViewport function sets the viewport. It sets the lower-left corner of the
viewport rectangle and specifies the height and width of the viewport.

glFrustum( )
Syntax:
void glFrustum (GLdouble left ,GLdouble right,GLdouble bottom ,GLdouble op
, GLdouble zNear , GLdouble zFar );

Description:
It multiplies the current matrix by a perspective matrix. It produces a perspective
projection.
Left, right specify the coordinates for the left and right vertical clipping planes.
Bottom, top Specify the coordinates for the bottom and top horizontal clipping
planes.
zNear, zFar

Specify the distances to the near and far depth clipping planes.

glRotate( )
Syntax:
void glRotatef (GLfloat angle,GLfloat x, GLfloat y,GLfloat z );

Description:
It multiplies the current matrix by a rotation matrix.it specifies the x,y,z coordinates of the vector and the angle of rotation.

glPushMatrix( )
Syntax:
void glPushMatrix(void);
Description:
It pushes the current matrix stack.
41

glPopMatrix( )
Syntax:
void glPopMatrix(void);
Description:
It pops out the current matrix stack.

GLU FUNCTIONS
gluOrtho2D( )

Syntax:
void gluOrtho2D(left,right,top,bottom);

Description:
It defines a 2-D orthographic projection matrix. It sets up a two-dimensional
orthographic viewing region

gluLookAt( )
Syntax:
void gluLookAt(GLdouble eyeX, GLdouble eyeY , GLdouble eyeZ ,
GLdouble centerX , GLdouble centerY, GLdouble centerZ ,
GLdouble upX , GLdouble upY , GLdouble upZ );

Description:
It defines a viewing transformation. gluLookAt creates a viewing matrix derived
from an eye point, a reference point indicating the center of the scene, and an UP vector.
eyeX, eyeY, eyeZ

Specifies the position of the eye point.

centerX, centerY, centerZ

Specifies the position of the reference point.

upX, upY, upZ

Specifies the direction of the up vector.

42

GLUT FUNCTIONS
glutInit( )

Syntax:
void glutInit(int *argcp , char **argv );

Description:
glutInit will initialize the GLUT library and negotiate a session with the window
system. During this process, glutInit may cause the termination of the GLUT program
with an error message to the user if GLUT cannot be properly initialized.

glutInitDisplayMode( )
Syntax:
void glutInitDisplayMode(unsigned int mode );

Description:
It sets the initial display mode.it sets buffering and color options.

GLUT_SINGLE

Bit mask to select a single buffered window.

GLUT_RGB

Bit mask to select an RGBA mode window

glutInitWindowPosition( )
Syntax:
void glutInitWindowPosition (int x , int y );

Description:
It sets the initial window position by specifying the location of the top left corner
of display window.

glutInitWindowSize( )
Syntax:
void glutInitWindowSize ( int width, int height );
43

Description:
It sets the initial width and height of the display window.

glutCreateWindow( )
Syntax:
int glutCreateWindow

(char *name);

Description:
It is used to create a top level window with the name in the title bar.

glutDisplayFunc( )
Syntax:
void glutDisplayFunc ( void (*func)(void));

Description:
It is used to indicate what is to be displayed on the window by specifying a new
callback display function as its parameter.

glutMainLoop( )
Syntax:
void glutMainLoop( );

Description:
It enters the GLUT event processing loop. This routine should be called at most
once in a GLUT program.

glutReshapeFunc( )
44

Syntax:
void glutReshapeFunc

(void (*func)(int width, int height));

Description:
It sets the reshape callback for the current window. The reshape callback is
triggered when a window is reshaped

glutSwapBuffers( )
Syntax:
void glutSwapBuffers ( );

Description:
It swaps the buffers of the current window if two buffers(front and back) are used.

glutPostRedisplay( )
Syntax:
void glutPostRedisplay( );

Description:
It marks the normal plane of current window as needing to be redisplayed.

glutKeyboardFunc( )
Syntax:
void glutKeyboardFunc

(void (*func)(unsigned char key, int x, int y));

Description:

45

It sets the keyboard callback for the current window. When a user types into the
window, each key press generating an ASCII character will generate a keyboard callback.
The key callback parameter is the generated ASCII character.

EX.NO:14

LINE DRAWING

AIM:
To draw line using opengl functions.
CODE:
#include "stdafx.h"
#include<GL/glut.h>
void init(void)
{
glClearColor(1.0,1.0,1.0,-1.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0,200.0,0.0,150.0);
}
void linesegment(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINES);
glVertex2i(150,15);
glVertex2i(10,145);
glEnd();
glFlush();
}
void main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowPosition(50,100);
glutInitWindowSize(300,400);
glutCreateWindow("Example");
init();
glutDisplayFunc(linesegment);
glutMainLoop();
}

46

SAMPLE OUTPUT:

47

EX. NO:15

THREE DIMENSIONAL TRANSFORMATIONS USING OPENGL

CUBE

AIM:
To draw cube using opengl functions.
CODE:
#include "stdafx.h"
#include<GL/glut.h>
void init(void)
{
glClearColor(0.0,0.0,0.0,1.0);
glShadeModel(GL_FLAT);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,0.0,0.0);
glLoadIdentity();
gluLookAt(0.0,0.0,5.0,0.0,0.0,0.0,0.0,1.0,0.0);
glScalef(1.0,2.0,1.0);
glRotatef(0.0,1.0,2.0,0.0);
glTranslatef(0.5,0.0,1.0);
glutWireCube(2.0);
glFlush();
}
void reshape(int w,int h)
{
glViewport(0,0,(GLsizei)w,(GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-1.0,1.0,-1.0,1.0,1.5,20.0);
glMatrixMode(GL_MODELVIEW);
}
void main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowPosition(50,100);
glutInitWindowSize(300,400);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
48

glutReshapeFunc(reshape);
glutMainLoop();
}

SAMPLE OUTPUT:

49

EX NO:16

COMPOSITE 3D TRANSFORMATIONS USING OPENGL

SOLAR SYSTEM
AIM:
To draw solar system using opengl functions.
CODE:
#include "stdafx.h"
#include "windows.h"
#include<GL/gl.h>
#include<GL/glu.h>
#include<GL/glut.h>
static int year=0,day=0;
void init(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glShadeModel(GL_FLAT);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,1.0,1.0);
glPushMatrix();
glutWireSphere(1.0,20,16);
//gluLookAt(0.0,0.0,5.0,0.0,0.0,0.0,0.0,1.0,0.0);
glRotatef((GLfloat)year,0.0,1.0,0.0);
glTranslatef(2.0,0.0,0.0);
glRotatef((GLfloat)day,0.0,1.0,0.0);
glutWireSphere(0.2,10,8);
glPopMatrix();
glutSwapBuffers();
}
void reshape(int w,int h)
{
glViewport(0,0,(GLsizei)w,(GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0,(GLfloat)w/(GLfloat)h,1.0,20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0.0,0.0,5.0,0.0,0.0,0.0,0.0,1.0,0.0);
}
void keyboard(unsigned char key,int x,int y)
{
switch(key)
{
50

case 'd':
day=(day+10)%360;
glutPostRedisplay();
break;
case 'D':
day=(day-10)%360;
glutPostRedisplay();
break;
case 'y':
year=(year+5)%360;
glutPostRedisplay();
break;
case 'Y':
year=(year-5)%360;
glutPostRedisplay();
break;
default: break;
}}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowPosition(100,100);
glutInitWindowSize(500,500);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
SAMPLE OUTPUT:

51

EX. NO :17

DRAWING 3D OBJECTS USING OPENGL

AIM:
To draw 3D objects with lighting effects .
DESCRIPTION:

We draw 3D objects Sphere ,Cone and Torus using GLUT functions


o

void glutSolidTorus(GLdouble innerRadius, GLdouble outerRadius,GLint


nsides, GLint rings);

void glutSolidCone(GLdouble radius, GLdouble height, GLint slices,GLint


stacks);

void glutSolidSphere(GLdouble radius,GLint slices, GLint stacks);

Here
Slices: The number of subdivisions around the Z axis (similar to lines of longitude).
Stacks:The number of subdivisions along the Z axis (similar to lines of latitude).

We use one light source LIGHT0 .The function glLightfv() to specify the position and
direction of the light source.We enable the lighting using glEnable().

LIGHTING:
Light effects are very important in OpenGL, for without the use of lights, an 3-D object will still look 2dimensional.
OpenGL provides two types of light sources:
Directional
Positional.
A directional light source is considered to be an infinite distance away from the objects in the scene.
Thus, its rays of light are considered parallel by the time they reach the object. A positional light, in
contrast, is near or within the scene and the direction of its rays are taken into account in lighting
calculations.
The command glLightfv() is used to specify the position of the light, regardless of whether it is
directional or positional. It is also used to specify whether the light source has ambient color, diffuse
color, specular color, or emissive color.
Ambient: Light that has been scattered so much by the environment that its direction is hard to
determine.
Diffuse: Light that comes from one direction, so it's brighter if it comes squarely down on a surface than
it it barely glances off the surface.

52

Specular: Light that comes from a particular direction, and it tends to bounce off the surface in a
preferred direction.
Emissive: Light seems to be orginating from an object.
RGB Values for Lights
The color components specified for lights mean something different than for materials. For a light, the
numbers correspond to a percentage of full intensity for each color. If the R, G, and B values for a
light's color are all 1.0, the light is the brightest possible white. If the values are 0.5, the color is
still white, but only at half intensity, so it appears gray.
Creating Light Sources
Light sources have a number of properties, such as color, position, and direction. The command used to
specify all properties of lights is glLight*(); it takes three arguments: to identify the light whose
property is being specified, the property, and the desired value for that property.
void glLightfv(GLenum light, GLenum pname, TYPEparam);

glLight sets the values of individual light source parameters. light names the light and is a symbolic name
of the form GL_LIGHTi, where 0 i < GL_MAX_LIGHTS. pname specifies one of ten light source
parameters, again by symbolic name. params is either a single value or a pointer to an array that contains
the new values.
Lighting calculation is enabled and disabled using glEnable and glDisable with
argument GL_LIGHTING. When lighting is enabled, light sources that are enabled contribute to the
lighting calculation. Light source i is enabled and disabled using glEnable and glDisable with
argument GL_LIGHTi.

53

Here's an example of using glLight*():


GLfloat light_ambient[] = { 0.0, 0.0, 0.0, 1.0 };
GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat light_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
As you can see, arrays are defined for the parameter values, and glLightfv() is called repeatedly to set the
various parameters. In this example, the first three calls toglLightfv() are superfluous, since they're being
used to specify the default values for the GL_AMBIENT, GL_DIFFUSE, and GL_SPECULAR
parameters.
Color
OpenGL allows you to associate three different color-related parameters - GL_AMBIENT,
GL_DIFFUSE, and GL_SPECULAR - with any particular light.

54

The GL_DIFFUSE parameter probably most closely correlates with what you naturally think of as "the
color of a light." It defines the RGBA color of the diffuse light that a particular light source adds to a
scene.
The GL_SPECULAR parameter affects the color of the specular highlight on an object.
Position
You can choose whether to have a light source that's treated as though it's located infinitely far away from
the scene or one that's nearer to the scene. The first type is referred to as an directional light source; the
effect of an infinite location is that the rays of light can be considered parallel by the time they reach an
object. An example of a real-world directional light source is the sun. The second type is called a
positional light source, since its exact position within the scene determines the effect it has on a scene
and, specifically, the direction from which the light rays come. A desk lamp is an example of a positional
light source.
Eg.
GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
glLightfv(GL_LIGHT0, GL_POSITION, light_position);

you supply a vector of four values (x, y, z, w) for the GL_POSITION parameter. If the
last value, w, is zero, the corresponding light source is a directional one, and the (x, y, z) values describe
its direction.

If the w value is nonzero, the light is positional, and the (x, y, z) values specify the
location of the light in homogeneous object coordinates .

SAMPLE OUTPUT:

55

EX.NO: 18

DRAWING 3D SCENES USING OPENGL

AIM:
To Draw a 3D scene and move the light source around the object.
DESCRIPTION:
In this program the light source is rotated around an object. When the left mouse button is pressed, the
light position rotates an additional 30 degrees. A small, unlit, wireframe cube is drawn to represent the
position of the light in the scene.
Controlling a Light's Position and Direction
OpenGL treats the position and direction of a light source just as it treats the position of a geometric
primitive. In other words, a light source is subject to the same matrix transformations as a primitive. More
specifically, whenglLight*() is called to specify the position or the direction of a light source, the position
or direction is transformed by the current modelview matrix and stored in eye coordinates. This means
you can manipulate a light source's position or direction by changing the contents of the modelview
matrix. (The projection matrix has no effect on a light's position or direction.) We can achieve the
following three different effects by changing the point in the program at which the light position is set,
relative to modeling or viewing transformations:

A light position that remains fixed


A light that moves around a stationary object
A light that moves along with the viewpoint.

Defining Material Properties for objects in the 3D scene:


Most of the material properties are conceptually similar to ones you've already used to create light
sources. The mechanism for setting them is similar, except that the command used is
called glMaterial*().
void glMaterial{if}(GLenum
face,
GLenum
void glMaterial{if}v(GLenum face, GLenum pname, TYPE *param);

pname,

TYPEparam);

Specifies a current material property for use in lighting calculations.


face can be GL_FRONT, GL_BACK, or GL_FRONT_AND_BACK to indicate which face of the
object the material should be applied to. The particular material property being set is identified
by pname and the desired values for that property are given by param, which is either a pointer to
a group of values (if the vector version is used) or the actual value (if the nonvector version is
used). The nonvector version works only for setting GL_SHININESS. The possible values for
pname are shown in Table 5-3. Note that GL_AMBIENT_AND_DIFFUSE allows you to set both
the ambient and diffuse material colors simultaneously to the same RGBA value.

56

Changing Material Properties


You might want to assign different material properties for different vertices on the same object. More
likely, you have more than one object in the scene, and each object has different material properties.
glMaterialfv() is used to set the desired material property for the vertices of the object.

57

SAMPLE OUTPUT:

58

3D SCENE RENDERED WITH SHADING


AIM:
To draw a 3D scene with lighting and shading effect.

PROGRAM DESCRIPTION:

The scene contains three objects resting on a table in the corner of a room.
The view uses a camera set by gluLookAt(2.3, 1.3, 2,0, 0.25, 0, 0.0,1.0,0.0).
Each of the three walls is made by flattening a cube into a thin sheet, and moving it into position.
(Again, they look somewhat unnatural due to the use of a parallel projection.) The jack is
composed of three stretched spheres oriented at right angles plus six small spheres at their ends.
The table consists of a table top and four legs. Each of the tables five pieces is a cube that has
been scaled to the desired size and shape. It is based on four parameters that characterize the size
of its part stopWidth, topThick, legLen, and legThick.
A routine tableLeg() draws each leg, and is called four times within
the routine table() to draw the legs in the four different locations. The different parameters used
produce different modeling transformations within tableLeg(). As always, a glPushMatrix(),
glPopMatrix() pair surrounds the modeling
functions to isolate their effect. Note that the solid version of each shape, such as
glutSolidSphere(), is used here, rather than the wire version.

Methods for 3D object used:


cube: glutSolidCube(GLdouble size); Each side is of length size
sphere: glutSolidSphere(GLdouble radius, GLint nSlices, GLint nStacks)
teapot: glutSolidTeapot(GLdouble size)

SAMPLE OUTPUT:

59

EX. NO :19

GENERATING FRACTAL IMAGES USING OPENGL

AIM:
TO generate and display Mandelbrot set using OpenGL.
DESCRIPTION:
A fractal is a natural phenomenon or a mathematical set that exhibits a repeating pattern that
displays at every scale. If the replication is exactly the same at every scale, it is called a selfsimilar pattern. An example of this is the Menger Sponge.[1] Fractals can also be nearly the same
at different levels. This latter pattern is illustrated in the magnifications of the Mandelbrot
set.[2][3][4][5] Fractals also includes the idea of a detailed pattern that repeats itself.[2]:166; 18[3][6]
Fractals are different from other geometric figures because of the way in which they scale.
Doubling the edge lengths of a polygon multiplies its area by four, which is two (the ratio of the
new to the old side length) raised to the power of two (the dimension of the space the polygon
resides in). Likewise, if the radius of a sphere is doubled, its volume scales by eight, which is
two (the ratio of the new to the old radius) to the power of three (the dimension that the sphere
resides in). But if a fractal's one-dimensional lengths are all doubled, the spatial content of the
fractal scales by a power that is not necessarily an integer.[2] This power is called the fractal
dimension of the fractal, and it usually exceeds the fractal's topological dimension.[7]
The Mandelbrot set is the set of complex numbers 'c' for which the sequence ( c, c + c, (c+c)
+ c, ((c+c)+c) + c, (((c+c)+c)+c) + c, ...) does not approach infinity. The set is closely
related to Julia sets (which include similarly complex shapes) and is named after the
mathematician Benoit Mandelbrot, who studied and popularized it. Mandelbrot set images are
made by sampling complex numbers and determining for each whether the result tends towards
infinity when a particular mathematical operation is iterated on it. Treating the real and
imaginary parts of each number as image coordinates, pixels are colored according to how
rapidly the sequence diverges, if at all.
More precisely, the Mandelbrot set is the set of values of c in the complex plane for which the
orbit of 0 under iteration of the complex quadratic polynomial remains bounded.[1] That is, a
complex number c is part of the Mandelbrot set if, when starting with z0 = 0 and applying the
iteration repeatedly, the absolute value of zn remains bounded however large n gets.
For example, letting c = 1 gives the sequence 0, 1, 2, 5, 26,, which tends to infinity. As this
sequence is unbounded, 1 is not an element of the Mandelbrot set. On the other hand, c = 1
gives the sequence 0, 1, 0, 1, 0,..., which is bounded, and so 1 belongs to the Mandelbrot set.
Images of the Mandelbrot set display an elaborate boundary that reveals progressively ever-finer
recursive detail at increasing magnifications. The "style" of this repeating detail depends on the
region of the set being examined. The set's boundary also incorporates smaller versions of the
60

main shape, so the fractal property of self-similarity applies to the entire set, and not just to its
parts.
The Mandelbrot set has become popular outside mathematics both for its aesthetic appeal and as
an example of a complex structure arising from the application of simple rules, and is one of the
best-known examples of mathematical visualization.

SAMPLE OUTPUT:

61

You might also like