OpenGL Setup & Basics Guide
OpenGL Setup & Basics Guide
PICT, INSTITUTE
SE-IT OF COMPUTER TECHNOLOGY
Computer Graphics Laboratory
SECOND YEAR
Information Technology
(2019 Course)
LABORATORY MANUAL
For
SEMESTER - III
[Subject code: 214457]
[Prepared By]
Dr. Kavita A. Sultanpure
Dr. Shweta C. Dharmadhikari
Mr. Abhinay G. Dhamankar
~1~
PICT, SE-IT Computer Graphics Laboratory
VISION
MISSION
VISION
MISSION
professionals.
~2~
PICT, SE-IT Computer Graphics Laboratory
~3~
PICT, SE-IT Computer Graphics Laboratory
~4~
PICT, SE-IT Computer Graphics Laboratory
~5~
PICT, SE-IT Computer Graphics Laboratory
Prerequisites:
Basic Geometry, Trigonometry, Vectors and Matrices, Data Structures and
Algorithms
Course Objectives:
1. To acquaint the learners with the concepts of OpenGL.
2. To acquaint the learners with the basic concepts of Computer Graphics.
3. To implement the various algorithms for generating and rendering the objects.
4. To get familiar with mathematics behind the transformations.
5. To understand and apply various methods and techniques regarding animation.
~6~
PICT, SE-IT Computer Graphics Laboratory
Assignment No 1
Aim: Install and explore the OpenGL
Prob Statements: Install and explore the OpenGL Functions and Commands
Theory :
How to Install OpenGL on Linux
Part-1 Prepare your Linux Mint operating system for OpenGL Development
1 Open a terminal and enter the following commands to install the
necessary libraries for OpenGL development:
Type/Copy/Paste following commands:
$ sudo apt-get update
$ sudo apt-get install freeglut3
$ sudo apt-get install freeglut3-dev
$ sudo apt-get install binutils-gold
$ sudo apt-get install g++ cmake
$ sudo apt-get install libglew-dev
$ sudo apt-get install g++
$ sudo apt-get install mesa-common-dev
$ sudo apt-get install build-essential
$ sudo apt-get install libglew1.5-dev libglm-dev
#include <GL/freeglut.h>
#include <GL/gl.h>
void renderFunction()
~7~
PICT, SE-IT Computer Graphics Laboratory
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
glBegin(GL_POLYGON);
glVertex2f(-0.5, -0.5);
glVertex2f(-0.5, 0.5);
glVertex2f(0.5, 0.5);
glVertex2f(0.5, -0.5);
glEnd();
glFlush();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowSize(500,500);
glutInitWindowPosition(100,100);
glutCreateWindow("OpenGL - First window demo");
glutDisplayFunc(renderFunction);
glutMainLoop();
return 0;
}
Header Files
In all of our graphics programs, we will need to include the header file for the OpenGL core library.
For most applications we will also need GLU, and on many systems we will need to include the header
file for the window system. For instance, with Microsoft Windows, the header file that accesses the
WGL routines is windows.h. This header file must be listed before the OpenGL and GLU header files
because it contains macros needed by the MicrosoftWindows version of the OpenGL libraries. So
the source file in this case would begin with
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
However, if we use GLUT to handle the window-managing operations, we do not need to include
gl.h and glu.h because GLUT ensures that these will be included correctly. Thus, we can replace the
header files for OpenGL and GLU with
#include <GL/glut.h>
~8~
PICT, SE-IT Computer Graphics Laboratory
(We could include gl.h and glu.h as well, but doing so would be redundant and could affect program
portability.) On some systems, the header files for OpenGL and GLUT routines are found in different
places in the filesystem. For instance, on Apple OS X systems, the header file inclusion statement
would be
#include <GLUT/glut.h>
In addition, we will often need to include header files that are required by the C++ code. For example,
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
With the ISO/ANSI standard for C++, these header files are called cstdio, cstdlib, and cmath.
To get started, we can consider a simplified, minimal number of operations for displaying a picture.
Since we are using the OpenGL Utility Toolkit, our first step is to initializeGLUT. This initialization
function could also process any command line arguments, but we will not need to use these
parameters for our first example programs.We perform the GLUT initialization with the statement
Next, we can state that a display window is to be created on the screen with a given caption for the
title bar. This is accomplished with the function
where the single argument for this function can be any character string that we want to use for the
display-window title. Then we need to specify what the display window is to contain. For this, we
create a picture using OpenGL functions and pass the picture definition to the GLUT routine
glutDisplayFunc, which assigns our picture to the display window. As an example, suppose we have
the OpenGL code for describing a line segment in a procedure called lineSegment. Then the following
function call passes the line-segment description to the display window:
glutDisplayFunc (lineSegment);
But the display window is not yet on the screen. We need one more GLUT function to complete the
window-processing operations. After execution of the following statement, all display windows that
we have created, including their graphic content, are now activated:
glutMainLoop ( );
This function must be the last one in our program. It displays the initial graphics and puts the program
into an infinite loop that checks for input from devices such as a mouse or keyboard. Our first
example will not be interactive, so the program will just continue to display our picture until we close
the display window. In later chapters, we consider how we can modify our OpenGL programs to
handle interactive input. Although the display window that we created will be in some default
location and size,wecan set these parameters using additionalGLUTfunctions.We use the
glutInitWindowPosition function to give an initial location for the upperleft corner of the display
window. This position is specified in integer screen
~9~
PICT, SE-IT Computer Graphics Laboratory
coordinates, whose origin is at the upper-left corner of the screen. For instance, the following
statement specifies that the upper-left corner of the display window should be placed 50 pixels to
the right of the left edge of the screen and 100 pixels down from the top edge of the screen:
Similarly, the glutInitWindowSize function is used to set the initial pixel width and height of the
display window. Thus, we specify a display window with an initial width of 400 pixels and a height of
300 pixels (Fig. 2) with the statement
After the display window is on the screen, we can reposition and resize it. We can also set a number
of other options for the display window, such as buffering and a choice of color modes, with the
glutInitDisplayMode function.
Arguments for this routine are assigned symbolicGLUTconstants. For example, the following
command specifies that a single refresh buffer is to be used for the display window and that we want
to use the color mode which uses red, green, and blue (RGB) components to select color values:
The values of the constants passed to this function are combined using a logical or operation.
Actually, single buffering and RGB color mode are the default options. But we will use the function
now as a reminder that these are the options that are set for our display. Later, we discuss color
modes in more detail, as well as other display options, such as double buffering for animation
applications and selecting parameters for viewing three-dimensional scenes.
Using RGB color values, we set the background color for the display window to be white, as in Figure
2, with the OpenGL function:
~ 10 ~
PICT, SE-IT Computer Graphics Laboratory
The first three arguments in this function set the red, green, and blue component colors to the value
1.0, giving us a white background color for the display window. If, instead of 1.0, we set each of the
component colors to 0.0, we would get a black background. And if all three of these components
were set to the same intermediate value between 0.0 and 1.0, we would get some shade of gray. The
fourth parameter in the glClearColor function is called the alpha value for the specified color. One
use for the alpha value is as a “blending” parameter. When we activate the OpenGL blending
operations, alpha values can be used to determine the resulting color for two overlapping objects.
An alpha value of 0.0 indicates a totally transparent object, and an alpha value of 1.0 indicates an
opaque object. Blending operations will not be used for a while, so the value of alpha is irrelevant to
our early example programs. For now, we will simply set alpha to 0.0.
Although the glClearColor command assigns a color to the display window, it does not put the
displaywindowon the screen. To get the assignedwindow color displayed, we need to invoke the
following OpenGL function:
glClear (GL_COLOR_BUFFER_BIT);
The argument GL COLOR BUFFER BIT is an OpenGL symbolic constant specifying that it is the bit
values in the color buffer (refresh buffer) that are to be set to the values indicated in the glClearColor
function. (OpenGL has several different kinds of buffers that can be manipulated.
In addition to setting the background color for the display window, we canchoose a variety of color
schemes for the objects we want to display in a scene. For our initial programming example, we will
simply set the object color to be a dark green
The suffix 3f on the glColor function indicates that we are specifying the three RGB color
components using floating-point (f) values. This function requires that the values be in the range from
0.0 to 1.0, and we have set red = 0.0, green = 0.4, and blue = 0.2.
For our first program, we simply display a two-dimensional line segment. To do this, we need to tell
OpenGL how we want to “project” our picture onto the display window because generating a two-
dimensional picture is treated by OpenGL as a special case of three-dimensional viewing. So,
although we only want to produce a very simple two-dimensional line, OpenGL processes our picture
through the full three-dimensional viewing operations. We can set the projection type (mode) and
other viewing parameters that we need with the following two functions:
glMatrixMode (GL_PROJECTION);
gluOrtho2D (0.0, 200.0, 0.0, 150.0);
This specifies that an orthogonal projection is to be used to map the contents of a two-dimensional
rectangular area of world coordinates to the screen, and that the x-coordinate values within this
rectangle range from 0.0 to 200.0 with y-coordinate values ranging from 0.0 to 150.0. Whatever
objects we define within this world-coordinate rectangle will be shown within the display window.
Anything outside this coordinate range will not be displayed. Therefore, the GLU function
gluOrtho2D defines the coordinate reference frame within the display window to be (0.0, 0.0) at the
lower-left corner of the display window and (200.0, 150.0) at the upper-right window corner. Since
we are only describing a two-dimensional object, the orthogonal projection has no other effect than
to “paste” our picture into the display window that we defined earlier. For now, we will use a world-
coordinate rectangle with the same aspect ratio as the display window, so that there is no distortion
of our picture. Later, we will consider how we can maintain an aspect ratio that does not depend
upon the display-window specification. Finally,weneed to call the appropriateOpenGLroutines to
create our line segment. The following code defines a two-dimensional, straight-line segment with
integer, Cartesian endpoint coordinates (180, 15) and (10, 145).
~ 11 ~
PICT, SE-IT Computer Graphics Laboratory
glBegin (GL_LINES);
glVertex2i (180, 15);
glVertex2i (10, 145);
glEnd ( );
Now we are ready to put all the pieces together. The following OpenGL program is organized into
three functions.We place all initializations and related one-time parameter settings in function init.
Our geometric description of the “picture” that we want to display is in function lineSegment, which
is the function that will be referenced by the GLUT function glutDisplayFunc. And the main function
contains the GLUT functions for setting up the display window and getting our line segment onto
the screen. Figure 3 shows the displaywindow and line segment generated by this program.
~ 12 ~
PICT, SE-IT Computer Graphics Laboratory
Conclusion : Successfully installed OpenGL and Successfully studies the OpenGL Commands
~ 13 ~
PICT, SE-IT Computer Graphics Laboratory
Assignment No 2
Aim: Understand and Implement DDA and Bresenham’s Line Drawing Algorithms using OpenGL.
Prob Statements : Implement DDA and Bresenham line drawing algorithm to draw: i) Simple
Line ii) Dotted Line iii) Dashed Line iv) Solid line ;
using mouse interface Divide the screen in four quadrants with center as (0, 0). The line should work
for all the slopes positive as well as negative.
Theory :
Theory:
A) DDA (Digital Differential Analyzer) Line Drawing Algorithm
~ 14 ~
PICT, SE-IT Computer Graphics Laboratory
Algorithm:
A) DDA :-
Given-
• Starting coordinates = (X0, Y0)
• Ending coordinates = (Xn, Yn)
The points generation using DDA Algorithm involves the following steps-
Step-01:
Calculate ΔX, ΔY and M from the given input.
These parameters are calculated as-
• ΔX = Xn – X0
• ΔY =Yn – Y0
• M = ΔY / ΔX
Step-02:
Find the number of steps or points in between the starting and ending coordinates.
if (absolute (ΔX) > absolute (ΔY))
Steps = absolute (ΔX);
else
Steps = absolute (ΔY);
Step-03:
Suppose the current point is (Xp, Yp) and the next point is (Xp+1, Yp+1).
Find the next point by following the below three cases-
Step-04:
Keep repeating Step-03 until the end point is reached or the number of generated new points
(including the starting and ending points) equals to the steps count.
B) Bresenham’s Algorithm :-
1. START
2. Get Initial Co-ordinates (xi, yi) and final coordinates (xf, yf).
3. Initialize dx and dy to abs (xi, xf) and abs (yi, yf) respectively where abs () represents absolute
difference between passed values.
4. Initialize x_change and y_change values on the basis of following conditions.
a) If xi > xf then x_change = -1 else x_change = 1
b) If yi > yf then y_change = -1 else y_change = 1
5. If dx is 0, plot vertical line and exit.
6. If dy is 0, plot horizontal line and exit.
~ 15 ~
PICT, SE-IT Computer Graphics Laboratory
7. Initialize x = xi and y = yi.
8. Initialize decision parameter P.
9. If dx > dy:
a) Set P = 2*dy – dx
b) Initialize loop variable i to 0.
c) If P > 0, y = y + y_change, P = P + 2*(dy - dx).
d) Else, P = P + 2*dy
e) x = x + x_change
f) Plot vertex (x, y).
g) i = i+1
h) If i < dx, Go To step (c).
10. Else:
a) Set P = 2*dx – dy
b) Initialize loop variable i to 0.
c) If P > 0, x = x + x_change, P = P + 2*(dx - dy)
d) Else, P = P + 2*dy
e) y = y + y_change
f) Plot vertex (x, y)/
g) i = i + 1.
h) If i < dy, Go to Step (c).
11. STOP
Conclusion:
1. DDA and Bresenham’s Algorithm for line drawing were studied and analyzed
mathematically.
2. Above algorithms were implemented using OpenGL library and mouse interface for trapping
co-ordinates and assigning menu was used.
~ 16 ~
PICT, SE-IT Computer Graphics Laboratory
Code :-
Bresenhem Algorithm :
#include <GL/freeglut.h>
#include <GL/gl.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
void render_function()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 0.0, 1.0);
gluOrtho2D(0, 500, 0, 500);
glBegin(GL_POINTS);
BSA_Algo(0,250,500,250);
BSA_Algo(250,0,250,500);
~ 19 ~
PICT, SE-IT Computer Graphics Laboratory
glEnd();
glFlush();
}
Output :-
DDA Algorithm :
#include<GL/glut.h>
#include<stdlib.h>
#include<stdio.h>
~ 20 ~
PICT, SE-IT Computer Graphics Laboratory
float x01,x2,y01,y2;
int ch;
float dx = x2-x1;
float dy = y2-y1;
if(abs(dx) >abs(dy)){
step = abs(dx);
}
else step = abs(dy);
float x = x1;
float y = y1;
glFlush();
float dx = x2-x1;
float dy = y2-y1;
if(abs(dx) >abs(dy)){
step = abs(dx);
}
~ 21 ~
PICT, SE-IT Computer Graphics Laboratory
else step = abs(dy);
float x = x1;
float y = y1;
displayPoint(x,y);
x= x + Xinc;
y= y + Yinc;
if(i % 3 ==0 ){
displayPoint(x,y);
}
glFlush();
float dx = x2-x1;
float dy = y2-y1;
if(abs(dx) >abs(dy)){
step = abs(dx);
}
else step = abs(dy);
float x = x1;
float y = y1;
displayPoint(x,y);
x= x + Xinc;
y= y + Yinc;
if(i % 7 ==0 ){
~ 22 ~
PICT, SE-IT Computer Graphics Laboratory
displayPoint(x,y);
}
glFlush();
if (pt == 0){
xst = x;
yst = y;
x01 = xst;
y01 = yst;
pt = pt+1;
}
else{
x2 = x;
y2 = y;
if (ch == 1){
SimpleLine(xst,yst,x,y);
}
else if(ch == 2){
DottedLine(xst,yst,x,y);
}
else if (ch == 3) {
DashedLine(xst,yst,x,y);
}
xst=x;
yst=y;
}
}
else if (button==GLUT_RIGHT_BUTTON && state==GLUT_DOWN)
pt = 0;
//Clear Screen
glFlush();
}
switch(key){
~ 23 ~
PICT, SE-IT Computer Graphics Laboratory
case 's':
{
ch = 1;
glutMouseFunc(myMouse);
break;
}
case 'd':
{
ch = 2;
glutMouseFunc(myMouse);
break;
}
case 'D':
{
ch = 3;
glutMouseFunc(myMouse);
break;
}
}
glutPostRedisplay();
}
void initialize(void)
{
void primitives(void){
Output :-
~ 25 ~
PICT, SE-IT Computer Graphics Laboratory
Assignment No 3
Prob Statements : Implement Bresenham circle drawing algorithm to draw any object.
The object should be displayed in all the quadrants with respect to center and radius.
Theory :
The best approximation of the true circle will be described by those pixels in the
raster that falls the least distance from the true circle. We want to generate the
points from
90° to 45°. Assume that the last scan-converted pixel is P1 as shown in fig. Each new
point closest to the true circle can be found by taking either of two actions.
2. Move in the x- direction one unit & move in the negative y-direction one unit.
~ 26 ~
PICT, SE-IT Computer Graphics Laboratory
Let D (Si) is the distance from the origin to the true circle squared minus the distance
to point P3 squared. D (Ti) is the distance from the origin to the true circle squared
minus the distance to point P2 squared. Therefore, the following expressions arise.
Since D (Si) will always be +ve & D (Ti) will always be -ve, a decision variable d may be
defined as follows:
Therefore,
di=(xi-1+1)2+ yi-12 -r2+(xi-1+1)2+(yi-1 -1)2-r2
If it is assumed that the circle is centered at the origin, then at the first step x = 0 & y
= r.
Therefore,
di=(0+1)2+r2 -r2+(0+1)2+(r-1)2-r2
=1+1+r2-2r+1-r2
= 3 - 2r
di+1=di+ 4xi+6
Algorithm :
Step4: Calculate d = 3 - 2r
Step5: Initialize x= r
Step7: Plot eight points by using concepts of eight-way symmetry. The center is at
(p, q). Current active pixel is (x, y).
putpixel (x+p, y+q)
putpixel (y+p, x+q) putpixel
(-y+p, x+q) putpixel (-x+p,
y+q) putpixel (-x+p, -y+q)
putpixel (-y+p, -x+q)
putpixel (y+p, -x+q)
putpixel (x+p, -y-q)
~ 28 ~
PICT, SE-IT Computer Graphics Laboratory
Conclusion :
Advantages
• It is a simple algorithm.
• It can be implemented easily
• It is totally based on the equation of circle i.e. x2 +y2 =r2
Disadvantages
• There is a problem of accuracy while generating points.
• This algorithm is not suitable for complex and high graphic images.
CODE :
#include <iostream>
#include <GL/glut.h>
#include <math.h>
}
//mid point circle drawing void
circleMP(int xc,int yc,int r)
{
int p=1-r,x=0,y=r;
//loop til the x become y equal to radius (r,r)
while(x<y)
{
octant(xc,yc,x,y);
x++;
if(p>0) //if p>0 decrement the y and 2(x-y)+1
y--,p+=2*(x-y)+1; else //if p<=0 add 2x+1 to p
p+=2*x+1;
}
}
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
glFlush();
~ 30 ~
PICT, SE-IT Computer Graphics Laboratory
}
void seedfill(int x,int y,color oc,color nc)
{
color c;
glReadPixels(x,y,1,1,GL_RGB,GL_UNSIGNED_BYTE,&c);
if(c.r==oc.r&&c.b==oc.b&&c.g==oc.g)
{
plottofill(x,y,nc); seedfill(x+1,y,oc,nc);
seedfill(x- 1,y,oc,nc);
seedfill(x,y+1,oc,nc);
seedfill(x,y-1,oc,nc);
}
}
//Draw all the Cirlces
void drawcircles(int x,int y,int r)
{
circleMP(x,y,r);
circleMP(x+2*r,y,r); circleMP(x-
2*r,y,r);
circleMP(x+2*r*cos(ang(60)),y+2*r*sin(ang(60)),r);
circleMP(x-2*r*cos(ang(60)),y+2*r*sin(ang(60)),r); circleMP(x-
2*r*cos(ang(60)),y-2*r*sin(ang(60)),r);
circleMP(x+2*r*cos(ang(60)),y-2*r*sin(ang(60)),r);
circleMP(x,y,3*r);
circleMP(x,y,(float)2*r-r*(0.20));
}
//Display Function
void draw() {
}
//Clear the whole screen
void clear_screen()
{
glClearColor(1,1,1,0);
glClear(GL_COLOR_BUFFER_BI
T);
}
~ 32 ~
PICT, SE-IT Computer Graphics Laboratory
//First point to get the xc,yc
if(flag&&button==GLUT_LEFT_BUTTON&&state==GLUT_
DOWN)
{
cout<<"Center Found"<<endl;
cx=x,cy=600-y;
glPointSize(5.0);
glColor3f(1,0,0);
glBegin(GL_POINTS);
glVertex2i(x,600-y);
glEnd();
glFlush();
flag=0;
}
//find the radius of the circle
else if
(!flag&&button==GLUT_LEFT_BUTTON&&state==GLUT_DOWN)
{
cout<<"Ohhho !!, I got a radius"<<endl;
glColor3f(0,0,1);
glPointSize(1.0);
glBegin(GL_POINTS);
glVertex2i(x,600-y);
glEnd();
glFlush();
R=abs(x-cx);
flag=1;
}
}
case 2:
case 4:
case 3:
~ 33 ~
PICT, SE-IT Computer Graphics Laboratory
break; ered Circle"<<endl; seedfill(cx+5,cy,oc,nc);
break;
c
l
e
a
r
_
s
c
r
e
e
n
(
)
;
b
r
e
a
k
;
c
o
u
t
<
<
"
F
i
l
l
t
h
e
C
e
n
t
~ 34 ~
PICT, SE-IT Computer Graphics Laboratory
exit(0); break;
}
}
int main(int agrc,char ** agrv)
{
glutInit(&agrc,agrv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowPosition(0,0); glutInitWindowSize(600,600);
glutCreateWindow("Circle");
init();
glutDisplayFunc(draw);
glutCreateMenu(menu);
glutAddMenuEntry("Draw",1);
glutAddMenuEntry("Clear",2);
glutAddMenuEntry("Color Fill",3);
glutAddMenuEntry("Exit",4);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutMouseFunc(mouseClick);
glutMainLoop();
}
~1~
PICT, SE-IT Computer Graphics Laboratory
OUTPUT :
Conclusion :
Successfully Implemented Bresenham’s Circle Generation Algorithms using
OpenGL
~2~
PICT, SE-IT Computer Graphics Laboratory
Assignment No 4
Prob Statements : Implement the following polygon filling methods : i) Flood fill / Seed
fill ii) Boundary fill ; using mouse click, keyboard interface and menu driven programming
Theory :
1) Flood Fill / Seed Fill Algorithm :-
In this method, a point or seed which is inside region is selected. This point is called a
seed point. Then four connected approaches or eight connected approaches is used to fill
with specified color.
The flood fill algorithm has many characters similar to boundary fill. But this method is
more suitable for filling multiple colors boundary. When boundary is of many colors and
interior is to be filled with one color we use this algorithm.
In fill algorithm, we start from a specified interior point (x, y) and reassign all pixel values
are currently set to a given interior color with the desired color. Using either a 4-
connected or 8-connected approaches, we then step through pixel positions until all
interior points have been repainted.
~3~
PICT, SE-IT Computer Graphics Laboratory
~4~
PICT, SE-IT Computer Graphics Laboratory
Algorithm:
1) Flood Fill / Seed Fill Algorithm :-
1. Procedure floodfill (x, y,fill_ color, old_color: integer)
2. If (getpixel (x, y)=old_color)
3. {
4. setpixel (x, y, fill_color);
5. fill (x+1, y, fill_color, old_color);
6. fill (x-1, y, fill_color, old_color);
7. fill (x, y+1, fill_color, old_color);
8. fill (x, y-1, fill_color, old_color);
9. }
10. }
Step 4 − Change the default color with the fill color at the seed point.
setPixel(seedx, seedy, fcol)
Step 5 − Recursively follow the procedure with four neighborhood points.
FloodFill (seedx – 1, seedy, fcol, dcol)
FloodFill (seedx + 1, seedy, fcol, dcol)
FloodFill (seedx, seedy - 1, fcol, dcol)
FloodFill (seedx – 1, seedy + 1, fcol, dcol)
Step 6 – Exit
~6~
PICT, SE-IT Computer Graphics Laboratory
• 4-connected boundary-fill regions can be defined by lines and arcs. By translating the
line and arc endpoints we can translate, scale and rotate the whole boundary-fill region.
Therefore 4-connected boundary-fill regions are better suited to modelling.
Code :-
#include<stdio.h>
#include<GL/gl.h>
#include<GL/glu.h>
#include<GL/glut.h>
#include<math.h>
pixel f_color,b_color;
float mat1[20][3];
float ans1[20][3];
float trans1[3][3];
int ch=1;
void initial_co()
{
int i,y,x;
y=90;
//horizontal lines
for(i=0;i<10;i+=2)
{
//first point
mat1[i][0]=90;
mat1[i][1]=y;
mat1[i][2]=1;
//second point
mat1[i+1][0]=210;
mat1[i+1][1]=y;
mat1[i+1][2]=1;
y+=30;
}
x=90;
//vertical lines
for(i;i<20;i+=2)
{
~7~
PICT, SE-IT Computer Graphics Laboratory
//first point
mat1[i][0]=x;
mat1[i][1]=90;
mat1[i][2]=1;
//second point
mat1[i+1][0]=x;
mat1[i+1][1]=210;
mat1[i+1][2]=1;
x+=30;
}
}
void rotate_fig()
{
int i,j,k;
float theta;
theta=45*3.14/180;
for(i=0;i<20;i++)
{
for(j=0;j<3;j++)
{
ans1[i][j]=0;
for(k=0;k<3;k++)
ans1[i][j]+=mat1[i][k]*trans1[k][j];
}
}
/*-----------------------rotation at origin--------------------------------*/
~8~
PICT, SE-IT Computer Graphics Laboratory
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i==j)
trans1[i][j]=1;
else
trans1[i][j]=0;
}
}
trans1[0][0]=trans1[1][1]=cos(theta);
trans1[0][1]=sin(theta);
trans1[1][0]=-sin(theta);
/*
trans1= cos sin 0
-sin cos 0
0 0 1
*/
for(i=0;i<20;i++)
{
for(j=0;j<3;j++)
{
mat1[i][j]=0;
for(k=0;k<3;k++)
mat1[i][j]+=ans1[i][k]*trans1[k][j];
}
}
/*-----------------------translation back-----------------------------*/
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i==j)
trans1[i][j]=1;
else
trans1[i][j]=0;
}
}
trans1[2][0]=trans1[2][1]=150;
for(i=0;i<20;i++)
{
for(j=0;j<3;j++)
{
ans1[i][j]=0;
for(k=0;k<3;k++)
~9~
PICT, SE-IT Computer Graphics Laboratory
ans1[i][j]+=mat1[i][k]*trans1[k][j];
}
}
//if color not equal to backgroung color and filling color put color
if((c.r!=b_color.r || c.g!=b_color.g || c.b!=b_color.b )&&(c.r!=f_color.r || c.g!=f_color.g ||
c.b!=f_color.b ))
{
glColor3ub(f_color.r,f_color.g,f_color.b);//set fill color for pixel
glBegin(GL_POINTS);
glVertex2d(x,y);//put pixel
glEnd();
glFlush();
boundary_fill(x+1,y);//right pixel
boundary_fill(x-1,y);//left pixel
boundary_fill(x,y+1);//upper pixel
boundary_fill(x,y-1);//lower pixel
}
}
void before()
{
int i;
initial_co();
glBegin(GL_LINES);//draws the new figure
for(i=0;i<20;i+=2)
{
glVertex2f(mat1[i][0],mat1[i][1]);
glVertex2f(mat1[i+1][0],mat1[i+1][1]);
}
glEnd();
glFlush();
}
void figure()
{
glClear(GL_COLOR_BUFFER_BIT);
int i;
float factor=30*cos(45*3.14/180);
//green
f_color.r=0;
f_color.g=255;
f_color.b=0;
boundary_fill(150,150+3*factor);
//blue
f_color.r=0;
f_color.g=0;
f_color.b=255;
boundary_fill(150,150-factor);
//yellow
f_color.r=255;
f_color.g=255;
f_color.b=0;
boundary_fill(150,150-3*factor);
//light blue
f_color.r=0;
f_color.g=255;
f_color.b=255;
boundary_fill(150+2*factor,150+factor);
//pink
f_color.r=255;
f_color.g=0;
f_color.b=255;
boundary_fill(150-2*factor,150+factor);
//purple
f_color.r=150;
f_color.g=0;
f_color.b=255;
boundary_fill(150+2*factor,150-factor);
~ 11 ~
PICT, SE-IT Computer Graphics Laboratory
//light violet
f_color.r=150;
f_color.g=150;
f_color.b=255;
boundary_fill(150-2*factor,150-factor);
}
void Init()
{
glClearColor(1.0,1.0,1.0,0.0);//sets the background colour
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0,0.0,0.0);//sets the drawing colour
gluOrtho2D(0,500,0,500);//sets the co ordinates
}
//border color
b_color.r=b_color.g=b_color.b=0;
//fill color
~ 12 ~
PICT, SE-IT Computer Graphics Laboratory
f_color.r=255;
f_color.g=0;
f_color.b=0;
Output :-
~ 13 ~
PICT, SE-IT Computer Graphics Laboratory
Conclusion: Successfully implemented Flood fill Polygon Filling Algorithms using OpenGL.
~ 14 ~
PICT, SE-IT Computer Graphics Laboratory
Assignment No 5
Prob Statements : Implement Cohen Sutherland polygon clipping method to clip the
polygon with respect the viewport and window. Use mouse click, keyboard interface
Theory :
A) Sutherland – Hodgeman Algorithm for Polygon Clipping.
1. If the first vertex is an outside the window, the second vertex is inside the window.
Then second vertex is added to the output list. The point of intersection of window
boundary and polygon side (edge) is also added to the output line.
2. If both vertexes are inside window boundary. Then only second vertex is added to
the output list.
3. If the first vertex is inside the window and second is an outside window. The edge
which intersects with window is added to output list.
4. If both vertices are the outside window, then nothing is added to output list.
Following figures shows original polygon and clipping of polygon against four windows.
~ 15 ~
PICT, SE-IT Computer Graphics Laboratory
This method requires a considerable amount of memory. The first of all polygons are stored
in original form. Then clipping against left edge done and output is stored. Then clipping
against right edge done, then top edge. Finally, the bottom edge is clipped. Results of all
these operations are stored in memory. So wastage of memory for storing intermediate
polygons.
In the algorithm, first of all, it is detected whether line lies inside the screen or it is outside
the screen. All lines come under any one of the following categories:
1. Visible
2. Not Visible
~ 16 ~
PICT, SE-IT Computer Graphics Laboratory
3. Clipping Case
1. Visible: If a line lies within the window, i.e., both endpoints of the line lie within the
window. A line is visible and will be displayed as it is.
2. Not Visible: If a line lies outside the window, it will be invisible and rejected. Such lines
will not display. If any one of the following inequalities is satisfied, then the line is
considered invisible. Let A (x1, y2) and B (x2, y2) are endpoints of line.
3. Clipping Case: If the line is neither visible case nor invisible case. It is considered to be
clipped case. First of all, the category of a line is found based on nine regions given below.
All nine regions are assigned codes. Each code is of 4 bits. If both endpoints of the line
have end bits zero, then the line is considered to be visible.
The centre area is having the code, 0000, i.e., region 5 is considered a rectangle window.
~ 17 ~
PICT, SE-IT Computer Graphics Laboratory
Algorithm:
~ 18 ~
PICT, SE-IT Computer Graphics Laboratory
~ 19 ~
PICT, SE-IT Computer Graphics Laboratory
where X = Xwmin
where Xwmin is the minimum value of X co-ordinate of window
Input:
1. The program asks for the initial and final co-ordinates of the line and the line is
plotted after the creation of the window.
2. The viewport is highlighted in the window and the line is plotted in blue.
3. To run the algorithm, ‘C’ key must be pressed.
4. The Inputs are given for the following cases:
a) Both end points lie inside the viewport. [(0, 0) and (40, 40)]
b) One end point lies inside and the other end point lies outside the viewport.
[(0, 0) and (320, 240)]
Output:
A) Both end points lie inside the viewport [(0, 0) and (40, 40)]
Input:
Output:
~ 20 ~
PICT, SE-IT Computer Graphics Laboratory
B) One end point lies inside and the other end point lies outside the view port. [(0, 0)
and (320, 240)]
Input:
Output:
~ 21 ~
PICT, SE-IT Computer Graphics Laboratory
Program:
#include<stdio.h> //initial inclusions
#include<GL/gl.h>
#include<GL/glu.h>
#include<GL/glut.h>
#include<math.h>
float xd1,yd1,xd2,yd2; //storing values for end points of line
int ymax=100; //initializing window coordinates
int ymin=-100;
int xmax=100;
int xmin=-100;
static int p=0;
void disp(); //declaring display function
float round_value(float v) //function to round value to next greater float
{
return (v+0.5);
}
void plotpoint(float a,float b)
{
glBegin(GL_POINTS);
glVertex2f(a,b);
glEnd();
}
void dda(float X1,float Y1,float X2,float Y2) //dda algorithm
{
/*
* Input : Initial and final co-ordinates of line points.
* Utility : plot line using Digital Differential Analyzer
* Output : Line on initialized window.
*/
float dx,dy,x,y,xinc,yinc;//initializations
~ 22 ~
PICT, SE-IT Computer Graphics Laboratory
int k,steps;
dx=X2-X1; //difference of x coordinates
dy=Y2-Y1; //difference of y coordinates
steps=abs(dx)>abs(dy)?abs(dx):abs(dy); //calculation of number of steps
xinc=dx/(float)steps; //value for incrementing x
yinc=dy/(float)steps; //value for incrementing y
x=X1,y=Y1;
plotpoint(x,y); //function to plot point on window
for(k=0;k<steps;k++) //loop to plot points
{
x+=xinc; //incrementing x by xinc
y+=yinc; //incrementing y by yinc
plotpoint(round_value(x),round_value(y)); //plotting point
}
glFlush();
}
int code(int x,int y)
{
/*
* Input : x and y coordinates of the point.
* Utility : Determine outcode for given point.
* Output : Out code.
*/
int c=0;
if(y>ymax) c=8; //if greater than ymax set code to 8
if(y<ymin) c=4; //if less than ymin set code to 4
if(x>xmax) c=c|2; //if greater than xmax set code to 2
if(x<xmin) c=c|1; //if less than ymin set code to 1
return c;
}
void cohen(float x1,float y1,float x2,float y2) //implementing cohen-sutherland
algorithm
{
int c1=code(x1,y1); //checking for outcode of point 1
int c2=code(x2,y2); //checking for outcode of point 2
float m=(y2-y1)/(x2-x1); //checking slope of line
while((c1|c2)>0) //iterating loop till c1|c2>0
{
if((c1 & c2)>0) //if both lie completely outside the
window
{
disp();
return;
}
int c;
float xi=x1;
float yi=y1;
c=c1;
~ 23 ~
PICT, SE-IT Computer Graphics Laboratory
float x,y;
if(c==0) //checking if outcode is
equal to 0
{
c=c2; //assigning outcode of c2
xi=x2; //assigning x coordinate of
c2
yi=y2; //assigning y coordinate of
c2
}
if((c & 8)>0) //checking if c&8 >0 ( greater than
ymax)
{
y=ymax; //assigning new
values to x and y
x=xi+1.0/(m*(ymax-yi));
}
if((c & 4)>0) //checking if c> 4 >0 (less than
ymin)
{
y=ymin; //assigning new
values to x and y
x=xi+1.0/(m*(ymin-yi));
}
if((c & 2)>0) //checking if c&2 >0 ( greater than
xmax)
{
x=xmax;
y=yi+m*(xmax-xi);
}
if((c & 1)>0) //checking if c&1 >0 (less than
xmin)
{
x=xmin;
y=yi+m*(xmin-xi);
}
if(c==c1) //checking code and
assigning new values
{
xd1=x;
yd1=y;
c1=code(xd1,yd1);
}
if(c==c2) //checking code and
assigning new values
{
xd2=x;
yd2=y;
c2=code(xd2,yd2);
~ 24 ~
PICT, SE-IT Computer Graphics Laboratory
}
}
p++;
disp(); //calling display function
again to display new line
}
void mykey(unsigned char ch,int x,int y)
{
if(ch=='c')
{
cohen(xd1,yd1,xd2,yd2); //if character c is pressed calling
algorithm
glFlush();
}
}
void disp()
{
glClear(GL_COLOR_BUFFER_BIT);//clearing buffer
glColor3f(1.0,0.0,0.0); //assigning color
dda(xmin,ymin,xmax,ymin); //creating window using dda algorithm to
draw lines
dda(xmax,ymin,xmax,ymax);
dda(xmax,ymax,xmin,ymax);
dda(xmin,ymax,xmin,ymin);
}
void init()
{
glClearColor(1.0,1.0,1.0,0); //clearing background color to new color
glClear(GL_COLOR_BUFFER_BIT); //clearing buffer
glPointSize(2); //assigning point size
gluOrtho2D(-320,320,-240,240);
glFlush();
}
int main(int argc,char **argv)
{
printf("Window coordinates are (-100,100,-100,100)\n");
printf("\nEnter coordinates of the line(limits : -320,320,-240,240) \nAfter entering
enter c to clip\n");
printf("\nCoordinates of first point");
printf("\nX1: ");
scanf("%f",&xd1); //accepting value of x1
printf("\nY1: "); //accepting value of y1
~ 25 ~
PICT, SE-IT Computer Graphics Laboratory
scanf("%f",&yd1);
printf("\nCoordinates of second point");
printf("\nX2: ");
scanf("%f",&xd2); //accepting value of x2
printf("\nY2: "); //accepting value of y2
scanf("%f",&yd2);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(100,100);
glutInitWindowSize(640,480);
glutCreateWindow("Line Clipping");
init();
glutDisplayFunc(disp);
glutKeyboardFunc(mykey);
glutMainLoop();
return 0;
}
Conclusion: Successfully implemented Cohen Sutherland Polygon Clipping Algorithms
using OpenGL.
~ 26 ~
PICT, SE-IT Computer Graphics Laboratory
Assignment No 6
Prob Statements : Implement the following polygon filling methods : i) Flood fill / Seed
fill ii) Boundary fill ; using mouse click, keyboard interface and menu driven programming
Implement following 2D transformations on the object with respect to axis : – i) Scaling
ii) Rotation about arbitrary point iii) Reflection
Theory:
Transformation means changing some graphics into something else by applying rules. We
can have various types of transformations such as translation, scaling up or down, rotation,
shearing, etc. When a transformation takes place on a 2D plane, it is called 2D
transformation.
Transformations play an important role in computer graphics to reposition the graphics on
the screen and change their size or orientation.
Homogenous Coordinates
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, YX, Y to
get the new coordinate X′, Y′X′, Y′.
~ 27 ~
PICT, SE-IT Computer Graphics Laboratory
Rotation
In rotation, we rotate the object at particular angle θ from its origin. From the following
figure, we can see that the point PX, YX, Y is located at angle φ from the horizontal X
coordinate with distance r from the origin.
Let us suppose you want to rotate it at the angle θ. After rotating it to a new location, you
will get a new point P’ X′, Y′X′, Y′.
~ 28 ~
PICT, SE-IT Computer Graphics Laboratory
Using standard trigonometric the original coordinate of point PX,YX,Y can be represented
as −
X=rcosϕ......(1)X=rcosϕ......(1)
Y=rsinϕ......(2)Y=rsinϕ......(2)
Same way we can represent the point P’ X′,Y′X′,Y′ as −
x′=rcos(ϕ+θ)=rcosϕcosθ−rsinϕsinθ.......(3)x′=rcos(ϕ+θ)=rcosϕcosθ−rsinϕsinθ.......(3)
y′=rsin(ϕ+θ)=rcosϕsinθ+rsinϕcosθ.......(4)y′=rsin(ϕ+θ)=rcosϕsinθ+rsinϕcosθ.......(4)
Substituting equation 11 & 22 in 33 & 44 respectively, we will get
x′=xcosθ−ysinθx′=xcosθ−ysinθ
y′=xsinθ+ycosθy′=xsinθ+ycosθ
Representing the above equation in matrix form,
[X′Y′]=[XY][cosθ−sinθsinθcosθ]OR[X′Y′]=[XY][cosθsinθ−sinθcosθ]OR
P’ = P . R
Where R is the rotation matrix
R=[cosθ−sinθsinθcosθ]R=[cosθsinθ−sinθcosθ]
The rotation angle can be positive and negative.
For positive rotation angle, we can use the above rotation matrix. However, for negative
angle rotation, the matrix will change as shown below −
R=[cos(−θ)−sin(−θ)sin(−θ)cos(−θ)]R=[cos(−θ)sin(−θ)−sin(−θ)cos(−θ)]
=[cosθsinθ−sinθcosθ](∵cos(−θ)=cosθandsin(−θ)=−sinθ)=[cosθ−sinθsinθcosθ](∵cos(−θ)=co
sθandsin(−θ)=−sinθ)
Scaling
To change the size of an object, scaling transformation is used. In the scaling process, you
either expand or compress the dimensions of the object. Scaling can be achieved by
~ 29 ~
PICT, SE-IT Computer Graphics Laboratory
multiplying the original coordinates of the object with the scaling factor to get the desired
result.
Let us assume that the original coordinates are X,YX,Y, the scaling factors are (SX, SY), and
the produced coordinates are X′,Y′X′,Y′. This can be mathematically represented as shown
below −
X' = X . SX and Y' = Y . SY
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 −
(X′Y′)=(XY)[Sx00Sy](X′Y′)=(XY)[Sx00Sy]
OR
P’ = P . S
Where S is the scaling matrix. The scaling process is shown in the following figure.
If we provide values less than 1 to the scaling factor S, then we can reduce the size of the
object. If we provide values greater than 1, then we can increase the size of the object.
Reflection
Reflection is the mirror image of original object. In other words, we can say that it is a
rotation operation with 180°. In reflection transformation, the size of the object does not
change.
The following figures show reflections with respect to X and Y axes, and about the origin
respectively.
~ 30 ~
PICT, SE-IT Computer Graphics Laboratory
Shear
A transformation that slants the shape of an object is called the shear transformation.
There are two shear transformations X-Shear and Y-Shear. One shifts X coordinates
values and other shifts Y coordinate values. However; in both the cases only one
coordinate changes its coordinates and other preserves its values. Shearing is also termed
as Skewing.
X-Shear
The X-Shear preserves the Y coordinate and changes are made to X coordinates, which
causes the vertical lines to tilt right or left as shown in below figure.
~ 31 ~
PICT, SE-IT Computer Graphics Laboratory
Y-Shear
The Y-Shear preserves the X coordinates and changes the Y coordinates which causes the
horizontal lines to transform into lines which slopes up or down as shown in the following
figure.
Composite Transformation
~ 32 ~
PICT, SE-IT Computer Graphics Laboratory
If a transformation of the plane T1 is followed by a second plane transformation T2, then
the result itself may be represented by a single transformation T which is the composition
of T1 and T2 taken in that order. This is written as T = T1∙T2.
Composite transformation can be achieved by concatenation of transformation matrices
to obtain a combined transformation matrix.
A combined matrix −
[T][X] = [X] [T1] [T2] [T3] [T4] …. [Tn]
Where [Ti] is any combination of
• Translation
• Scaling
• Shearing
• Rotation
• Reflection
The change in the order of transformation would lead to different results, as in general
matrix multiplication is not cumulative, that is [A] . [B] ≠ [B] . [A] and the order of
multiplication. The basic purpose of composing transformations is to gain efficiency by
applying a single composed transformation to a point, rather than applying a series of
transformation, one after another.
For example, to rotate an object about an arbitrary point (Xp, Yp), we have to carry out
three steps −
Algorithm:
A) Scaling
1. START
2. Create a 3x3 scaling matrix S as:
| Sx 0 0 |
| 0 Sy 0 |
|0 0 1|
where Sx and Sy are the scaling factors in x and y directions respectively.
3. For all points located on the polygon, generate a n x 3 matrix where each row in
the matrix represents a point on the polygon in the following manner:
4. [x, y, 1] where (x, y) are the co-ordinates of the point.
5. Multiply the generated point matrix with the scaling matrix to obtain the
transformation matrix.
6. Plot the transformation matrix.
~ 33 ~
PICT, SE-IT Computer Graphics Laboratory
7. END
B) Translation
1. START
2. Get the X and Y translation factor from the user.
3. Create a 3x3 scaling matrix S as:
|1 0 0|
|0 1 0|
| Tx Ty 1 |
where Tx and Ty are the scaling factors in x and y directions respectively.
4. For all points located on the polygon, generate a n x 3 matrix where each row in
the matrix represents a point on the polygon in the following manner:
5. [x, y, 1] where (x, y) are the co-ordinates of the point.
6. Multiply the generated point matrix with the translation matrix to obtain the
transformation matrix.
7. Plot the transformation matrix.
8. END
B) Rotation
1. START
2. Get the angle of rotation as theta
3. Create a 2x2 scaling matrix S as:
| cos(θ) sin(θ) |
| -sin(θ) cos(θ) |
4. For all points located on the polygon, generate a n x 2 matrix where each row in
the matrix represents a point on the polygon in the following manner:
[x, y] where (x, y) are the co-ordinates of the point.
5. Multiply the generated point matrix with the translation matrix to obtain the
transformation matrix.
6. Plot the transformation matrix.
7. END
Program:
#include<GL/glut.h>
#include<stdio.h>
#include<math.h>
//------------------DRAW-------------//
glBegin(GL_LINE_LOOP);
for(i=0;i<3;i++)
{
glVertex2i(ET[i][0],ET[i][1]);
}
glEnd();
}
glBegin(GL_LINE_LOOP);
for(i=0;i<4;i++)
{
glVertex2i(Rh[i][0],Rh[i][1]);
}
glEnd();
}
//----------------------------Display---------------------//
void Display()
{
glClearColor(0,0,0,0);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
gluOrtho2D(-320,320,-240,240);//note
glColor3f(1,1,1);
glBegin(GL_LINES);
glVertex2d(-320,0);
glVertex2d(320,0);
glVertex2d(0,-240);
glVertex2d(0,240);
glEnd();
glColor3f(1,0,0);
if(flag == 0)
drawET(ET);
else if(flag == 1)
drawR(Rh);
~ 35 ~
PICT, SE-IT Computer Graphics Laboratory
glFlush();
}
//---------MULTIPLY--------------//
//----------Translation-----------//
void translationET()
{
double tx,ty,temp[3][3];
~ 36 ~
PICT, SE-IT Computer Graphics Laboratory
printf("\nTranslating Equilateral triangle");
printf("\nEnter Tx: ");
scanf("%lf",&tx);
printf("\nEnter Ty: ");
scanf("%lf",&ty);
temp[3][3]={0};
temp[0][0]=1;
temp[1][1]=1;
temp[2][2]=1;
temp[2][0]=tx;
temp[2][1]=ty;
mult3X3(ET,temp);
glColor3f(0.0,1.0,0.0);
drawET(ETResult);
}
void translationRh()
{
double tx,ty,temp[4][4];
printf("\nTranslating Rhombus");
printf("\nEnter Tx: ");
scanf("%lf",&tx);
printf("\nEnter Ty: ");
scanf("%lf",&ty);
temp[4][4]={0};
temp[0][0]=1;
temp[1][1]=1;
temp[2][2]=1;
temp[3][3]=1;
temp[3][0]=tx;
temp[3][1]=ty;
mult4X4(Rh,temp);
glColor3f(0.0,1.0,0.0);
drawR(RhResult);
}
//------------Rotation------------//
void rotationET()
{
double rx,ry,angle, temp[3][3];
printf("\n**ROTATION**\n");
printf("\nArbitrary Point (x,y) : ");
~ 37 ~
PICT, SE-IT Computer Graphics Laboratory
scanf("%lf %lf",&rx,&ry);
printf("\nAngle (in degrees) : ");
scanf("%lf",&angle);
angle=angle*(M_PI/180);
temp[3][3]={0};
temp[0][0]=cos(angle);
temp[0][1]=sin(angle);
temp[1][0]=-sin(angle);
temp[1][1]=cos(angle);
temp[2][0]=(-(rx*cos(angle))+(ry*sin(angle))+rx);
temp[2][1]=(-(rx*sin(angle))-(ry*cos(angle))+ry);
temp[2][2]=1;
mult3X3(ET,temp);
glColor3f(0.0,1.0,0.0);
drawET(ETResult);
}
void rotationRh()
{
double rx,ry,angle, temp[4][4];
printf("\nRotating Rhombus");
printf("\nArbitrary Point (x,y): ");
scanf("%lf %lf",&rx,&ry);
printf("\nAngle (in degree): ");
scanf("%lf",&angle);
angle=angle*(M_PI/180);
temp[4][4]={0};
temp[0][0]=cos(angle);
temp[0][1]=sin(angle);
temp[1][0]=-sin(angle);
temp[1][1]=cos(angle);
temp[2][2]=1;
temp[3][0]=(-(rx*cos(angle))+(ry*sin(angle))+rx);
temp[3][1]=(-(rx*sin(angle))-(ry*cos(angle))+ry);
temp[3][3]=1;
mult4X4(Rh,temp);
glColor3f(0.0,1.0,0.0);
drawR(RhResult);
}
//----------Scaling-------------//
~ 38 ~
PICT, SE-IT Computer Graphics Laboratory
void scaleET()
{
double sx,sy, temp[3][3];
temp[3][3]={0};
temp[0][0]=sx;
temp[1][1]=sy;
temp[2][2]=1;
mult3X3(ET,temp);
glColor3f(1.0,1.0,0.0);
drawET(ETResult);
}
void scaleRh()
{
double sx,sy,temp[4][4];
printf("\nScaling Rhombus");
printf("\nSx: ");
scanf("%lf",&sx);
printf("\nSy: ");
scanf("%lf",&sy);
temp[4][4]={0};
temp[0][0]=sx;
temp[1][1]=sy;
temp[2][2]=1;
temp[3][3]=1;
mult4X4(Rh,temp);
glColor3f(1.0,1.0,0.0);
drawR(RhResult);
}
//-----------Shearing-------------//
void shearET()
{
double xs,ys,temp[3][3];
temp[3][3]={0};
switch(choice)
{
case 1: printf("\nX-shear value: ");
scanf("%lf",&xs);
temp[0][0]=1;
temp[1][0]=xs;
temp[1][1]=1;
temp[2][2]=1;
break;
case 2: printf("\nY-shear value: ");
scanf("%lf",&ys);
temp[0][0]=1;
temp[0][1]=ys;
temp[1][1]=1;
temp[2][2]=1;
break;
}
mult3X3(ET,temp);
glColor3f(1.0,1.0,0.0);
drawET(ETResult);
}
void shearRh()
{
double xs,ys,temp[4][4];
printf("\nPress 1: X - Shear");
printf("\nPress 2: Y - Shear");
printf("\nEnter your Choice: ");
scanf("%d",&choice);
temp[4][4]={0};
switch(choice)
{
case 1: printf("\nX-shear value: ");
scanf("%lf",&xs);
temp[0][0]=1;
temp[1][0]=xs;
temp[1][1]=1;
temp[2][2]=1;
temp[3][3]=1;
break;
~ 40 ~
PICT, SE-IT Computer Graphics Laboratory
case 2: printf("\nY-shear value: ");
scanf("%lf",&ys);
temp[0][0]=1;
temp[0][1]=ys;
temp[1][1]=1;
temp[2][2]=1;
temp[3][3]=1;
break;
}
mult4X4(Rh,temp);
glColor3f(0.0,1.0,0.0);
drawR(RhResult);
}
//----------MENU--------------//
void Menu(int item)
{
switch(item)
{
case 1: if(choice==1)
translationET();
else
translationRh();
break;
case 2: if(choice==1)
rotationET();
else
rotationRh();
break;
case 3: if(choice==1)
scaleET();
else
scaleRh();
break;
case 4: if(choice==1)
{
shearET();
}
else
{
shearRh();
}
break;
case 5:
exit(0);
~ 41 ~
PICT, SE-IT Computer Graphics Laboratory
break;
}
}
//----------MAIN-------------------//
switch(choice)
{
int i, j;
case 1:
flag = 0;
printf("\nEnter X co-ordinate of a Base point: ");
scanf("%d",&xi);
printf("\nEnter Y co-ordinate of the Base point: ");
scanf("%d",&yi);
printf("\nEnter length of sides: ");
scanf("%d",&length);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
ET[i][j]=1;
}
}
ET[0][0]=xi;
ET[0][1]=yi;
ET[1][0]=xi+length;
ET[1][1]=yi;
ET[2][0]=length/2+xi;
ET[2][1]=(sqrt(3)/2*length)+yi;
break;
case 2:
flag = 1;
printf("\nEnter X co-ordinates of a Base point: ");
scanf("%d",&xi);
printf("\nEnter Y co-ordinates of the Base point: ");
scanf("%d",&yi);
~ 42 ~
PICT, SE-IT Computer Graphics Laboratory
printf("\nEnter length of sides: ");
scanf("%d",&length);
printf("\nEnter angle of Rhombus (in degrees): ");
scanf("%lf",&angle);
angle = angle * M_PI / 180;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
Rh[i][j]=1;
}
}
Rh[0][0]=xi;
Rh[0][1]=yi;
Rh[1][0]=xi+length;
Rh[1][1]=yi;
Rh[2][0]=length+xi+length*cos(angle);
Rh[2][1]=yi+length*sin(angle);
Rh[3][0]=xi+length*cos(angle);
Rh[3][1]=yi+length*sin(angle);
break;
case 3:
exit(0);
break;
default:printf("\nInvalid Input!");
break;
}
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowSize(640,480);
glutInitWindowPosition(0,0);
glutCreateWindow("2D - TRANSFORMATIONS");
glutDisplayFunc(Display);
glutCreateMenu(Menu);
glutAddMenuEntry("1.Translation",1);
glutAddMenuEntry("2.Rotation",2);
glutAddMenuEntry("3.Scaling",3);
glutAddMenuEntry("4.Shear",4);
glutAddMenuEntry("5.EXIT",5);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutMainLoop();
return 0;
~ 43 ~
PICT, SE-IT Computer Graphics Laboratory
}
Input:
1. The program plots Equilateral triangle or a rhombus.
2. For the equilateral Triangle, the point of origin is given as (0, 0) and the size of one
side is given as 50px.
3. For the rhombus, the point of origin is given as (0,0), angle is given as 60 degrees
and the side length is given as 60px.
4. The transformation is selected using the menu.
Output:
1. Triangle
a) Translation:
b) Rotation:
~ 44 ~
PICT, SE-IT Computer Graphics Laboratory
c) Scaling
2. Rhombus
a) Translation
~ 45 ~
PICT, SE-IT Computer Graphics Laboratory
b) Rotation
c) Scaling
Conclusion:
1. Successfully implemented 2D transformation.
2. Matrix multiplication was used to implement the transformations.
~ 46 ~
PICT, SE-IT Computer Graphics Laboratory
Assignment No 7
Bezier Curves
Bezier curve is discovered by the French engineer Pierre Bézier. These curves can be
generated under the control of other points. Approximate tangents by using control
points are used to generate curve. The Bezier curve can be represented
mathematically as −
∑k=0nPiBni(t)∑k=0nPiBin(t)
Where pipi is the set of points and Bni(t)Bin(t) represents the Bernstein polynomials
which are given by −
Bni(t)=(ni)(1−t)n−itiBin(t)=(ni)(1−t)n−iti
Where n is the polynomial degree, i is the index, and t is the variable.
~ 47 ~
PICT, SE-IT Computer Graphics Laboratory
The simplest Bézier curve is the straight line from the point P0P0 to P1P1. A quadratic
Bezier curve is determined by three control points. A cubic Bezier curve is determined
by four control points.
Koch Curve
~ 48 ~
PICT, SE-IT Computer Graphics Laboratory
The Koch snowflake (also known as the Koch curve, Koch star, or Koch island) is a
mathematical curve and one of the earliest fractal curves to have been described. It
is based on the Koch curve, which appeared in a 1904 paper titled “On a continuous
curve without tangents, constructible from elementary geometry” by the Swedish
mathematician Helge von Koch.
The progression for the area of the snowflake converges to 8/5 times the area of
the original triangle, while the progression for the snowflake’s perimeter diverges to
infinity. Consequently, the snowflake has a finite area bounded by an infinitely long
line.
Step1:
Draw an equilateral triangle. You can draw it with a compass or protractor, or just
eyeball it if you don’t want to spend too much time drawing the snowflake.
It’s best if the length of the sides are divisible by 3, because of the nature of this
fractal. This will become clear in the next few steps.
Step2:
Divide each side in three equal parts. This is why it is handy to have the sides divisible
by three.
~ 49 ~
PICT, SE-IT Computer Graphics Laboratory
Step3:
Draw an equilateral triangle on each middle part. Measure the length of the
middle third to know the length of the sides of these new triangles.
Step4:
~ 50 ~
PICT, SE-IT Computer Graphics Laboratory
Divide each outer side into thirds. You can see the 2nd generation of triangles covers
a bit of the first. These three line segments shouldn’t be parted in three.
Step5:
Draw an equilateral triangle on each middle part.
Note how you draw each next generation of parts that are one 3rd of the mast one.
~ 51 ~
PICT, SE-IT Computer Graphics Laboratory
#include <iostream>
#include <GL/glut.h>
#include <GL/freeglut.h>
#include <math.h> using
namespace std;
void Initialize()
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0.0,0.0,0.0,0.0);
glColor3f(1.0,1.0,1.0);
gluOrtho2D(0.0,XMAX,0.0,YMAX);
}
void draw(int n)
{
glBegin(GL_LINES);
draw_koch(600,100,800,
400,n);
draw_koch(800,400,400,
400,n);
draw_koch(400,400,600,
100,n);
glEnd();
glFlush();
}
xc = (2*xa+xb)/3;
yc = (2*ya+yb)/3; xd
= (2*xb+xa)/3; yd =
(2*yb+ya)/3;
if(n>0)
~ 52 ~
PICT, SE-IT Computer Graphics Laboratory
{
draw_koch(xa,ya,xc,yc,n-1);
draw_koch(xc,yc,midx,midy,n-1); draw_koch(midx,midy,xd,yd,n-1);
draw_koch(xd,yd,xb,yb,n-1);
}
else
{
glVertex2f(xa,ya);
glVertex2f(xc,yc);
glVertex2f(xc,yc);
glVertex2f(midx,midy);
glVertex2f(midx,midy);
glVertex2f(xd,yd);
glVertex2f(xd,yd);
glVertex2f(xb,yb);
}
}
int main(int argc , char ** argv)
{
int n;
cout<<"\n Enter For How Many Iterations You Want to Draw ?::";
cin>>n;
glutInit( &argc , argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(XMAX,YMAX);
glutInitWindowPosition(0,0);
glutCreateWindow("KOCH
CURVE");
Initialize(); draw(n);
glutMainLoop();
return 0;
}
~ 53 ~
PICT, SE-IT Computer Graphics Laboratory
OUTPUT :
~ 54 ~
PICT, SE-IT Computer Graphics Laboratory
~ 55 ~
PICT, SE-IT Computer Graphics Laboratory
Conclusion:
Successfully implemented Koch Curve.
56
PICT, SE-IT Computer Graphics Laboratory
Assignment No 8
The physical movement of image parts through simple mechanics—for instance moving
images in magic lantern shows—can also be considered animation. The mechanical
manipulation of three-dimensional puppets and objects to emulate living beings has a
very long history in automata. Electronic automata were popularized by Disney as
animatronics.
Animators are artists who specialize in creating animation
Source Code:
#include <GL/gl.h>
#include <GL/glut.h>
#include <math.h>
void drawWindmill()
//Function to draw windmill
{
int i;
glColor3f(1.0,1.0,0.0);
//red green blue
glBegin(GL_POLYGON);
58
PICT, SE-IT Computer Graphics Laboratory
glVertex2f(-0.05f, 0);
//for drawing rectangular base part
glVertex2f(-0.05f, 3);
glVertex2f(0.05f, 3);
glVertex2f(0.05f, 0);
glEnd();
glTranslatef(0,3,0);
//x,y,z
glColor3f(1.0,0.0,0.0);
//red,green,blue (RED PLATES OF WINDMILL)
glRotated(90, 0, 0, 1);
//90,0,0,Z
glBegin(GL_POLYGON);
glVertex2f(0,0);
//FOR DRAWING TYIANGLULAR PLATE
glVertex2f(1.0f, 0.2f);
glVertex2f(1.0f,-0.2f);
glEnd();
}
}
void display()
//DISPLAY FUNCTION
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
//TAKES IDENTITY MATRIX
glPushMatrix();
//PUSH MATRIX
glTranslated(2.2,1.6,0);
//SET POSITION OF WINDMILL
59
PICT, SE-IT Computer Graphics Laboratory
glScaled(0.4,0.4,1);
//SCALLING WINDMILL WITH POINT (0.4,0.4,1)
drawWindmill();
//FUNCTION CALL TO DRAW WINDMILL
glPopMatrix();
//POP MATRIX
glPushMatrix();
//PUSH MATRIX
glTranslated(3.7,0.8,0);
//SET POSITION OF WINDMILL
glScaled(0.7,0.7,1);
//SCALLING WINDMILL WITH POINT(0.7,0.7,1)
drawWindmill();
//FUNCTION CALL TO DRAW WINDMILL
glPopMatrix();
//POP MATRIX
glutSwapBuffers();
//SWAP BUFFER
}
void doFrame(int v)
{
frameNumber++;
//INCREMENT FRAME NO
glutPostRedisplay();
//POST REDISPLAY
glutTimerFunc(10,doFrame,0);
}
void init()
//FUNCTION INITIALISATION
{
glClearColor(0,0,0,0);
glMatrixMode(GL_PROJECTION);
//MATRIX MODE FOR PROJECTION
glLoadIdentity();
//LOADS IDENTITY MATRIX
60
PICT, SE-IT Computer Graphics Laboratory
glMatrixMode(GL_MODELVIEW);
//MATRIX MODE FOR MODEL VIEW
}
glutInitDisplayMode(GLUT_DOUBLE);
glutInitWindowSize(700,500); //DEFINED
WINDOW SIZE 700*500
glutInitWindowPosition(100,100); //DEFINED
WINDOW POSITION 100,100
glutCreateWindow("WINDMILL");
//NAME OF WINDOW
init();
//FIRSTLY CALL TO INTIALISE VALUE
glutDisplayFunc(display);
//DISPLAY
glutMainLoop();
return 0;
}
Output :
61
PICT, SE-IT Computer Graphics Laboratory
Conclusion:
Successfully implemented Animated Windmill .
62