0% found this document useful (0 votes)
89 views50 pages

CG Lab Report Must Edit The Style

The document is a lab report submitted by a student for an experiment in computer graphics. The experiment involves drawing different shapes using OpenGL, including a star shape, and manipulating the shape through translation and rotation. The report describes code to draw a star shape, allow user input to translate the star by providing x and y distances, and allow user input to rotate the star by providing a degree value. It discusses how the code uses OpenGL functions like glTranslatef and glRotatef to achieve the transformations, and displays the results of translating and rotating the star interactively based on user input.

Uploaded by

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

CG Lab Report Must Edit The Style

The document is a lab report submitted by a student for an experiment in computer graphics. The experiment involves drawing different shapes using OpenGL, including a star shape, and manipulating the shape through translation and rotation. The report describes code to draw a star shape, allow user input to translate the star by providing x and y distances, and allow user input to rotate the star by providing a degree value. It discusses how the code uses OpenGL functions like glTranslatef and glRotatef to achieve the transformations, and displays the results of translating and rotating the star interactively based on user input.

Uploaded by

Hasanur Rahman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Sylhet Engineering

College
Department of Computer Science & Engineering

LAB REPORT
Course Code : CSE-802

Course Title : Computer Graphics (Sessional)

Topic(s) : Drawing different shapes.

Submission
Date : 28-01-2024

Submitted by Submitted to
Md Lysuzzaman
Reg. No:
Lecturer (CSE)
Session:
Sylhet Engineering College.
Experiment No: 01

Experiment Name: DRAWING OF A ‘STAR’ SHAPE

Objectives:

● To create a program to draw a star shape using OpenGL.


● To practice working with basic OpenGL functions and drawing primitives.
● To understand the concept of specifying coordinates for vertices in a 2D
space.

Code:

#include <GL/gl.h>
#include <GL/glut.h>
void display(void)
{
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 1.0, 1.0);
glBegin(GL_TRIANGLES);
//Triangle-1
glVertex3f(3.33f, 3.33f, 0.0f);
glVertex3f(5.0f, 0.0f, 0.0f);
glVertex3f(6.66f, 3.33f, 0.0f);
//Triangle-2
glVertex3f(6.66f, 3.33f, 0.0f);
glVertex3f(10.0f, 5.0f, 0.0f);
glVertex3f(6.66f, 6.66f, 0.0f);
//Triangle-3
glVertex3f(6.66f, 6.66f, 0.0f);
glVertex3f(5.0f, 10.0f, 0.0f);
glVertex3f(3.33f, 6.66f, 0.0f);
//Triangle-4
glVertex3f(3.33f, 6.66f, 0.0f);
glVertex3f(0.0f, 5.0f, 0.0f);
glVertex3f(3.33f, 3.33f, 0.0f);
//Triangle-5
glVertex3f(3.33f, 3.33f, 0.0f);
glVertex3f(6.66f, 3.33f, 0.0f);
glVertex3f(6.66f, 6.66f, 0.0f);
//Triangle-6
glVertex3f(6.66f, 6.66f, 0.0f);
glVertex3f(3.33f, 6.66f, 0.0f);

1|Page
glVertex3f(3.33f, 3.33f, 0.0f);
//End triangle coordinates
glEnd();
glFlush ();
}
void init (void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 10.0, 0.0, 10.0, -10.0, 10.0);
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (600, 600);
glutInitWindowPosition (100, 100);
glutCreateWindow ("Triangle");
init ();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

Output:

Fig: Star Shape

2|Page
Result and Discussion:

The provided code uses the OpenGL library to draw a star shape consisting of six
triangles. The star shape is created by connecting the vertices of these triangles.

Upon running the program, a window is opened with a black background. The star
shape is drawn with white color. The glOrtho function sets up an orthographic
projection, defining the coordinate system for the drawing.

The coordinates for the triangles are specified using the glVertex3f function, which
takes in the x, y, and z coordinates of each vertex. The star shape is formed by
connecting the vertices of each triangle.

The resulting star shape appears in the window, with the triangles forming the
desired pattern. The glFlush function ensures that all the drawing commands are
executed.

Overall, the program successfully achieves the objective of drawing a star shape
using OpenGL. It serves as a basic example of utilizing OpenGL functions for 2D
graphics rendering.

3|Page
Experiment No: 02

Experiment Name: TRANSLATION OF THE STAR (BY TAKING TRANSLATION


DISTANCE Tx & Ty AS USER INPUT)

[Note: Please after running this code-


-Type 't'/'T' to display a text on the console (follow the 'consol screen' which is
placed behind the 'display window') for taking Tx and Ty as user input.
-Then touch the 'consol screen' and type two floating point value (Tx Ty) and
press the 'enter' to see the change, follow the 'display window'.]

Objectives:

● To create a program that allows the user to translate the star shape by
providing translation distances.
● To practice handling user input and updating the translation parameters in
real-time.
● To understand the concept of translation in computer graphics.

Code:

#include <GL/gl.h>
#include <GL/glut.h>
#include <bits/stdc++.h>
using namespace std;
// Translation distances
float Tx = 0.0f;
float Ty = 0.0f;
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glPushMatrix();
glTranslatef(Tx, Ty, 0.0f);
glBegin(GL_TRIANGLES);
// Triangle-1
glVertex3f(3.33f, 3.33f, 0.0f);
glVertex3f(5.0f, 0.0f, 0.0f);
glVertex3f(6.66f, 3.33f, 0.0f);
// Triangle-2
glVertex3f(6.66f, 3.33f, 0.0f);
glVertex3f(10.0f, 5.0f, 0.0f);
glVertex3f(6.66f, 6.66f, 0.0f);

4|Page
// Triangle-3
glVertex3f(6.66f, 6.66f, 0.0f);
glVertex3f(5.0f, 10.0f, 0.0f);
glVertex3f(3.33f, 6.66f, 0.0f);
// Triangle-4
glVertex3f(3.33f, 6.66f, 0.0f);
glVertex3f(0.0f, 5.0f, 0.0f);
glVertex3f(3.33f, 3.33f, 0.0f);
// Triangle-5
glVertex3f(3.33f, 3.33f, 0.0f);
glVertex3f(6.66f, 3.33f, 0.0f);
glVertex3f(6.66f, 6.66f, 0.0f);
// Triangle-6
glVertex3f(6.66f, 6.66f, 0.0f);
glVertex3f(3.33f, 6.66f, 0.0f);
glVertex3f(3.33f, 3.33f, 0.0f);
glEnd();
glPopMatrix();
glFlush();
}
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 10.0, 0.0, 10.0, -10.0, 10.0);
}
void handleKeypress(unsigned char key, int x, int y)
{
if (key == 't' || key == 'T')
{
cout << "Enter translation distance (Tx Ty): ";
cin >> Tx >> Ty;
glutPostRedisplay();
}
}

int main(int argc, char **argv)


{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(600, 600);
glutInitWindowPosition(100, 100);
glutCreateWindow("Triangle");

5|Page
init();
glutDisplayFunc(display);
glutKeyboardFunc(handleKeypress);
glutMainLoop();
return 0;
}

Input:

Output:

Fig: Before Translate Fig: After Translate

6|Page
Result and Discussion:

The provided code builds upon the previous experiment of drawing a star shape
using OpenGL. In this experiment, the program introduces the capability to translate
the star shape based on user input for translation distances (Tx and Ty). The user
can provide the translation distances interactively while the program is running.

Upon running the program, a window is opened with a black background. The star
shape is initially drawn at its original position. The glTranslatef function is used to
apply the translation to the star shape.

When the user presses the 't' or 'T' key, the program prompts for the translation
distances (Tx and Ty) through the console. The user can then enter the desired
values, and the star shape will be translated accordingly. The glPushMatrix and
glPopMatrix functions are used to isolate the translation transformation so that it
doesn't affect subsequent rendering operations.

The glTranslatef function modifies the model-view matrix, translating the star by the
provided distances along the x and y axes. Subsequently, the star shape is redrawn
at the translated position using the updated translation parameters.

The glFlush function ensures that all the drawing commands are executed, and the
updated star shape is displayed in the window.

Overall, the program successfully achieves the objective of allowing the user to
translate the star shape using user-provided translation distances. It demonstrates
the concept of translation in computer graphics and offers an interactive experience
for manipulating the star shape in real-time.

7|Page
Experiment No: 03

Experiment Name: ROTATION OF THE STAR (BY TAKING ANGLE IN DEGREES


AS USER INPUT)

[Note: Please after running this code-


-Type 'r'/'R' to display a text on the console (follow the 'consol screen' which is
placed behind the 'display window') for taking angle as user input in degrees.
-Then touch the 'consol screen' and type a numeric valid 'angle value' and press
the 'enter' to see the change in 'display window'.]

Objectives:

● To create a program that allows the user to rotate the star shape by providing
an angle in degrees as user input.
● To practice handling user input and updating the rotation angle in real-time.
● To understand the concept of rotation in computer graphics.

Code:

#include <GL/gl.h>
#include <GL/glut.h>
#include <bits/stdc++.h>
using namespace std;
// Rotation angle (in degrees)
float angle = 0.0f;
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glPushMatrix();
glTranslatef(5.0f, 5.0f, 0.0f);
glRotatef(angle, 0.0f, 0.0f, 1.0f);
glTranslatef(-5.0f, -5.0f, 0.0f);
glBegin(GL_TRIANGLES);
// Triangle-1
glVertex3f(3.33f, 3.33f, 0.0f);
glVertex3f(5.0f, 0.0f, 0.0f);
glVertex3f(6.66f, 3.33f, 0.0f);
// Triangle-2
glVertex3f(6.66f, 3.33f, 0.0f);
glVertex3f(10.0f, 5.0f, 0.0f);
glVertex3f(6.66f, 6.66f, 0.0f);

8|Page
// Triangle-3
glVertex3f(6.66f, 6.66f, 0.0f);
glVertex3f(5.0f, 10.0f, 0.0f);
glVertex3f(3.33f, 6.66f, 0.0f);
// Triangle-4
glVertex3f(3.33f, 6.66f, 0.0f);
glVertex3f(0.0f, 5.0f, 0.0f);
glVertex3f(3.33f, 3.33f, 0.0f);
// Triangle-5
glVertex3f(3.33f, 3.33f, 0.0f);
glVertex3f(6.66f, 3.33f, 0.0f);
glVertex3f(6.66f, 6.66f, 0.0f);
// Triangle-6
glVertex3f(6.66f, 6.66f, 0.0f);
glVertex3f(3.33f, 6.66f, 0.0f);
glVertex3f(3.33f, 3.33f, 0.0f);
glEnd();
glPopMatrix();
glFlush();
}
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 10.0, 0.0, 10.0, -10.0, 10.0);
}
void handleKeypress(unsigned char key, int x, int y)
{
if (key == 'r' || key == 'R')
{
cout << "Enter rotation angle (in degrees): ";
cin >> angle;
glutPostRedisplay();
}
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(600, 600);
glutInitWindowPosition(100, 100);
glutCreateWindow("Triangle");
init();

9|Page
glutDisplayFunc(display);
glutKeyboardFunc(handleKeypress);
glutMainLoop();
return 0;
}

Input:

Output:

Fig: Before Rotate Fig: After Rotate

10 | P a g e
Result and Discussion:

The provided code extends the previous experiments of drawing and translating a
star shape using OpenGL. In this experiment, the program introduces the capability
to rotate the star shape based on user input for the rotation angle.

Upon running the program, a window is opened with a black background. The star
shape is initially drawn at its original position. The glRotatef function is used to apply
the rotation to the star shape.

When the user presses the 'r' or 'R' key, the program prompts for the rotation angle
in degrees through the console. The user can then enter the desired angle, and the
star shape will be rotated accordingly. The glPushMatrix and glPopMatrix functions
are used to isolate the rotation transformation so that it doesn't affect subsequent
rendering operations.

The glRotatef function modifies the model-view matrix, rotating the star shape
around the z-axis by the provided angle. The rotation is centered at the point (5.0,
5.0) in the coordinate system defined by glOrtho. The glTranslatef functions are used
to ensure that the rotation occurs around the center of the star.

Subsequently, the star shape is redrawn at the rotated position using the updated
rotation angle. The glFlush function ensures that all the drawing commands are
executed, and the updated star shape is displayed in the window.

Overall, the program successfully achieves the objective of allowing the user to
rotate the star shape using a user-provided rotation angle. It demonstrates the
concept of rotation in computer graphics and offers an interactive experience for
manipulating the star shape in real-time.

11 | P a g e
Experiment No: 04

Experiment Name: REFLECTION OF THE STAR

[Note: The reflected STAR shape (Blue color) is drawn directly below the original
STAR shape (White color) by using the y-coordinates for the reflection.]

Objectives:

● To create a program that displays the reflection of a star shape.


● To practice drawing and manipulating shapes using OpenGL.
● To understand the concept of reflection in computer graphics.

Code:

#include <GL/gl.h>
#include <GL/glut.h>
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
// Original Star Shape
glColor3f(1.0f, 1.0f, 1.0f); // Red color
glBegin(GL_TRIANGLES);
// Triangle-1
glVertex3f(3.33f, 3.33f, 0.0f);
glVertex3f(5.0f, 0.0f, 0.0f);
glVertex3f(6.66f, 3.33f, 0.0f);
// Triangle-2
glVertex3f(6.66f, 3.33f, 0.0f);
glVertex3f(10.0f, 5.0f, 0.0f);
glVertex3f(6.66f, 6.66f, 0.0f);
// Triangle-3
glVertex3f(6.66f, 6.66f, 0.0f);
glVertex3f(5.0f, 10.0f, 0.0f);
glVertex3f(3.33f, 6.66f, 0.0f);
// Triangle-4
glVertex3f(3.33f, 6.66f, 0.0f);
glVertex3f(0.0f, 5.0f, 0.0f);
glVertex3f(3.33f, 3.33f, 0.0f);
// Triangle-5
glVertex3f(3.33f, 3.33f, 0.0f);
glVertex3f(6.66f, 3.33f, 0.0f);
glVertex3f(6.66f, 6.66f, 0.0f);

12 | P a g e
// Triangle-6
glVertex3f(6.66f, 6.66f, 0.0f);
glVertex3f(3.33f, 6.66f, 0.0f);
glVertex3f(3.33f, 3.33f, 0.0f);
glEnd();
// Reflected Star Shape
glColor3f(0.0f, 0.0f, 1.0f); // Blue color
glBegin(GL_TRIANGLES);
// Reflected Triangle-1
glVertex3f(3.33f, -3.33f, 0.0f);
glVertex3f(5.0f, 0.0f, 0.0f);
glVertex3f(6.66f, -3.33f, 0.0f);
// Reflected Triangle-2
glVertex3f(6.66f, -3.33f, 0.0f);
glVertex3f(10.0f, -5.0f, 0.0f);
glVertex3f(6.66f, -6.66f, 0.0f);
// Reflected Triangle-3
glVertex3f(6.66f, -6.66f, 0.0f);
glVertex3f(5.0f, -10.0f, 0.0f);
glVertex3f(3.33f, -6.66f, 0.0f);
// Reflected Triangle-4
glVertex3f(3.33f, -6.66f, 0.0f);
glVertex3f(0.0f, -5.0f, 0.0f);
glVertex3f(3.33f, -3.33f, 0.0f);
// Reflected Triangle-5
glVertex3f(3.33f, -3.33f, 0.0f);
glVertex3f(6.66f, -3.33f, 0.0f);
glVertex3f(6.66f, -6.66f, 0.0f);
// Reflected Triangle-6
glVertex3f(6.66f, -6.66f, 0.0f);
glVertex3f(3.33f, -6.66f, 0.0f);
glVertex3f(3.33f, -3.33f, 0.0f);
glEnd();
glFlush();
}
void init()
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 10.0, -10.0, 10.0, -10.0, 10.0);
}
int main(int argc, char** argv)
{

13 | P a g e
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(600, 600);
glutInitWindowPosition(100, 100);
glutCreateWindow("Star Reflection");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

Output:

Fig: The Blue Color Star is the Reflected Star of White Color

14 | P a g e
Result and Discussion:

The provided code implements a program that displays the reflection of a star shape
using OpenGL. The program consists of a display function that draws the original
star shape and its reflection.

Upon running the program, a window is opened with a black background. The
original star shape is drawn using white color, and the reflected star shape is drawn
using blue color. The glOrtho function is used to set up the orthographic projection to
define the coordinate system.

The original star shape is defined by specifying the vertices of six triangles using the
glVertex3f function. Each triangle is formed by connecting three vertices. The
vertices are specified in a counter-clockwise order to ensure the front face of the
shape is visible.

To draw the reflected star shape, the same set of triangles is used, but the y-
coordinates of the vertices are negated to create the reflection effect. This is
achieved by changing the sign of the y-coordinate while keeping the x and z
coordinates the same. The glColor3f function is used to set the color of the reflected
star shape to blue.

After defining the vertices for both the original and reflected star shapes, the glBegin
and glEnd functions are used to enclose the drawing operations for each shape.

The glFlush function ensures that all the drawing commands are executed and the
updated frame is displayed in the window.

Overall, the program successfully achieves the objective of displaying the reflection
of a star shape. It demonstrates the concept of reflection in computer graphics and
provides a visual representation of how an object can appear when reflected.

15 | P a g e
Experiment No: 5

Experiment Name: DRAWING A LINE BY USING DDA LINE DRAWING


ALGORITHM

Objectives:

● To implement the DDA (Digital Differential Analyzer) line drawing algorithm.


● To draw a line on the screen using the DDA algorithm.
● To understand the concept of line drawing algorithms in computer graphics.

Code:

#include <GL/gl.h>
#include <GL/glut.h>
#include<iostream>
using namespace std;
int x0, y0, xn, yn;
void display() {
glClear(GL_COLOR_BUFFER_BIT);
// DDA Algorithm
float dx = xn - x0;
float dy = yn - y0;
float steps = max(abs(dx), abs(dy));
float x_increment = dx / steps;
float y_increment = dy / steps;
float x = xn, y = yn;
glBegin(GL_POINTS);
glColor3f(1.0, 0.0, 0.0);
for (int i = 0; i <= steps; ++i) {
glVertex2i(static_cast<int>(x), static_cast<int>(y));
x += x_increment;
y += y_increment;
}
glEnd();
glFlush();
}
int main(int argc, char** argv) {
cout << "Enter the Starting Point (x0 y0): "; cin>>x0>>y0;
cout << "Enter the Ending Point (xn yn): "; cin>>xn>>yn;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);

16 | P a g e
glutCreateWindow("DDA Line Drawing Algorithm");
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 500, 0, 500);
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

Input:

Output:

Fig: Drawing a Line by using DDA

Result and Discussion:

17 | P a g e
The provided code implements the DDA (Digital Differential Analyzer) line drawing
algorithm to draw a line on the screen. The program prompts the user to enter the
starting and ending coordinates of the line.

Upon running the program, a window is opened with a white background. The user is
prompted to enter the starting point (x0, y0) and the ending point (xn, yn) of the line.
The gluOrtho2D function is used to set up a 2D orthographic projection to define the
coordinate system.

The DDA algorithm is then applied to calculate the coordinates of each point on the
line. The algorithm calculates the increments in x and y directions based on the
difference between the ending and starting points. The number of steps required to
reach the ending point is determined by taking the maximum absolute difference
between dx (xn - x0) and dy (yn - y0). The x and y increments are then calculated by
dividing dx and dy by the number of steps, respectively.

Using a loop, the program iterates through each step and plots the points on the line
by rounding the calculated x and y coordinates to the nearest integer using
static_cast<int>. The glColor3f function is used to set the color of the line to red.

The glBegin and glEnd functions are used to enclose the drawing operations for the
line, and the glVertex2i function is used to specify the coordinates of each point on
the line.

Finally, the glFlush function ensures that all the drawing commands are executed,
and the line is displayed in the window.

Overall, the program successfully achieves the objective of implementing the DDA
line-drawing algorithm. It provides a simple and efficient method to draw a line on the
screen using the calculated coordinates. The DDA algorithm is widely used in
computer graphics for line drawing due to its simplicity and effectiveness.

18 | P a g e
Experiment No: 06

Experiment Name: DRAWING A LINE BY USING BRESENHAM LINE DRAWING


ALGORITHM

Objectives:

● To implement the Bresenham line drawing algorithm.


● To draw a line on the screen using the Bresenham algorithm.
● To understand the concept of line drawing algorithms in computer graphics.

Code:

#include <GL/gl.h>
#include <GL/glut.h>
#include<iostream>
using namespace std;
int x0,y0,xn,yn;
void myInit() {
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0.0, 0.0, 0.0, 1.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0, 500, 0, 500);
}
void draw_pixel(int x, int y) {
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
}
void draw_line(int x1, int x2, int y1, int y2) {
int dx, dy, i, e;
int incx, incy, inc1, inc2;
int x,y;
dx = x2-x1;
dy = y2-y1;
if (dx < 0) dx = -dx;
if (dy < 0) dy = -dy;
incx = 1;
if (x2 < x1) incx = -1;
incy = 1;
if (y2 < y1) incy = -1;
x = x1; y = y1;
if (dx > dy) {

19 | P a g e
draw_pixel(x, y);
e = 2 * dy-dx;
inc1 = 2*(dy-dx);
inc2 = 2*dy;
for (i=0; i<dx; i++) {
if (e >= 0) {
y += incy;
e += inc1;
}
else
e += inc2;
x += incx;
draw_pixel(x, y);
}

} else {
draw_pixel(x, y);
e = 2*dx-dy;
inc1 = 2*(dx-dy);
inc2 = 2*dx;
for (i=0; i<dy; i++) {
if (e >= 0) {
x += incx;
e += inc1;
}
else
e += inc2;
y += incy;
draw_pixel(x, y);
}
}
}
void myDisplay() {
draw_line(x0, xn, y0, yn);
glFlush();
}
int main(int argc, char **argv) {

cout<<"Enter the Starting Point (x0 y0): ";cin>>x0>>y0;


cout<<"Enter the Ending Point (xn yn): ";cin>>xn>>yn;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(0, 0);

20 | P a g e
glutCreateWindow("Bresenham's Line Drawing");
myInit();
glutDisplayFunc(myDisplay);
glutMainLoop();
return 0;
}

Input:

Output:

Fig: Drawing a Line by using Bresenham’s

21 | P a g e
Result and Discussion:

The provided code implements the Bresenham line drawing algorithm to draw a line
on the screen. The user is prompted to enter the starting and ending coordinates of
the line.

Upon running the program, a window is opened with a black background. The user is
prompted to enter the starting point (x0, y0) and the ending point (xn, yn) of the line.
The gluOrtho2D function is used to set up a 2D orthographic projection to define the
coordinate system.

The Bresenham algorithm is then applied to calculate the coordinates of each point
on the line. The algorithm avoids the use of floating-point arithmetic by utilizing
integer calculations and decision parameters. It determines the increments in x and y
directions based on the difference between the ending and starting points.

The algorithm then iterates through each step, calculating a decision parameter to
determine the next point to be drawn. Based on the decision parameter, the
algorithm increments the x and y coordinates accordingly. The draw_pixel function is
called to plot the points on the line.

The draw_line function handles the logic of the Bresenham algorithm by considering
the cases where the slope of the line is less than or greater than 1. The logic is
slightly different depending on the slope of the line to ensure accurate and efficient
line drawing.

Finally, the myDisplay function is called to draw the line using the provided starting
and ending coordinates. The glFlush function ensures that all the drawing
commands are executed, and the line is displayed in the window.

Overall, the program successfully achieves the objective of implementing the


Bresenham line drawing algorithm. The Bresenham algorithm is known for its
efficiency and accuracy in drawing lines, making it a popular choice in computer
graphics applications. It provides a practical method for drawing lines on the screen
using integer calculations, avoiding the need for costly floating-point operations.

22 | P a g e
Experiment No: 07

Experiment Name: COHEN SUTHERLAND LINE CLIPPING ALGORITHM

Objectives:

● To implement the Cohen-Sutherland line clipping algorithm.


● To clip a line against a rectangular window defined by its minimum and
maximum coordinates.
● To understand the concept of line clipping in computer graphics.

Code:

#include <GL/gl.h>
#include <GL/glut.h>
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
typedef struct {
GLfloat x, y;
} Point;
const GLint WIN_LEFT_BIT = 0x01;
const GLint WIN_RIGHT_BIT = 0x02;
const GLint WIN_BOTTOM_BIT = 0x04;
const GLint WIN_TOP_BIT = 0x08;
void init_graph(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(SCREEN_WIDTH, SCREEN_HEIGHT);
glutCreateWindow(argv[0]);
glClearColor(0.0, 0.0, 0.0, 0.0);
glPointSize(1.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT);
}
void close_graph() {
glutMainLoop();
}
void swap_points(Point *p1, Point *p2) {
Point t = *p1;
*p1 = *p2;
*p2 = t;

23 | P a g e
}
void swap_codes(GLint *x, GLint *y) {
GLint t = *x;
*x = *y;
*y = t;
}
GLint inside(GLint code) {
return !code;
}
GLint accept(GLint code1, GLint code2) {
return !(code1 | code2);
}
GLint reject(GLint code1, GLint code2) {
return code1 & code2;
}
GLint encode(Point p1, Point win_min, Point win_max) {
GLint code = 0x00;
if (p1.x < win_min.x) code |= WIN_LEFT_BIT;
if (p1.x > win_max.x) code |= WIN_RIGHT_BIT;
if (p1.y < win_min.y) code |= WIN_BOTTOM_BIT;
if (p1.y > win_max.y) code |= WIN_TOP_BIT;
return code;
}
GLint round(GLfloat a) {
return (GLint) (a + 0.5f);
}
void line_clip(Point p1, Point p2, Point win_min, Point win_max) {
GLint code1, code2;
GLint done = 0, plot_line = 0;
GLfloat m = 0;
if (p1.x != p2.x) {
m = (p2.y - p1.y) / (p2.x - p1.x);
}
while (!done) {
code1 = encode(p1, win_min, win_max);
code2 = encode(p2, win_min, win_max);
if (accept(code1, code2)) {
done = 1;
plot_line = 1;
} else if (reject(code1, code2)) {
done = 1;
} else {
if (inside(code1)) {
swap_points(&p1, &p2);

24 | P a g e
swap_codes(&code1, &code2);
}
if (code1 & WIN_LEFT_BIT) {
p1.y += (win_min.x - p1.x) * m;
p1.x = win_min.x;
} else if (code1 & WIN_RIGHT_BIT) {
p1.y += (win_max.x - p1.x) * m;
p1.x = win_max.x;
} else if (code1 & WIN_BOTTOM_BIT) {
if (p1.x != p2.x)
p1.x += (win_min.y - p1.y) / m;
p1.y = win_min.y;
} else if (code1 & WIN_TOP_BIT) {
if (p1.x != p2.x)
p1.x += (win_max.y - p1.y) / m;
p1.y = win_max.y;
}
}
}
if (plot_line) {
glColor3f(1, 0, 0);
glLineWidth(2);
glBegin(GL_LINES);
glVertex2i(round(p1.x), round(p1.y));
glVertex2i(round(p2.x), round(p2.y));
glEnd();
glFlush();
}
}
void draw_window(Point win_min, Point win_max) {
glColor3f(0, 1, 0);
glBegin(GL_LINE_LOOP);
glVertex2i(round(win_min.x), round(win_min.y));
glVertex2i(round(win_min.x), round(win_max.y));
glVertex2i(round(win_max.x), round(win_max.y));
glVertex2i(round(win_max.x), round(win_min.y));
glEnd();
glFlush();
}
void init_clip() {
glClear(GL_COLOR_BUFFER_BIT);
Point win_min = {60, 60};
Point win_max = {470, 290};
draw_window(win_min, win_max);

25 | P a g e
Point p1 = {50, 50};
Point p2 = {490, 310};
glColor3f(1, 1, 1);
glBegin(GL_LINES);
glVertex2i(round(p1.x), round(p1.y));
glVertex2i(round(p2.x), round(p2.y));
glEnd();
line_clip(p1, p2, win_min, win_max);
}
int main(int argc, char **argv) {
init_graph(argc, argv);
glutDisplayFunc(init_clip);
close_graph();
return EXIT_SUCCESS;
}

Output:

Fig: Line clipped by using Cohen Sutherland

26 | P a g e
Result and Discussion:

The provided code implements the Cohen-Sutherland line clipping algorithm to clip a
line against a rectangular window. The window is defined by its minimum (win_min)
and maximum (win_max) coordinates.

Upon running the program, a window is opened with a black background. The
rectangular window is drawn using the draw_window function, and the line to be
clipped is drawn using the glBegin(GL_LINES) and glEnd() functions.

The line_clip function applies the Cohen-Sutherland algorithm to determine if the line
needs to be clipped or if it lies entirely within the window. The algorithm works by
encoding the points and the window boundaries into binary codes, representing their
relative positions. These codes are then used to determine if the line should be
accepted, rejected, or clipped.

The algorithm iteratively checks the codes of the two endpoints of the line. If both
endpoints have a code of 0 (inside the window), the line is accepted and drawn as is.
If both codes indicate that the line is entirely outside the window, it is rejected and
not drawn. If the line is neither accepted nor rejected, the algorithm determines
which endpoint to adjust based on the code. The endpoint is adjusted to the
intersection point with the window boundary, and the process is repeated until the
line is either accepted or rejected.

If the line is accepted, it is drawn in red using the glBegin(GL_LINES) and glEnd()
functions.

Overall, the program successfully achieves the objective of implementing the Cohen-
Sutherland line clipping algorithm. The Cohen-Sutherland algorithm is commonly
used for line clipping in computer graphics applications. It provides an efficient way
to clip lines against rectangular windows or viewports, allowing for accurate
rendering of objects within a defined region.

27 | P a g e
Experiment No: 08

Experiment Name: SUTHERLAND-HODGMAN POLYGON CLIPPING


ALGORITHM

Objectives:

● To implement the Sutherland-Hodgman polygon clipping algorithm.


● To clip a polygon against a rectangular window defined by its minimum and
maximum coordinates.
● To understand the concept of polygon clipping in computer graphics.

Code:

#include <windows.h>
#include <gl/glut.h>

struct Point{
float x,y;
} w[4],oVer[4];
int Nout;

void drawPoly(Point p[],int n){


glBegin(GL_POLYGON);
for(int i=0;i<n;i++)
glVertex2f(p[i].x,p[i].y);
glEnd();
}

bool insideVer(Point p){


if((p.x>=w[0].x)&&(p.x<=w[2].x))
if((p.y>=w[0].y)&&(p.y<=w[2].y))
return true;
return false;
}

void addVer(Point p){


oVer[Nout]=p;
Nout=Nout+1;
}

Point getInterSect(Point s,Point p,int edge){


Point in;

28 | P a g e
float m;
if(w[edge].x==w[(edge+1)%4].x){ //Vertical Line
m=(p.y-s.y)/(p.x-s.x);
in.x=w[edge].x;
in.y=in.x*m+s.y;
}
else{//Horizontal Line
m=(p.y-s.y)/(p.x-s.x);
in.y=w[edge].y;
in.x=(in.y-s.y)/m;
}
return in;
}
void clipAndDraw(Point inVer[],int Nin){
Point s,p,interSec;
for(int i=0;i<4;i++)
{
Nout=0;
s=inVer[Nin-1];
for(int j=0;j<Nin;j++)
{
p=inVer[j];
if(insideVer(p)==true){
if(insideVer(s)==true){
addVer(p);
}
else{
interSec=getInterSect(s,p,i);
addVer(interSec);
addVer(p);
}
}
else{
if(insideVer(s)==true){
interSec=getInterSect(s,p,i);
addVer(interSec);
}
}
s=p;
}
inVer=oVer;
Nin=Nout;
}
drawPoly(oVer,4);

29 | P a g e
}
void init(){
glClearColor(0.0f,0.0f,0.0f,0.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0,100.0,0.0,100.0,0.0,100.0);
glClear(GL_COLOR_BUFFER_BIT);
w[0].x =20,w[0].y=10;
w[1].x =20,w[1].y=80;
w[2].x =80,w[2].y=80;
w[3].x =80,w[3].y=10;
}
void display(void){
Point inVer[4];
init();
// As Window for Clipping
glColor3f(1.0f,0.0f,0.0f);
drawPoly(w,4);
// As Rect
glColor3f(0.0f,1.0f,0.0f);
inVer[0].x =10,inVer[0].y=40;
inVer[1].x =10,inVer[1].y=60;
inVer[2].x =60,inVer[2].y=60;
inVer[3].x =60,inVer[3].y=40;
drawPoly(inVer,4);
// As Rect
glColor3f(0.0f,0.0f,1.0f);
clipAndDraw(inVer,4);
// Print
glFlush();
}
int main(int argc,char *argv[]){
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(400,400);
glutInitWindowPosition(100,100);
glutCreateWindow("Polygon Clipping!");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

30 | P a g e
Output:

Fig: The Red is window, the Blue is inside the


Window, and the Green is outside the window.

Result and Discussion:


31 | P a g e
The provided code implements the Sutherland-Hodgman polygon clipping algorithm
to clip a polygon against a rectangular window. The window is defined by its
minimum (w[0]) and maximum (w[2]) coordinates.

Upon running the program, a window is opened with a black background. The
rectangular window is drawn using the drawPoly function, and the polygon to be
clipped is drawn using the drawPoly function as well.

The Sutherland-Hodgman algorithm works by iteratively clipping the polygon against


each edge of the window. It checks each vertex of the polygon and determines if it is
inside or outside the window. If a vertex is inside the window, it is added to the
output vertex list. If a vertex is outside the window, the algorithm computes the
intersection point between the polygon edge and the window edge and adds it to the
output vertex list. The output vertex list is then used as the input for the next
iteration, and the process is repeated for each edge of the window.

The clipAndDraw function implements the Sutherland-Hodgman algorithm. It takes in


the input vertices of the polygon and the number of vertices (Nin). It iterates over
each edge of the window, clipping the polygon against that edge and updating the
output vertex list (oVer). The resulting clipped polygon is then drawn using the
drawPoly function.

The program also includes an init function to set up the initial OpenGL settings,
including the clear color and the projection matrix. The display function is responsible
for drawing the window, the input polygon, and the clipped polygon.

Overall, the program successfully achieves the objective of implementing the


Sutherland-Hodgman polygon clipping algorithm. The Sutherland-Hodgman
algorithm is commonly used for polygon clipping in computer graphics applications. It
allows for efficient clipping of polygons against arbitrary clipping windows, enabling
the rendering of complex shapes within defined regions.

32 | P a g e
Experiment No: 09

Experiment Name: WEILER ATHERTON POLYGON CLIPPING

Objectives:

 Implement the Weiler Atherton polygon clipping algorithm.


 Clip a polygon against another polygon using the implemented algorithm.
 Visualize the original polygons and the resulting clipped area using OpenGL.

Code:

#include <bits/stdc++.h>
#include <GL/glut.h>
#include <GL/glu.h>
#include <GL/gl.h>
#define Size 600
using namespace std;
typedef float Color[3];
struct Point
{int x, y;};
typedef struct IntersectionPoint
{
int pointFlag;
int index0, index1;
Point p;
bool inFlag;
int dis;
}IP;
class Pg
{
public:
vector<Point> pts;
Pg(void);
~Pg(void);
void drawPgLine(Color c);
};
Pg::Pg(void)
{}
Pg::~Pg(void)
{}
void Pg::drawPgLine(Color c)
{

33 | P a g e
glColor3fv(c);
glLineWidth(2.0);
glBegin(GL_LINE_LOOP);
int size = pts.size();
for (int i = 0; i < size; i++)
glVertex2i(pts[i].x, pts[i].y);
glEnd();
}
bool isPointInsidePg(Point p, Pg& py)
{
int cnt = 0, size = py.pts.size();
for (int i = 0; i < size; i++) {
Point p1 = py.pts[i];
Point p2 = py.pts[(i + 1) % size];
if (p1.y == p2.y) continue;
if (p.y < min(p1.y, p2.y)) continue;
if (p.y >= max(p1.y, p2.y)) continue;
double x = (double)(p.y - p1.y) * (double)(p2.x - p1.x) / (double)(p2.y -
p1.y) + p1.x;
if (x > p.x) cnt++;
}
return (cnt % 2 == 1);
}
int cross(Point& p0, Point& p1, Point& p2)
{return ((p2.x - p0.x) * (p1.y - p0.y) - (p1.x - p0.x) * (p2.y - p0.y));}
bool onSegment(Point& p0, Point& p1, Point& p2)
{
int minx = min(p0.x, p1.x), maxx = max(p0.x, p1.x);
int miny = min(p0.y, p1.y), maxy = max(p0.y, p1.y);
if (p2.x >= minx && p2.x <= maxx && p2.y >= miny && p2.y <= maxy) return
true;
return false;
}
bool segmentsIntersect(Point& p1, Point& p2, Point& p3, Point& p4)
{
int d1 = cross(p3, p4, p1);
int d2 = cross(p3, p4, p2);
int d3 = cross(p1, p2, p3);
int d4 = cross(p1, p2, p4);
if (((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) &&
((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0)))
return true;
if (d1 == 0 && onSegment(p3, p4, p1)) return true;
if (d2 == 0 && onSegment(p3, p4, p2)) return true;

34 | P a g e
if (d3 == 0 && onSegment(p1, p2, p3)) return true;
if (d4 == 0 && onSegment(p1, p2, p4)) return true;
return false;
}
Point getintersectPoint(Point p1, Point p2, Point p3, Point p4)
{
Point p;
int b1 = (p2.y - p1.y) * p1.x + (p1.x - p2.x) * p1.y;
int b2 = (p4.y - p3.y) * p3.x + (p3.x - p4.x) * p3.y;
int D = (p2.x - p1.x) * (p4.y - p3.y) - (p4.x - p3.x) * (p2.y - p1.y);
int D1 = b2 * (p2.x - p1.x) - b1 * (p4.x - p3.x);
int D2 = b2 * (p2.y - p1.y) - b1 * (p4.y - p3.y);
p.x = D1 / D;
p.y = D2 / D;
return p;
}
void generateIntersectPoints(Pg& pyclip, Pg& py, list<IP>& iplist)
{
int clipSize = pyclip.pts.size(), pySize = py.pts.size();
for (int i = 0; i < clipSize; i++) {
Point p1 = pyclip.pts[i];
Point p2 = pyclip.pts[(i + 1) % clipSize];
for (int j = 0; j < pySize; j++) {
Point p3 = py.pts[j];
Point p4 = py.pts[(j + 1) % pySize];
if (segmentsIntersect(p1, p2, p3, p4)) {
IP ip;
ip.index0 = j;
ip.index1 = i;
ip.p = getintersectPoint(p1, p2, p3, p4);
iplist.push_back(ip);
}
}
}
}
int getDistance(Point& p1, Point& p2) {
return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y);
}
bool distanceComparator(IP& ip1, IP& ip2) {
return ip1.dis < ip2.dis;
}
void generateList(Pg& py, list<IP>& iplist, list<IP>& comlist, int index) {
int size = py.pts.size();
list<IP>::iterator it;

35 | P a g e
for (int i = 0; i < size; i++) {
Point p1 = py.pts[i];
IP ip;
ip.pointFlag = 0;
ip.p = p1;
comlist.push_back(ip);
list<IP> oneSeg;
for (it = iplist.begin(); it != iplist.end(); it++) {
if ((index == 0 && i == it->index0) ||
(index == 1 && i == it->index1)) {
it->dis = getDistance(it->p, p1);
it->pointFlag = 1;
oneSeg.push_back(*it);
}
}
oneSeg.sort(distanceComparator);
for (it = oneSeg.begin(); it != oneSeg.end(); it++)
comlist.push_back(*it);
}
}
void getPgPointInOut(list<IP>& Pglist, Pg& pyclip) {
bool inFlag;
list<IP>::iterator it;
for (it = Pglist.begin(); it != Pglist.end(); it++) {
if (it->pointFlag == 0) {
if (isPointInsidePg(it->p, pyclip))
inFlag = true;
else inFlag = false;
}
else {
inFlag = !inFlag;
it->inFlag = inFlag;
}
}
}
bool operator==(Point& p1, Point& p2) {
return p1.x == p2.x && p1.y == p2.y;
}
void getClipPointInOut(list<IP>& cliplist, list<IP>& Pglist) {
list<IP>::iterator it, it1;
for (it = cliplist.begin(); it != cliplist.end(); it++) {
if (it->pointFlag == 0) continue;
for (it1 = Pglist.begin(); it1 != Pglist.end(); it1++) {
if (it1->pointFlag == 0) continue;

36 | P a g e
if (it->p == it1->p) it->inFlag = it1->inFlag;
}
}
}
void generateClipArea(list<IP>& Pglist, list<IP>& cliplist) {
list<IP>::iterator it, it1;
Pg py;
Color c = { 0.0, 0.0, 1.0 };
for (it = Pglist.begin(); it != Pglist.end(); it++)
if (it->pointFlag == 1 && it->inFlag) break;
py.pts.clear();
while (true) {
if (it == Pglist.end()) break;
py.pts.push_back(it->p);
for (; it != Pglist.end(); it++) {
if (it->pointFlag == 1 && !it->inFlag) break;
py.pts.push_back(it->p);
}
for (it1 = cliplist.begin(); it1 != cliplist.end(); it1++)
if (it1->p == it->p) break;
for (; it1 != cliplist.end(); it1++) {
if (it1->pointFlag == 1 && it1->inFlag) break;
py.pts.push_back(it1->p);
}
if (py.pts[0] == it1->p) {
py.drawPgLine(c);
py.pts.clear();
for (; it != Pglist.end(); it++)
if (it->pointFlag == 1 && it->inFlag) break;
continue;
}
for (; it != Pglist.end(); it++)
if (it->p == it1->p) break;
}
}
void weilerAtherton(Pg& pyclip, Pg& py) {
list<IP> iplist, Pglist, cliplist;
generateIntersectPoints(pyclip, py, iplist);
generateList(py, iplist, Pglist, 0);
generateList(pyclip, iplist, cliplist, 1);
getPgPointInOut(Pglist, pyclip);
getClipPointInOut(cliplist, Pglist);
generateClipArea(Pglist, cliplist);
}

37 | P a g e
void init()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glColor3f(1.0, 0.0, 0.0);
glPointSize(1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, Size - 1, 0.0, Size - 1);
}
void GenerateRandomSimplePg(Pg &G, int M)
{
Point P;
G.pts.clear();
for (int i = 0; i < M; ++i)
{
bool flag;
do
{
P.x = rand() % Size;
P.y = rand() % Size;
flag = true;
for (int j = 1; j < i - 1; ++j)
if (segmentsIntersect(G.pts[j - 1], G.pts[j], G.pts[i - 1], P))
{flag = false;break;}
if (flag && i == M - 1)
{
for (int j = 2; j < i; ++j)
if (segmentsIntersect(G.pts[j - 1], G.pts[j], P,
G.pts[0]))
{flag = false;break;}
}
} while (!flag);
G.pts.push_back(P);
}
}
void KeyboardAction(unsigned char key, int x, int y)
{exit(0);}

void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_POINT_SMOOTH);
Pg pyclip, py;
//GenerateRandomSimplePg(pyclip, 4);

38 | P a g e
//GenerateRandomSimplePg(py, 4);
Point p1, p2, p3, p4;
p1.x = 553, p1.y = 495;
p2.x = 351, p2.y = 175;
p3.x = 486, p3.y = 71;
p4.x = 61, p4.y = 86;
pyclip.pts.push_back(p1);
pyclip.pts.push_back(p2);
pyclip.pts.push_back(p3);
pyclip.pts.push_back(p4);
Point p5, p6, p7, p8;
p5.x = 390, p5.y = 424;
p6.x = 579, p6.y = 585;
p7.x = 257, p7.y = 112;
p8.x = 68, p8.y = 245;
py.pts.push_back(p5);
py.pts.push_back(p6);
py.pts.push_back(p7);
py.pts.push_back(p8);
int size = pyclip.pts.size();
for (int i = 0; i < size; ++i)
cout << pyclip.pts[i].x << " " << pyclip.pts[i].y << endl;
cout << endl;
size = py.pts.size();
for (int i = 0; i < size; ++i)
cout << py.pts[i].x << " " << py.pts[i].y << endl;
Color a = { 1.0, 0.0, 0.0 };
Color b = { 0.0, 1.0, 0.0 };
py.drawPgLine(a);
pyclip.drawPgLine(b);
weilerAtherton(pyclip, py);
glFlush();
}
int main(int argc, char **argv)
{
srand(time(NULL));
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(Size, Size);
glutInitWindowPosition(100, 100);
glutCreateWindow("Weiler-Atherton Clipping Algorithm");
glutKeyboardFunc(KeyboardAction);
glutDisplayFunc(display);
init();

39 | P a g e
glutMainLoop();
return 0;
}

Input:

Output:

Fig: Green (original polygon) and Blue (clipped


polygon) and the Red polygon is Window.
Result and Discussion:

40 | P a g e
The code successfully implements the Weiler Atherton polygon clipping algorithm.
The algorithm takes two polygons as input: the original polygon (py) and the clipping
polygon (pyclip). The algorithm performs the necessary calculations to determine the
intersection points between the polygons and generates the clipped area.

The code initializes the py and pyclip polygons with predefined points, but it also
provides a GenerateRandomSimplePg function that can generate random simple
polygons. The display function is responsible for visualizing the polygons by drawing
their line segments using different colors.

The weilerAtherton function orchestrates the entire clipping process. It generates the
intersection points between the polygons, creates lists of points for the original and
clipping polygons, determines the in/out flags for each point, and finally generates
the clipped area by connecting the points based on their in/out flags.

The resulting clipped area is drawn using OpenGL, with the original polygons
displayed in one color and the clipped area displayed in another color. The
generateClipArea function handles the drawing of the clipped area by iterating over
the points in py and pyclip and drawing the corresponding line segments.

Overall, the code achieves its objectives by implementing the Weiler Atherton
polygon clipping algorithm and visualizing the results. The algorithm effectively clips
the original polygon against the clipping polygon, resulting in a new polygon that
represents the intersection of the two polygons. The visualization using OpenGL
provides a clear representation of the original polygons and the resulting clipped
area, allowing for easy interpretation and analysis of the clipping process.

41 | P a g e
Experiment No: 10

Experiment Name: BRESENHAM CIRCLE DRAWING ALGORITHM

Objectives:

● Implement the Bresenham Circle Drawing algorithm using OpenGL and


GLUT.
● Allow the user to input the radius and center coordinates of the circle.
● Display the circle using OpenGL's point primitive.

Code:

#include <GL/glut.h>
#include<bits/stdc++.h>
#include <cmath>
using namespace std;
int radius;
int centerX;
int centerY;
void drawCircle(int x, int y) {
glBegin(GL_POINTS);
glVertex2i(centerX + x, centerY + y);
glVertex2i(centerX + x, centerY - y);
glVertex2i(centerX - x, centerY + y);
glVertex2i(centerX - x, centerY - y);
glVertex2i(centerX + y, centerY + x);
glVertex2i(centerX + y, centerY - x);
glVertex2i(centerX - y, centerY + x);
glVertex2i(centerX - y, centerY - x);
glEnd();
}
void bresenhamCircle() {
int x = 0;
int y = radius;
int decision = 3 - 2 * radius;
while (x <= y) {
drawCircle(x, y);
if (decision < 0) {
decision += 4 * x + 6;
} else {
decision += 4 * (x - y) + 10;
y--;

42 | P a g e
}
x++;
}
}
void display() {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 0.0, 0.0);
bresenhamCircle();
glFlush();
}
void reshape(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, width, 0, height);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
cout<<"Enter the Radius: ";cin>>radius;
cout<<"Enter the CenterX: ";cin>>centerX;
cout<<"Enter the CenterY: ";cin>>centerY;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutCreateWindow("Bresenham Circle Drawing");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glClearColor(1.0, 1.0, 1.0, 0.0);
glutMainLoop();
return 0;
}

43 | P a g e
Input:

Output:

Fig: Drawing a Circle by using


Bresenham Circle Drawing Algorithm

44 | P a g e
Result and Discussion:

The implemented code demonstrates the Bresenham Circle Drawing algorithm using
the OpenGL library. The algorithm efficiently approximates the points on the
circumference of a circle by taking advantage of integer arithmetic and minimizing
computational complexity.

The program prompts the user to enter the radius and center coordinates of the
circle. Upon receiving the input, the algorithm calculates the points on the
circumference using the Bresenham algorithm. The calculated points are then
rendered on the screen using OpenGL's point primitive.

The Bresenham Circle Drawing algorithm works by iteratively plotting points in eight
octants of the circle, taking advantage of symmetry to reduce the number of
calculations. It uses integer variables and simple arithmetic operations to determine
the next point to be plotted, which makes it computationally efficient compared to
other algorithms. The algorithm handles cases where the circle center is not at the
origin and is capable of drawing circles of any size.

By implementing the Bresenham Circle Drawing algorithm, we can draw circles


accurately and efficiently in computer graphics applications. The algorithm's
simplicity and speed make it suitable for real-time rendering and interactive
applications. It provides a viable alternative to other circle drawing algorithms, such
as the midpoint circle algorithm.

Overall, the implemented code successfully draws a circle on the screen using the
Bresenham Circle Drawing algorithm, showcasing the algorithm's effectiveness and
practicality in computer graphics.

Experiment No: 11

45 | P a g e
Experiment Name: MID-POINT CIRCLE DRAWING ALGORITHM

Objectives:

● Implement the Mid-Point Circle Drawing algorithm using OpenGL and GLUT.
● Allow the user to input the radius and center coordinates of the circle.
● Display the circle using OpenGL's point primitive.

Code:

#include <GL/glut.h>
#include<bits/stdc++.h>
#include <cmath>
using namespace std;
int radius;
int centerX;
int centerY;
void drawCircle(int x, int y) {
glBegin(GL_POINTS);
glVertex2i(centerX + x, centerY + y);
glVertex2i(centerX + x, centerY - y);
glVertex2i(centerX - x, centerY + y);
glVertex2i(centerX - x, centerY - y);
glVertex2i(centerX + y, centerY + x);
glVertex2i(centerX + y, centerY - x);
glVertex2i(centerX - y, centerY + x);
glVertex2i(centerX - y, centerY - x);
glEnd();
}
void midpointCircle() {
int x = 0;
int y = radius;
int decision = 1 - radius;
while (x <= y) {
drawCircle(x, y);
if (decision < 0) {
decision += 2 * x + 3;
} else {
decision += 2 * (x - y) + 5;
y--;
}
x++;

46 | P a g e
}
}
void display() {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 0.0, 0.0);
midpointCircle();
glFlush();
}
void reshape(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, width, 0, height);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
cout<<"Enter the Radius: ";cin>>radius;
cout<<"Enter the CenterX: ";cin>>centerX;
cout<<"Enter the CenterY: ";cin>>centerY;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutCreateWindow("Midpoint Circle Drawing");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glClearColor(1.0, 1.0, 1.0, 0.0);
glutMainLoop();
return 0;
}

Input:

47 | P a g e
Output:

Fig: Drawing a Circle by using Mid-


point Circle drawing Algorithm

Result and Discussion:

48 | P a g e
The provided code demonstrates the implementation of the Mid-Point Circle Drawing
algorithm using the OpenGL library. This algorithm efficiently approximates the
points on the circumference of a circle by utilizing the midpoint of the circle to
determine the next point to be plotted.

The program prompts the user to enter the radius and center coordinates of the
circle. Once the input is provided, the algorithm calculates the points on the
circumference using the Mid-Point Circle Drawing algorithm. The calculated points
are then rendered on the screen using OpenGL's point primitive.

The Mid-Point Circle Drawing algorithm works by iteratively plotting points in eight
octants of the circle. It uses the midpoint between two candidate points to determine
the next point to be plotted, taking advantage of symmetry to reduce the number of
calculations. The algorithm uses integer variables and simple arithmetic operations,
making it computationally efficient.

By implementing the Mid-Point Circle Drawing algorithm, we can accurately and


efficiently draw circles in computer graphics applications. The algorithm is
particularly useful for real-time rendering and interactive applications due to its
simplicity and speed. It provides an alternative approach to circle drawing compared
to other algorithms, such as the Bresenham Circle Drawing algorithm.

Overall, the provided code successfully draws a circle on the screen using the Mid-
Point Circle Drawing algorithm. This implementation highlights the effectiveness and
practicality of the algorithm in computer graphics.

49 | P a g e

You might also like