0% found this document useful (0 votes)
129 views

CG Lab PDF

This document outlines the syllabus for the Computer Graphics & Visualization Laboratory course. It includes 10 learning objectives related to designing and implementing computer graphics algorithms and programs. The syllabus is divided into two parts: Part A lists 10 programming assignments related to topics like 3D modeling, transformations, lighting, clipping, and mesh generation. Part B involves developing a graphics package or library to implement the skills from Part A using OpenGL. Exams will involve evaluating student performance on one Part A assignment and their graphics package from Part B. Preliminary concepts about OpenGL and GLUT are also provided as background information.

Uploaded by

anantha innanje
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views

CG Lab PDF

This document outlines the syllabus for the Computer Graphics & Visualization Laboratory course. It includes 10 learning objectives related to designing and implementing computer graphics algorithms and programs. The syllabus is divided into two parts: Part A lists 10 programming assignments related to topics like 3D modeling, transformations, lighting, clipping, and mesh generation. Part B involves developing a graphics package or library to implement the skills from Part A using OpenGL. Exams will involve evaluating student performance on one Part A assignment and their graphics package from Part B. Preliminary concepts about OpenGL and GLUT are also provided as background information.

Uploaded by

anantha innanje
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

MITE 062

VISVESVARAYA TECHNOLOGICAL UNIVERSITY

Jnana Sangam, Belgaum-590018

COMPUTER GRAPHICS & VISUALIZATION


LABORATORY
(10CSL67)

MANGALORE INSTITUTE OF TECHNOLOGY AND ENGINEERING


(An ISO 9001:2008 Certified Institution)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


Badaga Mijar, Moodbidri – 574225, Karnataka
Computer Graphics & Visualization Lab 10CSL67

Computer graphics & Visualization Laboratory

Subject Code: 10CSL67 I.A. Marks: 25


Hours/Week: 04 Exam Hours: 03
Total Hours: 42 Exam Marks: 50

COURSE LEARNING OBJECTIVES

C315.1 Design and implement various line clipping algorithms and polygon filling
algorithm (any one)
C315.2 Understand and implement 3D Sierpinski gasket; Implement a color cube ,
apply transformations and perspective view on it
C315.3 Implement various advanced primitives such as mesh, teapot and extruding
surfaces and apply lighting and shading to them(any one)

SYLLABUS
PART - A
Design, develop, and implement the following programs in C / C++
1. Program to recursively subdivide a tetrahedron to from 3D Sierpinski gasket. The number of
recursive steps is to be specified by the user.
2. Program to implement Liang-Barsky line clipping algorithm.
3. Program to draw a color cube and spin it using OpenGL transformation matrices.
4. Program to create a house like figure and rotate it about a given fixed point using OpenGL
functions.
5. Program to implement the Cohen-Sutherland line-clipping algorithm. Make provision to
specify the input line, window for clipping and view port for displaying the clipped image.
6. Program to create a cylinder and a parallelepiped by extruding a circle and quadrilateral
respectively. Allow the user to specify the circle and the quadrilateral.
7. Program, using OpenGL functions, to draw a simple shaded scene consisting of a tea pot on
a table. Define suitably the position and properties of the light source along with the
properties of the properties of the surfaces of the solid object used in the scene.
8. Program to draw a color cube and allow the user to move the camera suitably to experiment
with perspective viewing. Use OpenGL functions.
9. Program to fill any given polygon using scan-line area filling algorithm. (Use appropriate
data structures.)
10. Program to display a set of values {fij} as a rectangular mesh.

PART - B
Develop a suitable Graphics package to implement the skills learnt in the theory and the exercises
indicated in Part A. Use the OpenGL.
Note:
1. Any question from Part A may be asked in the examination.
2. A report of about 10 – 12 pages on the package developed in Part B, duly certified by the
department must be submitted during examination.
Instructions:
In the examination, one exercise from Part A is to be asked for a total of 30 marks. The package
developed under Part B has to be evaluated for a total of 20 marks.

Dept of CSE, MITE, Moodabidri Page 1


Computer Graphics & Visualization Lab 10CSL67

Preliminary Concepts

OpenGL
As a software interface for graphics hardware, OpenGL's main purpose is to render two- and three-
dimensional objects into a frame buffer. These objects are described as sequences of vertices (which
define geometric objects) or pixels (which define images). OpenGL performs several processing
steps on this data to convert it to pixels to form the final desired image in the frame buffer.

OpenGL draws primitives—points, line segments, or polygons—subject to several selectable


modes. You can control modes independently of each other; that is, setting one mode doesn't affect
whether other modes are set (although many modes may interact to determine what eventually ends
up in the frame buffer). Primitives are specified, modes are set, and other OpenGL operations are
described by issuing commands in the form of function calls.

Primitives are defined by a group of one or more vertices. A vertex defines a point, an endpoint of a
line, or a corner of a polygon where two edges meet. Data (consisting of vertex coordinates, colors,
normals, texture coordinates, and edge flags) is associated with a vertex, and each vertex and its
associated data are processed independently, in order, and in the same way. The only exception to
this rule is if the group of vertices must be clipped so that a particular primitive fits within a
specified region; in this case, vertex data may be modified and new vertices created. The type of
clipping depends on which primitive the group of vertices represents.

Commands are always processed in the order in which they are received, although there may be an
indeterminate delay before a command takes effect. This means that each primitive is drawn
completely before any subsequent command takes effect. It also means that state-querying
commands return data that's consistent with complete execution of all previously issued OpenGL
commands

The figure shown below gives an abstract, high-level block diagram of how OpenGL processes
data. In the diagram, commands enter from the left and proceed through what can be thought of as a
processing pipeline. Some commands specify geometric objects to be drawn, and others control
how the objects are handled during the various processing stages.

Dept of CSE, MITE, Moodabidri Page 2


Computer Graphics & Visualization Lab 10CSL67

Fig: OpenGL Block Diagram

As shown by the first block in the diagram, rather than having all commands proceed immediately
through the pipeline, you can choose to accumulate some of them in a display list for processing at
a later time.

The evaluator stage of processing provides an efficient means for approximating curve and surface
geometry by evaluating polynomial commands of input values. During the next stage, per-vertex
operations and primitive assembly, OpenGL processes geometric primitives—points, line segments,
and polygons, all of which are described by vertices. Vertices are transformed and lit, and
primitives are clipped to the viewport in preparation for the next stage.

Rasterization produces a series of frame buffer addresses and associated values using a two-
dimensional description of a point, line segment, or polygon. Each fragment so produced is fed into
the last stage, per-fragment operations, which perform the final operations on the data before it's
stored as pixels in the frame buffer. These operations include conditional updates to the frame
buffer based on incoming and previously stored z-values (for z-buffering) and blending of incoming
pixel colors with stored colors, as well as masking and other logical operations on pixel values.

Input data can be in the form of pixels rather than vertices. Such data, which might describe an
image for use in texture mapping, skips the first stage of processing described above and instead is
processed as pixels, in the pixel operations stage. The result of this stage is either stored as texture
memory, for use in the rasterization stage, or rasterized and the resulting fragments merged into the
frame buffer just as if they were generated from geometric data.

Dept of CSE, MITE, Moodabidri Page 3


Computer Graphics & Visualization Lab 10CSL67

GLUT gives you the ability to create a window, handle input and render to the screen without being
Operating System dependent. The first things you will need are the OpenGL and GLUT header files
and libraries for your current Operating System. Once you have them setup on your system
correctly, open your first c++ file and include them at the start of your file like so:

#include <GL/gl.h> //include the gl header file


#include <GL/glut.h> //include the GLUT header file

Now, just double check that your system is setup correctly, and try compiling your current file. If
you get no errors, you can proceed. If you have any errors, try your best to fix them. Once you are
ready to move onto the next step, create a main() method in your current file. Inside this is where all
of your main GLUT calls will go. The first call we are going to make will initialize GLUT and is
done like so:

glutInit (&argc, argv); //initialize the program.

Once we have GLUT initialized, we need to tell GLUT how we want to draw. There are several
parameters we can pass here, but we are going to stick the with most basic GLUT_SINGLE, which
will give use a single buffered window.

glutInitDisplayMode (GLUT_SINGLE);//set up a basic display buffer (only singular for now)

The next two methods we are going to use, simply set the size and position of the GLUT
window on our screen:

glutInitWindowSize (500, 500); //set whe width and height of the window
glutInitWindowPosition (100, 100); //set the position of the window

And then we give our window a caption/title, and create it.

glutCreateWindow ("A basic OpenGL Window"); //set the caption for the window

Dept of CSE, MITE, Moodabidri Page 4


Computer Graphics & Visualization Lab 10CSL67

We now have a window of the size and position that we want. But we need to be able to draw to it.
We do this, by telling GLUT which method will be our main drawing method. In this case, it is a
void method called display()

glutDisplayFunc (display); //call the display function to draw our world

Finally, we tell GLUT to start our program. It does this by executing a loop that will continue until
the program ends.

glutMainLoop (); //initialize the OpenGL loop cycle

So thus far, we have a window. But the display method that I mentioned is needed. Lets take a look
at this and dissect it.

void display (void) {


glClearColor (0.0,0.0,0.0,1.0); //clear the color of the window
glClear (GL_COLOR_BUFFER_BIT); //Clear the Color Buffer (more buffers later on)
glLoadIdentity(); //load the Identity Matrix
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); //set the view
glFlush(); //flush it all to the screen
}

The first method, glClearColor will set the background color of our window. In this example, we
are setting the background to black (RGB 0, 0, 0). The 1.0 value on the end is an alpha value and
makes no difference at this stage as we don't have alpha enabled.

The next thing we want to do, is erase everything currently stored by OpenGL. We need to do this
at the start of the method, as the method keeps looping over itself and if we draw something, we
need to erase it before we draw our next frame

Dept of CSE, MITE, Moodabidri Page 5


Computer Graphics & Visualization Lab 10CSL67

PROGRAM -1
TITLE

Design, develop, and implement the following programs in C/C++ program to recursively subdivide
a tetrahedron to from 3D Sierpinski gasket. The number of recursive steps is to be specified by the
user

AIM

To construct the 3D Sierpinski gasket and recursively divide it using the input from the user
using OpenGL

DESCRIPTION

The Sierpinski triangle (also with the original orthography Sierpiński), also called the Sierpinski
gasket or the Sierpinski Sieve, is a fractal and attractive fixed set with the overall shape of
an equilateral triangle, subdivided recursively into smaller equilateral triangles. Originally
constructed as a curve, this is one of the basic examples of self-similar sets, i.e., it is a
mathematically generated pattern that can be reproducible at any magnification or reduction. It is
named after the Polish mathematician Waclaw Sierpinki but appeared as a decorative pattern many
centuries prior to the work of Sierpiński

A fractal is generally "a rough or fragmented geometric shape that can be split into parts, Each of
which is (at least approximately) a reduced-size copy of the whole―.

To generate this fractal, a few steps are involved,


We begin with a triangle in the plane and then apply a repetitive scheme of operations to it (when
we say triangle here, we mean a blackened, 'filled-in' triangle). Pick the midpoints of its three sides.
Together with the old vertices of the original triangle, these midpoints define four congruent
triangles of which we drop the center one. This completes the basic construction step. In other
words, after the first step we have three congruent triangles whose sides have exactly half the size
of the original triangle and which touch at three points which are common vertices of two
contiguous triangles. Now we follow the same procedure with the three remaining triangles and
repeat the basic step as often as desired. That is, we start with one triangle and then produce 3, 9, 27
triangles, each of which is an exact scaled down version of the triangles in the Preceding step
Dept of CSE, MITE, Moodabidri Page 6
Computer Graphics & Visualization Lab 10CSL67

ALGORITHM

1. Define and initializes the array to hold the vertices as follows:


point v[]={{0,0},{250,500,100},{500,250,100},{250,100,250}};
2. Define and initialize initial location inside tetrahedron.
GLfloat p[3] ={25.0,10.0,25.0};
3. Define Triangle function that uses points in three dimensions to display one triangle
glBegin(GL_POLYGON)
glVertex3fv(a)
glVertex3fv(b)
glVertex3fv(c)
glEnd();
4. Subdivide a tetrahedron using divide_triangle function
i) if no of subdivision(m) > 0 means perform following functions
ii) Compute six midpoints using for loop.
iii) Create 4 tetrahedrons by calling divide_triangle function
iv) Else draw triagle at end of recursion.
5. Define tetrahedron function to apply triangle subdivision to faces of tetrahedron by calling the
function divide_triangle.
6. Define display function to clear the color buffer and to call tetrahedron function.
7. Define main function to create window and to call display function

INPUT

The number of recursive subdivisions i.e. ―n‖ by the user

EXPECTED OUTPUT

Generates a 3D Sierpinski gasket with the specified number of subdivisions by the user

Dept of CSE, MITE, Moodabidri Page 7


Computer Graphics & Visualization Lab 10CSL67

PROGRAM
#include<stdio.h>
#include<GL/glut.h>
typedef float point[3];
point v[]={{0,0},{250,500,100},{500,250,100},{250,100,250}};
int n;
void myinit()
{
glClearColor(0,1,1,1);
glOrtho(0,500,0,500,-500,500);
glEnable(GL_DEPTH_TEST);
}
void triangle(point a,point b,point c)
{
glBegin(GL_TRIANGLES);
glVertex3fv(a);
glVertex3fv(b);
glVertex3fv(c);
glEnd();
glFlush();
}
void divide_triangle(point a,point b,point c,int m)
{
point v1,v2,v3;
int j;
if(m>0)
{
for(j=0;j<3;j++)
v1[j]=(a[j]+b[j])/2;
for(j=0;j<3;j++)
v2[j]=(a[j]+c[j])/2;
for(j=0;j<3;j++)
v3[j]=(b[j]+c[j])/2;
divide_triangle(a,v1,v2,m-1);
divide_triangle(b,v1,v3,m-1);
divide_triangle(c,v2,v3,m-1);
}
else(triangle(a,b,c));
}

void tetrahedron(int m)
{
Dept of CSE, MITE, Moodabidri Page 8
Computer Graphics & Visualization Lab 10CSL67

glColor3f(1.0,0.0,0.0);
divide_triangle(v[0],v[1],v[2],m);
glColor3f(0.0,1.0,0.0);
divide_triangle(v[3],v[2],v[1],m);
glColor3f(0.0,0.0,1.0);
divide_triangle(v[0],v[3],v[1],m);
glColor3f(0.0,0.0,0.0);
divide_triangle(v[0],v[2],v[3],m);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
tetrahedron(n);
}

void main(int argc,char **argv)


{
printf("enter no of recursion:");
scanf("%d",&n);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE|GLUT_DEPTH);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("3Dgasket");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}

Dept of CSE, MITE, Moodabidri Page 9


Computer Graphics & Visualization Lab 10CSL67

RESULT

Dept of CSE, MITE, Moodabidri Page 10


Computer Graphics & Visualization Lab 10CSL67

PROGRAM -2
TITLE

Design, develop, and implement the following programs in C/C++ program to implement Liang-
Barsky line clipping algorithm

AIM

To implement Liang-Barsky line clipping algorithm using OpenGL

DESCRIPTION

In computer graphics, the Liang–Barsky algorithm (named after You-Dong Liang and Brian A.
Barsky) is a line clipping algorithm. The Liang–Barsky algorithm uses the parametric equation of a
line and inequalities describing the range of the clipping window to determine the intersections
between the line and the clip window. With these intersections it knows which portion of the line
should be drawn. This algorithm is significantly more efficient than Cohen–Sutherland. The idea of
the Liang–Barsky clipping algorithm is to do as much testing as possible before computing line
intersections.

Let P(x1,y1) and Q(x2,y2) be the line which we


want to study.
The parametric equation of the line segment
from gives x-values and y-values for every point
in terms of a parameter t that ranges from 0 to 1.
The equations are

And

We can see that when t = 0, the point computed is


P(x1,y1); and when t = 1, the point
computed is Q(x2,y2).

Dept of CSE, MITE, Moodabidri Page 11


Computer Graphics & Visualization Lab 10CSL67

ALGORITHM

INPUT

User presses the mouse button to do the clipping

EXPECTED OUTPUT

The line portion which is inside the clipping rectangle shall be retained as it is and the rest
of the portions are clipped off.

PROGRAM

#include<GL/glut.h>
GLdouble xmin=200.0,ymin=200.0,xmax=500.0,ymax=500.0,x0=150.0,y0=300.0,
x1=300.0,y1=600.0;
GLint clip=0,click=0;

void draw_rect()
{
glColor3f(1.0,0.0,1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xmin,ymin);
glVertex2f(xmin,ymax);
glVertex2f(xmax,ymax);
glVertex2f(xmax,ymin);
glEnd();

Dept of CSE, MITE, Moodabidri Page 12


Computer Graphics & Visualization Lab 10CSL67

glFlush();
}

void draw_line()
{
glBegin(GL_LINES);
glVertex2f(x0,y0);
glVertex2f(x1,y1);
glEnd();
glFlush();
}

int clip_test(double p,double q,double *t1,double *t2)


{
double t=q/p;
if(p<0.0)
{
if(t>*t1)
*t1=t;
if(t>*t2)
return 0;
}
else if(p>0.0)
{
if(t<*t2)
*t2=t;
if(t<*t1)
return 0;
}
else if(p==0)
{
if(q<0.0)
return 0;
}
return 1;
}

void LBclip()
{
double dx=x1-x0,dy=y1-y0,t1=0,t2=1;

if(clip_test(-dx,x0-xmin,&t1,&t2) &&

Dept of CSE, MITE, Moodabidri Page 13


Computer Graphics & Visualization Lab 10CSL67

clip_test(dx,xmax-x0,&t1,&t2) &&
clip_test(-dy,y0-ymin,&t1,&t2) &&
clip_test(dy,ymax-y0,&t1,&t2))
{
clip=1;
if(t2<1.0)
{
x1=x0+t2*dx;
y1=y0+t2*dy;
}
if(t1>0.0)
{
x0=x0+t1*dx;
y0=y0+t1*dy;
}
}
}
void mouse(int button,int state,int a,int b)
{
if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN)
click=1;
glutPostRedisplay();
}

void display()
{
glClear(GL_COLOR_BUFFER_BIT);
draw_rect();
glColor3f(0.0,0.0,1.0);
draw_line();
LBclip();
if(clip&&click)
{
glColor3f(0.0,1.0,0.0);
draw_line();
}
}

void myinit()
{
glClearColor(0.0,0.0,0.0,1.0);
glMatrixMode(GL_PROJECTION);

Dept of CSE, MITE, Moodabidri Page 14


Computer Graphics & Visualization Lab 10CSL67

glLoadIdentity();
gluOrtho2D(0.0,800.0,0.0,800.0);
}

void main(int argc,char **argv)


{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE);
glutInitWindowSize(800.0,800.0);
glutInitWindowPosition(0.0,0.0);
glutCreateWindow("Clipping Line");
glutMouseFunc(mouse);
glutDisplayFunc(display);
myinit();
glutMainLoop();
}

RESULT

Before Clipping

Dept of CSE, MITE, Moodabidri Page 15


Computer Graphics & Visualization Lab 10CSL67

After Clipping

Dept of CSE, MITE, Moodabidri Page 16


Computer Graphics & Visualization Lab 10CSL67

PROGRAM -3
TITLE

Design, develop, and implement the following programs in C/C++ program to draw a color cube
and spin it using OpenGL transformation matrices

AIM

To draw a color cube and rotate it using transformation matrices using OpenGL

DESCRIPTION
A color cube is a graphic primitive generated using set of vertices and edges. A Color cube consists
of 6 facets and 8 vertices and it. OpenGL's object is made up of primitives (such as triangle, quad,
polygon, point and line). A primitive is defined via one or more vertices. The color-cube is made up
of 6 quads. Each quad is made up of 4 vertices, defined in counter-clockwise (CCW) order, such as
the normal vector is pointing out, indicating the front face. All the 4 vertices have the same color.
The color-cube is defined in its local space (called model space) with origin at the center of the
cube with sides of 2 units.

ALGORITHM

1. Define global arrays for vertices and colors


GLfloat vertices[][3] = {{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0},
{1.0,1.0,-1.0}, {-1.0,1.0,-1.0}, {-1.0,-1.0,1.0},
{1.0,-1.0,1.0}, {1.0,1.0,1.0}, {-1.0,1.0,1.0}};
GLfloat colors[][3] = {{0.0,0.0,0.0},{1.0,0.0,0.0},
{1.0,1.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0},
{1.0,0.0,1.0}, {1.0,1.0,1.0}, {0.0,1.0,1.0}};

2. Draw a polygon from a list of indices into the array vertices and use color
corresponding to first index
void polygon(int a, int b, int c, int d)
{
glBegin(GL_POLYGON);
glColor3fv(colors[a]);
glVertex3fv(vertices[a]);
Dept of CSE, MITE, Moodabidri Page 17
Computer Graphics & Visualization Lab 10CSL67

glVertex3fv(vertices[b]);
glVertex3fv(vertices[c]);
glVertex3fv(vertices[d]);
glEnd();
}

3.Draw cube from faces.


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);
polygo n(0,1,5,4);
}
4. Define the Display function to clear frame buffer , Z-buffer ,rotate cube and
draw,swap
buffers.
void display(void)
{
/* display callback, clear frame buffer and z buffer,
rotate cube and draw, swap buffers */

glLoadIdentity();
glRotatef(theta[0], 1.0, 0.0, 0.0);
glRotatef(theta[1], 0.0, 1.0, 0.0);
glRotatef(theta[2], 0.0, 0.0, 1.0);
colorcube();
glutSwapBuffers();
}
5. Define the spincube function to spin cube 2 degrees about selected axis.

Dept of CSE, MITE, Moodabidri Page 18


Computer Graphics & Visualization Lab 10CSL67

6. Define mouse callback to select axis about which to rotate.


7. Define reshape function to maintain aspect ratio.
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);
}

8. Define main function to create window and to call all function.

INPUT

Mouse input, Right-Click for rotation w.r.t x axis, Middle-Click for rotation w.r.t z axis and
Left click for rotation w.r.t y axis

EXPECTED OUTPUT

A color cube which can be rotated with respect to all the three axes, whose rotation is
controlled by the mouse input given by the user

Dept of CSE, MITE, Moodabidri Page 19


Computer Graphics & Visualization Lab 10CSL67

PROGRAM

/* 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};
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)
{
/* 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);
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, cubeIndices);
/*glBegin(GL_LINES);
glVertex3f(0.0,0.0,0.0);
glVertex3f(1.0,1.0,1.0);
glEnd(); */
glFlush();
glutSwapBuffers();
}

void spinCube()
{

Dept of CSE, MITE, Moodabidri Page 20


Computer Graphics & Visualization Lab 10CSL67

/* Idle callback, spin cube 2 degrees about selected axis */


theta[axis] += 2.0;
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();
glOrtho(-2.0, 2.0, -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 */
Dept of CSE, MITE, Moodabidri Page 21
Computer Graphics & Visualization Lab 10CSL67

glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, vertices);
glColorPointer(3,GL_FLOAT, 0, colors);
glColor3f(1.0,1.0,1.0);
glutMainLoop();
}

RESULT

Dept of CSE, MITE, Moodabidri Page 22


Computer Graphics & Visualization Lab 10CSL67

PROGRAM -4
TITLE

Design, develop, and implement the following programs in C/C++ program to create a house like
figure and rotate it about a given fixed point using OpenGL functions

AIM

To create a house like structure using basic OpenGL primitives and rotate it w.r.t fixed point
using OpenGL

DESCRIPTION
A house can be constructed using OpenGL primitives such as triangles and quads. In order to rotate
the structure we use rotation about fixed point logic which is a combination of set of
transformations in a sequence which is
 Translating the object back from its location to origin of coordinate system
 Rotating the object about the origin
 Translating the object back to its original location

ALGORITHM

1. Initialize the house array to draw the house


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

2. Initialize the rotation matrix as follow:


GLfloat rot_mat[3][3]={{0},{0},{0}};

3. Initialize the resultant matrix


GLfloat result[3][9] = {{0},{0},{0}};

4. Initialize the pivot point h,k as 100,100

5. Define the rotate function as follows:


i) Calculate m and n value m=-h*(cos(theta)-1)+k*(sin(theta));

Dept of CSE, MITE, Moodabidri Page 23


Computer Graphics & Visualization Lab 10CSL67

n=-k*(cos(theta)-1)-h*(sin(theta));
ii) Rotation matrix is
cos(theta) -sin(theta) m
sin(theta) cos(theta) n
0 0 1
iii) Call Multiply function to multiply the two matrices Rotation matrix and object
matrix.
6. Define the multiply function to multiply Rotation matrix and object matrix to give
resultant transformed house.
7. Define the function drawhouse to draw house using GL_LINE_LOOP.
8. Define the function Drawrotatehouse to draw house after rotating.
9. Define the display function which is used to call all function.
10. Define the myinit function to specify matrixmode and gluortho.
11. Define main to get theta value from user and to create window.

INPUT

Rotation angle taken as input from the user

EXPECTED OUTPUT

A graphics output depicting the original house rotated by the angle specified by the user.

PROGRAM

#include<GL/glut.h>
#include<math.h>
#include<stdio.h>
GLfloat h=700.0,k=400.0,theta=0.0,angle=0.0;
GLfloat v[3][9]={{500,575,625,700,625,575,500,700,600},{400,400,400,400,650,
650,700,700,800},{1,1,1,1,1,1,1,1,1}};
GLfloat r[3][9]={0.0},rot_mat[3][3]={0.0};
void multiply();
void draw_house();
void myinit();
void rotate_house();
void rotate();
void display();

Dept of CSE, MITE, Moodabidri Page 24


Computer Graphics & Visualization Lab 10CSL67

void main(int argc,char **argv)


{

glutInit(&argc,argv);
printf("enter the rotation angle\n");
scanf("%f",&angle);
theta=(3.14*angle)/180;

glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE);
glutInitWindowSize(900,900);
glutInitWindowPosition(0,0);
glutCreateWindow("house");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}

void myinit()
{
glClearColor(0.0,0.0,0.0,1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,900.0,0.0,900.0);
}
void draw_house()
{
glColor3f(1.0,0.0,0.0);
glBegin(GL_TRIANGLES);
glVertex2f(v[0][8],v[1][8]);
glVertex2f(v[0][7],v[1][7]);
glVertex2f(v[0][6],v[1][6]);
glEnd();

glColor3f(0.0,1.0,0.0);
glBegin(GL_QUADS);
glVertex2f(v[0][6],v[1][6]);
glVertex2f(v[0][7],v[1][7]);
glVertex2f(v[0][3],v[1][3]);
glVertex2f(v[0][0],v[1][0]);
glEnd();

Dept of CSE, MITE, Moodabidri Page 25


Computer Graphics & Visualization Lab 10CSL67

glColor3f(1.0,1.0,0.0);
glBegin(GL_QUADS);
glVertex2f(v[0][5],v[1][5]);
glVertex2f(v[0][4],v[1][4]);
glVertex2f(v[0][2],v[1][2]);
glVertex2f(v[0][1],v[1][1]);
glEnd();
glFlush();
}

void multiply()
{
int i,j,l;
for(i=0;i<3;i++)
for(j=0;j<9;j++)
{
r[i][j]=0;
for(l=0;l<3;l++)
r[i][j]=r[i][j]+rot_mat[i][l]*v[l][j];
}
}

void rotate()
{
GLfloat m,n;
m=-h*(cos(theta)-1)+k*(sin(theta));
n=-k*(cos(theta)-1)-h*(sin(theta));
rot_mat[0][0]=cos(theta);
rot_mat[0][1]=-sin(theta);
rot_mat[0][2]=m;
rot_mat[1][0]=sin(theta);
rot_mat[1][1]=cos(theta);
rot_mat[1][2]=n;
rot_mat[2][0]=0;
rot_mat[2][1]=0;
rot_mat[2][2]=1;
multiply();
}

void rotate_house()

Dept of CSE, MITE, Moodabidri Page 26


Computer Graphics & Visualization Lab 10CSL67

{
glColor3f(0.0,1.0,1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(r[0][8],r[1][8]);
glVertex2f(r[0][7],r[1][7]);
glVertex2f(r[0][6],r[1][6]);
glEnd();

glColor3f(0.0,1.0,1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(r[0][6],r[1][6]);
glVertex2f(r[0][7],r[1][7]);
glVertex2f(r[0][3],r[1][3]);
glVertex2f(r[0][0],r[1][0]);
glEnd();

glColor3f(0.0,1.0,1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(r[0][5],r[1][5]);
glVertex2f(r[0][4],r[1][4]);
glVertex2f(r[0][2],r[1][2]);
glVertex2f(r[0][1],r[1][1]);
glEnd();
glFlush();
}

void display()
{
glClear(GL_COLOR_BUFFER_BIT);
draw_house();
rotate();
rotate_house();

}
RESULT

Dept of CSE, MITE, Moodabidri Page 27


Computer Graphics & Visualization Lab 10CSL67

Dept of CSE, MITE, Moodabidri Page 28


Computer Graphics & Visualization Lab 10CSL67

PROGRAM -5
TITLE

Design, develop, and implement the following programs in C/C++ program to implement the
Cohen-Sutherland line-clipping algorithm. Make provision to specify the input line, window for
clipping and view port for displaying the clipped image

AIM

To implement Cohen-Sutherland Line Clipping Algorithm using OpenGL

DESCRIPTION
The Cohen-Sutherland algorithm uses a divide-and-conquer strategy. The line segment's endpoints
are tested to see if the line can be trivially accepted or rejected. If the line cannot be trivially
accepted or rejected, an intersection of the line with a window edge is determined and the trivial
reject/accept test is repeated. This process is continued until the line is accepted. To perform the
trivial acceptance and rejection tests, we extend the edges of the window to divide the plane of the
window into the nine regions. Each end point of the line segment is then assigned the code of the
region in which it lies.

ALGORITHM

Dept of CSE, MITE, Moodabidri Page 29


Computer Graphics & Visualization Lab 10CSL67

INPUT

Mouse input, Right-Click for rotation w.r.t x axis, Middle-Click for rotation w.r.t z axis and
Left click for rotation w.r.t y axis

EXPECTED OUTPUT

The line portion which is inside the clipping rectangle shall be retained as it is and the rest
of the portions are clipped off.

PROGRAM

#include<GL/glut.h>
GLdouble xmin=200.0,ymin=200.0,xmax=500.0,ymax=500.0,x0=150.0,y0=300.0,
x1=300.0,y1=600.0;
GLint accept=0,done=0,click=0;
const int RIGHT=8;
const int LEFT=2;
const int TOP=4;
const int BOTTOM=1;
void draw_rect()
{
glColor3f(1.0,0.0,1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xmin,ymin);
glVertex2f(xmin,ymax);
glVertex2f(xmax,ymax);
glVertex2f(xmax,ymin);
glEnd();
glFlush();
}

void draw_line()
{
glBegin(GL_LINES);
glVertex2f(x0,y0);
glVertex2f(x1,y1);
glEnd();
glFlush();
}

int ComputeCode(double x,double y)


{
int code=0;
if(y>ymax)
code|=TOP;
else if(y<ymin)
code|=BOTTOM;
if(x>xmax)
Dept of CSE, MITE, Moodabidri Page 30
Computer Graphics & Visualization Lab 10CSL67

code|=RIGHT;
else if(x<xmin)
code|=LEFT;
return code;
}

void CSclip()
{
int code0,code1,outcode;
code0=ComputeCode(x0,y0);
code1=ComputeCode(x1,y1);
do{
if(!(code0|code1))
{
accept=1;
done=1;
}
else if(code0&code1)
done=1;
else
{
double x,y;
outcode=code0?code0:code1;
if(outcode&TOP)
{
x=x0+(x1-x0)*(ymax-y0)/(y1-y0);
y=ymax;
}
else if(outcode&BOTTOM)
{
x=x0+(x1-x0)*(ymin-y0)/(y1-y0);
y=ymin;
}
else if(outcode&RIGHT)
{
y=y0+(y1-y0)*(xmax-x0)/(x1-x0);
x=xmax;
}
else
{
y=y0+(y1-y0)*(xmin-x0)/(x1-x0);
x=xmin;
}
if(outcode==code0)
{
x0=x;
y0=y;
code0=ComputeCode(x0,y0);
}
Dept of CSE, MITE, Moodabidri Page 31
Computer Graphics & Visualization Lab 10CSL67

else
{
x1=x;
y1=y;
code1=ComputeCode(x1,y1);
}
}
}
while(!done);
}
void mouse(int button,int state,int a,int b)
{
if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN)
click=1;
glutPostRedisplay();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
draw_rect();
glColor3f(0.0,0.0,1.0);
draw_line();
CSclip();
if(accept&&click)
{
glColor3f(0.0,1.0,0.0);
draw_line();
}
}
void myinit()
{
glClearColor(0.0,0.0,0.0,1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,800.0,0.0,800.0);
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE);
glutInitWindowSize(800.0,800.0);
glutInitWindowPosition(0.0,0.0);
glutCreateWindow("Clipping Line");
glutMouseFunc(mouse);
glutDisplayFunc(display);
myinit();
glutMainLoop();
return 0;
}
Dept of CSE, MITE, Moodabidri Page 32
Computer Graphics & Visualization Lab 10CSL67

RESULT

Before Clipping

After Clipping

Dept of CSE, MITE, Moodabidri Page 33


Computer Graphics & Visualization Lab 10CSL67

PROGRAM -6
TITLE

Design, develop, and implement the following programs in C/C++ program to create a cylinder and
a parallelepiped by extruding a circle and quadrilateral respectively. Allow the user to specify the
circle and the quadrilateral

AIM

To implement advanced primitives such as cylinder a parallelepiped using basic primitives


such as circle and quadrilateral using OpenGL

DESCRIPTION
In geometry, a parallelepiped is a three-dimensional figure formed by six parallelograms (the
term rhomboid is also sometimes used with this meaning). By analogy, it relates to
a parallelogram just as a cube relates to a square or as a cuboid to a rectangle. In Euclidean
geometry, its definition encompasses all four concepts (i.e., parallelepiped, parallelogram, cube,
and square). In this context of affine geometry, in which angles are not differentiated, its definition
admits only parallelograms and parallelepipeds. Three equivalent definitions of parallelepiped are

 A polyhedron with six faces (hexahedron), each of which is a parallelogram,


 A hexahedron with three pairs of parallel faces, and
 A prism of which the base is a parallelogram.
In its simplest form, a cylinder is the surface formed by the points at a fixed distance from a
given straight line called the axis of the cylinder. It is one of the most basic curvilinear geometric
shapes.

ALGORITHM
1. Include glut header files.
2. Define draw_pixel function to plot points.
void draw_pixel(Glint cx,Glint cy)
{
glcolor3f(1.0,0.0,0.0);
glBegin(GL_POINTS);
glVertex2i(cx,cy);
glEnd();
}
3. Define plot pixel function to plot eight points in perimeter of circle.

Dept of CSE, MITE, Moodabidri Page 34


Computer Graphics & Visualization Lab 10CSL67

Void plotpixel(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+h);
draw_pixel(y+h,-x+h);
draw_pixel(-y+h,-x+h);
}

4. Define circle_draw function to draw circle using mid-point circle algorithm by calling
plotpixel function.

5. Define cylinder_draw function and initialize mid-point and radius value.


i) initialize n value as 50
ii) for(i=10,i<n;i+=3)
{
Circle_draw(xc,yc+I,r);
}

6. Define parallelepiped function to draw 4 sides of parallelepiped.


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

7. Define parallelepiped_draw function.


i) Initialize all vertices value and n=40;
for(i=0;i<n,i+=2)
{
parallelepiped(x1+i,x2+i,y1+i,y2+i,y3+i,y4+i)
}

8. Define display function to call cylinder_draw and parallelepiped_draw function.

9. Define main function to create window and to call all function.

Dept of CSE, MITE, Moodabidri Page 35


Computer Graphics & Visualization Lab 10CSL67

INPUT

None

EXPECTED OUTPUT

Graphics output depicting both cylinder and parallelepiped extruding from the basic
primitive circle and quad respectively.

PROGRAM

#include <GL/glut.h>
#include <math.h>
#include <stdio.h>
void draw_pixel(GLint x, GLint y)
{
glBegin(GL_POINTS);
glVertex2f(x,y);
glEnd();
}
void plotpixels(GLint h, GLint k, GLint x, GLint y)
{
draw_pixel(x+h,y+k);
draw_pixel(-x+h,y+k);
draw_pixel(x+h,-y+k);
draw_pixel(-x+h,-y+k);
draw_pixel(y+h,x+k);
draw_pixel(-y+h,x+k);
draw_pixel(y+h,-x+k);
draw_pixel(-y+h,-x+k);
}
void Circle_draw(GLint h, GLint k, GLint r)
{
GLint d = 1-r, x=0, y=r;
plotpixels(h,k,x,y);
while(y > x)

Dept of CSE, MITE, Moodabidri Page 36


Computer Graphics & Visualization Lab 10CSL67

{
if(d < 0)
d+=2*x+3;
else
{ d+=2*(x-y)+5;
--y;
}
++x;
plotpixels(h,k,x,y);
}

}
void rect_draw(int x1,int y1,int x2,int y2)
{
glLineWidth(2.0);
glBegin(GL_LINE_LOOP);
glVertex2i(x1,y1);
glVertex2i(x2,y1);
glVertex2i(x2,y2);
glVertex2i(x1,y2);
glEnd();
glPointSize(8.0);
glColor3f(0.0,0.0,0.0);
glBegin(GL_POINTS);
glVertex2i(x1,y1);
glVertex2i(x2,y1);
glVertex2i(x2,y2);
glVertex2i(x1,y2);
glEnd();
}

Dept of CSE, MITE, Moodabidri Page 37


Computer Graphics & Visualization Lab 10CSL67

void init(void)
{
glClearColor(1.0,0.0,0.0,0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0,400.0,0.0,400.0);
}
void display(void)
{
GLint i,xc=100, yc=100, r=50;
int x1=200,y1=200,x2=300,y2=300;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0,0.0,0.0);
Circle_draw(xc-1,yc-1,r);
glColor3f(1.0,1.0,0.0);
for(i=1;i<80;i++)
Circle_draw(xc,yc+i,r);
glColor3f(0.0,0.0,0.0);
Circle_draw(xc,yc+81,r);
glColor3f(0.0,0.0,0.0);
rect_draw(x1-1,y1-1,x2-1,y2-1);
for(i=1;i<80;i++)
{
glColor3f(0.0, 0.0, 1.0);
rect_draw(x1+i,y1+i,x2+i,y2+i);
}
glColor3f(0.0,0.0,0.0);
rect_draw(x1+80,y1+80,x2+80,y2+80);
glFlush();
}

int main(int argc, char **argv)


{
glutInit(&argc,argv);
Dept of CSE, MITE, Moodabidri Page 38
Computer Graphics & Visualization Lab 10CSL67

glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(50,50);
glutInitWindowSize(400,400);
glutCreateWindow("Cylinder ");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

RESULT

Dept of CSE, MITE, Moodabidri Page 39


Computer Graphics & Visualization Lab 10CSL67

PROGRAM -7
TITLE

Design, develop, and implement the following programs in C/C++ program, using OpenGL
functions, to draw a simple shaded scene consisting of a tea pot on a table. Define suitably the
position and properties of the light source along with the properties of the properties of the surfaces
of the solid object used in the scene

AIM

To implement a simple shaded scene consisting of a tea pot on a table under various lighting
& shading conditions using OpenGL

ALGORITHM
1. Include glut header files.

2. Define wall function as following


void wall(double thickness)
{
glPushMatrix();
glTranslated(0.5,0.5*thickness,0.5);
glScaled(1.0,thickness,1.0);
glutSolidCube(1.0);
gPopMatrix();
}

3. Draw one tableleg using tableLeg function as following


void tableLeg(double thick,double len)
{
glpushMatrix();
glTranslated(0,len/2,0);
glScaled(thick,len,thick);
glutsolidCube(1.0);
glPopMatrix();
}

4. Draw the table using table function.


i) draw the table top using glutSolidCube(1.0) function.Before this use gltranslated and
glScaled function to fix table in correct place.
ii) Draw four legs by calling the function tableleg .before each call use gltranslated function
to fix four legs in correct place.

5. Define the function displaySolid


i) Initialize the properties of the surface material and set the light source
properties.
Dept of CSE, MITE, Moodabidri Page 40
Computer Graphics & Visualization Lab 10CSL67

ii) Set the camera position.


iii) Draw the teapot using glutSolidTeapot(0.08).before this call gltranslated
and glRotated.
iv) Call table function and wall function
v) Rotate wall about 90 degree and then call wall function.
vi) Rotate wall about -90 degree and then call wall function.

6. Define the main function to create window and enable lighting function using
glEnable(GL_LIGHTING)

INPUT

None

EXPECTED OUTPUT

Graphics output depicting a room with a table and a teapot under a specific lighting and
shading parameters set through OpenGL API

PROGRAM

#include<GL/glut.h>
void wall(double thickness)
{
glPushMatrix();
glTranslated(0.5,0.5*thickness,0.5);
glScaled(1.0,thickness,1.0);
glutSolidCube(1.0);
glPopMatrix();
}
void tableLeg(double thick,double len)
{
glPushMatrix();
glTranslated(0,len/2,0);
glScaled(thick,len,thick);
glutSolidCube(1.0);
glPopMatrix();
}

Dept of CSE, MITE, Moodabidri Page 41


Computer Graphics & Visualization Lab 10CSL67

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);
glMaterialfv(GL_FRONT,GL_SHININESS,mat_shininess);

GLfloat lightIntensity[]={0.7f,0.7f,0.7f,1.0f};
GLfloat light_position[]={2.0f,6.0f,3.0f,0.0f};
glLightfv(GL_LIGHT0,GL_POSITION,light_position);
Dept of CSE, MITE, Moodabidri Page 42
Computer Graphics & Visualization Lab 10CSL67

glLightfv(GL_LIGHT0,GL_DIFFUSE,lightIntensity);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
double winHt=1.0;
glOrtho(-winHt*64/48.0,winHt*64/48.0,-winHt,winHt,0.1,100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(2.3,1.3,2.0,0.0,0.25,0.0,0.0,1.0,0.0);

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslated(0.4,0.4,0.6);
glRotated(45,0,0,1);
glScaled(0.08,0.08,0.08);

glPopMatrix();

glPushMatrix();
glTranslated(0.6,0.38,0.5);
glRotated(30,0,1,0);
glutSolidTeapot(0.08);

glPopMatrix();

glPushMatrix();
glTranslated(0.25,0.42,0.35);
glPopMatrix();
glPushMatrix();
glTranslated(0.4,0,0.4);
table(0.6,0.02,0.02,0.3);
glPopMatrix();
wall(0.02);
Dept of CSE, MITE, Moodabidri Page 43
Computer Graphics & Visualization Lab 10CSL67

glPushMatrix();
glRotated(90.0,0.0,0.0,1.0);
wall(0.02);
glPopMatrix();
glPushMatrix();
glRotated(-90.0,1.0,0.0,0.0);
wall(0.02);
glPopMatrix();
glFlush();
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(640,480);
glutInitWindowPosition(100,100);
glutCreateWindow("Simple shaded scene consisting of a tea pot on a table");
glutDisplayFunc(displaySolid);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
glClearColor(0.1,0.1,0.1,0.0);
glViewport(0,0,640,480);
glutMainLoop();
return 0 ;
}

Dept of CSE, MITE, Moodabidri Page 44


Computer Graphics & Visualization Lab 10CSL67

RESULT

Dept of CSE, MITE, Moodabidri Page 45


Computer Graphics & Visualization Lab 10CSL67

PROGRAM -8
TITLE

Design, develop, and implement the following programs in C/C++ program to draw a color cube
and allow the user to move the camera suitably to experiment with perspective viewing. Use
OpenGL functions

AIM

To implement a rotating cube and experiment with perspective viewing on it

DESCRIPTION

Perspective projections create more realistic looking scenes, so that's what you will most likely be
using most often. In perspective projections, as an object gets farther from the viewer it will appear
smaller on the screen- an effect often referred to as foreshortening. The viewing volume for a
perspective projection is a frustum, which looks like a pyramid with the top cut off, with the narrow
End towards the user.

There is a few different ways you can setup the view frustum, and thus the perspective projection.
The first we will look at is as follows:
void glFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble
near, GLdouble far);
Using glFrustum enables you to specify an asymmetrical frustum, which can be very useful in some
instances, but isn't what you typically want to do.

For a different solution we again turn to the Utility Library:


void gluPerspective(GLdouble fov, GLdouble aspect, GLdouble near, GLdouble far);
fov specifies, in degrees, the angle in the y direction that is visible to the user; aspect is the aspect
ratio of the scene, which is width divided by the height. This will determine the field of view in the
x direction.
The gluLookAt function creates a viewing matrix derived from an eye point, a reference point
indicating the center of the scene, and an up vector.
void gluLookAt(GLdouble eyex, GLdouble eyey, GLdouble eyez, GLdouble centerx,
GLdouble centery, GLdouble centerz, GLdouble upx, GLdouble upy, GLdouble upz);

Dept of CSE, MITE, Moodabidri Page 46


Computer Graphics & Visualization Lab 10CSL67

PSUEDO CODE
1. Define global arrays for vertices and colors
GLfloat vertices[][3] = {{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0},
{1.0,1.0,-1.0}, {-1.0,1.0,-1.0}, {-1.0,-1.0,1.0},
{1.0,-1.0,1.0}, {1.0,1.0,1.0}, {-1.0,1.0,1.0}};
GLfloat colors[][3] = {{0.0,0.0,0.0},{1.0,0.0,0.0},
{1.0,1.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0},
{1.0,0.0,1.0}, {1.0,1.0,1.0}, {0.0,1.0,1.0}};

2. Draw a polygon from a list of indices into the array vertices and use color corresponding to first
index
void polygon(int a, int b, int c, int d)
{
glBegin(GL_POLYGON);
glColor3fv(colors[a]);
glVertex3fv(vertices[a]);
glVertex3fv(vertices[b]);
glVertex3fv(vertices[c]);
glVertex3fv(vertices[d]);
glEnd();
}

3. Draw cube from faces.


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);
polygo n(0,1,5,4);
}
4. Initialize the theta value and initial viewer location and axis
static GLfloat theta[]={0.0,0.0,0.0}
static Glint axis =2;
static GLdouble viewer[]={0.0,0.0,5,0}

5. Define display function to update viewer position in model view matrix


void display(void)
{
/* display callback, clear frame buffer and z buffer,
rotate cube and draw, swap buffers */
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();
Dept of CSE, MITE, Moodabidri Page 47
Computer Graphics & Visualization Lab 10CSL67

glutSwapBuffers();
}
6. Define mouse callback function to rotate about axis
7. Define key function to move viewer position .use x, X,y,Y z,Z keys to move viewer position
8. Define reshape function to maintain aspect ratio and then use perspective view
9. Define main function to create window and to call all function

INPUT

Mouse and keyboard input , i.e. Mouse Input – Right, Left & Middle click to control the
rotation and Keyboard input X- Zoom in (X axis), x – Zoom out(X axis) , Y- Zoom in (Y axis), y –
Zoom out(Y axis) & Z- Zoom in (Z axis), z – Zoom out(Z axis)

EXPECTED OUTPUT

Graphics output depicting a rotating cube whose rotation can be controlled by the mouse
input and keyboard input to control the zooming in and zooming out operation along all 3 axes.

PROGRAM
#include<stdlib.h>
#include<GL/glut.h>
GLfloat vertices[][3]={{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0},{1.0,1.0,-1.0},{-1.0,1.0,-1.0},{-1.0,-
1.0,1.0},{1.0,-1.0,1.0},{1.0,1.0,1.0},{-1.0,1.0,1.0}};
GLfloat normals[][3]={{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0},{1.0,1.0,-1.0},{-1.0,1.0,-1.0},{-1.0,-
1.0,1.0},{1.0,-1.0,1.0},{1.0,1.0,1.0},{-1.0,1.0,1.0}};
GLfloat
colors[][3]={{0.0,0.0,0.0},{1.0,0.0,0.0},{1.0,1.0,0.0},{0.0,1.0,0.0},{0.0,0.0,1.0},{1.0,0.0,1.0},{1.0,
1.0,1.0},{0.0,1.0,1.0}};

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

Dept of CSE, MITE, Moodabidri Page 48


Computer Graphics & Visualization Lab 10CSL67

glNormal3fv(normals[b]);
glVertex3fv(vertices[b]);
glColor3fv(colors[c]);
glNormal3fv(normals[c]);
glVertex3fv(vertices[c]);
glColor3fv(colors[d]);
glNormal3fv(normals[d]);
glVertex3fv(vertices[d]);
glEnd();
}
void colorcube()
{
polygon(0,3,2,1);
polygon(2,3,7,6);
polygon(0,4,7,3);
polygon(1,2,6,5);
polygon(4,5,6,7);
polygon(0,1,5,4);
}
static GLfloat theta[]={0.0,0.0,0.0};
static GLint axis=2;
static GLdouble viewer[]={0.0,0.0,5.0};
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt(viewer[0],viewer[1],viewer[2],0.0,0.0,0.0,0.0,1.0,0.0);
glRotatef(theta[0],1.0,0.0,0.0);
glRotatef(theta[1],0.0,1.0,0.0);
glRotatef(theta[2],0.0,0.0,1.0);
colorcube();
glFlush();
glutSwapBuffers();
Dept of CSE, MITE, Moodabidri Page 49
Computer Graphics & Visualization Lab 10CSL67

}
void mouse(int btn,int state,int x,int y)
{
if(btn==GLUT_LEFT_BUTTON && state==GLUT_DOWN)
axis=0;
if(btn==GLUT_MIDDLE_BUTTON && state==GLUT_DOWN)
axis=1;
if(btn==GLUT_RIGHT_BUTTON && state==GLUT_DOWN)
axis=2;
theta[axis]+=2.0;
if(theta[axis]>360.0)
theta[axis]-=360.0;
display();
}
void keys(unsigned char key,int x,int y)
{
if(key=='x') viewer[0]-=1.0;
if(key=='X') viewer[0]+=1.0;
if(key=='y') viewer[1]-=1.0;
if(key=='Y') viewer[1]+=1.0;
if(key=='z') viewer[2]-=1.0;
if(key=='Z') viewer[2]+=1.0;
display();
}
void myReshape(int w,int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w<=h)
glFrustum(-2.0,2.0,2.0*(GLfloat)h/(GLfloat)w,2.0*(GLfloat)h/(GLfloat)w,2.0,20.0);
else
glFrustum(-2.0,2.0,2.0*(GLfloat)w/(GLfloat)h,2.0*(GLfloat)w/(GLfloat)h,2.0,20.0);
Dept of CSE, MITE, Moodabidri Page 50
Computer Graphics & Visualization Lab 10CSL67

glMatrixMode(GL_MODELVIEW);
}

int 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();
return 0;
}

RESULT

Dept of CSE, MITE, Moodabidri Page 51


Computer Graphics & Visualization Lab 10CSL67

PROGRAM -9
TITLE

Design, develop, and implement the following programs in C/C++ program to fill any given
polygon using scan-line area filling algorithm. (Use appropriate data structures.)

AIM

To implement the scan-line area filling algorithm using OpenGL

DESCRIPTION

Scanline rendering (also scan line rendering and scan-line rendering) is an algorithm for visible
surface determination, in 3D computer graphics, that works on a row-by-row basis rather than
a polygon-by-polygon or pixel-by-pixel basis. All of the polygons to be rendered are first sorted by
the top y coordinate at which they first appear, then each row or scan line of the image is computed
using the intersection of a scanline with the polygons on the front of the sorted list, while the sorted
list is updated to discard no-longer-visible polygons as the active scan line is advanced down the
picture.

The main advantage of this method is that sorting vertices along the normal of the scanning plane
reduces the number of comparisons between edges. Another advantage is that it is not necessary to
translate the coordinates of all vertices from the main memory into the working memory—only
vertices defining edges that intersect the current scan line need to be in active memory, and each
vertex is read in only once. The main memory is often very slow compared to the link between the
central processing unit and cache memory, and thus avoiding re-accessing vertices in main memory
can provide a substantial speedup

ALGORITHM
1. Set y to the smallest y coordinate that has an entry in the ET; i.e., y for the first Nonempty
bucket.
2. Initialize the AET to be empty.
3. Repeat until the AET and ET are empty:
 Move from ET bucket y to the AET those edges whose y_min = y (entering edges).
 Remove from the AET those entries for which y = y_max (edges not involved in the
next scanline), the sort the AET on x (made easier because ET is presorted).

Dept of CSE, MITE, Moodabidri Page 52


Computer Graphics & Visualization Lab 10CSL67

 Fill in desired pixel values on scanline y by using pairs of x coordinates from AET.
 Increment y by 1 (to the coordinate of the next scanline).
 For each non vertical edge remaining in the AET, update x for the new y.

INPUT

None

EXPECTED OUTPUT

Graphics output depicting the filling up of a polygon (Rhombus) using scan-line filling
algorithm

PROGRAM

#define BLACK 0

#include<stdlib.h>

#include<stdio.h>

#include<GL/glut.h>

float x1,x2,x3,x4,y1,y2,y3,y4;

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;

Dept of CSE, MITE, Moodabidri Page 53


Computer Graphics & Visualization Lab 10CSL67

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

Dept of CSE, MITE, Moodabidri Page 54


Computer Graphics & Visualization Lab 10CSL67

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

Dept of CSE, MITE, Moodabidri Page 55


Computer Graphics & Visualization Lab 10CSL67

glVertex2f(x1,y1);

glVertex2f(x2,y2);

glVertex2f(x3,y3);

glVertex2f(x4,y4);

glEnd();

scanfill(x1,y1,x2,y2,x3,y3,x4,y4);

glFlush();

void myinit()

glClearColor(0.0,0.0,0.0,1.0);

glColor3f(1.0,1.0,0.0);

glPointSize(0.5);

glMatrixMode(GL_PROJECTION);

glLoadIdentity();

gluOrtho2D(0.0,499.0,0.0,499.0);

void main(int argc,char **argv)

glutInit(&argc,argv);

glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);

glutInitWindowSize(500,500);

glutInitWindowPosition(0,0);

glutCreateWindow("Filling a Ploygon using Scan-line Algorithm");

Dept of CSE, MITE, Moodabidri Page 56


Computer Graphics & Visualization Lab 10CSL67

glutDisplayFunc(display);

myinit();

glutMainLoop();

RESULT

Dept of CSE, MITE, Moodabidri Page 57


Computer Graphics & Visualization Lab 10CSL67

PROGRAM -10
TITLE

Design, develop, and implement the following programs in C/C++ program to display a set of
values {fij} as a rectangular mesh

AIM

To implement a mesh like structure using OpenGL

DESCRIPTION

A mesh is a collection of vertices, edges and faces that define the shape of a 3D object. The most
popular type of polygon mesh used in computer graphics is a triangle mesh. Any object, either a
mountain or a game character can be modeled with meshes.

PSEUDO CODE

1. Include the header files.

2. Define the maxx ,maxy,n value and dx,dy value

3. Initialize the values for x0 and y0 value and declare array x[maxx],y[maxy].

4. Define the init function to clear color, defining point size, to specify matrix mode, to request
redisplay.
void init()
{
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(1.0,0.0,0.0);
glPointSize(5.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,499.0,0.0,499.0);
glutPostRedisplay();
}

5. Define display function


i) Clear the window using glClear(GL_COLOR_BUFFER_BIT)
ii) Set the color
iii) Compute x[i] and y[i] value by adding dx ,dy value to x0 and y0
repectively.
iv) Using GL_LINE_LOOP draw the lines.

6. Define main function to create window and to call display and init function

Dept of CSE, MITE, Moodabidri Page 58


Computer Graphics & Visualization Lab 10CSL67

INPUT

None

EXPECTED OUTPUT

Graphics output depicting the mesh like structure

PROGRAM
#include<GL/glut.h>
#define maxx 20
#define maxy 20
#define dx 10
#define dy 10
int x0=40,y0=40;
float x[maxx],y[maxy];
void display()
{
int i,j;
glClear(GL_COLOR_BUFFER_BIT);
for(i=0;i<maxx;i++)
x[i]=x0+i*dx;
for(j=0;j<maxy;j++)
y[j]=y0+j*dy;
for(i=0;i<maxx-1;i++)
for(j=0;j<maxy-1;j++)
{
glLineWidth(8.0);
glBegin(GL_LINE_LOOP);
glVertex2f(x[i],y[j]);
glVertex2f(x[i],y[j+1]);
glVertex2f(x[i+1],y[j+1]);
glVertex2f(x[i+1],y[j]);
glEnd();
glFlush(); }
Dept of CSE, MITE, Moodabidri Page 59
Computer Graphics & Visualization Lab 10CSL67

glFlush();
}
void myinit()
{
glClearColor(1,1,1,1);
glColor3f(0,0.1,0.2);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,500.0,0.0,500.0);
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE);
glutInitWindowSize(900,900);
glutInitWindowPosition(0,0);
glutCreateWindow("Rectangular Mesh");
glutDisplayFunc(display);
myinit();
glutMainLoop();
return 0;
}
RESULT

Dept of CSE, MITE, Moodabidri Page 60

You might also like