INTRODUCTION
OpenGL (Open Graphics Library) is an application program
interface (API) that is used to define 2D and 3D computer graphics.
The interface consists of over 250 different function
calls which can be used to draw complex three-dimensional scenes from simple
primitives. OpenGL was developed by Silicon Graphics Inc. (SGI) in 1992 and is
widely used in CAD, virtual reality, scientific visualization, information
visualization, and flight simulation.
OpenGL's basic operation is to accept primitives such as points,
lines and polygons, and convert them into pixels. This is done by a graphics
pipeline known as the OpenGL state machine.
FEATURES OF OpenGL :-
- Geometric Primitives Allow you to construct mathematical descriptions of objects.
- Color coding in RGBA (Red-Green-Blue-Alpha) or in color index mode.
- Viewing and Modeling permits arranging objects in a 3-dimensional scene, move our camera around space and select the desired vantage point for viewing the scene to be rendered.
- Texture mapping helps to bring realism into our models by rendering images of realistic looking surfaces on to the faces of the polygon in our model.
- Materials lighting OpenGL provides commands to compute the color of any point given the properties of the material and the sources of light in the room.
- Double buffering helps to eliminate flickering from animations. Each successive frame in an animation is built in a separate memory buffer and displayed only when rendering of the frame is complete.
- Anti-aliasing reduces jagged edges in lines drawn on a computer display. Jagged lines often appear when lines are drawn at low resolution. Anti-aliasing is a common computer graphics technique that modifies the color and intensity of the pixels near the line in order to reduce the artificial zig-zag.
- Gouraud shading is a technique used to apply smooth shading to a 3D object and provide subtle color differences across its surfaces.
- Z-buffering keeps track of the Z coordinate of a 3D object. The Z-buffer is used to keep track of the proximity of the viewer's object. It is also crucial for hidden surface removal
- Transformations: rotation, scaling, translations, perspectives in 3D, etc.
GLUT Fuctions :-
The OpenGL Utility
Toolkit (GLUT) is a programming interface with ANSI
C and FORTRAN bindings for writing window system independent OpenGL programs.
glutInit :- glutInit is used to initialize the GLUT
library.
Syntax:- void glutInit(int *argcp, char **argv);
argcp
A pointer to the program's unmodified argc variable from
main. Upon return, the value pointed to by argcp will be updated, because
glutInit extracts any command line options intended for the GLUT library.
argv
The program's unmodified argv variable from main. Like
argcp, the data for argv will be updated because glutInit extracts any command
line options understood by the GLUT library.
glutInitWindowPosition,
glutInitWindowSize :-
glutInitWindowPosition and glutInitWindowSize set the initial window
position and size respectively.
Syntax:- void glutInitWindowSize(int width, int height);
void
glutInitWindowPosition(int x, int y);
width : Width in pixels.
Height:- Height in pixels.
x :- Window X location in pixels.
Y :- Window Y location in pixels.
glutInitDisplayMode:- glutInitDisplayMode sets the initial display
mode.
Syntax:- void
glutInitDisplayMode(unsigned int mode);
mode :- Display mode,
normally the bitwise OR-ing of GLUT display mode bit masks. Mode can take
following values.
Values
|
Meaning
|
GLUT_RGBA
|
Bit mask to
select an RGBA mode window. This is the default if neither GLUT_RGBA nor
GLUT_INDEX are specified.
|
GLUT_RGB
|
An alias for
GLUT_RGBA.
|
GLUT_INDEX
|
Bit mask to
select a color index mode window. This overrides GLUT_RGBA if it is also
specified.
|
GLUT_SINGLE
|
Bit mask to
select a single buffered window. This is the default if neither
|
GLUT_DOUBLE
|
Bit mask to
select a double buffered window. This overrides GLUT_SINGLE if it is also
specified.
|
GLUT_DEPTH
|
Bit mask to
select a window with a depth buffer.
|
glutMainLoop:- glutMainLoop enters the GLUT event
processing loop.
Syntax:- void glutMainLoop(void);
glutCreateWindow:- glutCreateWindow
creates a top-level window.
Syntax:- int glutCreateWindow(char
*name);
name :- ASCII character string for use as window name.
glutPositionWindow:-
glutPositionWindow requests a change to the position of the current window.
Syntax:- void
glutPositionWindow(int x, int y);
x :- New X location of window in pixels.
Y :- New Y location of window in pixels.
glutReshapeFunc :- glutReshapeFunc sets the reshape callback
for the current window.
Syntax:- void glutReshapeFunc(void
(*func)(int width, int height));
func :- The new reshape callback function.
glutDisplayFunc:- glutDisplayFunc sets the display callback
for the current window.
Syntax:- void glutDisplayFunc(void
(*func)(void));
func :- The new display callback function.
glutKeyboardFunc :- glutKeyboardFunc
sets the keyboard callback for the current window.
Syntax:- void glutKeyboardFunc(void (*func)(unsigned char key, int x, int y));
func :- The new keyboard callback function.
glutMouseFunc:- glutMouseFunc sets the mouse callback for
the current window.
Syntax:- void glutMouseFunc(void (*func)(int button, int state, int x, int
y));
func :- The new mouse callback function.
GL Fuctions :-
glBegin & glEnd :- The glBegin and glend
functions delimit the vertices of a primitive or a group of like primitives.
Syntax :- void glBegin( GLenum mode );
mode :- The primitive or primitives that will be created from vertices
presented between glBegin and the subsequent glEnd.
The following are accepted symbolic constants and their meanings:
Value
|
Meaning
|
GL_POINTS
|
Treats each vertex as a single
point. Vertex n defines point n. N points are
drawn.
|
GL_LINES
|
Treats each pair of vertices as an
independent line segment. Vertices 2n - 1 and 2n define
line n. N/2 lines are drawn.
|
GL_LINE_STRIP
|
Draws a connected group of line
segments from the first vertex to the last. Vertices n and n+1
define line n. N - 1 lines are drawn.
|
GL_LINE_LOOP
|
Draws a connected group of line
segments from the first vertex to the last, then back to the first. Vertices n
and n + 1 define line n. The last line, however, is defined
by vertices N and 1. N lines are drawn.
|
GL_TRIANGLES
|
Treats each triplet of vertices as
an independent triangle. Vertices 3n - 2, 3n - 1, and 3n
define triangle n. N/3 triangles are drawn.
|
GL_TRIANGLE_STRIP
|
Draws a connected group of
triangles. One triangle is defined for each vertex presented after the first
two vertices. For odd n, vertices n, n + 1, and n
+ 2 define triangle n. For even n, vertices n + 1,
n, and n + 2 define triangle n. N - 2
triangles are drawn.
|
GL_TRIANGLE_FAN
|
Draws a connected group of
triangles. one triangle is defined for each vertex presented after the first
two vertices. Vertices 1, n + 1, n + 2 define
triangle n. N - 2 triangles are drawn.
|
GL_QUADS
|
Treats each group of four vertices
as an independent quadrilateral. Vertices 4n - 3, 4n - 2, 4n
- 1, and 4n define quadrilateral n. N/4
quadrilaterals are drawn.
|
GL_QUAD_STRIP
|
Draws a connected group of
quadrilaterals. One quadrilateral is defined for each pair of vertices
presented after the first pair. Vertices 2n - 1, 2n, 2n
+ 2, and 2n + 1 define quadrilateral n. N/2 - 1
quadrilaterals are drawn. Note that the order in which vertices are used to
construct a quadrilateral from strip data is different from that used with
independent data.
|
GL_POLYGON
|
Draws a single, convex polygon.
Vertices 1 through N define this polygon.
|
glclear :- The glClear function clears buffers to preset
values.
Syntax:- void glClear(GLbitfield mask);
mask :- Bitwise OR operators of masks that indicate the buffers to be
cleared. The four masks are as follows.
Value
|
Meaning
|
GL_COLOR_BUFFER_BIT
|
The buffers currently enabled for
color writing.
|
GL_DEPTH_BUFFER_BIT
|
The depth buffer.
|
GL_ACCUM_BUFFER_BIT
|
The accumulation buffer.
|
GL_STENCIL_BUFFER_BIT
|
The stencil buffer.
|
glClearColor:- The glClearColor function specifies clear values
for the color buffers.
Syntax :-void glClearColor(red, green, blue, alpha);
red :- The red value that glClear
uses to clear the color buffers. The default value is zero.
green :-The green value that glClear
uses to clear the color buffers. The default value is zero.
blue :- The blue value that glClear
uses to clear the color buffers. The default value is zero.
alpha :-The alpha value that glClear
uses to clear the color buffers. The default value is zero.
glColor3i :- Sets the current color.
Syntax :- void glColor3i(GLint red, GLint green, GLint blue);
red :- The new red value for the current color.
green :-The new green value for the current color.
blue :- The new blue value for the current color.
glColor3fv:- Sets the current color from an already existing array of color
values.
Syntax :- void glColor3fv(const GLfloat *v);
V:- A pointer to an array that contains red, green, and blue values.
glEnable, glDisable :- The glEnable
and glDisable functions enable or disable OpenGL capabilities.
Syntax :- void glEnable(GLenum cap);
void glDisable(GLenum cap);
cap :- Both glEnable
and glDisable take a single argument, cap, which can
assume one of the following values:
Value
|
Meaning
|
GL_DEPTH_TEST
|
If
enabled, do depth comparisons and update the depth buffer. See glDepthFunc
and glDepthRange.
|
GL_LINE_SMOOTH
|
If
enabled, draw lines with correct filtering. If disabled, draw aliased lines.
See glLineWidth.
|
GL_LINE_STIPPLE
|
If
enabled, use the current line stipple pattern when drawing lines. See glLineStipple.
|
GL_NORMALIZE
|
If
enabled, normal vectors specified with glNormal are scaled
to unit length after transformation. See glNormal.
|
GL_POINT_SMOOTH
|
If
enabled, draw points with proper filtering. If disabled, draw aliased points.
See glPointSize.
|
glFlush:- The glFlush function forces execution of OpenGL
functions in finite time.
Syntax:- void glFlush(void);
This function has no parameters.
glFrustum:- The glFrustum function multiplies the current
matrix by a perspective matrix.
Syntax :- void glFrustum(GLdouble left, GLdouble right, GLdouble bottom,
GLdouble top, GLdouble zNear, GLdouble zFar);
left :- The coordinate for the left-vertical clipping plane.
right :- The coordinate for the right-vertical clipping plane.
bottom :- The coordinate for the bottom-horizontal clipping plane.
top :- The coordinate for the bottom-horizontal clipping plane.
zNear :-The distances to the near-depth clipping plane. Must be positive.
zFar :- The distances to the far-depth clipping planes. Must be
positive.
glLightfv:- The glLightfv
function returns light source parameter values.
Syntax:- void
glLightfv(GLenum light, GLenum pname, const GLfloat *params);
Light:- The identifier of a light. The number of possible lights depends on
the implementation, but at least eight lights are supported. They are
identified by symbolic names of the form GL_LIGHTi where i is
a value: 0 to GL_MAX_LIGHTS - 1.
pname :- A single-valued light source
parameter for light. The following symbolic names are accepted.
Value
|
Meaning
|
GL_AMBIENT
|
The params
parameter contains four floating-point values that specify the ambient RGBA
intensity of the light. Floating-point values are mapped directly. Neither
integer nor floating-point values are clamped. The default ambient light
intensity is (0.0, 0.0, 0.0, 1.0).
|
GL_DIFFUSE
|
The params
parameter contains four floating-point values that specify the diffuse RGBA
intensity of the light. Floating-point values are mapped directly. Neither
integer nor floating-point values are clamped. The default diffuse intensity
is (0.0, 0.0, 0.0, 1.0) for all lights other than light zero. The default
diffuse intensity of light zero is (1.0, 1.0, 1.0, 1.0).
|
GL_SPECULAR
|
The params
parameter contains four floating-point values that specify the specular RGBA
intensity of the light. Floating-point values are mapped directly. Neither
integer nor floating-point values are clamped. The default specular intensity
is (0.0, 0.0, 0.0, 1.0) for all lights other than light zero. The default
specular intensity of light zero is (1.0, 1.0, 1.0, 1.0).
|
GL_POSITION
|
The params
parameter contains four floating-point values that specify the position of
the light in homogeneous object coordinates. Both integer and floating-point
values are mapped directly. Neither integer nor floating-point values are
clamped.
|
param :- Specifies the value that
parameter pname of light source light will be set to.
glLoadIdentity :- The glLoadIdentity
function replaces the current matrix with the identity matrix.
Syntax :- void WINAPI glLoadIdentity(void);’
glMatrixMode:- The glMatrixMode function specifies which matrix is
the current matrix.
Syntax:-
void
glMatrixMode(GLenum mode);
mode :- The matrix stack that is the
target for subsequent matrix operations. The mode parameter can assume
one of three values.
Value
|
Meaning
|
GL_MODELVIEW
|
Applies
subsequent matrix operations to the modelview matrix stack.
|
GL_PROJECTION
|
Applies
subsequent matrix operations to the projection matrix stack.
|
GL_TEXTURE
|
Applies
subsequent matrix operations to the texture matrix stack.
|
glOrtho:- The glOrtho function multiplies the current matrix
by an orthographic matrix.
Syntax:- void glOrtho(GLdouble left, GLdouble right, GLdouble
bottom,
GLdouble top, GLdouble
zNear, GLdouble zFar);
left :-The coordinates for the left
vertical clipping plane.
right :- The coordinates for theright
vertical clipping plane.
Bottom:- The coordinates for the bottom
horizontal clipping plane.
top :- The coordinates for the top
horizontal clipping plans.
zNear :- The distances to the nearer
depth clipping plane. This distance is negative if the plane is to be behind
the viewer.
zFar :- The distances to the farther
depth clipping plane. This distance is negative if the plane is to be behind
the viewer.
glPointSize :- The glPointSize function specifies the diameter of
rasterized points.
Syntax
:- void
glPointSize(GLfloat size);
Size:-The diameter of rasterized
points. The default is 1.0.
glPushMatrix
& glPopMatrix:- The glPushMatrix
and glPopMatrix functions push and pop the current matrix
stack.
Syntax:- void WINAPI glPopMatrix(void);
glRotatef:- The glRotatef function multiplies the current
matrix by a rotation matrix.
Syntax
:- void glRotatef(GLfloat
angle, GLfloat x, GLfloat y, GLfloat z);
angle :- The angle of rotation, in
degrees.
X :- The x coordinate of a
vector.
y :- The y coordinate of a
vector.
z :- The z coordinate of a
vector.
glScalef :- The glScaled
and glScalef functions multiply the current matrix by a
general scaling matrix.
Syntax
:- void
glScalef(GLfloat x, GLfloat y, GLfloat z);
x :- Scale factors along the x
axis.
y :- Scale factors along the y
axis.
z :- Scale factors along the z
axis.
Syntax:- void glTranslatef(GLfloat x, GLfloat y, GLfloat z);
x :- The x coordinate of a
translation vector.
y :- The y coordinate of a
translation vector.
z :- The z coordinate of a
translation vector.
glVertex2d :- Specifies a vertex.
Syntax:- void glVertex2d(GLdouble x, GLdouble y);
x :- Specifies the x-coordinate of a
vertex.
y :-Specifies the y-coordinate of a
vertex.
glViewport :- The glViewport function sets the viewport.
Syntax:- void glViewport(GLint x, GLint y, GLsizei width,
GLsizei height);
x :- The lower-left corner of the
viewport rectangle, in pixels. The default is (0,0).
y :- The lower-left corner of the
viewport rectangle, in pixels. The default is (0,0).
Width :-The width of the viewport. When
an OpenGL context is first attached to a window, width and height
are set to the dimensions of that window.
height :- The height of the viewport.
When an OpenGL context is first attached to a window, width and height
are set to the dimensions of that window.
GLU Functions :-
gluLookAt :- The gluLookAt function defines a viewing
transformation.
Syntax:- void
gluLookAt(GLdouble eyex, GLdouble eyey, GLdouble eyez,
GLdouble centerx, GLdouble centery,GLdouble centerz,
GLdouble upx, GLdouble upy, GLdouble upz);
eyex :- The
position of the eye point.
eyey :-The position
of the eye point.
eyez :- The
position of the eye point.
centerx :- The
position of the reference point.
centery :- The
position of the reference point.
centerz :- The
position of the reference point.
upx :- The
direction of the up vector.
upy :- The
direction of the up vector.
upz :- The
direction of the up vector.
gluOrtho2D :- The gluOrtho2D function defines
a 2-D orthographic projection matrix.
Syntax :- void gluOrtho2D(GLdouble left, GLdouble right, GLdouble top, GLdouble bottom);
left :- The
coordinate for the left vertical clipping plane.
right :- The
coordinate for the right vertical clipping plane.
top :- The
coordinate for the top horizontal clipping plane.
bottom :- The
coordinate for the bottom horizontal clipping plane.
Program 1:- Recursive subdivision of tetrahedron to
form 3D Sierpinski gasket
#include
<stdlib.h>
#include
<stdio.h>
#include
<GL/glut.h>
typedef float
point[3];
/* initial
tetrahedron */
point v[]={{0.0,
0.0, 1.0}, {0.0, 0.942809, -0.33333},
{-0.816497, -0.471405, -0.333333},
{0.816497, -0.471405, -0.333333}};
static GLfloat
theta[] = {0.0,0.0,0.0};
int n;
void triangle(
point a, point b, point c)
/* display one
triangle using a line loop for wire frame, a single
normal for
constant shading, or three normals for interpolative shading */
{
glBegin(GL_POLYGON);
glNormal3fv(a);
glVertex3fv(a);
glVertex3fv(b);
glVertex3fv(c);
glEnd();
}
void divide_triangle(point
a, point b, point c, int m)
{ /* triangle subdivision using
vertex numbers
Righth and rule applied to
create outward pointing faces */
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(c, v2, v3, m-1);
divide_triangle(b, v3, v1, m-1);
}
else(triangle(a,b,c)); /* draw triangle at
end of recursion */
}
void tetrahedron(
int m)
{ /* Apply triangle subdivision to faces
of tetrahedron */
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);
glLoadIdentity();
tetrahedron(n);
glFlush();
}
void myReshape(int
w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= h)
glOrtho(-2.0, 2.0, -2.0 * (GLfloat) h /
(GLfloat) w,
2.0 * (GLfloat) h / (GLfloat) w, -10.0,
10.0);
else
glOrtho(-2.0 * (GLfloat) w / (GLfloat)
h,
2.0 * (GLfloat) w / (GLfloat) h,
-2.0, 2.0, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glutPostRedisplay();
}
void main(int argc,
char **argv)
{
printf("
No. of Divisions ? ");
scanf("%d",&n);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB
| GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutCreateWindow("3D Gasket");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glEnable(GL_DEPTH_TEST);
glClearColor (1.0, 1.0, 1.0, 1.0);
glutMainLoop();
}
Output:
Viva Questions:
1.
Explain sierpinski Gasket
(using points).
2.
Explain sierpinski Gasket (using
polye )
3.
Tracing of the program.
4.
Difference between 2D
Tetrohedron and 3D Tetrahedron.
Program 2 :- Liang-Barsky Line Clipping Algorithm with
Window to viewport
Mapping
#include
<stdio.h>
#include
<GL/glut.h>
double xmin=50,ymin=50,
xmax=100,ymax=100; // Window boundaries
double
xvmin=200,yvmin=200,xvmax=300,yvmax=300; // Viewport boundaries
int
cliptest(double p, double q, double *t1, double *t2)
{ double t=q/p;
if(p < 0.0) // potentially enry point, update te
{
if( t > *t1) *t1=t;
if( t > *t2) return(false); // line portion is outside
}
else if(p > 0.0) //
Potentially leaving point, update tl
{
if( t < *t2) *t2=t;
if( t < *t1) return(false); // line portion is outside
}
else if(p == 0.0)
{
if( q < 0.0)
return(false); // line parallel to edge but
outside
}
return(true);
}
void
LiangBarskyLineClipAndDraw (double x0, double y0,double x1, double y1)
{
double dx=x1-x0, dy=y1-y0, te=0.0,
tl=1.0;
if(cliptest(-dx,x0-xmin,&te,&tl)) // inside test wrt left edge
if(cliptest(dx,xmax-x0,&te,&tl))
// inside test wrt right edge
if(cliptest(-dy,y0-ymin,&te,&tl))
// inside test wrt bottom edge
if(cliptest(dy,ymax-y0,&te,&tl))
// inside test wrt top edge
{
if( tl < 1.0 )
{
x1 = x0 +
tl*dx;
y1 = y0 +
tl*dy;
}
if( te > 0.0 )
{ x0 = x0 + te*dx;
y0 = y0 +
te*dy;
}
// Window to viewport mappings
double
sx=(xvmax-xvmin)/(xmax-xmin); // Scale parameters
double sy=(yvmax-yvmin)/(ymax-ymin);
double
vx0=xvmin+(x0-xmin)*sx;
double
vy0=yvmin+(y0-ymin)*sy;
double
vx1=xvmin+(x1-xmin)*sx;
double
vy1=yvmin+(y1-ymin)*sy;
//draw a red
colored viewport
glColor3f(1.0, 0.0,
0.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xvmin,
yvmin);
glVertex2f(xvmax,
yvmin);
glVertex2f(xvmax,
yvmax);
glVertex2f(xvmin,
yvmax);
glEnd();
glColor3f(0.0,0.0,1.0);
// draw blue colored clipped line
glBegin(GL_LINES);
glVertex2d
(vx0, vy0);
glVertex2d
(vx1, vy1);
glEnd();
}
}// end of line clipping
void display()
{
double
x0=60,y0=20,x1=80,y1=120;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINES);
glVertex2d (x0, y0);
glVertex2d (x1, y1);
glEnd();
//draw a blue
colored window
glColor3f(0.0,
0.0, 1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xmin, ymin);
glVertex2f(xmax, ymin);
glVertex2f(xmax, ymax);
glVertex2f(xmin, ymax);
glEnd();
LiangBarskyLineClipAndDraw(x0,y0,x1,y1);
glFlush();
}
void myinit()
{
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(1.0,0.0,0.0);
glPointSize(1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,499.0,0.0,499.0);
}
void main(int
argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("Liang Barsky
Line Clipping Algorithm");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
Output:-
Viva Questions:
1.
What is clipping?
2.
Explain liang-Bareky line clipping
algorithm?
3.
Explain window to
viewpoint mapping?
4.
Tracing of the program.
Program 3 :- Rotating cube with color interpolation
#include
<stdlib.h>
#include
<GL/glut.h>
GLfloat vertices[]
= {-1.0,-1.0,-1.0,1.0,-1.0,-1.0, 1.0,1.0,-1.0, -1.0,1.0,-1.0, -1.0,-1.0,1.0,
1.0,-1.0,1.0, 1.0,1.0,1.0, -1.0,1.0,1.0};
GLfloat colors[] =
{0.0,0.0,0.0,1.0,0.0,0.0, 1.0,1.0,0.0,
0.0,1.0,0.0, 0.0,0.0,1.0,
1.0,0.0,1.0, 1.0,1.0,1.0,
0.0,1.0,1.0};
static GLfloat
theta[] = {0.0,0.0,0.0};
static GLint axis
= 2;
void display(void)
{ /* display callback, clear frame buffer and
z buffer,
rotate cube and draw, swap buffers */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glRotatef(theta[0], 1.0, 0.0, 0.0);
glRotatef(theta[1], 0.0, 1.0, 0.0);
glRotatef(theta[2], 0.0, 0.0, 1.0);
glBegin(GL_LINES);
glVertex3f(0.0,0.0,0.0);
glVertex3f(1.0,1.0,1.0);
glEnd();
glFlush();
glutSwapBuffers();
}
void spinCube()
{/* Idle callback,
spin cube 2 degrees about selected axis */
theta[axis] += 0.5;
if( theta[axis] > 360.0 )
theta[axis] -= 360.0;
glutPostRedisplay();
}
void mouse(int
btn, int state, int x, int y)
{/* mouse
callback, selects an axis about which to rotate */
if(btn==GLUT_LEFT_BUTTON &&
state == GLUT_DOWN) axis = 0;
if(btn==GLUT_MIDDLE_BUTTON
&& state == GLUT_DOWN) axis = 1;
if(btn==GLUT_RIGHT_BUTTON &&
state == GLUT_DOWN) axis = 2;
}
void myReshape(int
w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= h)
glOrtho(-2.0, 2.0, -2.0 * (GLfloat) h /
(GLfloat) w,
2.0 * (GLfloat) h / (GLfloat) w,
-10.0, 10.0);
else
glOrtho(-2.0 * (GLfloat) w / (GLfloat)
h,
2.0 * (GLfloat) w / (GLfloat) h,
-2.0, 2.0, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
}
void main(int
argc, char** argv)
{/* need both
double buffering and z buffer */
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB
| GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutCreateWindow("Spin a
colorcube");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutIdleFunc(spinCube);
glutMouseFunc(mouse);
glEnable(GL_DEPTH_TEST); /* Enable
hidden--surface--removal */
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0,
vertices);
glColorPointer(3,GL_FLOAT, 0, colors);
glNormalPointer(GL_FLOAT,0, normals);
glColor3f(1.0,1.0,1.0);
glutMainLoop();
}
Output:
Viva Questions:
1.
Explain the Inward and Outward
pointing face?
2.
Explain the data structure for
object representation?
3.
Explain the vertex list
representation of a cube?
4.
Tracing of the program.
Program 4:- Progam to
draw a house and rotate about the pivot point
#include
<stdio.h>
#include
<math.h>
#include
<GL/glut.h>
GLfloat
house[3][9]={ {100.0,100.0,175.0,250.0,250.0,150.0,150.0,200.0,200.0},
{100.0,300.0,400.0,300.0,100.0,100.0,150.0,150.0,100.0},
{1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0}};
GLfloat
rot_mat[3][3]={{0},{0},{0}};
GLfloat
result[3][9]={{0}, {0}, {0}};
GLfloat h=100.0;
// Pivot point
GLfloat k=100.0;
GLfloat theta;
void multiply()
{ // Rotation MATRIX and Object Matrix
=> Resultant Transformed House
int i,j,l;
for(i=0;i<3;i++)
for(j=0;j<9;j++)
{
result[i][j]=0;
for(l=0;l<3;l++)
result[i][j]=result[i][j]+rot_mat[i][l]*house[l][j];
}
}
void rotate()
{
GLfloat m,n;
// Build the rotation matrix
m=-h*(cos(theta)-1)+k*(sin(theta));
n=-k*(cos(theta)-1)-h*(sin(theta));
rot_mat[0][0]=cos(theta);
rot_mat[0][1]=-sin(theta);
rot_mat[0][2]=m;
rot_mat[1][0]=sin(theta);
rot_mat[1][1]=cos(theta);
rot_mat[1][2]=n;
rot_mat[2][0]=0;
rot_mat[2][1]=0;
rot_mat[2][2]=1;
//multiply the two matrices:
Rotation Matrix * Objet Matrix(house)
multiply();
}
void drawhouse()
{
glColor3f(0.0,
0.0, 1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(house[0][0],house[1][0]);
glVertex2f(house[0][1],house[1][1]);
glVertex2f(house[0][3],house[1][3]);
glVertex2f(house[0][4],house[1][4]);
glEnd();
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINE_LOOP);
glVertex2f(house[0][5],house[1][5]);
glVertex2f(house[0][6],house[1][6]);
glVertex2f(house[0][7],house[1][7]);
glVertex2f(house[0][8],house[1][8]);
glEnd();
glColor3f(0.0,
0.0, 1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(house[0][1],house[1][1]);
glVertex2f(house[0][2],house[1][2]);
glVertex2f(house[0][3],house[1][3]);
glEnd();
}
void
drawrotatedhouse()
{
glColor3f(0.0,
0.0, 1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(result[0][0],result[1][0]);
glVertex2f(result[0][1],result[1][1]);
glVertex2f(result[0][3],result[1][3]);
glVertex2f(result[0][4],result[1][4]);
glEnd();
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINE_LOOP);
glVertex2f(result[0][5],result[1][5]);
glVertex2f(result[0][6],result[1][6]);
glVertex2f(result[0][7],result[1][7]);
glVertex2f(result[0][8],result[1][8]);
glEnd();
glColor3f(0.0,
0.0, 1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(result[0][1],result[1][1]);
glVertex2f(result[0][2],result[1][2]);
glVertex2f(result[0][3],result[1][3]);
glEnd();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
drawhouse();
rotate();
drawrotatedhouse();
glFlush();
}
void myinit()
{
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(1.0,0.0,0.0);
glPointSize(1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,499.0,0.0,499.0);
}
void main(int
argc, char** argv)
{
printf("Enter the rotation
angle\n");
scanf("%f", &theta);
theta=theta * 3.142/180;
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("house
rotation");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
Output:-
Viva Questions:
Define the rotation matrix
and object matrix.
1.
Explain the procedure to obtain
the resultant matrix using rotation matrix and object matrix.
2.
Tracing of the program.
Program 5:-Cohen-Suderland Line Clipping Algorithm
with Window to viewport
Mapping
#include
<stdio.h>
#include
<GL/glut.h>
#define outcode
int
double xmin=50,ymin=50,
xmax=100,ymax=100; // Window boundaries
double
xvmin=200,yvmin=200,xvmax=300,yvmax=300; // Viewport boundaries
//bit codes for
the right, left, top, & bottom
const int RIGHT =
8;
const int LEFT =
2;
const int TOP = 4;
const int BOTTOM =
1;
//used to compute
bit codes of a point
outcode
ComputeOutCode (double x, double y);
//Cohen-Sutherland
clipping algorithm clips a line from
//P0 = (x0, y0) to
P1 = (x1, y1) against a rectangle with
//diagonal from
(xmin, ymin) to (xmax, ymax).
void CohenSutherlandLineClipAndDraw
(double x0, double y0,double x1, double y1)
{
//Outcodes for P0, P1, and whatever
point lies outside the clip rectangle
outcode outcode0, outcode1,
outcodeOut;
bool accept = false, done = false;
//compute outcodes
outcode0 = ComputeOutCode (x0, y0);
outcode1 = ComputeOutCode (x1, y1);
do{
if (!(outcode0 |
outcode1)) //logical or is 0
Trivially accept & exit
{
accept =
true;
done = true;
}
else if (outcode0
& outcode1) //logical and is not 0.
Trivially reject and exit
done = true;
else
{
//failed
both tests, so calculate the line segment to clip
//from an
outside point to an intersection with clip edge
double x, y;
//At least
one endpoint is outside the clip rectangle; pick it.
outcodeOut =
outcode0? outcode0: outcode1;
//Now find
the intersection point;
//use formulas y = y0 +
slope * (x - x0), x = x0 + (1/slope)* (y - y0)
if
(outcodeOut & TOP) //point
is above the clip rectangle
{
x
= x0 + (x1 - x0) * (ymax - y0)/(y1 - y0);
y
= ymax;
}
else if (outcodeOut
& BOTTOM) //point is below the clip
rectangle
{
x
= x0 + (x1 - x0) * (ymin - y0)/(y1 - y0);
y
= ymin;
}
else if (outcodeOut
& RIGHT) //point is to the right of
clip rectangle
{
y
= y0 + (y1 - y0) * (xmax - x0)/(x1 - x0);
x
= xmax;
}
else //point is to the
left of clip rectangle
{
y
= y0 + (y1 - y0) * (xmin - x0)/(x1 - x0);
x
= xmin;
}
//Now we
move outside point to intersection point to clip
//and get
ready for next pass.
if
(outcodeOut == outcode0)
{
x0
= x;
y0
= y;
outcode0
= ComputeOutCode (x0, y0);
}
else
{
x1
= x;
y1
= y;
outcode1
= ComputeOutCode (x1, y1);
}
}
}while (!done);
if (accept)
{ // Window to viewport mappings
double
sx=(xvmax-xvmin)/(xmax-xmin); // Scale parameters
double
sy=(yvmax-yvmin)/(ymax-ymin);
double
vx0=xvmin+(x0-xmin)*sx;
double
vy0=yvmin+(y0-ymin)*sy;
double vx1=xvmin+(x1-xmin)*sx;
double
vy1=yvmin+(y1-ymin)*sy;
//draw a red
colored viewport
glColor3f(1.0, 0.0,
0.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xvmin,
yvmin);
glVertex2f(xvmax,
yvmin);
glVertex2f(xvmax,
yvmax);
glVertex2f(xvmin,
yvmax);
glEnd();
glColor3f(0.0,0.0,1.0);
// draw blue colored clipped line
glBegin(GL_LINES);
glVertex2d
(vx0, vy0);
glVertex2d
(vx1, vy1);
glEnd();
}
}
//Compute the bit
code for a point (x, y) using the clip rectangle
//bounded
diagonally by (xmin, ymin), and (xmax, ymax)
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
code |= BOTTOM;
if (x > xmax) //to the right of clip window
code |= RIGHT;
else if (x < xmin) //to the left of clip window
code |= LEFT;
return code;
}
void display()
{
double
x0=60,y0=20,x1=80,y1=120;
glClear(GL_COLOR_BUFFER_BIT);
//draw the line
with red color
glColor3f(1.0,0.0,0.0);
//bres(120,20,340,250);
glBegin(GL_LINES);
glVertex2d
(x0, y0);
glVertex2d
(x1, y1);
glEnd();
//draw a blue
colored window
glColor3f(0.0,
0.0, 1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xmin, ymin);
glVertex2f(xmax, ymin);
glVertex2f(xmax, ymax);
glVertex2f(xmin, ymax);
glEnd();
CohenSutherlandLineClipAndDraw(x0,y0,x1,y1);
glFlush();
}
void myinit()
{
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(1.0,0.0,0.0);
glPointSize(1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,499.0,0.0,499.0);
}
void main(int
argc, char** argv)
{
//int x1, x2, y1, y2;
//printf("Enter End
points:");
//scanf("%d%d%d%d",
&x1,&x2,&y1,&y2);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("Cohen
Suderland Line Clipping Algorithm");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
Output:
Viva Questions:
1.
Explain the cases of outcodes
in cohen-sutherland algorithm.
2.
Explain the cohen-sutherland
line clipping algorithm
3.
Mention the difference between
liang – Bassky and cohen-sutherland line clipping algorithm.
4.
Tracing of the program.
Program 6:-Cylinder and Parallelepiped by extruding
Circle and Quadrilateral
#include
<GL/glut.h>
#include
<math.h>
#include
<stdio.h>
void
draw_pixel(GLint cx, GLint cy)
{ glColor3f(1.0,0.0,0.0);
glBegin(GL_POINTS);
glVertex2i(cx,cy);
glEnd();
}
void
plotpixels(GLint h, GLint k, GLint x, GLint y)
{
draw_pixel(x+h,y+k);
draw_pixel(-x+h,y+k);
draw_pixel(x+h,-y+k);
draw_pixel(-x+h,-y+k);
draw_pixel(y+h,x+k);
draw_pixel(-y+h,x+k);
draw_pixel(y+h,-x+k);
draw_pixel(-y+h,-x+k);
}
void
Circle_draw(GLint h, GLint k, GLint r)
// Midpoint Circle Drawing Algorithm
{
GLint d =
1-r, x=0, y=r;
while(y > x)
{
plotpixels(h,k,x,y);
if(d < 0) d+=2*x+3;
else
{d+=2*(x-y)+5;
--y;
}
++x;
}
plotpixels(h,k,x,y);
}
void
Cylinder_draw()
{
GLint xc=100, yc=100, r=50;
GLint i,n=50;
for(i=0;i<n;i+=3)
{
Circle_draw(xc,yc+i,r);
}
}
void
parallelepiped(int x1, int x2,int y1,
int y2, int y3, int y4)
{
glColor3f(0.0,
0.0, 1.0);
glPointSize(2.0);
glBegin(GL_LINE_LOOP);
glVertex2i(x1,y1);
glVertex2i(x2,y3);
glVertex2i(x2,y4);
glVertex2i(x1,y2);
glEnd();
}
void
parallelepiped_draw()
{
int
x1=200,x2=300,y1=100,y2=175,y3=100,y4=175;
GLint i,n=40;
for(i=0;i<n;i+=2)
{
parallelepiped(x1+i,x2+i,y1+i,y2+i,y3+i,y4+i);
}
}
void init(void)
{
glClearColor(1.0,1.0,1.0,0.0); // Set display window color to white
glMatrixMode(GL_PROJECTION); // Set Projection parameters
gluOrtho2D(0.0,400.0,0.0,300.0);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT); // Clear Display Window
glColor3f(1.0,0.0,0.0); // Set
circle color to red (R G B)
glPointSize(2.0);
Cylinder_draw(); // Call cylinder
parallelepiped_draw();// call
parallelepiped
glFlush(); // Process all OpenGL
routines as quickly as possible
}
void main(int
argc, char **argv)
{
glutInit(&argc,argv); // Initialize GLUT
glutInitDisplayMode(GLUT_SINGLE |
GLUT_RGB); // Set Display mode
glutInitWindowPosition(50,50); // Set top left window position
glutInitWindowSize(400,300); // Set
Display window width and height
glutCreateWindow("Cylinder and
parallelePiped Display by Extruding Circle and Quadrilaterl "); // Create
Display Window
init();
glutDisplayFunc(display); // Send
the graphics to Display Window
glutMainLoop();
}
Output:
Viva Questions:
1.
What is midpoint circle drawing
algorithm
2.
How do you get the equation
d+=2x+3, d+=2(x-y)+5
3.
What is gluOrtho2D function
4.
Explain plot pixel function
5.
Why do we use GLFlush function
in Display
Program 7:- simple shaded scene consisting of a tea
pot on a table */
#include
<GL/glut.h>
void wall (double
thickness)
{
//draw thin wall with top =
xz-plane, corner at origin
glPushMatrix();
glTranslated (0.5, 0.5 * thickness,
0.5);
glScaled (1.0, thickness, 1.0);
glutSolidCube (1.0);
glPopMatrix();
}
//draw one table
leg
void tableLeg (double
thick, double len)
{
glPushMatrix();
glTranslated (0, len/2, 0);
glScaled (thick, len, thick);
glutSolidCube (1.0);
glPopMatrix();
}
void table (double
topWid, double topThick, double legThick, double legLen)
{
//draw the table - a top and four
legs
//draw the top first
glPushMatrix();
glTranslated (0, legLen, 0);
glScaled(topWid, topThick, topWid);
glutSolidCube (1.0);
glPopMatrix();
double dist = 0.95 * topWid/2.0 -
legThick/2.0;
glPushMatrix();
glTranslated (dist, 0, dist);
tableLeg (legThick, legLen);
glTranslated (0.0, 0.0, -2 * dist);
tableLeg (legThick, legLen);
glTranslated (-2*dist, 0, 2 *dist);
tableLeg (legThick, legLen);
glTranslated(0, 0, -2*dist);
tableLeg (legThick, legLen);
glPopMatrix();
}
void displaySolid
(void)
{ //set properties of the surface
material
GLfloat mat_ambient[] = {0.7f, 0.7f,
0.7f, 1.0f}; // gray
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);
//set the light source properties
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);
//set the camera
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
double winHt = 1.0; //half-height of
window
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);
//start drawing
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);
//glutSolidSphere (0.1, 15, 15);
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();
}
void 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();
}
Output:-
Viva Questions:
1.
what is glutSolidCube function
? what are its Parameters
2.
what are the parameters to
glScale function
3.
Explain Push & Pop matrix
Functions
4.
What is Materialfv function
& its Parameters
5.
Explain GLULookAt Function
Program 8 :- Rotating cube with viewer movement
/* We use the Lookat function in the display callback to point the
viewer, whose position can be altered by the x,X,y,Y,z, and Z keys.The
perspective view is set in the reshape callback */
#include
<stdlib.h>
#include
<GL/glut.h>
GLfloat vertices[][3] =
{{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0},
{1.0,1.0,-1.0}, {-1.0,1.0,-1.0},
{-1.0,-1.0,1.0},
{1.0,-1.0,1.0}, {1.0,1.0,1.0},
{-1.0,1.0,1.0}};
GLfloat colors[][3] =
{{0.0,0.0,0.0},{1.0,0.0,0.0},
{1.0,1.0,0.0}, {0.0,1.0,0.0},
{0.0,0.0,1.0},
{1.0,0.0,1.0}, {1.0,1.0,1.0},
{0.0,1.0,1.0}};
void polygon(int
a, int b, int c , int d)
{ glBegin(GL_POLYGON);
glColor3fv(colors[a]);
glNormal3fv(normals[a]);
glVertex3fv(vertices[a]);
glColor3fv(colors[b]);
glNormal3fv(normals[b]);
glVertex3fv(vertices[b]);
glColor3fv(colors[c]);
glNormal3fv(normals[c]);
glVertex3fv(vertices[c]);
glColor3fv(colors[d]);
glNormal3fv(normals[d]);
glVertex3fv(vertices[d]);
glEnd();
}
void colorcube()
{
polygon(0,3,2,1);
polygon(2,3,7,6);
polygon(0,4,7,3);
polygon(1,2,6,5);
polygon(4,5,6,7);
polygon(0,1,5,4);
}
static GLfloat
theta[] = {0.0,0.0,0.0};
static GLint axis
= 2;
static GLdouble
viewer[]= {0.0, 0.0, 5.0}; /* initial viewer location */
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT |
GL_DEPTH_BUFFER_BIT);
/* Update viewer
position in modelview matrix */
glLoadIdentity();
gluLookAt(viewer[0],viewer[1],viewer[2],
0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
/* rotate cube */
glRotatef(theta[0], 1.0, 0.0, 0.0);
glRotatef(theta[1], 0.0, 1.0, 0.0);
glRotatef(theta[2], 0.0, 0.0, 1.0);
colorcube();
glFlush();
glutSwapBuffers();
}
void mouse(int
btn, int state, int x, int y)
{
if(btn==GLUT_LEFT_BUTTON &&
state == GLUT_DOWN) axis = 0;
if(btn==GLUT_MIDDLE_BUTTON
&& state == GLUT_DOWN) axis = 1;
if(btn==GLUT_RIGHT_BUTTON &&
state == GLUT_DOWN) axis = 2;
theta[axis] += 2.0;
if( theta[axis] > 360.0 )
theta[axis] -= 360.0;
display();
}
void keys(unsigned
char key, int x, int y)
{
/* Use x, X, y, Y,
z, and Z keys to move viewer */
if(key == 'x') viewer[0]-= 1.0;
if(key == 'X') viewer[0]+= 1.0;
if(key == 'y') viewer[1]-= 1.0;
if(key == 'Y') viewer[1]+= 1.0;
if(key == 'z') viewer[2]-= 1.0;
if(key == 'Z') viewer[2]+= 1.0;
display();
}
void myReshape(int
w, int h)
{
glViewport(0, 0, w, h);
/* Use a
perspective view */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w<=h) glFrustum(-2.0, 2.0,
-2.0 * (GLfloat) h/ (GLfloat) w,
2.0* (GLfloat) h / (GLfloat) w, 2.0,
20.0);
else glFrustum(-2.0, 2.0, -2.0 *
(GLfloat) w/ (GLfloat) h,
2.0* (GLfloat) w / (GLfloat) h, 2.0,
20.0);
/* Or we can use
gluPerspective gluPerspective(45.0, w/h,
-10.0, 10.0); */
glMatrixMode(GL_MODELVIEW);
}
void main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB |
GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutCreateWindow("Colorcube
Viewer");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutKeyboardFunc(keys);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
}
Output:-
Viva questions:
1.
Explain how the cube is
constructed
2.
Explain rotate function
3.
What is GLFrustum function what
are its Parameters
4.
What is viewport
5.
What is glutKeyboard Function
what are its Parameters
Program 9 :- Scan-Line algorithm for filling a polygon
#define BLACK 0
#include
<stdlib.h>
#include
<stdio.h>
#include
<GL/glut.h>
float
x1,x2,x3,x4,y1,y2,y3,y4;
void
edgedetect(float x1,float y1,float x2,float y2,int *le,int *re)
{
float mx,x,temp;
int i;
if((y2-y1)<0)
{
temp=y1;y1=y2;y2=temp;
temp=x1;x1=x2;x2=temp;
}
if((y2-y1)!=0)
mx=(x2-x1)/(y2-y1);
else
mx=x2-x1;
x=x1;
for(i=y1;i<=y2;i++)
{
if(x<(float)le[i])
le[i]=(int)x;
if(x>(float)re[i])
re[i]=(int)x;
x+=mx;
}
}
void
draw_pixel(int x,int y,int value)
{
glColor3f(1.0,1.0,0.0);
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
}
void
scanfill(float x1,float y1,float x2,float y2,float x3,float y3,float x4,float
y4)
{
int le[500],re[500];
int i,y;
for(i=0;i<500;i++)
{
le[i]=500;
re[i]=0;
}
edgedetect(x1,y1,x2,y2,le,re);
edgedetect(x2,y2,x3,y3,le,re);
edgedetect(x3,y3,x4,y4,le,re);
edgedetect(x4,y4,x1,y1,le,re);
for(y=0;y<500;y++)
{
if(le[y]<=re[y])
for(i=(int)le[y];i<(int)re[y];i++)
draw_pixel(i,y,BLACK);
}
}
void display()
{
x1=200.0;y1=200.0;x2=100.0;y2=300.0;x3=200.0;y3=400.0;x4=300.0;y4=300.0;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0,
0.0, 1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(x1,y1);
glVertex2f(x2,y2);
glVertex2f(x3,y3);
glVertex2f(x4,y4);
glEnd();
scanfill(x1,y1,x2,y2,x3,y3,x4,y4);
glFlush();
}
void myinit()
{
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(1.0,0.0,0.0);
glPointSize(1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,499.0,0.0,499.0);
}
void main(int
argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("Filling a
Polygon using Scan-line Algorithm");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
Output:-
Viva Questions:
1.
Explain Polygon Filling
algorithm
2.
What is slope
3.
How the edges of polygon are
detected
4.
Why you use GL_PROJECTION in
MatrixMode Function
5.
How the cube is constructed
Program 10:- Rectangular Mesh using set of points
#include
<stdlib.h> // standard definitions
#include
<GL/glut.h> // GLUT
#define maxx 20
#define maxy 25
#define dx 15
#define dy 10
GLfloat
x[maxx]={0.0},y[maxy]={0.0};
GLfloat
x0=50,y0=50; // initial values for x, y
GLint i,j;
void init()
{
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(1.0,0.0,0.0);
glPointSize(5.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,499.0,0.0,499.0);
glutPostRedisplay(); // request redisplay
}
void display(void)
{ /* clear window */
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 0.0, 1.0); // set color
to blue
/* draw rectangles
*/
for(i=0;i<maxx;i++)
x[i]=x0+i*dx; // compute x[i]
for(j=0;j<maxy;j++)
y[j]=y0+j*dy; // compute y[i]
glColor3f(0.0, 0.0,
1.0);
for(i=0;i<maxx-1;i++)
for(j=0;j<maxy-1;j++)
{
glColor3f(0.0,
0.0, 1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(x[i],y[j]);
glVertex2f(x[i],y[j+1]);
glVertex2f(x[i+1],y[j+1]);
glVertex2f(x[i+1],y[j]);
glEnd();
glFlush();
}
glFlush();
}
void main(int
argc, char** argv)
{
glutInit(&argc,
argv); // OpenGL initializations
glutInitDisplayMode(GLUT_SINGLE
| GLUT_RGB);// single buffering and RGB
glutInitWindowSize(500,
400); // create a 500x400 window
glutInitWindowPosition(0,
0); // ...in the upper left
glutCreateWindow("Rectangular
Mesh"); // create the window
glutDisplayFunc(display);
// setup callbacks
init();
glutMainLoop(); //
start it running
}
Output:-
Viva Questions:
1.
What is dx & dy
2.
What is maxx & maxy
3.
What is glutPostRedisplay
4.
Why do we use glutMainLoop
function
5.
What do you mean by
GL_LINE_LOOP in GL_Begin function
plz explain plot pixel function
ReplyDeleteVery much use full .....add some more notes
ReplyDeletevery usefull contents it will help the students.
ReplyDeleteFind Flats in east Bangalore
please explain with detail each and ever line of the programs(please help)
ReplyDeleteplease explain each line of all programs ..........
ReplyDelete