CG Manual - CG MANUAL

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 57

COMPUTER GRAPHICS AND VISUALIZATION LAB

1. Getting Started
Before starting programming it is good idea to know details about system, say
renderer/graphics card and CPU, as well as OpenGL and DirectX versions installed in your
computer. Of course, we are here assuming that your computer is a PC running Microsoft
Windows XP or Vista.

The idea of producing pictures or images using a computer requires two processes: modeling
and rendering. Modeling has to do with the creation, manipulation, and storage of geometric
objects on computer, while rendering just means converting a scene to an image. Rendering
involves a number of transformations, namely: rasterization, shading, illumination, and
animation of the image. Computer graphics has been widely used in many areas of interest
from graphics presentation, paint systems, computer-aided design (CAD), and scientific
visualization to simulation of natural phenomena, virtual reality, computer games and, in
general, entertainment.

2. Installing Graphics Libraries: OpenGL and GLUT


We are going to use the Microsoft Visual C++ Studio in the labs. This IDE (Integrated
Development Environment) only runs on Windows XP/Vista machines.
In order to run OpenGL programs on any machine (Windows, Linux or Mac OSX), it is
necessary to use a supplementary library, called GLUT (The OpenGL Utility Toolkit). GLUT
is a window system independent toolkit for writing OpenGL programs. It implements a
simple windowing API for OpenGL that interfaces to proprietary windowing systems of
specific operating system; hence its platform independence.
GLUT supports:
1. Multiple windows for OpenGL rendering
2. Callback driven event processing
3. Sophisticated input devices
4. An 'idle' routine and timers
5. A simple, cascading pop-up menu facility
6. Utility routines to generate various solid and wire frame objects
7. Support for bitmap and stroke fonts
8. Miscellaneous window management functions

VI SEM, Dept of CSE, SJCIT 1 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
Download the GLUT toolkit from glut-3.7.6-bin.zip (117 KB). This zip file contains the
following files must be moved into the corresponding path

glut32.dll C:\WINDOWS\system32 or C:\WinNT\System


glut32.h C:\Program Files\Microsoft Visual Studio\VC98\Include\Gl
glut32.lib C:\Program Files\Microsoft Visual Studio\VC98\Lib
OR

Install Glut into the following directories:

glut32.dll -> C:\Windows\System or C:\WinNT\System


glut32.lib -> C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib
glut32.h -> C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\include\gl

Step 1: Create a Visual Studio 2005 Project


To create an empty console project in Visual Studio, do the following:
1. Create a new project (File --->  New --->  --->Project

2. In the Project Types: pane, select  Visual C++,  Win32. Then select  Win 32 Console
Application in the Templates: pane. Name your project, select the location for the project
and click OK.

VI SEM, Dept of CSE, SJCIT 2 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

3. Click the Application Settings tab on the left, and check the Empty Project box. Then
click Finish button.

Step 2: Add Source Code

VI SEM, Dept of CSE, SJCIT 3 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
1.  Select Project, Add New Item.

2. In the Categories pane, select  Visual C++,  Code. Then select  C++ File( ,cpp) in the
Templates pane. Name your file,  and then click Add.

VI SEM, Dept of CSE, SJCIT 4 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

Step 3: Modify the project properties

1. Use Visual Studio's menu Project options (Project --> Draw Properties)

2. The Draw Property Page dialog will open. Once it appears, do the following:

a. Select the Configuration combo box, select All Configuration

VI SEM, Dept of CSE, SJCIT 5 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

b. In the left pane, select the linker subtree and then click the Input option. Add the
following code to the Additional Dependencies text in the right pane.

Copy and Paste:  opengl32.lib  glu32.lib  glut32.lib

Now Visual Studio knows where to find GLUT. Click OK button

VI SEM, Dept of CSE, SJCIT 6 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
Step 4: Compile and Run the project
a. Compile 
 From the Visual Studio's menu Build option (Build  ---> Build Solution)

b. Execute the program


From the Visual Studio's menu Debug option (Debug  ---> Start Without
Debugging)

VI SEM, Dept of CSE, SJCIT 7 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

Introduction to OpenGL
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.

VI SEM, Dept of CSE, SJCIT 8 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

GLUT Functions:
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.

VI SEM, Dept of CSE, SJCIT 9 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

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 Functions:
glBegin & glEnd :‐ The glBegin and glend functions delimit the vertices of a primitive or a
group of like primitives.
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:

VI SEM, Dept of CSE, SJCIT 10 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

Values 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.


mask :‐ Bitwise OR operators of masks that indicate the buffers to be cleared. The four
masks are as follows.

Values 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_BI The stencil buffer.
T

VI SEM, Dept of CSE, SJCIT 11 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

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.

Values 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);

VI SEM, Dept of CSE, SJCIT 12 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
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.

VI SEM, Dept of CSE, SJCIT 13 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
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.

Values Meaning
GL_MODELVIEW Applies subsequent matrix operations to the model view matrix
stack.
GL_PROJECTION Applies subsequent matrix operations to the projection matrix
stack.
GL_TEXTURE Applies subsequent matrix operations to the texture matrix stack.

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 the right 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.

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.

VI SEM, Dept of CSE, SJCIT 14 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

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.

glTranslatef :‐ The glTranslatef function multiplies the current matrix by a translation


matrix.
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.

VI SEM, Dept of CSE, SJCIT 15 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

GLU Functions: Syntax

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.

VI SEM, Dept of CSE, SJCIT 16 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

1. Implement Brenham’s line drawing algorithm for all types of slope.

#include <GL/glut.h>
#include <stdio.h>
int x1, y1, x2, y2;
void myInit() {
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0.0, 0.0, 0.0, 1.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0, 500, 0, 500);
}
void draw_pixel(int x, int y) {
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
}
void draw_line(int x1, int x2, int y1, int y2) {
int dx, dy, i, e;
int incx, incy, inc1, inc2;
int x,y;
dx = x2-x1;
dy = y2-y1;
if (dx < 0) dx = -dx;
if (dy < 0) dy = -dy;
incx = 1;
if (x2 < x1) incx = -1;
incy = 1;
if (y2 < y1) incy = -1;
x = x1; y = y1;
if (dx > dy) {
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);
}
}
}

VI SEM, Dept of CSE, SJCIT 17 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

void myDisplay() {
draw_line(x1, x2, y1, y2);
glFlush();
}
int main(int argc, char **argv) {
printf( "Enter (x1, y1, x2, y2)\n");
scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(0, 0);
glutCreateWindow("Bresenham's Line Drawing");
myInit();
glutDisplayFunc(myDisplay);
glutMainLoop();
return 0;
}

SAMPLE OUTPUT:

VI SEM, Dept of CSE, SJCIT 18 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

STUDENT'S OBSERVATIONS

VI SEM, Dept of CSE, SJCIT 19 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

2. Create and rotate a triangle about the origin and a fixed point.

#include <GL/glut.h>
#include <stdlib.h>
#include <math.h>
/* Set initial display-window size. */
GLsizei winWidth = 600, winHeight = 600;
/* Set range for world coordinates. */
GLfloat xwcMin = 0.0, xwcMax = 225.0;
GLfloat ywcMin = 0.0, ywcMax = 225.0;
class wcPt2D {
public:
GLfloat x, y;
};
typedef GLfloat Matrix3x3 [3][3];
Matrix3x3 matComposite;
const GLdouble pi = 3.14159;
void init (void)
{
/* Set color of display window to white. */
glClearColor (1.0, 1.0, 1.0, 0.0);
}
/* Construct the 3 x 3 identity matrix. */
void matrix3x3SetIdentity (Matrix3x3 matIdent3x3)
{
GLint row, col;
for (row = 0; row < 3; row++)
for (col = 0; col < 3; col++)
matIdent3x3 [row][col] = (row == col);
}
void matrix3x3PreMultiply (Matrix3x3 m1, Matrix3x3 m2)
{
GLint row, col;
Matrix3x3 matTemp;
for (row = 0; row < 3; row++)
for (col = 0; col < 3 ; col++)
matTemp [row][col] = m1 [row][0] * m2 [0][col] + m1 [row][1] *
m2 [1][col] + m1 [row][2] * m2 [2][col];
for (row = 0; row < 3; row++)
for (col = 0; col < 3; col++)
m2 [row][col] = matTemp [row][col];
}

VI SEM, Dept of CSE, SJCIT 20 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
void translate2D (GLfloat tx, GLfloat ty)
{
Matrix3x3 matTransl;
/* Initialize translation matrix to identity. */
matrix3x3SetIdentity (matTransl);
matTransl [0][2] = tx;
matTransl [1][2] = ty;
/* Concatenate matTransl with the composite matrix. */
matrix3x3PreMultiply (matTransl, matComposite);
}
void rotate2D (wcPt2D pivotPt, GLfloat theta)
{
Matrix3x3 matRot;
/* Initialize rotation matrix to identity. */
matrix3x3SetIdentity (matRot);
matRot [0][0] = cos (theta);
matRot [0][1] = -sin (theta);
matRot [0][2] = pivotPt.x * (1 - cos (theta)) +
pivotPt.y * sin (theta);
matRot [1][0] = sin (theta);
matRot [1][1] = cos (theta);
matRot [1][2] = pivotPt.y * (1 - cos (theta)) -
pivotPt.x * sin (theta);
/* Concatenate matRot with the composite matrix. */
matrix3x3PreMultiply (matRot, matComposite);
}
void scale2D (GLfloat sx, GLfloat sy, wcPt2D fixedPt)
{
Matrix3x3 matScale;
/* Initialize scaling matrix to identity. */
matrix3x3SetIdentity (matScale);
matScale [0][0] = sx;
matScale [0][2] = (1 - sx) * fixedPt.x;
matScale [1][1] = sy;
matScale [1][2] = (1 - sy) * fixedPt.y;
/* Concatenate matScale with the composite matrix. */
matrix3x3PreMultiply (matScale, matComposite);
}
/* Using the composite matrix, calculate transformed coordinates. */
void transformVerts2D (GLint nVerts, wcPt2D * verts)
{
GLint k;
GLfloat temp;
for (k = 0; k < nVerts; k++) {

VI SEM, Dept of CSE, SJCIT 21 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
temp = matComposite [0][0] * verts [k].x + matComposite [0][1] *
verts [k].y + matComposite [0][2];
verts [k].y = matComposite [1][0] * verts [k].x + matComposite [1][1] *
verts [k].y + matComposite [1][2];
verts [k].x = temp;
}
}
void triangle (wcPt2D *verts)
{
GLint k;
glBegin (GL_TRIANGLES);
for (k = 0; k < 3; k++)
glVertex2f (verts [k].x, verts [k].y);
glEnd ( );
}
void displayFcn (void)
{
/* Define initial position for triangle. */
GLint nVerts = 3;
wcPt2D verts [3] = { {50.0, 25.0}, {150.0, 25.0}, {100.0, 100.0} };
/* Calculate position of triangle centroid. */
wcPt2D centroidPt;
GLint k, xSum = 0, ySum = 0;
for (k = 0; k < nVerts; k++) {
xSum += verts [k].x;
ySum += verts [k].y;
}
centroidPt.x = GLfloat (xSum) / GLfloat (nVerts);
centroidPt.y = GLfloat (ySum) / GLfloat (nVerts);
/* Set geometric transformation parameters. */
wcPt2D pivPt,fixedPt;
pivPt = centroidPt;
fixedPt = centroidPt;
GLfloat tx = 0.0, ty = 100.0;
GLfloat sx = 0.5, sy = 0.5;
GLdouble theta = pi/2.0;
glClear (GL_COLOR_BUFFER_BIT); // Clear display window.
glColor3f (0.0, 0.0, 1.0); // Set initial fill color to blue.
triangle (verts); // Display blue triangle.
/* Initialize composite matrix to identity. */
matrix3x3SetIdentity (matComposite);
/* Construct composite matrix for transformation sequence. */
scale2D (sx, sy, fixedPt); // First transformation: Scale.
rotate2D (pivPt, theta); // Second transformation: Rotate

VI SEM, Dept of CSE, SJCIT 22 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
translate2D (tx, ty); // Final transformation: Translate.
/* Apply composite matrix to triangle vertices. */
transformVerts2D (nVerts, verts);
glColor3f (1.0, 0.0, 0.0); // Set color for transformed triangle.
triangle (verts);
glFlush ( );
}
void winReshapeFcn (GLint newWidth, GLint newHeight)
{
glMatrixMode (GL_PROJECTION);
glLoadIdentity ( );
gluOrtho2D (xwcMin, xwcMax, ywcMin, ywcMax);
glClear (GL_COLOR_BUFFER_BIT);
}
int main (int argc, char ** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition (50, 50);
glutInitWindowSize (winWidth, winHeight);
glutCreateWindow ("Geometric Transformation Sequence");
init ( );
glutDisplayFunc (displayFcn);
glutReshapeFunc (winReshapeFcn);
glutMainLoop ( );
return 0;
}

SAMPLE OUTPUT:

VI SEM, Dept of CSE, SJCIT 23 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

STUDENT'S OBSERVATIONS

VI SEM, Dept of CSE, SJCIT 24 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

3. Draw a color cube and spin it using OpenGL transformation matrices.


#include<stdlib.h>
#include<GL/glut.h>
GLfloat vertices[]={-1.0,-1.0,-1.0,1.0,-1.0,-1.0,1.0,
1.0,-1.0,-1.0,1.0,-1.0,-1.0,-1.0,1.0,
1.0,-1.0,1.0,1.0,1.0,1.0,-1.0,1.0,1.0};
GLfloat colors[]= {0.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,
0.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0,
1.0,1.0,1.0,1.0,0.0,1.0,1.0};
GLubyte cubeIndices[]={0,3,2,1,2,3,7,6,0,4,7,3,1,2,6,5,4, 5,6,7,0,1,5,4};
static GLfloat theta[]={0.0,0.0,0.0};
static GLint axis=2;

void display(void)
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glRotatef(theta[0],1.0,0.0,0.0);
glRotatef(theta[1],0.0,1.0,0.0);
glRotatef(theta[2],0.0,0.0,1.0);
glDrawElements(GL_QUADS,24,GL_UNSIGNED_BYTE, cubeIndices);
glFlush();
glutSwapBuffers();
}

void spinCube()
{
theta[axis]+=2.0;
if(theta[axis]>360.0) theta[axis]-=360.0;
glutPostRedisplay();
}

VI SEM, Dept of CSE, SJCIT 25 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

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;
}

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)


{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(500,500);
glutCreateWindow("Spin a color cube");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutIdleFunc(spinCube);
glutMouseFunc(mouse);
glEnable(GL_DEPTH_TEST);
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();
}

Output

VI SEM, Dept of CSE, SJCIT 26 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

STUDENT'S OBSERVATIONS

VI SEM, Dept of CSE, SJCIT 27 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

4. Draw a color cube and allow the user to move the camera suitably to experiment with
perspective viewing.

#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]);
glVertex3fv(vertices[a]);
glColor3fv(colors[b]);

VI SEM, Dept of CSE, SJCIT 28 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
glVertex3fv(vertices[b]);
glColor3fv(colors[c]);
glVertex3fv(vertices[c]);
glColor3fv(colors[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();
}

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();

VI SEM, Dept of CSE, SJCIT 29 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
}

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);
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:

VI SEM, Dept of CSE, SJCIT 30 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

STUDENT'S OBSERVATIONS

VI SEM, Dept of CSE, SJCIT 31 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

VI SEM, Dept of CSE, SJCIT 32 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
5. Clip a lines using Cohen-Sutherland algorithm
#include<stdio.h>
#include<GL/glut.h>
#define outcode int
double xmin=50,ymin=50,xmax=100,ymax=100;
double xvmin=200,yvmin=200,xvmax=300,yvmax=300;
double x0,y0,x1,y1;
const int RIGHT=8;
const int LEFT=2;
const int TOP=4;
const int BOTTOM=1;
outcode ComputeOutCode(double x, double y);

void CohenSutherland(double x0, double y0, double x1, double y1)


{
outcode outcode0, outcode1, outcodeOut;
bool accept=false, done=false;
outcode0=ComputeOutCode(x0,y0);
outcode1=ComputeOutCode(x1,y1);
do
{
if(!(outcode0|outcode1))
{
accept=true;
done=true;
}
else if(outcode0&outcode1)
done=true;
else
{
double x, y;
outcodeOut=outcode0?outcode0:outcode1;
if(outcodeOut&TOP)
{
x=x0+(x1-x0)*(ymax-y0)/(y1-y0);
y=ymax;
}
else if(outcodeOut&BOTTOM)
{
x=x0+(x1-x0)*(ymin-y0)/(y1-y0);
y=ymin;
}
else if(outcodeOut&RIGHT)
{
y=y0+(y1-y0)*(xmax-x0)/(x1-x0);
x=xmax;
}
else
{
y=y0+(y1-y0)*(xmin-x0)/(x1-x0);
x=xmin;
}
if(outcodeOut==outcode0)
{

VI SEM, Dept of CSE, SJCIT 33 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
x0=x;
y0=y;
outcode0=ComputeOutCode(x0,y0);
}
else
{
x1=x;
y1=y;
outcode1=ComputeOutCode(x1,y1);
}
}
}while(!done);
if(accept)
{
double sx=(xvmax-xvmin)/(xmax-xmin);
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;
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);
glBegin(GL_LINES);
glVertex2d(vx0,vy0);
glVertex2d(vx1,vy1);
glEnd();
}
}

outcode ComputeOutCode(double x, double y)


{
outcode code=0;
if(y>ymax)
code=TOP;
else if(y<ymin)
code=BOTTOM;
if(x>xmax)
code=RIGHT;
else if(x<xmin)
code=LEFT;
return code;
}

void display()
{

VI SEM, Dept of CSE, SJCIT 34 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINES);
glVertex2d(x0,y0);
glVertex2d(x1,y1);
glEnd();
glColor3f(0.0,0.0,1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xmin, ymin);
glVertex2f(xmax, ymin);
glVertex2f(xmax, ymax);
glVertex2f(xmin, ymax);
glEnd();
CohenSutherland(x0,y0,x1,y1);
glFlush();
}

void myinit()
{
glClearColor(1.0,1.0,1.0,1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,499.0,0.0,499.0);
}

void main(int argc, char** argv)


{
printf("Enter the end points of the line: ");
scanf("%lf%lf%lf%lf", &x0,&y0,&x1,&y1);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("Cohen-Sutherland Line Clipping");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}

VI SEM, Dept of CSE, SJCIT 35 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
Output

STUDENT'S OBSERVATIONS

VI SEM, Dept of CSE, SJCIT 36 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

VI SEM, Dept of CSE, SJCIT 37 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
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.

#include<GL/glut.h>
#include<stdio.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();
}

void table(double topwid, double topthick, double legthick, double leglen)


{
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)
{
GLfloat mat_ambient[]={0.7f,0.7f,0.7f,1.0f};
GLfloat mat_diffuse[]={0.5f,0.5f,0.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);

VI SEM, Dept of CSE, SJCIT 38 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
glMaterialfv(GL_FRONT,GL_SHININESS, mat_shininess);

GLfloat lightintensity[]={0.7f,0.7f,0.7f,1.0f};
GLfloat lightposition[]={2.0f,6.0f,3.0f,0.0f};
glLightfv(GL_LIGHT0, GL_POSITION, lightposition);
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightintensity);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
double winht=1.0;
glOrtho(-winht*64/48, winht*64/48, -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.6,0.38,0.5);
glRotated(30,0,1,0);
glutSolidTeapot(0.08);
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);
glutInitWindowPosition(50,50);
glutInitWindowSize(400,300);
glutCreateWindow("Shaded Scene");
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();
}

VI SEM, Dept of CSE, SJCIT 39 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

Output

VI SEM, Dept of CSE, SJCIT 40 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

STUDENT'S OBSERVATIONS

VI SEM, Dept of CSE, SJCIT 41 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

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.

#include<stdlib.h>
#include<stdio.h>
#include<GL/glut.h>
typedef float point[3];
point v[]={{0.0,0.0,1.0},{0.0,1.0,0.0},
{-1.0,-0.5,0.0}, {1.0,-0.5,0.0}};
int n;
void triangle(point a,point b,point c)
{
glBegin(GL_POLYGON);
glVertex3fv(a);
glVertex3fv(b);
glVertex3fv(c);
glEnd();
}
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]=(c[j]+b[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));
}
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);
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();

VI SEM, Dept of CSE, SJCIT 42 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
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 Division?: ");
scanf("%d",&n);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH;
glutCreateWindow("3D gasket");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glEnable(GL_DEPTH_TEST);
glClearColor(1.0,1.0,1.0,0.0);
glutMainLoop();
}

Output:

VI SEM, Dept of CSE, SJCIT 43 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

STUDENT'S OBSERVATIONS

VI SEM, Dept of CSE, SJCIT 44 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

8. Develop a menu driven program to animate a flag using Bezier Curve algorithm
#include<GL/glut.h>
#include<stdio.h>
#include<math.h>
#define PI 3.1416

GLsizei winWidth = 600, winHeight = 600;


GLfloat xwcMin = 0.0, xwcMax = 130.0;
GLfloat ywcMin = 0.0, ywcMax = 130.0;
typedef struct wcPt3D { GLfloat x, y, z; };

void bino(GLint n, GLint *C)


{
GLint k, j;
for(k=0;k<=n;k++)
{
C[k]=1;
for(j=n;j>=k+1; j--)
C[k]*=j;
for(j=n-k;j>=2;j--)
C[k]/=j;
}
}
void computeBezPt(GLfloat u, wcPt3D *bezPt, GLint nCtrlPts, wcPt3D *ctrlPts, GLint *C)
{

VI SEM, Dept of CSE, SJCIT 45 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
GLint k, n=nCtrlPts-1;
GLfloat bezBlendFcn;
bezPt ->x =bezPt ->y = bezPt->z=0.0;
for(k=0; k< nCtrlPts; k++)
{
bezBlendFcn = C[k] * pow(u, k) * pow( 1-u, n-k);
bezPt ->x += ctrlPts[k].x * bezBlendFcn;
bezPt ->y += ctrlPts[k].y * bezBlendFcn;
bezPt ->z += ctrlPts[k].z * bezBlendFcn;
}
}
void bezier(wcPt3D *ctrlPts, GLint nCtrlPts, GLint nBezCurvePts)
{
wcPt3D bezCurvePt;
GLfloat u;
GLint *C, k; C= new GLint[nCtrlPts];
bino(nCtrlPts-1, C);
glBegin(GL_LINE_STRIP);
for(k=0; k<=nBezCurvePts; k++)
{
u=GLfloat(k)/GLfloat(nBezCurvePts);
computeBezPt(u, &bezCurvePt, nCtrlPts, ctrlPts, C);
glVertex2f(bezCurvePt.x, bezCurvePt.y);
}
glEnd();
delete[]C;
}
void displayFcn()
{
GLint nCtrlPts = 4, nBezCurvePts =20;
static float theta = 0;
wcPt3D ctrlPts[4] = { {20, 100, 0}, {30, 110, 0}, {50, 90, 0}, {60, 100, 0}};
ctrlPts[1].x +=10*sin(theta * PI/180.0);
ctrlPts[1].y +=5*sin(theta * PI/180.0);
ctrlPts[2].x -= 10*sin((theta+30) * PI/180.0);
ctrlPts[2].y -= 10*sin((theta+30) * PI/180.0);
ctrlPts[3].x-= 4*sin((theta) * PI/180.0);
ctrlPts[3].y += sin((theta-30) * PI/180.0);
theta+=0.1; glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glPointSize(5);
glPushMatrix();
glLineWidth(5);
glColor3f(255/255, 153/255.0, 51/255.0); //Indian flag: Orange color code
for(int i=0;i<8;i++)
{
glTranslatef(0, -0.8, 0);
bezier(ctrlPts, nCtrlPts, nBezCurvePts);
}
glColor3f(1, 1, 1); //Indian flag: white color code

VI SEM, Dept of CSE, SJCIT 46 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
for(int i=0;i<8;i++)
{
glTranslatef(0, -0.8, 0);
bezier(ctrlPts, nCtrlPts, nBezCurvePts);
}
glColor3f(19/255.0, 136/255.0, 8/255.0); //Indian flag: green color code
for(int i=0;i<8;i++)
{
glTranslatef(0, -0.8, 0);
bezier(ctrlPts, nCtrlPts, nBezCurvePts);
}
glPopMatrix();
glColor3f(0.7, 0.5,0.3);
glLineWidth(5);
glBegin(GL_LINES);
glVertex2f(20,100);
glVertex2f(20,40);
glEnd();
glFlush();
glutPostRedisplay();
glutSwapBuffers();
}
void winReshapeFun(GLint newWidth, GLint newHeight)
{
glViewport(0, 0, newWidth, newHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(xwcMin, xwcMax, ywcMin, ywcMax);
glClear(GL_COLOR_BUFFER_BIT);
}
void main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition(50, 50);
glutInitWindowSize(winWidth, winHeight);
glutCreateWindow("Bezier Curve");
glutDisplayFunc(displayFcn);
glutReshapeFunc(winReshapeFun);
glutMainLoop();
}

OUTPUT

VI SEM, Dept of CSE, SJCIT 47 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

STUDENT'S OBSERVATIONS

VI SEM, Dept of CSE, SJCIT 48 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

9. Develop a menu driven program to fill the polygon using scan line algorithm
#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

VI SEM, Dept of CSE, SJCIT 49 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
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)


{
glColor3f(0.0,1.0,1.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);
}
}

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();

VI SEM, Dept of CSE, SJCIT 50 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
}

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("Scan line area filling algorithm");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}

Output

VI SEM, Dept of CSE, SJCIT 51 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

STUDENT'S OBSERVATIONS

VI SEM, Dept of CSE, SJCIT 52 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

Viva-Questions

VI SEM, Dept of CSE, SJCIT 53 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
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 Rasterization?
6. What do you mean by clipping?
7. How is Liang-Barsky clipping different from Cohen Sutherland Clipping Algorithm?
8. How do you set the color attributes in Opengl?
9. What is the command for clear screen?
10. What is Event callback function?
11. What are vertex arrays?
12. How are the faces of the color cube modeled?
13. How do you consider the inward and outward pointing of the faces?
14. Explain the OpenGL function used to rotate the color cube?
15. What is the difference between 2D and 3D orthographic projection statements?
16. What is transformation?
17. Explain the OpenGL functions used for translation, rotation and scaling?
18. What is the order of transformation?
19. State the difference between model view and projection?
20. What is Homogeneous-coordinate representation?
21. What is the principle of Cohen-Sutherland Algorithm?
22. State the advantages and disadvantages of Cohen-Sutherland Algorithm?
23. What is an out code?
24. What is Synthetic Camera Model?
25. What are the Camera Specifications?
26. Explain about gluLookAt(…), glFrustrum(…), gluPerspective?
27. Explain the different types of projections?
28. Explain Z-buffer algorithm?
29. What is antialiasing?
30. What is COP, DOP?
31. Explain Specular, Diffuse and Translucent surfaces.
32. What is ambient light?
33. What is umbra, penumbra?
34. Explain Phong lighting model.
35. Explain glLightfv(…), glMaterialfv(…).
36. Explain the keyboard and mouse events used in this program?
37. What is Hidden surface Removal? How do you achieve this in OpenGL?
38. What are the functions for creating Menus in OpenGL?
39. Explain about fonts in GLUT?
40. Explain about glutPostRedisplay ()?
41. Explain scan line filling algorithm?
42. What is AspectRatio,Viewport?
43. How do you use timer?
44. What are the different frames in OpenGL?
45. What is fragment processing?
46. Explain Specular, Diffuse and Translucent surfaces.
47. What is ambient light?
48. What is umbra, penumbra?
49. Explain Phong lighting model?
50. Explain glLightfv (…), glMaterialfv (…).?

VI SEM, Dept of CSE, SJCIT 54 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB

PART-B
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)
Sample Topics:
Simulation of concepts of OS, Data structures, algorithms etc

VI SEM, Dept of CSE, SJCIT 55 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
Guidelines for the preparation of Mini CG Project Reports

Cover Page & Certificate Page


Abstract
Acknowledgements
Table of Contents
List of tables and figures (optional)

Contents (Template)
1. Introduction
1.1 Introduction of mini project
1.2 OpenGL concepts
1.3 Scope and applications
2. Literature survey
2.1 related work
2.2 problem statement
2.3 proposed system
2.4 advantages and disadvantages
3. Software, Hardware and Functional Requirements
3.1 Minimum hardware and software requirements
3.2 functional requirements
4. Analysis and Design
4.1 Architecture of proposed system
4.2 High level and low level design
5.  Implementation
5.1 Algorithm
5.2 Module description
5.3 Application development
6. Discussions and Snapshots 
7. Conclusion
Bibliography
Appendices-full code in a very small font size and single line spacing (as few
pages as possible)

VI SEM, Dept of CSE, SJCIT 56 2020


COMPUTER GRAPHICS AND VISUALIZATION LAB
NOTE
1. Project reports should be typed neatly only on one side of the paper with 1.5 or
double line spacing on a A4 size bind paper (210X297 mm).
The margins should be left 1.25”, Right – 1”, Top and Bottom-0.75”.

2. Before taking final print out, the approval of the concerned guide(s) is mandatory and
suggested corrections if any, must be incorporated.

3. For making copies dry tone Xerox is suggested.

Every copy of the report must contain

 Outer title page


 Inner title page
 Certificate in the format enclosed by the college and the organization where the
project is carried out
 Abstract not exceeding 100 words, indicating sailent features of the work
 Chapters (to be numbered in Arabic) Containing Introduction which is usually
specific scope of work and its importance and relation to previous work and the
present developments. Many body of the report should be divided into chapters,
Sections and subscriptions.
 The chapters, sections and subsections may be numbered in the decimal form.
 The Chapter must be left or right justified(Font size 16) followed by the title of
the chapter centered (font size 18),section/subsection numbers along with their
headings must be left justified with section numbers and its heading in font size
16 and subsection and its heading in font size 14. The body or the text of the
report should have font size 12.
 The figures and table must be numbered chapter wise.
 The last chapter should contain the summary of the work carried, contributions if
any, their utility along with the scope of the further work.
 Reference or bibliography- The references should be serially numbered in the
order of their occurrence in text and their numbers should be indicated in [ ]
brackets.
 Proper attention is to be paid not only to the technical contents but also to the
organization of the report and the clarity of the expression. Due care should be
taken to avoid spelling and typing errors.

VI SEM, Dept of CSE, SJCIT 57 2020

You might also like