CG Lab Manual
CG Lab Manual
E(Sem-1) [2022-23]
STES’s
NBN SINGHAD SCHOOL OF ENGINEERING
Ambegaon (Bk), Pune
Department of Computer Engineering
LABORATORY MANUAL
2022-23
Computer Graphics Laboratory
SE-COMPUTER ENGINEERING
SEMESTER-1
Subject Code:210248
TEACHING SCHEME EXAMINATION SCHEME
Lectures: 4Hrs/Week Practical: 25 Marks
Practical: 4 Hrs/Week Term Work: 25
-: Name of Faculty :-
Prof. Pushpanjali S. Sajjanshetti
Prof . Asharani M. Chadchankar
Department of Computer Engineering
NBN Sinhgad School of Engineering
OR
b) Write C++ program to draw the following pattern. Use DDA and Bresenham‘s drawing
algorithm
Group B
4 Write C++ program to draw a 2-D object and perform following basic transformation,
Scaling b) Translation c) Rotation. Apply the concept of operator overloading.
5 Write C++ program generate fractal patterns using Koch Curves.
Group C
7 a) Write C++ program to draw man walking in the rain with an umbrella. Apply the
concept of polymorphism.
This is a step by step tutorial on how to install graphics.h for C++ on Linux [Ubuntu 20.04].
(Lines in bold are commands for the terminal)
Step 1:
Download the library required from given link:
http://download.savannah.gnu.org/releases/libgraph/libgraph-1.0.2.tar.gz
Step 2:
Launch the terminal.
(Use Ctrl + Alt + T for quick access)
Step 3:
Type
Step 4:
Following are the other libraries to be installed;
Step 5:
Find the package for the library on your computer. It is generally in the downloads folder.
The name may resemble something like “libgraph-1.0.2.tar.gz”.
4| Department of Computer Engineering, NBN SSOE,PUNE
Computer Graphics Laboratory S.E.C.E(Sem-1) [2022-23]
Step 6:
Extract the folder inside the archive.
Extracted folder tends to have the same name as the archive.
Step 7:
Change the terminal directory to the extracted folder.
Considering that the folder is in the Downloads directory, The command should look something
like this:
cd Downloads/libgraph-1.0.2
If you have any queries or get any errors, contact the lab faculty.
Step 8:
In the terminal, after changing to above mentioned directory, run the following command:
./configure
Step 9:
Now type make in the terminal and press Enter.
Step 10:
Then type
sudo make install
Step 11:
Finally, type the following line:
sudo cp /usr/local/lib/libgraph.* /usr/lib
This concludes the installation process of the library graphics.h for the g++ compiler on Ubuntu
20.04 lts.
Signature
Assignment No:1
Write C++ program for line drawing using Bradenham’s algorithm with patterns such
as solid, dotted, dashed, dash dot and thick
Title of Assignment: Draw a line with styles.
Problem Definition: Write C++ program for line drawing using DDA or
Bradenham’s algorithm with patterns such as solid, dotted, dashed, dash dot
and thick.
LINE: It is the path between two end points. We can draw line by two methods
1] Using inbuilt function
Syntax: -void far line(int x1, int y1, int x2, int y2);
Comments: -Line() draws a line in the current color using current line style and
thickness.
Linestyle : This is a function used to sets the line style and width or pattern . Sets
8| Department of Computer Engineering, NBN SSOE,PUNE
Computer Graphics Laboratory S.E.C.E(Sem-1) [2022-23]
the style for all lines drawn by line, line to, rectangle,drawpoly, etc.
Syntax : void far setline style(int style, unsigned pattern, int thickness)
unpattern is a 16-bit pattern that applies only if line style is USERBIT_LINE (4).
In that case, whenever a bit in the pattern word is 1, the corresponding pixel in the
line is drawn in the current drawing color.
For example, a solid line corresponds to a unpattern of 0xFFFF (all pixels drawn),
while a dashed line can correspond to a unpattern of 0x3333(short dashes) or
0x0F0F(long dashes) or 0x3F3F (longer dashes).
Thickness: Sets the width of the line. Two available widths are given in the table.
Name Value Meaning
NORM_WIDTH 1 1 pixel
THICK_WIDTH 3 3 pixel
We can use general line drawing algorithm to display solid line. Such as DDA,
Bradenham’s etc.
• Dotted Line
We can easily modify the general line drawing algorithm to
display dotted line. By plotting the alternate pixels in line we can
display the dotted line
• Dashed Line
We can easily modify the general line drawing algorithm to display dashed
line. We have to plot alternate group of pixels along the line to get dashed line.
• Thick Line
To produce a thick line we have to run two line drawing algorithms in parallel to
find the pixel along the line edges.
Settextjustuify() : It is used for text alignment i:e left, right and centre
Questions:-
Q 1: How to draw line with different styles without using inbuilt function?
1. Conclusion:-
In This way we have studied that how to draw a line with line style.
#include <iostream>
#include <stdlib.h>
#include <graphics.h>
#include <math.h>
using namespace std;
int xmax,ymax,xmid,ymid;
class Line
{
public:
int x1,x2,y1,y2,ch;
void bss(int x1,int y1,int x2,int y2)
{
int dx,dy,x,y,s1,s2,ex,e,i,flag=0,temp;
dx=abs(x2-x1);
dy=abs(y2-y1);
x=x1;
y=y1;
putpixel(x+xmid,ymid-y,15);
if(x2>x1)
{
s1=1;
}
if(x2==x1)
{
s1=0;
}
if(x2<x1)
{
s1=-1;
}
if(y2>y1) {
s2=1;
}
if(y2==y1)
{
s2=0;
}
if(y2<y1)
{
s2=-1;
}
if(dy>dx)
{
temp=dx;
dx=dy;
dy=temp;
ex=1;
}
else
ex=0;
e=2*dy-dx;
i=1;
do
{
while(e>0)
{
if(ex==1)
x=x+s1;
else
y=y+s2;
e=e-2*dx;
}
while(e<0)
{
if(ex==1)
y=y+s2;
else
x=x+s1;
e=e+2*dy;
}
switch(ch)
{
case 1:
putpixel(x+xmid,ymid-y,15);
break;
case 2:
if(flag==0)
{putpixel(x+xmid,ymid-y,15);
delay(1000);}
if(i%5==0)
{
if(flag==1)
flag=0;
else
flag=1;
}
break;
case 3:
if(flag==0)
putpixel(x+xmid,ymid-y,15);
delay(100);
if(i%5==0)
{
if(flag==1)
flag=0;
else
flag=1;
}
if(i%3==0)
{
putpixel(x+xmid,ymid-y,15);
delay(1000);}
break;
case 4:
if(flag==0)
{delay(1000);
}
else
{
if(i%3==0)
{
putpixel(x+xmid,ymid-y,15);
delay(1000);
}
}
break;
case 5:
putpixel(x+xmid,ymid-y,15);
break;
}
i=i+1;
delay(50);
}while(i<=dx);
}
};
int main()
{
int gd=DETECT,gm;
int x1,y1,x2,y2,thick,wx,wy,i;
Line B;
cout<<"Enter two end points of line\n";
cin>>x1>>y1;
cin>>x2>>y2;
while(1)
{
cout<<"\nEnter the Style\n";
cout<<"1.Simple\n";
cout<<"2.Dash\n";
cout<<"3.Dash Dot\n";
cout<<"4.Dot\n";
cout<<"5.Thick\n";
cout<<"6.Exit\n";
cout<<"Enter your Style\n";
cin>>B.ch;
if(B.ch==5)
{
cin>>thick;
}
initgraph(&gd,&gm,NULL); cout<<"Enter The Thickness of line: ";
xmax=getmaxx();
ymax=getmaxy();
xmid=xmax/2;
ymid=ymax/2;
if(B.ch<=4)
{
B.bss(x1,y1,x2,y2);
delay(300);
}
else
{
B.bss(x1,y1,x2,y2);
delay(300);
if((y2-y1)/(x2-x1)<1)
{
wy=(thick-1)*sqrt(pow((x2-x1),2)+pow((y2-y1),2))/(2*fabs(x2-x1));
for(i=0;i<wy;i++)
{
B.bss(x1,y1-i,x2,y2-i);
delay(300);
B.bss(x1,y1+i,x2,y2+i);
delay(300);
}
}
else
wx=(thick-1)*sqrt(pow((x2-x1),2)+pow((y2-y1),2))/(2*fabs(y2-y1));
for(i=0;i<wx;i++)
{
B.bss(x1-i,y1,x2-i,y2);
delay(300);
B.bss(x1+i,y1,x2+i,y2);
delay(300);
}
}
if(B.ch==6)
{
cout<<"Exiting....";
exit(1);
}
closegraph();
}
return 0;
}
Date
Assignment No:2
Write C++ program to draw circle using Bradenham’s algorithm
Drawing a circle on the screen is a little complex than drawing a line. There are
two popular algorithms for generating a circle − Bradenham’s Algorithm and
Midpoint Circle Algorithm. These algorithms are based on the idea of
determining the subsequent points required to draw the circle. Let us discuss the
algorithms in detail −
For every pixel (x, y) it calculates, we draw a pixel in each of the 8 octants of the
circle as shown below,
Bresenham’s Algorithm
Now, we will see how to calculate the next pixel location from a previously
known pixel location (x, y). In Bradenham’s algorithm at any point (x, y) we
have two option either to choose the next pixel in the east i.e. (x+1, y) or in
th e south east i.e. (x+1, y-1).
• If d > 0, then (x+1, y-1) is to be chosen as the next pixel as it will be closer
to the arc.
• else (x+1, y) is to be chosen as next pixel.
Now to draw the circle for a given radius ‘r’ and center (xc, yc) We will start
from (0, r) and move in first quadrant till x=y (i.e. 45 degree). We should start
from listed initial condition:
d = 3 - (2 *
r) x = 0
y = r
5. Increment value of x.
RED); putpixel(xc-x,
yc-y, RED);
putpixel(xc+y, yc+x,
RED); putpixel(xc-y,
yc+x, RED);
putpixel(xc+y, yc-x,
RED); putpixel(xc-y,
yc-x, RED);
}
2.4 Questions:-
2.5 Conclusion:-
In This way we have studied that how to draw a circle on the screen.
#include<graphics.h>
#include<iostream>
using namespace std;
class pixel
{
public:
float x1,y1,r;
void brecircle(float x1,float y1,float r);
};
class point : public pixel
{
pixel p;
public:
void Drawcircle()
{
cout<<"Enter the starting co-ordinates of a center:";
cin>>p.x1>>p.y1;
cout<<"Enter the value of radius:";
cin>>p.r;
brecircle(p.x1,p.y1,p.r);
}
};
void pixel::brecircle(float x1,float y1,float r)
{
float x,y,p;
x=0;
y=r;
p=3-(2*r);
while(x<=y)
{
putpixel(x1+x,y1+y,WHITE);
putpixel(x1-x,y1+y,WHITE);
putpixel(x1+x,y1-y,WHITE);
putpixel(x1-x,y1-y,WHITE);
putpixel(x1+y,y1+x,WHITE);
putpixel(x1+y,y1-x,WHITE);
putpixel(x1-y,y1+x,WHITE);
putpixel(x1-y,y1-x,WHITE);
x=x+1;
if(p<0)
{
p=p+4*(x)+6;
}
else
{
p=p+4*(x-y)+10;
y=y-1;
}
delay(20);
}
}
int main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,NULL);
point pt;
pt.Drawcircle();
delay(50000);
closegraph();
return 0;
}
Signature
ExperimentNo:3
Title: Implement Following pattern using Line Drawing and Circle Drawing
Algorithm.
Aim: Write a program to draw using following algorithms- Circle generation and
Line Drawing.
Prerequisites:
Line and Line segment, Slope of Line, General Equation of Line
Objectives:
Understand DDA, Bresenham’s line drawing algorithm and Bresenham’s
Circle drawing. Further using these algorithms to draw real time pictures.
Theory:
DDA Line Drawing:
It is Digital Differential Analyzer (DDA).
It is also called as Vector generation line drawing algorithm.
Here we solve the differential equation for straight line. For drawing a line we
need to turn ON the pixels which are on the line segment. For this we consider
the slope of line.
For simplicity we divide the line segment in two types.
a) Line with Gentle Slope.
x
D Dy
Dx
Here Dx>Dy. We increment x by one unit and fine corresponding new value of y.
b) Line with Sharpe Slope
Dy
Dx
Here Dy>Dx, we increment y by one unit and calculate corresponding new value of
x.
Algorithm:
DDA line(Draw a figure)
Read the line endpoints (X1, Y1) and (X2, Y2) such that they are not equal.
1) Calculate
dx = X2 –
X1 dy = Y2 –Y1
2) if (dx >dy)
then step =
dx
else step = dy
end
if
3) Xin = dx /
y = Y1
5) i = 1
31 | Department of Computer Engineering, NBN SSOE,PUNE
Computer Graphics Laboratory S.E.C.E(Sem-1) [2022-23]
Algorithm:
1) Read the line endpoints (X1, Y1) and (X2, Y2) such that they are not equal.
2) Calculate
dx = X2 – X1 dy = Y2 – Y1
3) Initialize
x = X1
y = Y1
4) Calculate decision variable e = 2 * dy – dx
5) i = 1
put pixel ( x, y,1)
6) while ( e >= 0)
{
y=y+1
e = e – 2 * dx
}
32 | Department of Computer Engineering, NBN SSOE,PUNE
Computer Graphics Laboratory S.E.C.E(Sem-1) [2022-23]
x=x+1
e = e + 2 * dy
7) i = 1
8) if ( i <= dx) then go to step
9) Stop.
Questions:
# include <iostream>
# include <graphics.h>
# include <stdlib.h>
using namespace std;
class dcircle
{
private: int x0, y0;
public:
dcircle()
{
x0=0;
y0=0;
}
void setoff(int xx, int yy)
{
x0=xx;
y0=yy;
}
void drawc(int x1, int y1, int r)
{
float d;
int x,y;
x=0;
y=r;
d=3-2*r;
do
{
putpixel(x1+x0+x, y0+y-y1, 15);
putpixel(x1+x0+y, y0+x-y1,15);
putpixel(x1+x0+y, y0-x-y1,15);
putpixel(x1+x0+x,y0-y-y1,15);
putpixel(x1+x0-x,y0-y-y1,15);
putpixel(x1+x0-y, y0-x-y1,15);
putpixel(x1+x0-y, y0+x-y1,15);
putpixel(x1+x0-x, y0+y-y1,15);
if (d<=0)
{
d = d+4*x+6;
}
else
{
d=d+4*(x-y)+10;
y=y-1;
}
x=x+1;
}
while(x<y);
}
};
class pt
{
protected: int xco, yco,color;
public:
pt()
{
xco=0,yco=0,color=15;
}
void setco(int x, int y)
{
xco=x;
yco=y;
}
void setcolor(int c)
{
color=c;
}
void draw()
{
putpixel(xco,yco,color);
}
};
class dline:public pt
{
private: int x2, y2;
public:
dline():pt()
{
x2=0;
y2=0;
}
void setline(int x, int y, int xx, int yy)
{
pt::setco(x,y);
x2=xx;
y2=yy;
}
void drawl( int colour)
{
float x,y,dx,dy,length;
int i;
pt::setcolor(colour);
dx= abs(x2-xco);
dy=abs(y2-yco);
if(dx>=dy)
{
length= dx;
}
else
{
length= dy;
}
dx=(x2-xco)/length;
dy=(y2-yco)/length;
x=xco+0.5;
y=yco+0.5;
i=1;
while(i<=length)
{
pt::setco(x,y);
pt::draw();
x=x+dx;
y=y+dy;
i=i+1;
}
pt::setco(x,y);
pt::draw();
}
};
int main()
{
int gd=DETECT, gm;
initgraph(&gd, &gm, NULL);
int x,y,r, x1, x2, y1, y2, xmax, ymax, xmid, ymid, n, i;
dcircle c;
cout<<"\nenter coordinates of centre of circle : ";
cout<<"\n enter the value of x : ";
cin>>x;
cout<<"\nenter the value of y : ";
cin>>y;
cout<<"\nenter the value of radius : ";
cin>>r;
xmax= getmaxx();
ymax=getmaxy();
xmid=xmax/2;
ymid=ymax/2;
setcolor(1);
c.setoff(xmid,ymid);
line(xmid, 0, xmid, ymax);
line(0,ymid,xmax,ymid);
setcolor(15);
c.drawc(x,y,r);
pt p1;
p1.setco(100,100);
p1.setcolor(14);
dline l;
l.setline(x1+xmid, ymid-y1, x2+xmid, ymid-y2);
cout<<"Enter Total Number of lines : ";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Enter co-ordinates of point x1 : ";
cin>>x1;
cout<<"enter coordinates of point y1 : ";
cin>>y1;
cout<<"Enter co-ordinates of point x2 : ";
cin>>x2;
cout<<"enter coordinates of point y2 : ";
cin>>y2;
l.setline(x1+xmid, ymid-y1, x2+xmid, ymid-y2);
l.drawl(15);
}
cout<<"\nEnter coordinates of centre of circle : ";
cout<<"\n Enter the value of x : ";
cin>>x;
cout<<"\nEnter the value of y : ";
cin>>y;
cout<<"\nEnter the value of radius : ";
cin>>r;
setcolor(5);
c.drawc(x,y,r);
getch();
delay(200);
closegraph();
return 0;
}
GROUP B
(2 ASSIGNMENT)
Assignment 4(GROUP B)
No.
Write C++ program to draw a 2-D object and
perform following basic transformation, Scaling b)
Translation c) Rotation. Apply the concept of
Title operator overloading.
S.E. (C.E)
Class
Date
Signature
Assignment No: 4
Title: 2D Transformations
Problem Statement: Write C++ program to draw 2-D object and perform
following basic transformations,
a) Scaling
b) Translation
c) Rotation
Apply concept of operator overloading
PREREQUISITES:
1. Knowledge of matrix fundamentals and basic transformations on polygon -
translation, rotation & scaling.
COURSE OBJECTIVE:
1. To acquaint the learner with the basic concepts of Computer Graphics
2. To get familiar with mathematics behind the graphical transformations
THEORY:
2D tansformations:
Transformations allow us to uniformly alter the entire picture. The geometric
transformations considered here - translation, scaling and rotation are expressed in
terms of matrix multiplication.
Scaling
scaling refers to changing the size of the object either by increasing or decreasing.
Scaling can be achieved by multiplying the original coordinates of the object
42 | Department of Computer Engineering, NBN SSOE,PUNE
Computer Graphics Laboratory S.E.C.E(Sem-1) [2022-23]
with the scaling factor to get the desired result. The scaling factor SX, SY scales
the object in X and Y direction respectively. The above equations can also be
represented in matrix form as below −
Rotation:
In rotation, we rotate the object at particular angle θ (theta) from its origin. From the
following figure, we can see that the point P(X, Y) is located at angle φ from the
horizontal X coordinate with distance r from the origin.
Translation
A translation moves an object to a different position on the screen. You can
translate a point in 2D by adding translation coordinate (tx, ty) to the original
coordinate (X, Y) to get the new coordinate (X’, Y’).
Translation Distance: It is nothing but by how much units we should shift the
object from one location to another along x, y-axis.
Operator Overloading
Algorithm:
5. stop
2. Operator Overloading
#include<iostream>
#include<graphics.h>
#include<math.h>
using namespace std;
class transform
{
public:
int m,a[20][20],c[20][20];
int i,j,k;
public:
void object();
void accept();
void operator *(float b[20][20])
{
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
c[i][j]=0;
for(int k=0;k<m;k++)
{
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
}
}
};
void transform::object()
{
int gd,gm;
gd=DETECT;
initgraph(&gd,&gm,NULL);
line(300,0,300,600);
line(0,300,600,300);
for( i=0;i<m-1;i++)
{
line(300+a[i][0],300-a[i][1],300+a[i+1][0],300-a[i+1][1]);
}
line(300+a[0][0],300-a[0][1],300+a[i][0],300-a[i][1]);
for( i=0;i<m-1;i++)
{
line(300+c[i][0],300-c[i][1],300+c[i+1][0],300-c[i+1][1]);
}
line(300+c[0][0],300-c[0][1],300+c[i][0],300-c[i][1]);
int temp;
cout << "Press 1 to continue";
cin >> temp;
closegraph();
}
void transform::accept()
{
cout<<"\n";
cout<<"Enter the Number Of Edges:";
cin>>m;
cout<<"\nEnter The Coordinates :";
for(int i=0;i<m;i++)
{
for(int j=0;j<3;j++)
{
if(j>=2)
a[i][j]=1;
else
cin>>a[i][j];
}
}
}
int main()
{
int ch,tx,ty,sx,sy;
float deg,theta,b[20][20];
transform t;
t.accept();
b[2][0]=tx;
b[2][1]=ty;
t * b;
t.object();
break;
case 2: cout<<"\nSCALING OPERATION\n";
cout<<"Enter value for sx,sy:";
cin>>sx>>sy;
b[0][0]=sx;
b[1][1]=sy;
b[0][1]=b[0][2]=b[1][0]=b[1][2]=0;
b[2][0]=b[2][1]=0;
b[2][2] = 1;
t * b;
t.object();
break;
case 3: cout<<"\nROTATION OPERATION\n";
cout<<"Enter value for angle:";
cin>>deg;
theta=deg*(3.14/100);
b[0][0]=b[1][1]=cos(theta);
b[0][1]=sin(theta);
b[1][0]=sin(-theta);
b[0][2]=b[1][2]=b[2][0]=b[2][1]=0;
b[2][2]=1;
t * b;
t.object();
break;
default:
cout<<"\nInvalid choice";
getch();
return 0;
}
Signature
Experiment No:5
TITLE: Fractal Graphics
PROBLEM STATEMENT:
Write C++ program to generate fractal patterns by using Koch curves.
PREREQUISITES:
Basic knowledge of mathematic primitives
COURSE OBJECTIVE:
1. To acquaint the learnerwith the basic concepts of fractal graphics
2. To get familiar with mathematics behind the graphical transformations
COURSE OUTCOME:
Develop the competency to understand the concepts related to fractals
THEORY:
Fractals: Fractals are very complex pictures generated by a computer from a single
formula. They are created using iterations. This means one formula is repeated with
slightly different values over and over again, taking into account the results from the
previous iteration.
Fractals are used in many areas such as −
Astronomy − For analyzing galaxies, rings of Saturn, etc.
Biology/Chemistry − For depicting bacteria cultures, Chemical reactions, human
anatomy, molecules, plants,
Others − For depicting clouds, coastline and borderlines, data compression, diffusion,
economy, fractal art, fractal music, landscapes, special effect, etc.
Koch curve :
The Koch curve is also known as snowflake curve. The Koch curve originally
described by Helge von Koch is constructed with only one of the three sides of the
original triangle. In other words, three Koch curves make a Koch snowflake.
ALGORITHM:
• Remove the line segment that is the base of the triangle from step 2.
• After one iteration of this process, the resulting shape is the outline of a hexagram.
1. The Koch snowflake is the limit approached as the above steps are followed
over and over again.
2. The Koch curve originally described by Koch is constructed with only one of
the three sides of the original triangle.
3. In other words, three Koch curves make a Koch snowflake.
QUESTIONS:-
1) Define Koch curve
2) How to construct Koch curve
#include <iostream>
#include <math.h>
#include <graphics.h>
using namespace std;
class kochCurve
{
public:
void koch(int it,int x1,int y1,int x5,int y5)
{
int x2,y2,x3,y3,x4,y4;
int dx,dy;
if (it==0)
{
line(x1,y1,x5,y5);
}
else
{
delay(10);
dx=(x5-x1)/3;
dy=(y5-y1)/3;
x2=x1+dx;
y2=y1+dy;
x3=(int)(0.5*(x1+x5)+sqrt(3)*(y1-y5)/6);
y3=(int)(0.5*(y1+y5)+sqrt(3)*(x5-x1)/6);
x4=2*dx+x1;
y4=2*dy+y1;
koch(it-1,x1,y1,x2,y2);
koch(it-1,x2,y2,x3,y3);
koch(it-1,x3,y3,x4,y4);
koch(it-1,x4,y4,x5,y5);
}
}
};
int main()
{
kochCurve k;
int it;
cout<<"Enter Number Of Iterations : "<<endl;
cin>>it;
int gd=DETECT,gm;
initgraph(&gd,&gm,NULL);
k.koch(it,150,20,20,280);
k.koch(it,280,280,150,20);
k.koch(it,20,280,280,280);
getch();
closegraph();
return 0;
}
GROUP C
(2 ASSIGNMENT)
Signature
Experiment No:6
Aim: Write OpenGL program to draw Sun Rise and Sun Set
➢ Development: It is an evolving API and Khronos Group regularly releases its new
version having some extended feature compare to previous one. GPU vendors may also
provide some additional functionality in the form of extension.
➢ Main
• Open window and configure frame buffer (using GLUT for example)
• Initialize GL states and display (Double buffer, color mode, etc.)
➢ Loop
• Check for events
if window event (resize, unhide, maximize etc.) modify the viewport and Redrawvzelse if
input event (keyboard and mouse etc.)
handle the event (such as move the camera or change the state)
and usually draw the scene
➢ Redraw
• Clear the screen (and buffers e.g., z-buffer)
• Change states (ifdesired)
• Render
• Swap buffers (if double buffer)
OpenGL Syntax
➢ All functions have the form: gl*
• glVertex3f() – 3 means that this function take three arguments, and f means that
the type of those arguments is float.
• glVertex2i() – 2 means that this function take two arguments, and i means that
the type of those arguments is integer
➢ All variable types have the form: GL*
• In OpenGL program it is better to use OpenGL variable types (portability)
▪ Glfloat instead of float
▪ Glint instead of int
OpenGL primitives
Drawing two lines
glBegin(GL_LINES);
glVertex3f(_,_,_); // start point of line 1
glVertex3f(_,_,_); // end point of line 1
glVertex3f(_,_,_); // start point of line 2
glVertex3f(_,_,_); // end point of line 2 glEnd();
We can replace GL_LINES with GL_POINTS, GL_LINELOOP, GL_POLYGON etc.
OpenGL states
➢ On/off (e.g., depth buffer test)
• glEnable( GLenum )
• glDisable( GLenum )
• Examples:
63 | Department of Computer Engineering, NBN SSOE,PUNE
Computer Graphics Laboratory S.E.C.E(Sem-1) [2022-23]
▪ glEnable(GL_DEPTH_TEST);
▪ glDisable(GL_LIGHTING);
➢ Mode States
• Once the mode is set the effect stays until reset
• Examples:
▪ glShadeModel(GL_FLAT) or glShadeModel(GL_SMOOTH)
▪ glLightModel(…) etc.
Drawing in 3D
➢ Depth buffer (or z-buffer) allows scene to remove hidden surfaces.
Use
glEnable(GL_DEPTH_TEST) to enable it.
GLU is the OpenGL utility library. It contains useful functions at a higher level than those
64 | Department of Computer Engineering, NBN SSOE,PUNE
Computer Graphics Laboratory S.E.C.E(Sem-1) [2022-23]
provided by OpenGL, for example, to draw complex shapes or set up cameras. All GLU
functions are written on top of OpenGL. Like OpenGL, GLU function names begin with
glu, and constants begin with GLU.
GLUT, the OpenGL Utility Toolkit, provides a system for setting up callbacks for
interacting with the user and functions for dealing with the windowing system. This
abstraction allows a program to run on different operating systems with only a recompile.
Glut follows the convention of prepending function names with glut and constants with
GLUT.
Writing an OpenGL Program with GLUT
An OpenGL program using the three libraries listed above must include the appropriate
headers. This requires the following threelines: #include <GL/gl.h>
#include <GL/glu.h> #include
<GL/glut.h>
Before OpenGL rendering calls can be made, some initialization has to be done. With
GLUT, this consists of initializing the GLUT library, initializing the display mode, creating
the window, and setting up callback functions. The following lines initialize a full color,
double buffered display: glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
Double buffering means that there are two buffers, a front buffer and a back buffer. The
front buffer is displayed to the user, while the back buffer is used for rendering operations.
This prevents flickering that would occur if we rendered directly to the front buffer.
Next, a window is created with GLUT that will contain the viewport which displays the
OpenGL front buffer with the following three lines: glutInitWindowPosition(px, py);
glutInitWindowSize(sx, sy); glutCreateWindow(name);
To register callback functions, we simply pass the name of the function that handles the event
to the appropriate GLUT function. glutReshapeFunc(reshape);
glutDisplayFunc(display);
Here, the functions should have the following prototypes:
void reshape(int width, int height); void display();
In this example, when the user resizes the window, reshape is called by GLUT, and when
65 | Department of Computer Engineering, NBN SSOE,PUNE
Computer Graphics Laboratory S.E.C.E(Sem-1) [2022-23]
the display needs to be refreshed, the display function is called. For animation, an idle
event handler that takes no arguments can be created to call the display function to
constantly redraw the scene with glutIdleFunc. Once all the callbacks have been set up, a
call to glutMainLoop allows the program torun.
In the display function, typically the image buffer is cleared, primitives are rendered to it,
and the results are presented to the user. The following line clears the image buffer, setting
each pixel color to the clear color, which can be configured to be anycolor:
glClear(GL_COLOR_BUFFER_BIT);
The next line sets the current rendering color to blue. OpenGL behaves like a state
machine, so certain state such as the rendering color is saved by OpenGL and used
automatically later as it is needed.
To render a primitive, such as a point, line, or polygon, OpenGL requires that a call to
glBegin is made to specify the type of primitive being rendered.
glBegin(GL_LINES);
Only a subset of OpenGL commands is available after a call to glBegin. The main
command that is used is glVertex, which specifies a vertex position. In GL LINES mode,
each pair of vertices define endpoints of a line segment. In this case, a line would be drawn
from the point at ( x0, y0) to (x1, y1).
glVertex2f(x0, y0);
glVertex2f(x1, y1);
A call to glEnd completes rendering of the current primitive. glEnd(); Finally, the back buffer needs to
be swapped to the front buffer that the user will see, which GLUT can handle for us:
glutSwapBuffers();
Signature
Group C
Assignment No: 7
PROBLEM STATEMENT:
Write C++ program to to draw man walking in the rain with an umbrella.
Apply the concept of polymorphism.
PREREQUISITES:
Basic knowledge of graphics primitives.
COURSE OBJECTIVE:
1. To implement the features of graphics.
2. To interface the applications of graphics to the real world.
3. To give some benefits to the disability.
4. To make the life easier.
5. To become familiarization with Graphics and its logical coding.
COURSE OUTCOME:
To understand the concepts related to polymorphism and graphics primitives.
THEORY:
Computer Graphics has revolutionized almost every computer-based
application in science and technology. Information technology is a trend
today.The importance of computer graphics lies in its applications. In
engineering applications (e.g. automotive and aerospace) the ability to quickly
visualize newly designed shapes is indispensible. Computer graphics has also
expanded the boundaries of art and entertainment. Movies such as
“JURASSIC PARK” make extensive use of computer graphics to create
images that test the bounds of imagination. The development of computer
graphics has made possible virtual reality, a synthetic reality that exists only
inside a computer. Virtual reality is fast becoming an indispensable tool in
education. Flight simulators are used to train pilot for extreme conditions.
Surgical simulators are used to train novice surgeons without endangering
patients.
Setfillstyle function: setfillstyle function sets the current fill pattern and
fill color.
#include<iostream>
#include<graphics.h>
#include<stdlib.h>
using namespace std;
class walkingman
{
int rhx,rhy;
public:
void draw(int,int);
void draw(int);
};
void walkingman::draw(int i)
{
line(20,380,580,380);
if(i%2)
{
line(25+i,380,35+i,340);
line(45+i,380,35+i,340);
line(35+i,310,25+i,330);
delay(20);
}
else
{
line(35+i,340,35+i,310);
line(35+i,310,40+i,330);
delay(20);
}
line(35+i,340,35+i,310);
circle(35+i,300,10);
line(35+i,310,50+i,330);
line(50+i,330,50+i,280);
line(15+i,280,85+i,280);
arc(50+i,280,0,180,35);
arc(55+i,330,180,360,5);
}
void walkingman::draw(int x,int y)
{
int j;
rhx=x;
rhy=y;
for
(j=0;j<100;j++)
{
outtextxy(rand()%rhx,rand()%(rhy-50),"|");
setcolor(WHITE);
}
}
int main()
{
int gd=DETECT,gm;
int rhx,rhy,j,i;
walkingman obj;
initgraph(&gd,&gm,"");
for(i=0;i<500;i++)
{
obj.draw(i);
rhx=getmaxx();
rhy=getmaxy();
obj.draw(rhx,rhy);
delay(150);
cleardevice();
}
getch();
}
MINI PROJECT
MINI PROJECT
Title: Mini project for animation of moving car
Theory:
Function used:
(1) initgraph : It initializes the graphics system by loading the passed graphics
driver then Charging the system into graphics mode.
(2) get maxx : It returns the maximum & Co-ordinate in current graphics mode and
diver
(3) getmaxy: It returns the maximum X Cordinate in Current graphics mode and
driver
(4) Set color: It changes the Current drawing colour. Default Colour is White. Each
color is assigned a number like BLACK is and RED is 4. Here we are using
colour constants defined Inside graphics.h header file.
(5) Setfillstyle: It states the Current Fill pattern and fill color.
(8) Arc: It draws a Circular arc from start angle till end angle.
(9) Floodfill: It is used to fill a closed area with current fill pattern and fill color. It
takes any point inside. Closed area and Color of the boundary as input.
(10) Cleardevice: It clear the screen and sets Current position to (0,0).
(12) Close graph: It includes the graphics drivers and sets the Screen back to meet
mode.
Approach:
1. In this program we first draw a red color car on left side of the Screen (x,y) and
then erases it wing cleardevice function.
2. we again draw this car at (x+5,y).
3. This will look like a moving car from left to right direction.
4. we will repeat above step, until car reaches then right side of screen.
Conclusion.-
In this Ways created a mini project for animation of moving car using graphics and
successfully implemented it.
#include <stdio.h>
#include <graphics.h>
#include <conio.h>
#include <dos.h>
int main() {
int gd = DETECT, gm;
int i, maxx, midy;
/* initialize graphic mode */
initgraph(&gd, &gm, "X:\\TC\\BGI");
/* maximum pixel in horizontal axis */
maxx = getmaxx();
/* mid pixel in vertical axis */
midy = getmaxy()/2;
for (i=0; i < maxx-150; i=i+5) {
/* clears screen */
cleardevice();
/* draw a white road */
setcolor(WHITE);
line(0, midy + 37, maxx, midy + 37);
/* Draw Car */
setcolor(YELLOW);
setfillstyle(SOLID_FILL, RED);
line(i, midy + 23, i, midy);
line(i, midy, 40 + i, midy - 20);
line(40 + i, midy - 20, 80 + i, midy - 20);
line(80 + i, midy - 20, 100 + i, midy);
line(100 + i, midy, 120 + i, midy);
line(120 + i, midy, 120 + i, midy + 23);
line(0 + i, midy + 23, 18 + i, midy + 23);
arc(30 + i, midy + 23, 0, 180, 12);
line(42 + i, midy + 23, 78 + i, midy + 23);
arc(90 + i, midy + 23, 0, 180, 12);
line(102 + i, midy + 23, 120 + i, midy + 23);
line(28 + i, midy, 43 + i, midy - 15);
line(43 + i, midy - 15, 57 + i, midy - 15);
line(57 + i, midy - 15, 57 + i, midy);
line(57 + i, midy, 28 + i, midy);
line(62 + i, midy - 15, 77 + i, midy - 15);
line(77 + i, midy - 15, 92 + i, midy);
line(92 + i, midy, 62 + i, midy);
line(62 + i, midy, 62 + i, midy - 15);
floodfill(5 + i, midy + 22, YELLOW);
setcolor(BLUE);
setfillstyle(SOLID_FILL, DARKGRAY);
/* Draw Wheels */
circle(30 + i, midy + 25, 9);
circle(90 + i, midy + 25, 9);
floodfill(30 + i, midy + 25, BLUE);
floodfill(90 + i, midy + 25, BLUE);
getch();
closegraph();
return 0;