CG Lab Manual 2020
CG Lab Manual 2020
BENJANAPADAVU
Laboratory Manual
MISSION
M1. Provide a learning environment enriched with ethics that helps in enhancing problem
solving skills of students and, cater to the needs of the society and industry.
M2. Expose the students to cutting-edge technologies and state-of-the-art tools in the many areas
of Computer Science & Engineering.
M3. Create opportunities for all round development of students through co-curricular and extra-
curricular activities.
M4. Promote research, innovation and development activities among staff and students.
PROGRAMME OUTCOMES
Engineering graduates in Computer Science and Engineering will be able to:
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specific needs with appropriate
consideration for the public health and safety, and the cultural, societal and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods, including design of experiments, analysis and interpretation of data and synthesis of
the information to provide valid conclusions.
5. Modern tool usage: Select/Create and apply appropriate techniques, resources and modern
engineering and IT tools, including prediction and modeling to complex engineering
activities, taking comprehensive cognizance of their limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
7. Environment and Sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts and demonstrate the knowledge of and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the relevant scientific and/or engineering practices.
9. Individual and team work: Function effectively as an individual and as a member or leader
in diverse teams and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with the society-at-large, such as being able to comprehend and
write effective reports and design documentation, make effective presentations and give and
receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work as a member and
leader in a team to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for and above have the preparation and ability to
engage in independent and life-long learning in the broadcast context of technological
changes.
SEMESTER – VI
CREDITS – 02
Lab Experiments:
Design, develop, and implement the following programs using OpenGL API
1. Implement Brenham’s line drawing algorithm for all types of slope.
2. Create and rotate a triangle about the origin and a fixed point.
3. Draw a colour cube and spin it using OpenGL transformation matrices.
4. Draw a color cube and allow the user to move the camera suitably to experiment
with perspective viewing.
5. Clip a lines using Cohen-Sutherland algorithm
6. 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 surfaces of the solid object used in
the scene.
7. Design, develop and implement recursively subdivide a tetrahedron to form 3D sierpinski gasket.
The number of recursive steps is to be specified by the user.
8. Develop a menu driven program to animate a flag using Bezier Curve algorithm
9. Develop a menu driven program to fill the polygon using scan line algorithm
PART –B ( MINI-PROJECT) :
Student should develop mini project on the topics mentioned below or similar applications
using Open GL API. Consider all types of attributes like color, thickness, styles, font,
background, speed etc., while doing mini project.
(During the practical exam: the students should demonstrate and answer Viva-Voce)
Conduction of Practical Examination:
1. All laboratory experiments from part A are to be included for practical
examination.
2. Mini project has to be evaluated for 40 Marks.
3. Report should be prepared in a standard format prescribed for project work.
4. Students are allowed to pick one experiment from the lot.
5. Strictly follow the instructions as printed on the cover page of answer script.
6. Marks distribution:
a) Part A: Procedure + Conduction + Viva: 09 + 42 + 09 = 60 Marks
b) Part B: Demonstration + Report + Viva voce = 20 + 14 + 06 = 40 Marks
7. Change of experiment is allowed only once and marks allotted to the procedure
part to be made zero.
Reference books:
1. Donald Hearn & Pauline Baker: Computer Graphics-OpenGL Version,3rd Edition, Pearson
Education,2011
2. Edward Angel: Interactive computer graphics- A Top Down approach with OpenGL,
5th edition. Pearson Education, 2011
3. M M Raikar, Computer Graphics using OpenGL, Fillip Learning / Elsevier,
Bangalore / New Delhi (2013)
Computer Graphics Laboratory with Mini Project 17CSL68
INTRODUCTION
OpenGL provides a powerful but primitive set of rendering commands, and all higher-level
drawing must be done in terms of these commands. Also, OpenGL programs have to use the
underlying mechanisms of the windowing system. A number of libraries exist to allow you to
simplify your programming tasks, including the following:
The OpenGL Utility Library (GLU) contains several routines that use lower-level
OpenGL commands to perform such tasks as setting up matrices for specific viewing
orientations and projections, performing polygon tessellation, and rendering surfaces.
GLU routines use the prefix glu.
For every window system, there is a library that extends the functionality of that window system
to support OpenGL rendering. For machines that use the X Window System, the OpenGL
Extension to the X Window System (GLX) is provided as an adjunct to OpenGL. GLX routines
use the prefix glX. For Microsoft Windows, the WGL routines provide the Windows to OpenGL
interface. All WGL routines use the prefix wgl. For IBM OS/2, the PGL is the Presentation
Manager to OpenGL interface, and its routines use the prefix pgl.
o Open a window
o Get input from mouse and keyboard
o Menus
o Event-driven
Code is portable but GLUT lacks the functionality of a good toolkit for a specific
platform
o No slide bars
Prepared By: Shatananda Bhat P, Asst. Professor, Department of CS & E, CEC | 1
Computer Graphics Laboratory with Mini Project 17CSL68
Open Inventor is an object-oriented toolkit based on OpenGL which provides objects and
methods for creating interactive three-dimensional graphics applications. Open Inventor,
which is written in C++, provides prebuilt objects and a built-in event model for user
interaction, high-level application components for creating and editing three-dimensional
scenes, and the ability to print objects and exchange data in other graphics formats. Open
Inventor is separate from OpenGL.
OpenGL #defines:
• Most constants are defined in the include files gl.h, glu.h and glut.h
Note #include <GL/glut.h> should automatically include the others
Examples
glBegin(GL_POLYGON)
glClear(GL_COLOR_BUFFER_BIT)
• include files also define OpenGL data types: GLfloat, GLdouble.
Program Structure
• Most OpenGL programs have a similar structure that consists of the following functions
main():
• defines the callback functions
• opens one or more windows with the required properties
• enters event loop (last executable statement)
init(): sets the state variables
• Viewing
• Attributes
callbacks:
• Display function
• Input and window functions
GLUT functions
• glutInit allows application to get command line arguments and initializes system
• gluInitDisplayMode requests properties for the window (the rendering context)
RGB color
Single buffering
Properties logically ORed together
• glutWindowSize in pixels
• glutWindowPosition from top-left corner of display
Line segments (GL_LINES): The line-segment type causes successive pairs of vertices to be
interpreted as the endpoints of individual segments. Because the interpretation is done on a pair
wise basis, successive segments usually are disconnected.
Polygons (GL_POLYGON):
Successive vertices define line segments, and a line segment connects the final
vertex to the first.
The interior is filled according to the state of the relevant attributes.
Note that a mathematical polygon has an inside and an outside that are separated
by the edge. The edge itself has no width.
Consequently, most graphics systems allow to fill the polygon with a color or
pattern or to draw lines around the edges, but not to do both.
In OpenGL, glPolygonMode function can be used to select edges instead of fill
(the default).
However, to draw a filled polygon and to display its edges, it must be drawn twice,
once in each mode, or a polygon and a line loop with the same vertices must be
drawn.
Triangles and Quadrilaterals (GL_TRIANGLES, GL_QUADS):
These objects are special cases of polygons. Successive groups of three and four
vertices are interpreted as triangles and quadrilaterals, respectively.
Using these types may lead to a rendering more efficient than that obtained with
polygons.
Stripsand Fans (GLTRIANGLE_STRIP, GL_QUAD_STRIP,
GL_TRIANGLE_FAN) :
These objects are based on groups of triangles or quadrilaterals that share vertices
and edges.
In the triangle_strip, for example, each additional vertex is combined with the
previous two vertices to define a new triangle.
For the quad_strip, two new vertices are combined with the previous two vertices
to define a new quadrilateral.
A triangle fan is based on one fixed point. The next two points determine the first
triangle, and subsequent triangles are formed from one new point, the previous
point, and the first (fixed) point.
* Note that the program defines a display callback function named display
Every glut program must have a display callback
The display callback is executed whenever OpenGL decides the display must be refreshed, for
example when the window is opened
The main function ends with the program entering an event loop.
Output:
Output:
PART-A
1. Design, develop, and implement Brenham’s line drawing algorithm for all types of slope in
C/C++ using OpenGL API.
Algorithm:
If the initial position for a line with positive slope is the right endpoint, both x and y
decrease as we step from right to left. To ensure that the same pixels are plotted regardless of
the starting endpoint, we always choose the upper (or the lower) of the two candidate pixels
whenever the two vertical separations from the line path are equal (d1 = d2).
For negative slopes, the procedures are similar, except that now one coordinate
decreases as the other increases. Finally, special cases can be handled separately: Horizontal
lines (Δy = 0), vertical lines (Δx = 0), and diagonal lines with (|Δy| = |Δx|) each can be loaded
directly into the frame buffer without processing them through the line-plotting algorithm.
Program:
{
draw_pixel(x, y);
e = 2 * dy-dx;
inc1 = 2*(dy-dx);
inc2 = 2*dy;
for (i=0; i<dx; i++)
{
if (e >= 0)
{
y += incy;
e += inc1;
}
else
e += inc2;
x += incx;
draw_pixel(x, y);
}
}
else
{
draw_pixel(x, y);
e = 2*dx-dy;
inc1 = 2*(dx-dy);
inc2 = 2*dx;
for (i=0; i<dy; i++)
{
if (e >= 0)
{
x += incx;
e += inc1;
}
else
e += inc2;
y += incy;
draw_pixel(x, y);
}
}
}
void myDisplay()
{
draw_line(x1, x2, y1, y2);
glFlush();
}
Output:
2. Design, develop, and implement a program in C/C++ to create and rotate a triangle about
the origin and a fixed point, using OpenGL API.
Program:
#include <GL/glut.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int x,y;
int rFlag=0;
void triangle()
{
glColor3f(1.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2f(100,100);
glVertex2f(250,400);
glVertex2f(400,100);
glEnd();
}
float th=0.0;
float trX=0.0,trY=0.0;
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
void myInit()
{
glClearColor(0.0,0.0,0.0,1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-500.0, 500.0, -500.0, 500.0);
glMatrixMode(GL_MODELVIEW);
}
Output:
Before Rotation
3. Design, develop, and implement a program in C/C++ to draw a color cube and spin it using
OpenGL transformation matrices, using OpenGL API.
Program:
#include<stdio.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 colors[][3]=
{
{0.0,0.0,0.0},{0,0.0,0.0},
{1.0,1.0,0.0},{0.0,1.0,1.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}
};
glColor3fv(colors[b]);
glVertex3fv(vertices[b]);
glColor3fv(colors[c]);
glVertex3fv(vertices[c]);
glColor3fv(colors[d]);
glVertex3fv(vertices[d]);
glEnd();
}
void colorcube(void)
{
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);
//similarly for remaining 5 faces
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glRotatef(theta[0],1.0,0.0,0.0);//for x axis
glRotatef(theta[1],0.0,1.0,0.0);
glRotatef(theta[2],0.0,0.0,1.0);
colorcube();
glutSwapBuffers();
}
void spinCube()
{
theta[axis]+=0.1;
if(theta[axis]>360.0) theta[axis]-=360.0;
glutPostRedisplay();
}
glutInitWindowSize(500,500);
glutCreateWindow("color cube viewer");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutIdleFunc(spinCube);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
return 0;
}
Output:
4. Design, develop, and implement a program in C/C++ to Draw a color cube and allow the
user to move the camera suitably to experiment with perspective viewing, using OpenGL API.
Program:
#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glut.h>
void colorcube(void)
{
polygon(0,3,2,1);
polygon(0,4,7,3);
polygon(5,4,0,1);
polygon(2,3,7,6);
polygon(1,2,6,5);
polygon(4,5,6,7);
}
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();
}
if(key == 'Y')
viewer[1]+= 1.0;
if(key == 'z')
viewer[2]-= 1.0;
if(key == 'Z')
viewer[2]+= 1.0;
display();
}
Output:
5. Design, develop, and implement a program in C/C++ to Clip a line using Cohen-Sutherland
algorithm, using OpenGL API.
Algorithm
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.
1. Given a line segment with endpoint P1 = (x1, y1) and P1 = (x2, y2)
2. Compute the 4-bit codes for each endpoint.
If both codes are 0000,(bitwise OR of the codes yields 0000 ) line lies completely inside
the window: pass the endpoints to the draw routine.
If both codes have a 1 in the same bit position (bitwise AND of the codes is not 0000),
the line lies outside the window. It can be trivially rejected.
3. If a line cannot be trivially accepted or rejected, at least one of the two endpoints must
lie outside the window and the line segment crosses a window edge. This line must
be clipped at the window edge before being passed to the drawing routine.
4. Examine one of the endpoints, say P1 = (x1, y1) Read P1's 4-bit code in order: Left-to-
Right, Bottom-to-Top.
5. When a set bit (1) is found, compute the intersection I of the corresponding window
edge with the line from P1 to P2 . Replace P1 with I and repeat the algorithm.
If the line cannot be trivially accepted or rejected, we must compute the intersection of the line
with an appropriate window edge.
Program:
#include <stdio.h>
#include <GL/gl.h>
#include <GL/glut.h>
#define outcode int
//Cohen-Sutherland clipping algorithm clips a line from P0 = (x0, y0) to P1 = (x1, y1)
x = xmin;
}
//Now we move outside point to intersection point to clip
//and gets ready for next pass.
if (outcodeOut == outcode0)
{
x0 = x;
y0 = y;
outcode0 = ComputeOutCode (x0, y0);
}
else
{
x1 = x;
y1 = y;
outcode1 = ComputeOutCode (x1, y1);
}
}
} while (!done);
if (accept)
{
//draw a red colored viewport
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xmin+200, ymin+200);
glVertex2f(xmax+200, ymin+200);
glVertex2f(xmax+200, ymax+200);
glVertex2f(xmin+200, ymax+200);
glEnd();
glColor3f(0.0,0.0,1.0); // draw blue colored clipped line
glBegin(GL_LINES);
glVertex2d (x0+200, y0+200);
glVertex2d (x1+200, y1+200);
glEnd();
}
}
//Compute the bit code for a point (x, y) using the clip rectangle
//bounded diagonally by (xmin, ymin), and (xmax, ymax)
outcode ComputeOutCode (double x, double y)
{
outcode code = 0;
if (y > ymax) //above the clip window
code |= TOP;
else if (y < ymin) //below the clip window
Prepared By: Shatananda Bhat P, Asst. Professor, Department of CS & E, CEC | 32
Computer Graphics Laboratory with Mini Project 17CSL68
code |= BOTTOM;
if (x > xmax) //to the right of clip window
code |= RIGHT;
else if (x < xmin) //to the left of clip window
code |= LEFT;
return code;
}
void display()
{
double x0=120,y0=10,x1=40,y1=130;
glClear(GL_COLOR_BUFFER_BIT);
//draw the line with red color
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINES);
glVertex2d (x0, y0);
glVertex2d (x1, y1);
glVertex2d (10,70);
glVertex2d (250,90);
glEnd();
//draw a blue colored window
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_LINE_LOOP);
glVertex2d(xmin, ymin);
glVertex2d(xmax, ymin);
glVertex2d(xmax, ymax);
glVertex2d(xmin, ymax);
glEnd();
CohenSutherlandLineClipAndDraw(x0,y0,x1,y1);
CohenSutherlandLineClipAndDraw(10,70,250,90);
glFlush();
}
void myInit()
{
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(1.0,0.0,0.0);
glPointSize(1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,499.0,0.0,499.0);
}
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("Cohen Sutherland Line Clipping Algorithm");
glutDisplayFunc(display);
myInit();
glutMainLoop();
return 0;
}
Output:
6. Design, develop, and implement a program in C/C++ 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 surfaces of the solid object used in the scene, using
OpenGL API.
Program:
#include<GL/glut.h>
tableLeg(legThick,legLen);
glTranslated(0,0,-2*dist);
tableLeg(legThick,legLen);
glPopMatrix();
}
void displaySolid(void)
{
GLfloat mat_ambient[]={0.7f,0.7f,0.7f,1.0f};
GLfloat mat_diffuse[]={.5f,.5f,.5f,1.0f};
GLfloat mat_specular[]={1.0f,1.0f,1.0f,1.0f};
GLfloat mat_shininess[]={50.0f};
glMaterialfv(GL_FRONT,GL_AMBIENT,mat_ambient);
glMaterialfv(GL_FRONT,GL_DIFFUSE,mat_diffuse);
glMaterialfv(GL_FRONT,GL_SPECULAR,mat_specular);
glMaterialfv(GL_FRONT,GL_SHININESS,mat_shininess);
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);
glLightfv(GL_LIGHT0,GL_DIFFUSE,lightIntensity);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1.3,1.3,-1.3,1.3,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.38,0.45);
glRotated(30,0,1,0);
glutSolidTeapot(0.10);
glPopMatrix();
glPushMatrix();
glTranslated(0.4,0,0.4);
table(0.6,0.02,0.02,0.3);
glPopMatrix();
wall(0.02);
glPushMatrix();
glRotated(90.0,0.0,0.0,1.0);
wall(0.02);
glPopMatrix();
glPushMatrix();
glRotated(-90.0,1.0,0.0,0.0);
wall(0.02);
glPopMatrix();
glFlush();
}
Output:
Algorithm:
Step 3: Select any three vertices that form one of the triangular faces of the tetrahedron
Step 4: Find the mid-points of the edges that form the triangular face
Step 5: Subdivide the triangular face by drawing three triangles using the original vertices and
the midpoints.
Step 7: if n ≠ 0, then select each newly formed triangle and subdivide them recursively.
Step 8: if n ==0, select the next three set of original vertices that form the tetrahedron and
repeat the steps 4 to 7.
Program:
#include <stdio.h>
#include <GL/glut.h>
/* initial tetrahedron */
typedef float point[3];
point v[] = { {0.0,0.0,-0.0},
{0.0,0.9,-1.0},
{-0.8,-0.4,-1.0},
{0.8,-0.4,-1.0}
};
int n;
//tetrahedron
void tetrahedron(int m)
{
glColor3f(1.0,0.0,0.0);
divide_triangle(v[0],v[1],v[2],m);
glColor3f(0.0, 1.0, 0.0);
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
tetrahedron(n);
glFlush();
}
glutInitWindowPosition(0,0);
glutCreateWindow("3D Gasket");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glEnable(GL_DEPTH_TEST);
glClearColor(1.0,1.0,1.0,1.0);
glutMainLoop();
return 0;
}
Output:
8. Design, develop, and implement a menu driven program to animate a flag using Bezier
Curve algorithm, using OpenGL API.
Description:
Bezier curve section can be fitted to any number of control points. The number of
control points to be approximated and their relative position determine the degree of the
Bezier polynomial. As with the interpolation splines, a bezier curve can be specified with
boundary conditions, with a characterizing matrix, or with blending functions. For general
Bezier curves, the blending-function specification is the most convenient.
Suppose we are given n + 1 control-point positions: pk = (xk, yk, zk), with k varying from 0
to n. These coordinate points can be blended to produce the following position vector P(u),
which describes the path of an approximating BCzier polynomial function between p0 and pn.
Equivalently, we can define Bezier blending functions with the recursive calculation
The first equation represents a set of three parametric equations for the individual curve
coordinates:
As a rule, a bezier curve is a polynomial of degree one less than the number of control points
used: Three points generate a parabola, four points a cubic curve, and so forth.
Efficient methods for determining coordinate positions along a Bezier curve can be set up using
recursive calculations. For example, successive binomial coefficients can be calculated as
Program:
#include<GL/gl.h>
#include<GL/glut.h>
#include<stdio.h>
#include<math.h>
#define PI 3.1416
float theta = 0;
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
int c[4],k,n=3;
int cp[4][2]={{100,400},{150,450},{250,350},{300,400}};
theta+=10.0;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glPointSize(5);
bino(n,c);
glPushMatrix();
glLineWidth(5);
glColor3f(1, 0.4, 0.2); //Indian flag: Orange color code for(int i=0;i<50;i++)
Prepared By: Shatananda Bhat P, Asst. Professor, Department of CS & E, CEC | 46
Computer Graphics Laboratory with Mini Project 17CSL68
for(int i=0;i<50;i++)
{
glTranslatef(0, -0.8, 0);
bezier(c,cp,n);
}
glColor3f(0, 1, 0);
for(int i=0;i<50;i++)
{
glTranslatef(0, -0.8, 0);
bezier(c,cp,n);
}
glPopMatrix();
glColor3f(0.7, 0.5,0.3);
glLineWidth(5);
glBegin(GL_LINES);
glVertex2f(100,400);
glVertex2f(100,40);
glEnd();
glutPostRedisplay();
glutSwapBuffers();
}
void init()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,500,0,500);
}
glutInitWindowSize(500,500);
glutCreateWindow("Bezier Curve");
init();
glutDisplayFunc(display);
glutMainLoop();
}
Output:
10. Design, develop, and implement a menu driven program to fill the polygon using scan line
algorithm using OpenGL API.
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:
3.1 Move from ET bucket y to the AET those edges whose y_min = y (entering edges).
3.2 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).
3.3 Fill in desired pixel values on scanline y by using pairs of x coordinates from AET.
3.4 Increment y by 1 (to the coordinate of the next scanline).
3.5 For each nonvertical edge remaining in the AET, update x for the new y.
Program:
#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
#include <windows.h>
float x1,x2,x3,x4,y1,y2,y3,y4;
int fillFlag=0;
x=x1;
for(i=y1;i<=y2;i++)
{
if(x<(float)le[i])
le[i]=(int)x;
if(x>(float)re[i])
re[i]=(int)x;
x+=mx;
}
}
void 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++)
{
for(i=(int)le[y];i<(int)re[y];i++)
draw_pixel(i,y);
}
}
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();
if(fillFlag==1)
scanfill(x1,y1,x2,y2,x3,y3,x4,y4);
glFlush();
}
void init()
{
glClearColor(0.0,0.0,0.0,1.0);
glColor3f(1.0,0.0,0.0);
glPointSize(1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,499.0,0.0,499.0);
}
Output:
Viva questions
1. Explain all the OpenGL functions used in this program?
2. What is the principle of Sierpinski gasket?
3. Difference between additive and subtractive color?
4. What is the Graphics Architecture used in OpenGL?
5. What is Rasterisation?
6. Explain sierpinski Gasket (using points).
7. Explain sierpinski Gasket (using polye )
8. Difference between 2D Tetrohedron and 3D Tetrahedron.
9. What do you mean by clipping?
10. How is Liang-Barsky clipping different from CohenSutherland Clipping Algorithm?
11. How do you set the color attributes in Opengl?
12. What is the command for clearscreen?
13. What is Event callback function?
14. Explain Liang-Barsky line clipping algorithm?
15. Explain window to viewpoint mapping?
16. What are vertex arrays?
17. How are the faces of the color cube modeled?
18. How do you consider the inward and outward pointing of the faces?
19. Explain the OpenGL function used to rotate the color cube?
20. What is the difference between 2D and 3D orthographic projection statements?
21. Explain the Inward and Outward pointing face?
22. Explain the data structure for object representation?
23. Explain the vertex list representation of a cube?
24. What is transformation?
25. Explain the OpenGL functions used for translation, rotation and scaling?
26. What is the order of transformation?
27. State the difference between modelview and projection?
28. What is Homogeneous-coordinate representation?
29. Define the rotation matrix and object matrix.
30. Explain the procedure to obtain the resultant matrix using rotation matrix and object
matrix.
31. What is the principle of Cohen-Sutherland Algorithm?
32. State the advantages and disadvantages of Cohen-Sutherland Algorithm?
33. What is an outcode?
34. What is Synthetic Camera Model?
35. What are the Camera Specifications?
36. Explain the cases of outcodes in Cohen-Sutherland algorithm.
37. Explain the cohen-sutherland line clipping algorithm
38. Mention the difference between Liang-Barsky and Cohen-Sutherland line clipping
algorithm.
39. Explain about gluLookAt(...), glFrustum(...), gluPerspective?
40. Explain the different types of projections?
41. Explain Z-buffer algorithm?
42. What is antialiasing?
2. What is OpenGL?
Answer: OpenGL is the most extensively documented 3D graphics API (Application Pro-
gram Interface) to date. It is used to create Graphics.
3. What is GLUT?
Answer: The OpenGL Utility Toolkit (GLUT) is a library of utilities for OpenGL programs,
which primarily perform system-level I/O with the host operating system.
structure is created that contains a list of edges that begin on each scanline of the
image. The program progresses from the first scanline upward. For each line, any pixels
that contain an intersection between this scanline and an edge of the polygon are filled
in. Then, the algorithm progresses along the scanline, turning on when it reaches a
polygon pixel and turning o_ when it reaches another one, all the way across the
scanline.
program_entrypoint
{
// Determine which depth or pixel format should be used.
// Create a window with the desired format.
// Create a rendering context and make it current with the window.
// Set up initial OpenGL state.
// Set up callback routines for window resize and window refresh.
}
handle_resize
{
glViewport(...);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Set projection transform with glOrtho, glFrustum, gluOrtho2D, gluPerspective, etc.
}
handle_refresh
{
glClear(...);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Set view transform with gluLookAt or equivalent
// For each object (i) in the scene that needs to be rendered:
// Push relevant stacks, e.g., glPushMatrix, glPushAttrib.
// Set OpenGL state speci_c to object (i).
// Set model transform for object (i) using glTranslatef, glScalef, glRotatef, and/or equiv-
alent.
// Issue rendering commands for object (i).
// Pop relevant stacks, (e.g., glPopMatrix, glPopAttrib.)
// End for loop.
// Swap bu_ers.
}
19. What does the .gl or .GL _le format have to do with OpenGL?
Answer: .gl _les have nothing to do with OpenGL, but are sometimes confused with it.
.gl is a file format for images, which has no relationship to OpenGL.
20. Who needs to license OpenGL? Who doesn't? Is OpenGL free software?
Answer: Companies which will be creating or selling binaries of the OpenGL library will
need to license OpenGL. Typical examples of licensees include hardware vendors,
such as Digital Equipment, and IBM who would distribute OpenGL with the system
software on their workstations or PCs. Also, some software vendors, such as Portable
Graphics and Template Graphics, have a business in creating and distributing versions
of OpenGL, and they need to license OpenGL. Applications developers do NOT need to
license OpenGL. If a developer wants to use OpenGL that developer needs to obtain
copies of a linkable OpenGL library for a particular machine. Those OpenGL libraries
may be bundled in with the development and/or run-time options or may be purchased
from a third-party software vendor, without licensing the source code or use of the
OpenGLtrademark.