CG Lab PDF
CG Lab PDF
C315.1 Design and implement various line clipping algorithms and polygon filling
algorithm (any one)
C315.2 Understand and implement 3D Sierpinski gasket; Implement a color cube ,
apply transformations and perspective view on it
C315.3 Implement various advanced primitives such as mesh, teapot and extruding
surfaces and apply lighting and shading to them(any one)
SYLLABUS
PART - A
Design, develop, and implement the following programs in C / C++
1. Program to recursively subdivide a tetrahedron to from 3D Sierpinski gasket. The number of
recursive steps is to be specified by the user.
2. Program to implement Liang-Barsky line clipping algorithm.
3. Program to draw a color cube and spin it using OpenGL transformation matrices.
4. Program to create a house like figure and rotate it about a given fixed point using OpenGL
functions.
5. 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.
6. Program to create a cylinder and a parallelepiped by extruding a circle and quadrilateral
respectively. Allow the user to specify the circle and the quadrilateral.
7. Program, using OpenGL functions, to draw a simple shaded scene consisting of a tea pot on
a table. Define suitably the position and properties of the light source along with the
properties of the properties of the surfaces of the solid object used in the scene.
8. Program to draw a color cube and allow the user to move the camera suitably to experiment
with perspective viewing. Use OpenGL functions.
9. Program to fill any given polygon using scan-line area filling algorithm. (Use appropriate
data structures.)
10. Program to display a set of values {fij} as a rectangular mesh.
PART - B
Develop a suitable Graphics package to implement the skills learnt in the theory and the exercises
indicated in Part A. Use the OpenGL.
Note:
1. Any question from Part A may be asked in the examination.
2. A report of about 10 – 12 pages on the package developed in Part B, duly certified by the
department must be submitted during examination.
Instructions:
In the examination, one exercise from Part A is to be asked for a total of 30 marks. The package
developed under Part B has to be evaluated for a total of 20 marks.
Preliminary Concepts
OpenGL
As a software interface for graphics hardware, OpenGL's main purpose is to render two- and three-
dimensional objects into a frame buffer. These objects are described as sequences of vertices (which
define geometric objects) or pixels (which define images). OpenGL performs several processing
steps on this data to convert it to pixels to form the final desired image in the frame buffer.
Primitives are defined by a group of one or more vertices. A vertex defines a point, an endpoint of a
line, or a corner of a polygon where two edges meet. Data (consisting of vertex coordinates, colors,
normals, texture coordinates, and edge flags) is associated with a vertex, and each vertex and its
associated data are processed independently, in order, and in the same way. The only exception to
this rule is if the group of vertices must be clipped so that a particular primitive fits within a
specified region; in this case, vertex data may be modified and new vertices created. The type of
clipping depends on which primitive the group of vertices represents.
Commands are always processed in the order in which they are received, although there may be an
indeterminate delay before a command takes effect. This means that each primitive is drawn
completely before any subsequent command takes effect. It also means that state-querying
commands return data that's consistent with complete execution of all previously issued OpenGL
commands
The figure shown below gives an abstract, high-level block diagram of how OpenGL processes
data. In the diagram, commands enter from the left and proceed through what can be thought of as a
processing pipeline. Some commands specify geometric objects to be drawn, and others control
how the objects are handled during the various processing stages.
As shown by the first block in the diagram, rather than having all commands proceed immediately
through the pipeline, you can choose to accumulate some of them in a display list for processing at
a later time.
The evaluator stage of processing provides an efficient means for approximating curve and surface
geometry by evaluating polynomial commands of input values. During the next stage, per-vertex
operations and primitive assembly, OpenGL processes geometric primitives—points, line segments,
and polygons, all of which are described by vertices. Vertices are transformed and lit, and
primitives are clipped to the viewport in preparation for the next stage.
Rasterization produces a series of frame buffer addresses and associated values using a two-
dimensional description of a point, line segment, or polygon. Each fragment so produced is fed into
the last stage, per-fragment operations, which perform the final operations on the data before it's
stored as pixels in the frame buffer. These operations include conditional updates to the frame
buffer based on incoming and previously stored z-values (for z-buffering) and blending of incoming
pixel colors with stored colors, as well as masking and other logical operations on pixel values.
Input data can be in the form of pixels rather than vertices. Such data, which might describe an
image for use in texture mapping, skips the first stage of processing described above and instead is
processed as pixels, in the pixel operations stage. The result of this stage is either stored as texture
memory, for use in the rasterization stage, or rasterized and the resulting fragments merged into the
frame buffer just as if they were generated from geometric data.
GLUT gives you the ability to create a window, handle input and render to the screen without being
Operating System dependent. The first things you will need are the OpenGL and GLUT header files
and libraries for your current Operating System. Once you have them setup on your system
correctly, open your first c++ file and include them at the start of your file like so:
Now, just double check that your system is setup correctly, and try compiling your current file. If
you get no errors, you can proceed. If you have any errors, try your best to fix them. Once you are
ready to move onto the next step, create a main() method in your current file. Inside this is where all
of your main GLUT calls will go. The first call we are going to make will initialize GLUT and is
done like so:
Once we have GLUT initialized, we need to tell GLUT how we want to draw. There are several
parameters we can pass here, but we are going to stick the with most basic GLUT_SINGLE, which
will give use a single buffered window.
The next two methods we are going to use, simply set the size and position of the GLUT
window on our screen:
glutInitWindowSize (500, 500); //set whe width and height of the window
glutInitWindowPosition (100, 100); //set the position of the window
glutCreateWindow ("A basic OpenGL Window"); //set the caption for the window
We now have a window of the size and position that we want. But we need to be able to draw to it.
We do this, by telling GLUT which method will be our main drawing method. In this case, it is a
void method called display()
Finally, we tell GLUT to start our program. It does this by executing a loop that will continue until
the program ends.
So thus far, we have a window. But the display method that I mentioned is needed. Lets take a look
at this and dissect it.
The first method, glClearColor will set the background color of our window. In this example, we
are setting the background to black (RGB 0, 0, 0). The 1.0 value on the end is an alpha value and
makes no difference at this stage as we don't have alpha enabled.
The next thing we want to do, is erase everything currently stored by OpenGL. We need to do this
at the start of the method, as the method keeps looping over itself and if we draw something, we
need to erase it before we draw our next frame
PROGRAM -1
TITLE
Design, develop, and implement the following programs in C/C++ program to recursively subdivide
a tetrahedron to from 3D Sierpinski gasket. The number of recursive steps is to be specified by the
user
AIM
To construct the 3D Sierpinski gasket and recursively divide it using the input from the user
using OpenGL
DESCRIPTION
The Sierpinski triangle (also with the original orthography Sierpiński), also called the Sierpinski
gasket or the Sierpinski Sieve, is a fractal and attractive fixed set with the overall shape of
an equilateral triangle, subdivided recursively into smaller equilateral triangles. Originally
constructed as a curve, this is one of the basic examples of self-similar sets, i.e., it is a
mathematically generated pattern that can be reproducible at any magnification or reduction. It is
named after the Polish mathematician Waclaw Sierpinki but appeared as a decorative pattern many
centuries prior to the work of Sierpiński
A fractal is generally "a rough or fragmented geometric shape that can be split into parts, Each of
which is (at least approximately) a reduced-size copy of the whole―.
ALGORITHM
INPUT
EXPECTED OUTPUT
Generates a 3D Sierpinski gasket with the specified number of subdivisions by the user
PROGRAM
#include<stdio.h>
#include<GL/glut.h>
typedef float point[3];
point v[]={{0,0},{250,500,100},{500,250,100},{250,100,250}};
int n;
void myinit()
{
glClearColor(0,1,1,1);
glOrtho(0,500,0,500,-500,500);
glEnable(GL_DEPTH_TEST);
}
void triangle(point a,point b,point c)
{
glBegin(GL_TRIANGLES);
glVertex3fv(a);
glVertex3fv(b);
glVertex3fv(c);
glEnd();
glFlush();
}
void divide_triangle(point a,point b,point c,int m)
{
point v1,v2,v3;
int j;
if(m>0)
{
for(j=0;j<3;j++)
v1[j]=(a[j]+b[j])/2;
for(j=0;j<3;j++)
v2[j]=(a[j]+c[j])/2;
for(j=0;j<3;j++)
v3[j]=(b[j]+c[j])/2;
divide_triangle(a,v1,v2,m-1);
divide_triangle(b,v1,v3,m-1);
divide_triangle(c,v2,v3,m-1);
}
else(triangle(a,b,c));
}
void tetrahedron(int m)
{
Dept of CSE, MITE, Moodabidri Page 8
Computer Graphics & Visualization Lab 10CSL67
glColor3f(1.0,0.0,0.0);
divide_triangle(v[0],v[1],v[2],m);
glColor3f(0.0,1.0,0.0);
divide_triangle(v[3],v[2],v[1],m);
glColor3f(0.0,0.0,1.0);
divide_triangle(v[0],v[3],v[1],m);
glColor3f(0.0,0.0,0.0);
divide_triangle(v[0],v[2],v[3],m);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
tetrahedron(n);
}
RESULT
PROGRAM -2
TITLE
Design, develop, and implement the following programs in C/C++ program to implement Liang-
Barsky line clipping algorithm
AIM
DESCRIPTION
In computer graphics, the Liang–Barsky algorithm (named after You-Dong Liang and Brian A.
Barsky) is a line clipping algorithm. The Liang–Barsky algorithm uses the parametric equation of a
line and inequalities describing the range of the clipping window to determine the intersections
between the line and the clip window. With these intersections it knows which portion of the line
should be drawn. This algorithm is significantly more efficient than Cohen–Sutherland. The idea of
the Liang–Barsky clipping algorithm is to do as much testing as possible before computing line
intersections.
And
ALGORITHM
INPUT
EXPECTED OUTPUT
The line portion which is inside the clipping rectangle shall be retained as it is and the rest
of the portions are clipped off.
PROGRAM
#include<GL/glut.h>
GLdouble xmin=200.0,ymin=200.0,xmax=500.0,ymax=500.0,x0=150.0,y0=300.0,
x1=300.0,y1=600.0;
GLint clip=0,click=0;
void draw_rect()
{
glColor3f(1.0,0.0,1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xmin,ymin);
glVertex2f(xmin,ymax);
glVertex2f(xmax,ymax);
glVertex2f(xmax,ymin);
glEnd();
glFlush();
}
void draw_line()
{
glBegin(GL_LINES);
glVertex2f(x0,y0);
glVertex2f(x1,y1);
glEnd();
glFlush();
}
void LBclip()
{
double dx=x1-x0,dy=y1-y0,t1=0,t2=1;
if(clip_test(-dx,x0-xmin,&t1,&t2) &&
clip_test(dx,xmax-x0,&t1,&t2) &&
clip_test(-dy,y0-ymin,&t1,&t2) &&
clip_test(dy,ymax-y0,&t1,&t2))
{
clip=1;
if(t2<1.0)
{
x1=x0+t2*dx;
y1=y0+t2*dy;
}
if(t1>0.0)
{
x0=x0+t1*dx;
y0=y0+t1*dy;
}
}
}
void mouse(int button,int state,int a,int b)
{
if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN)
click=1;
glutPostRedisplay();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
draw_rect();
glColor3f(0.0,0.0,1.0);
draw_line();
LBclip();
if(clip&&click)
{
glColor3f(0.0,1.0,0.0);
draw_line();
}
}
void myinit()
{
glClearColor(0.0,0.0,0.0,1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,800.0,0.0,800.0);
}
RESULT
Before Clipping
After Clipping
PROGRAM -3
TITLE
Design, develop, and implement the following programs in C/C++ program to draw a color cube
and spin it using OpenGL transformation matrices
AIM
To draw a color cube and rotate it using transformation matrices using OpenGL
DESCRIPTION
A color cube is a graphic primitive generated using set of vertices and edges. A Color cube consists
of 6 facets and 8 vertices and it. OpenGL's object is made up of primitives (such as triangle, quad,
polygon, point and line). A primitive is defined via one or more vertices. The color-cube is made up
of 6 quads. Each quad is made up of 4 vertices, defined in counter-clockwise (CCW) order, such as
the normal vector is pointing out, indicating the front face. All the 4 vertices have the same color.
The color-cube is defined in its local space (called model space) with origin at the center of the
cube with sides of 2 units.
ALGORITHM
2. Draw a polygon from a list of indices into the array vertices and use color
corresponding to first index
void polygon(int a, int b, int c, int d)
{
glBegin(GL_POLYGON);
glColor3fv(colors[a]);
glVertex3fv(vertices[a]);
Dept of CSE, MITE, Moodabidri Page 17
Computer Graphics & Visualization Lab 10CSL67
glVertex3fv(vertices[b]);
glVertex3fv(vertices[c]);
glVertex3fv(vertices[d]);
glEnd();
}
glLoadIdentity();
glRotatef(theta[0], 1.0, 0.0, 0.0);
glRotatef(theta[1], 0.0, 1.0, 0.0);
glRotatef(theta[2], 0.0, 0.0, 1.0);
colorcube();
glutSwapBuffers();
}
5. Define the spincube function to spin cube 2 degrees about selected axis.
INPUT
Mouse input, Right-Click for rotation w.r.t x axis, Middle-Click for rotation w.r.t z axis and
Left click for rotation w.r.t y axis
EXPECTED OUTPUT
A color cube which can be rotated with respect to all the three axes, whose rotation is
controlled by the mouse input given by the user
PROGRAM
void spinCube()
{
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, vertices);
glColorPointer(3,GL_FLOAT, 0, colors);
glColor3f(1.0,1.0,1.0);
glutMainLoop();
}
RESULT
PROGRAM -4
TITLE
Design, develop, and implement the following programs in C/C++ program to create a house like
figure and rotate it about a given fixed point using OpenGL functions
AIM
To create a house like structure using basic OpenGL primitives and rotate it w.r.t fixed point
using OpenGL
DESCRIPTION
A house can be constructed using OpenGL primitives such as triangles and quads. In order to rotate
the structure we use rotation about fixed point logic which is a combination of set of
transformations in a sequence which is
Translating the object back from its location to origin of coordinate system
Rotating the object about the origin
Translating the object back to its original location
ALGORITHM
n=-k*(cos(theta)-1)-h*(sin(theta));
ii) Rotation matrix is
cos(theta) -sin(theta) m
sin(theta) cos(theta) n
0 0 1
iii) Call Multiply function to multiply the two matrices Rotation matrix and object
matrix.
6. Define the multiply function to multiply Rotation matrix and object matrix to give
resultant transformed house.
7. Define the function drawhouse to draw house using GL_LINE_LOOP.
8. Define the function Drawrotatehouse to draw house after rotating.
9. Define the display function which is used to call all function.
10. Define the myinit function to specify matrixmode and gluortho.
11. Define main to get theta value from user and to create window.
INPUT
EXPECTED OUTPUT
A graphics output depicting the original house rotated by the angle specified by the user.
PROGRAM
#include<GL/glut.h>
#include<math.h>
#include<stdio.h>
GLfloat h=700.0,k=400.0,theta=0.0,angle=0.0;
GLfloat v[3][9]={{500,575,625,700,625,575,500,700,600},{400,400,400,400,650,
650,700,700,800},{1,1,1,1,1,1,1,1,1}};
GLfloat r[3][9]={0.0},rot_mat[3][3]={0.0};
void multiply();
void draw_house();
void myinit();
void rotate_house();
void rotate();
void display();
glutInit(&argc,argv);
printf("enter the rotation angle\n");
scanf("%f",&angle);
theta=(3.14*angle)/180;
glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE);
glutInitWindowSize(900,900);
glutInitWindowPosition(0,0);
glutCreateWindow("house");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
void myinit()
{
glClearColor(0.0,0.0,0.0,1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,900.0,0.0,900.0);
}
void draw_house()
{
glColor3f(1.0,0.0,0.0);
glBegin(GL_TRIANGLES);
glVertex2f(v[0][8],v[1][8]);
glVertex2f(v[0][7],v[1][7]);
glVertex2f(v[0][6],v[1][6]);
glEnd();
glColor3f(0.0,1.0,0.0);
glBegin(GL_QUADS);
glVertex2f(v[0][6],v[1][6]);
glVertex2f(v[0][7],v[1][7]);
glVertex2f(v[0][3],v[1][3]);
glVertex2f(v[0][0],v[1][0]);
glEnd();
glColor3f(1.0,1.0,0.0);
glBegin(GL_QUADS);
glVertex2f(v[0][5],v[1][5]);
glVertex2f(v[0][4],v[1][4]);
glVertex2f(v[0][2],v[1][2]);
glVertex2f(v[0][1],v[1][1]);
glEnd();
glFlush();
}
void multiply()
{
int i,j,l;
for(i=0;i<3;i++)
for(j=0;j<9;j++)
{
r[i][j]=0;
for(l=0;l<3;l++)
r[i][j]=r[i][j]+rot_mat[i][l]*v[l][j];
}
}
void rotate()
{
GLfloat m,n;
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();
}
void rotate_house()
{
glColor3f(0.0,1.0,1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(r[0][8],r[1][8]);
glVertex2f(r[0][7],r[1][7]);
glVertex2f(r[0][6],r[1][6]);
glEnd();
glColor3f(0.0,1.0,1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(r[0][6],r[1][6]);
glVertex2f(r[0][7],r[1][7]);
glVertex2f(r[0][3],r[1][3]);
glVertex2f(r[0][0],r[1][0]);
glEnd();
glColor3f(0.0,1.0,1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(r[0][5],r[1][5]);
glVertex2f(r[0][4],r[1][4]);
glVertex2f(r[0][2],r[1][2]);
glVertex2f(r[0][1],r[1][1]);
glEnd();
glFlush();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
draw_house();
rotate();
rotate_house();
}
RESULT
PROGRAM -5
TITLE
Design, develop, and implement the following programs in C/C++ 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
AIM
DESCRIPTION
The Cohen-Sutherland algorithm uses a divide-and-conquer strategy. The line segment's endpoints
are tested to see if the line can be trivially accepted or rejected. If the line cannot be trivially
accepted or rejected, an intersection of the line with a window edge is determined and the trivial
reject/accept test is repeated. This process is continued until the line is accepted. To perform the
trivial acceptance and rejection tests, we extend the edges of the window to divide the plane of the
window into the nine regions. Each end point of the line segment is then assigned the code of the
region in which it lies.
ALGORITHM
INPUT
Mouse input, Right-Click for rotation w.r.t x axis, Middle-Click for rotation w.r.t z axis and
Left click for rotation w.r.t y axis
EXPECTED OUTPUT
The line portion which is inside the clipping rectangle shall be retained as it is and the rest
of the portions are clipped off.
PROGRAM
#include<GL/glut.h>
GLdouble xmin=200.0,ymin=200.0,xmax=500.0,ymax=500.0,x0=150.0,y0=300.0,
x1=300.0,y1=600.0;
GLint accept=0,done=0,click=0;
const int RIGHT=8;
const int LEFT=2;
const int TOP=4;
const int BOTTOM=1;
void draw_rect()
{
glColor3f(1.0,0.0,1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xmin,ymin);
glVertex2f(xmin,ymax);
glVertex2f(xmax,ymax);
glVertex2f(xmax,ymin);
glEnd();
glFlush();
}
void draw_line()
{
glBegin(GL_LINES);
glVertex2f(x0,y0);
glVertex2f(x1,y1);
glEnd();
glFlush();
}
code|=RIGHT;
else if(x<xmin)
code|=LEFT;
return code;
}
void CSclip()
{
int code0,code1,outcode;
code0=ComputeCode(x0,y0);
code1=ComputeCode(x1,y1);
do{
if(!(code0|code1))
{
accept=1;
done=1;
}
else if(code0&code1)
done=1;
else
{
double x,y;
outcode=code0?code0:code1;
if(outcode&TOP)
{
x=x0+(x1-x0)*(ymax-y0)/(y1-y0);
y=ymax;
}
else if(outcode&BOTTOM)
{
x=x0+(x1-x0)*(ymin-y0)/(y1-y0);
y=ymin;
}
else if(outcode&RIGHT)
{
y=y0+(y1-y0)*(xmax-x0)/(x1-x0);
x=xmax;
}
else
{
y=y0+(y1-y0)*(xmin-x0)/(x1-x0);
x=xmin;
}
if(outcode==code0)
{
x0=x;
y0=y;
code0=ComputeCode(x0,y0);
}
Dept of CSE, MITE, Moodabidri Page 31
Computer Graphics & Visualization Lab 10CSL67
else
{
x1=x;
y1=y;
code1=ComputeCode(x1,y1);
}
}
}
while(!done);
}
void mouse(int button,int state,int a,int b)
{
if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN)
click=1;
glutPostRedisplay();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
draw_rect();
glColor3f(0.0,0.0,1.0);
draw_line();
CSclip();
if(accept&&click)
{
glColor3f(0.0,1.0,0.0);
draw_line();
}
}
void myinit()
{
glClearColor(0.0,0.0,0.0,1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,800.0,0.0,800.0);
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE);
glutInitWindowSize(800.0,800.0);
glutInitWindowPosition(0.0,0.0);
glutCreateWindow("Clipping Line");
glutMouseFunc(mouse);
glutDisplayFunc(display);
myinit();
glutMainLoop();
return 0;
}
Dept of CSE, MITE, Moodabidri Page 32
Computer Graphics & Visualization Lab 10CSL67
RESULT
Before Clipping
After Clipping
PROGRAM -6
TITLE
Design, develop, and implement the following programs in C/C++ program to create a cylinder and
a parallelepiped by extruding a circle and quadrilateral respectively. Allow the user to specify the
circle and the quadrilateral
AIM
DESCRIPTION
In geometry, a parallelepiped is a three-dimensional figure formed by six parallelograms (the
term rhomboid is also sometimes used with this meaning). By analogy, it relates to
a parallelogram just as a cube relates to a square or as a cuboid to a rectangle. In Euclidean
geometry, its definition encompasses all four concepts (i.e., parallelepiped, parallelogram, cube,
and square). In this context of affine geometry, in which angles are not differentiated, its definition
admits only parallelograms and parallelepipeds. Three equivalent definitions of parallelepiped are
ALGORITHM
1. Include glut header files.
2. Define draw_pixel function to plot points.
void draw_pixel(Glint cx,Glint cy)
{
glcolor3f(1.0,0.0,0.0);
glBegin(GL_POINTS);
glVertex2i(cx,cy);
glEnd();
}
3. Define plot pixel function to plot eight points in perimeter of circle.
4. Define circle_draw function to draw circle using mid-point circle algorithm by calling
plotpixel function.
INPUT
None
EXPECTED OUTPUT
Graphics output depicting both cylinder and parallelepiped extruding from the basic
primitive circle and quad respectively.
PROGRAM
#include <GL/glut.h>
#include <math.h>
#include <stdio.h>
void draw_pixel(GLint x, GLint y)
{
glBegin(GL_POINTS);
glVertex2f(x,y);
glEnd();
}
void plotpixels(GLint h, GLint k, GLint x, GLint y)
{
draw_pixel(x+h,y+k);
draw_pixel(-x+h,y+k);
draw_pixel(x+h,-y+k);
draw_pixel(-x+h,-y+k);
draw_pixel(y+h,x+k);
draw_pixel(-y+h,x+k);
draw_pixel(y+h,-x+k);
draw_pixel(-y+h,-x+k);
}
void Circle_draw(GLint h, GLint k, GLint r)
{
GLint d = 1-r, x=0, y=r;
plotpixels(h,k,x,y);
while(y > x)
{
if(d < 0)
d+=2*x+3;
else
{ d+=2*(x-y)+5;
--y;
}
++x;
plotpixels(h,k,x,y);
}
}
void rect_draw(int x1,int y1,int x2,int y2)
{
glLineWidth(2.0);
glBegin(GL_LINE_LOOP);
glVertex2i(x1,y1);
glVertex2i(x2,y1);
glVertex2i(x2,y2);
glVertex2i(x1,y2);
glEnd();
glPointSize(8.0);
glColor3f(0.0,0.0,0.0);
glBegin(GL_POINTS);
glVertex2i(x1,y1);
glVertex2i(x2,y1);
glVertex2i(x2,y2);
glVertex2i(x1,y2);
glEnd();
}
void init(void)
{
glClearColor(1.0,0.0,0.0,0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0,400.0,0.0,400.0);
}
void display(void)
{
GLint i,xc=100, yc=100, r=50;
int x1=200,y1=200,x2=300,y2=300;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0,0.0,0.0);
Circle_draw(xc-1,yc-1,r);
glColor3f(1.0,1.0,0.0);
for(i=1;i<80;i++)
Circle_draw(xc,yc+i,r);
glColor3f(0.0,0.0,0.0);
Circle_draw(xc,yc+81,r);
glColor3f(0.0,0.0,0.0);
rect_draw(x1-1,y1-1,x2-1,y2-1);
for(i=1;i<80;i++)
{
glColor3f(0.0, 0.0, 1.0);
rect_draw(x1+i,y1+i,x2+i,y2+i);
}
glColor3f(0.0,0.0,0.0);
rect_draw(x1+80,y1+80,x2+80,y2+80);
glFlush();
}
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(50,50);
glutInitWindowSize(400,400);
glutCreateWindow("Cylinder ");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
RESULT
PROGRAM -7
TITLE
Design, develop, and implement the following programs in C/C++ 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
AIM
To implement a simple shaded scene consisting of a tea pot on a table under various lighting
& shading conditions using OpenGL
ALGORITHM
1. Include glut header files.
6. Define the main function to create window and enable lighting function using
glEnable(GL_LIGHTING)
INPUT
None
EXPECTED OUTPUT
Graphics output depicting a room with a table and a teapot under a specific lighting and
shading parameters set through OpenGL API
PROGRAM
#include<GL/glut.h>
void wall(double thickness)
{
glPushMatrix();
glTranslated(0.5,0.5*thickness,0.5);
glScaled(1.0,thickness,1.0);
glutSolidCube(1.0);
glPopMatrix();
}
void tableLeg(double thick,double len)
{
glPushMatrix();
glTranslated(0,len/2,0);
glScaled(thick,len,thick);
glutSolidCube(1.0);
glPopMatrix();
}
GLfloat lightIntensity[]={0.7f,0.7f,0.7f,1.0f};
GLfloat light_position[]={2.0f,6.0f,3.0f,0.0f};
glLightfv(GL_LIGHT0,GL_POSITION,light_position);
Dept of CSE, MITE, Moodabidri Page 42
Computer Graphics & Visualization Lab 10CSL67
glLightfv(GL_LIGHT0,GL_DIFFUSE,lightIntensity);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
double winHt=1.0;
glOrtho(-winHt*64/48.0,winHt*64/48.0,-winHt,winHt,0.1,100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(2.3,1.3,2.0,0.0,0.25,0.0,0.0,1.0,0.0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslated(0.4,0.4,0.6);
glRotated(45,0,0,1);
glScaled(0.08,0.08,0.08);
glPopMatrix();
glPushMatrix();
glTranslated(0.6,0.38,0.5);
glRotated(30,0,1,0);
glutSolidTeapot(0.08);
glPopMatrix();
glPushMatrix();
glTranslated(0.25,0.42,0.35);
glPopMatrix();
glPushMatrix();
glTranslated(0.4,0,0.4);
table(0.6,0.02,0.02,0.3);
glPopMatrix();
wall(0.02);
Dept of CSE, MITE, Moodabidri Page 43
Computer Graphics & Visualization Lab 10CSL67
glPushMatrix();
glRotated(90.0,0.0,0.0,1.0);
wall(0.02);
glPopMatrix();
glPushMatrix();
glRotated(-90.0,1.0,0.0,0.0);
wall(0.02);
glPopMatrix();
glFlush();
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(640,480);
glutInitWindowPosition(100,100);
glutCreateWindow("Simple shaded scene consisting of a tea pot on a table");
glutDisplayFunc(displaySolid);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
glClearColor(0.1,0.1,0.1,0.0);
glViewport(0,0,640,480);
glutMainLoop();
return 0 ;
}
RESULT
PROGRAM -8
TITLE
Design, develop, and implement the following programs in C/C++ program to draw a color cube
and allow the user to move the camera suitably to experiment with perspective viewing. Use
OpenGL functions
AIM
DESCRIPTION
Perspective projections create more realistic looking scenes, so that's what you will most likely be
using most often. In perspective projections, as an object gets farther from the viewer it will appear
smaller on the screen- an effect often referred to as foreshortening. The viewing volume for a
perspective projection is a frustum, which looks like a pyramid with the top cut off, with the narrow
End towards the user.
There is a few different ways you can setup the view frustum, and thus the perspective projection.
The first we will look at is as follows:
void glFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble
near, GLdouble far);
Using glFrustum enables you to specify an asymmetrical frustum, which can be very useful in some
instances, but isn't what you typically want to do.
PSUEDO CODE
1. Define global arrays for vertices and colors
GLfloat vertices[][3] = {{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0},
{1.0,1.0,-1.0}, {-1.0,1.0,-1.0}, {-1.0,-1.0,1.0},
{1.0,-1.0,1.0}, {1.0,1.0,1.0}, {-1.0,1.0,1.0}};
GLfloat colors[][3] = {{0.0,0.0,0.0},{1.0,0.0,0.0},
{1.0,1.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0},
{1.0,0.0,1.0}, {1.0,1.0,1.0}, {0.0,1.0,1.0}};
2. Draw a polygon from a list of indices into the array vertices and use color corresponding to first
index
void polygon(int a, int b, int c, int d)
{
glBegin(GL_POLYGON);
glColor3fv(colors[a]);
glVertex3fv(vertices[a]);
glVertex3fv(vertices[b]);
glVertex3fv(vertices[c]);
glVertex3fv(vertices[d]);
glEnd();
}
glutSwapBuffers();
}
6. Define mouse callback function to rotate about axis
7. Define key function to move viewer position .use x, X,y,Y z,Z keys to move viewer position
8. Define reshape function to maintain aspect ratio and then use perspective view
9. Define main function to create window and to call all function
INPUT
Mouse and keyboard input , i.e. Mouse Input – Right, Left & Middle click to control the
rotation and Keyboard input X- Zoom in (X axis), x – Zoom out(X axis) , Y- Zoom in (Y axis), y –
Zoom out(Y axis) & Z- Zoom in (Z axis), z – Zoom out(Z axis)
EXPECTED OUTPUT
Graphics output depicting a rotating cube whose rotation can be controlled by the mouse
input and keyboard input to control the zooming in and zooming out operation along all 3 axes.
PROGRAM
#include<stdlib.h>
#include<GL/glut.h>
GLfloat vertices[][3]={{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0},{1.0,1.0,-1.0},{-1.0,1.0,-1.0},{-1.0,-
1.0,1.0},{1.0,-1.0,1.0},{1.0,1.0,1.0},{-1.0,1.0,1.0}};
GLfloat normals[][3]={{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0},{1.0,1.0,-1.0},{-1.0,1.0,-1.0},{-1.0,-
1.0,1.0},{1.0,-1.0,1.0},{1.0,1.0,1.0},{-1.0,1.0,1.0}};
GLfloat
colors[][3]={{0.0,0.0,0.0},{1.0,0.0,0.0},{1.0,1.0,0.0},{0.0,1.0,0.0},{0.0,0.0,1.0},{1.0,0.0,1.0},{1.0,
1.0,1.0},{0.0,1.0,1.0}};
glNormal3fv(normals[b]);
glVertex3fv(vertices[b]);
glColor3fv(colors[c]);
glNormal3fv(normals[c]);
glVertex3fv(vertices[c]);
glColor3fv(colors[d]);
glNormal3fv(normals[d]);
glVertex3fv(vertices[d]);
glEnd();
}
void colorcube()
{
polygon(0,3,2,1);
polygon(2,3,7,6);
polygon(0,4,7,3);
polygon(1,2,6,5);
polygon(4,5,6,7);
polygon(0,1,5,4);
}
static GLfloat theta[]={0.0,0.0,0.0};
static GLint axis=2;
static GLdouble viewer[]={0.0,0.0,5.0};
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt(viewer[0],viewer[1],viewer[2],0.0,0.0,0.0,0.0,1.0,0.0);
glRotatef(theta[0],1.0,0.0,0.0);
glRotatef(theta[1],0.0,1.0,0.0);
glRotatef(theta[2],0.0,0.0,1.0);
colorcube();
glFlush();
glutSwapBuffers();
Dept of CSE, MITE, Moodabidri Page 49
Computer Graphics & Visualization Lab 10CSL67
}
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') viewer[0]-=1.0;
if(key=='X') viewer[0]+=1.0;
if(key=='y') viewer[1]-=1.0;
if(key=='Y') viewer[1]+=1.0;
if(key=='z') viewer[2]-=1.0;
if(key=='Z') viewer[2]+=1.0;
display();
}
void myReshape(int w,int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w<=h)
glFrustum(-2.0,2.0,2.0*(GLfloat)h/(GLfloat)w,2.0*(GLfloat)h/(GLfloat)w,2.0,20.0);
else
glFrustum(-2.0,2.0,2.0*(GLfloat)w/(GLfloat)h,2.0*(GLfloat)w/(GLfloat)h,2.0,20.0);
Dept of CSE, MITE, Moodabidri Page 50
Computer Graphics & Visualization Lab 10CSL67
glMatrixMode(GL_MODELVIEW);
}
RESULT
PROGRAM -9
TITLE
Design, develop, and implement the following programs in C/C++ program to fill any given
polygon using scan-line area filling algorithm. (Use appropriate data structures.)
AIM
DESCRIPTION
Scanline rendering (also scan line rendering and scan-line rendering) is an algorithm for visible
surface determination, in 3D computer graphics, that works on a row-by-row basis rather than
a polygon-by-polygon or pixel-by-pixel basis. All of the polygons to be rendered are first sorted by
the top y coordinate at which they first appear, then each row or scan line of the image is computed
using the intersection of a scanline with the polygons on the front of the sorted list, while the sorted
list is updated to discard no-longer-visible polygons as the active scan line is advanced down the
picture.
The main advantage of this method is that sorting vertices along the normal of the scanning plane
reduces the number of comparisons between edges. Another advantage is that it is not necessary to
translate the coordinates of all vertices from the main memory into the working memory—only
vertices defining edges that intersect the current scan line need to be in active memory, and each
vertex is read in only once. The main memory is often very slow compared to the link between the
central processing unit and cache memory, and thus avoiding re-accessing vertices in main memory
can provide a substantial speedup
ALGORITHM
1. Set y to the smallest y coordinate that has an entry in the ET; i.e., y for the first Nonempty
bucket.
2. Initialize the AET to be empty.
3. Repeat until the AET and ET are empty:
Move from ET bucket y to the AET those edges whose y_min = y (entering edges).
Remove from the AET those entries for which y = y_max (edges not involved in the
next scanline), the sort the AET on x (made easier because ET is presorted).
Fill in desired pixel values on scanline y by using pairs of x coordinates from AET.
Increment y by 1 (to the coordinate of the next scanline).
For each non vertical edge remaining in the AET, update x for the new y.
INPUT
None
EXPECTED OUTPUT
Graphics output depicting the filling up of a polygon (Rhombus) using scan-line filling
algorithm
PROGRAM
#define BLACK 0
#include<stdlib.h>
#include<stdio.h>
#include<GL/glut.h>
float x1,x2,x3,x4,y1,y2,y3,y4;
float mx,x,temp;
int i;
if((y2-y1)<0)
temp=y1;
y1=y2;
y2=temp;
temp=x1;
x1=x2;
x2=temp;
if((y2-y1)!=0)
mx=(x2-x1)/(y2-y1);
else
mx=x2-x1;
x=x1;
for(i=y1;i<=y2;i++)
if(x<(float)le[i])
le[i]=(int)x;
if(x>(float)re[i])
re[i]=(int)x;
x+=mx;
glColor3f(1.0,1.0,0.0);
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
void scanfill(float x1,float y1,float x2,float y2,float x3,float y3,float x4,float y4)
int le[500],re[500];
int i,y;
for(i=0;i<500;i++)
le[i]=500;
re[i]=0;
edgedetect(x1,y1,x2,y2,le,re);
edgedetect(x2,y2,x3,y3,le,re);
edgedetect(x3,y3,x4,y4,le,re);
edgedetect(x4,y4,x1,y1,le,re);
for(y=0;y<500;y++)
if(le[y]<=re[y])
for(i=(int)le[y];i<(int)re[y];i++)
draw_pixel(i,y,BLACK);
void display()
x1=200.0;y1=200.0;x2=100.0;y2=300.0;x3=200.0;y3=400.0;x4=300.0,y4=300.0;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0,0.0,1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(x1,y1);
glVertex2f(x2,y2);
glVertex2f(x3,y3);
glVertex2f(x4,y4);
glEnd();
scanfill(x1,y1,x2,y2,x3,y3,x4,y4);
glFlush();
void myinit()
glClearColor(0.0,0.0,0.0,1.0);
glColor3f(1.0,1.0,0.0);
glPointSize(0.5);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,499.0,0.0,499.0);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutDisplayFunc(display);
myinit();
glutMainLoop();
RESULT
PROGRAM -10
TITLE
Design, develop, and implement the following programs in C/C++ program to display a set of
values {fij} as a rectangular mesh
AIM
DESCRIPTION
A mesh is a collection of vertices, edges and faces that define the shape of a 3D object. The most
popular type of polygon mesh used in computer graphics is a triangle mesh. Any object, either a
mountain or a game character can be modeled with meshes.
PSEUDO CODE
3. Initialize the values for x0 and y0 value and declare array x[maxx],y[maxy].
4. Define the init function to clear color, defining point size, to specify matrix mode, to request
redisplay.
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();
}
6. Define main function to create window and to call display and init function
INPUT
None
EXPECTED OUTPUT
PROGRAM
#include<GL/glut.h>
#define maxx 20
#define maxy 20
#define dx 10
#define dy 10
int x0=40,y0=40;
float x[maxx],y[maxy];
void display()
{
int i,j;
glClear(GL_COLOR_BUFFER_BIT);
for(i=0;i<maxx;i++)
x[i]=x0+i*dx;
for(j=0;j<maxy;j++)
y[j]=y0+j*dy;
for(i=0;i<maxx-1;i++)
for(j=0;j<maxy-1;j++)
{
glLineWidth(8.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(); }
Dept of CSE, MITE, Moodabidri Page 59
Computer Graphics & Visualization Lab 10CSL67
glFlush();
}
void myinit()
{
glClearColor(1,1,1,1);
glColor3f(0,0.1,0.2);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,500.0,0.0,500.0);
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE);
glutInitWindowSize(900,900);
glutInitWindowPosition(0,0);
glutCreateWindow("Rectangular Mesh");
glutDisplayFunc(display);
myinit();
glutMainLoop();
return 0;
}
RESULT