Nothing Special   »   [go: up one dir, main page]

CG Lab File

Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

School of Computer Science

UNIVERSITY OF PETROLEUM AND ENERGY


STUDIES
DEHRADUN, UTTARAKHAND

Computer Graphics Lab


B.Tech CSE AIML B2 (Non Honours)

Lab File

Submitted to: Submitted by:


Dr. Tarandeep Kaur Bhatia Priyam Jain
500091908
CG LAB EXP-1

Introduction to OpenGL

OpenGL:

OpenGL (Open Graphics Library) is an open-source, cross-platform API (application


programming interface) used for rendering 2D and 3D graphics. It has been widely used as a
standard for graphics programming since it was first introduced by Silicon Graphics Inc. in
1992.

OpenGL provides many functions for creating and manipulating graphics. For drawing
primitive shapes (points, lines, triangles), textures, and lighting. It's used in a variety of
applications, including video games, scientific simulations, virtual and augmented reality, and
computer-aided design. One of OpenGL's strengths is its portability. It is available for various
platforms such as Windows, macOS, Linux, Android and iOS. It is also compatible with
various programming languages such as C, C++, Java and Python.

OpenGL has been updated several times over the years, with the latest version being OpenGL
4.6 released in 2017.

GLU & GLUT:


GLU (OpenGL Utility Library) is a set of utility functions built on top of OpenGL, providing
additional functionality to simplify common tasks associated with graphics rendering. GLU
was originally developed by Silicon Graphics Inc., the same company that developed
OpenGL, but is now part of the OpenGL standard.

GLU provides functions for performing common operations such as transforming


coordinates, generating 2D and 3D primitives, tessellating curves and surfaces, and handling
texture mapping. Some of the more commonly used GLU functions include gluPerspective()
for setting a perspective projection, gluLookAt() for positioning the camera, and gluQuadric()
for generating geometric primitives such as spheres and cylinders. And so on.

Although GLU has been largely superseded by other libraries and APIs in modern graphics
programming, it is still sometimes used in applications that require compatibility with legacy
code and older systems.
GLUT (OpenGL Utility Toolkit) is an open source, cross-platform library that provides a set
of tools and functions for creating and managing windows and user interfaces in OpenGL
applications. It was originally developed by Mark Kilgard in 1993 to make writing OpenGL
programs easier.

GLUT simplifies the task of creating graphical user interfaces in OpenGL applications by
providing numerous functions for managing windows, keyboard and mouse input, and
timing. It also provides a simple API for drawing geometric primitives, text, and images on
the screen.

Commonly used to create simple graphic demos, educational software, and small games,
GLUT remains popular for quick prototyping and experimenting with new ideas. However, it
has limited functionality, and developers of more complex applications often use other
libraries and frameworks such as GLFW, SDL, and Qt.

OpenGL Architecture:

OpenGL is designed as a layered architecture that provides a modular structure for


implementing graphics rendering pipelines. The architecture consists of several layers, each
with its own functions and responsibilities.

Application layer:
At this level, graphics application code is written. Connect to the OpenGL API to specify the
desired rendering operations, such as: For example, camera settings, object creation, lighting
and shading definitions, etc.

OpenGL API layer:


This layer provides an interface between the application layer and the OpenGL
implementation. Defines a set of functions that an application can call to specify rendering
operations such as: These include drawing primitives, specifying texture mappings, and
controlling the graphics pipeline. OpenGL library layer:
This layer is the core of the OpenGL implementation. Provides the software and hardware
interfaces required to perform application-specified playback operations. Library layers are
responsible for managing the graphics pipeline, including vertex and fragment processing,
rasterization, and blending.

Device driver layer:


This layer provides the interface between the OpenGL library layer and the graphics
hardware. It translates OpenGL commands into hardware-specific instructions that can be
executed on a graphics processing unit (GPU). Graphics hardware layer:
This layer is the physical hardware that performs rendering operations. It contains the GPU,
memory, and other hardware components required for graphics processing.
OpenGL's layered architecture provides a clean separation of concerns between the various
components of the graphics rendering pipeline. This makes it easier for developers to
understand and optimise their code, and easier for hardware vendors to implement OpenGL
on devices.

Setting up the Environment:

1. Install Codeblock.
2. Go to https://www.transmissionzero.co.uk/software/freeglut-devel/
3. Click on Download freeglut 3.0.0 for MinGW (with PGP signature and PGP key)
4. Extract the contents of the extracted file (freeglut-MinGW-3.0.0-1.mp).

5. Go to Downloadfreeglut-MinGW-3.0.0-1.mp folder freeglut folder bin


Folder
a. Copy the freeglut.dll file, if your PC is of 32 bit.
b. If your PC is of 64 bit, go to folder and copy the freeglut.dll file.

6. Navigate to “C:\Windows” directory and paste your copied freeglut.dll file. You have
to provide administrator permission.

7. Now we have to set up the compiler. Go to Downloadfreeglut-MinGW-3.0.0-1.mp


folder freeglut folder include GL folder. Copy all the four files (having .h
extension)
8. Navigate to the directory where codeblock compiler is installed, i.e., C:\Program
Files\CodeBlocks\MinGW
a. Open the include folder and check whether the “GL” folder exists or not. If
yes, then paste the files copied from Downloadfreeglut-MinGW-3.0.0-1.mp
folder freeglut include GL to the path C:\ProgramFiles\CodeBlocks\MinGW.
b. If no, then check for the GL folder in x86_64-w64-mingw32\include folder.
Paste the copied files from Downloadfreeglut-MinGW-3.0.0-1.mp folder
freeglut include GL to the path C:\ProgramFiles\CodeBlocks\MinGW\x86_64-
w64-mingw32\include\GL.

9. Allow the contents to be merged with the folder for all the items.

10. Now we have to set up the compiler. Go to Downloadfreeglut-MinGW-3.0.0-1.mp


folder freeglut lib ×64 folder. Copy all the two files (having .a extension)
11. Navigate to the directory where codeblock compiler is installed, i.e., C:\Program
Files\CodeBlocks\MinGW
a. Open the lib folder and paste the copied files from Downloadfreeglut-
MinGW-3.0.0-1.mp folder freeglut lib ×64 to the path C:\Program
Files\CodeBlocks\MinGW\lib. (If you have followed the step 9(b), avoid
doing this step, rather do step 11(b))

b. If not, then check for the lib folder in x86_64-w64-mingw32 folder. Paste the
copied files from Downloadfreeglut-MinGW-3.0.0-1.mp folder freeglut
lib to the path C:\Program Files\CodeBlocks\MinGW\x86_64-w64-
mingw32\lib.

12. Allow the contents to be merged with the folder for all the items.
13. Go to C:\Program Files\CodeBlocks\share\CodeBlocks\templates\wizard\glut
directory and open wizard.script file in notepad.
14. Search for the term “glut32” in the wizard.script file and replace all the occurrence in
with “freeglut”. Save the file.

15. Go to C:\Program Files\CodeBlocks\share\CodeBlocks\templates directory and open


glut.cbp file in notepad for editing.

16. Search for the term “glut32” in the glut.cbp file and replace all the occurrence in it
with “freeglut”. Save the file.

17. Now create a new GLUT project in codeblocks. Type a title of the project and enter
the GLUT’s location as installation directory of the GLUT compiler (the directory
used in step 8, i.e., C:\Program Files\CodeBlocks\MinGW\x86_64-w64-mingw32).
Click Next and then Finish.

First OpenGL Program:


Code:

#include<GL/freeglut.h>
void init(){
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); //Line C
glutInitWindowSize(640,480);
glutInitWindowPosition(1000,200);
glutCreateWindow("Simple Window");
}

void display()
{
glClearColor(0,0,1.0,1.0);
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}

int main(int argc,char **argv)


{
glutInit(&argc,argv); //Line A
init(); //Line B
glutDisplayFunc(display);
glutMainLoop();

return 0;
}

Output:
Difference between C & OpenGL
Differences between C and OpenGL:

Purpose:
C is a general-purpose programming language used for developing a wide range of software
applications, while OpenGL is a graphics rendering API used for creating 2D and 3D
graphics.

Syntax:
C has its own syntax, control structures, and libraries that enable developers to create
software applications, while OpenGL provides a set of functions and interfaces for graphics
rendering.

Abstraction level:
C is a low-level programming language that provides direct access to hardware and memory,
while OpenGL provides a higher level of abstraction by hiding the details of the graphics
hardware and providing a set of functions and interfaces that can be used to create graphics.

Implementation:
C can be implemented on a variety of platforms and hardware architectures, while OpenGL
requires an implementation that supports the specific hardware and operating system being
used.

Scope:
C can be used to develop a wide range of software applications, including systems
programming, operating systems, compilers, and more, while OpenGL is specifically
designed for graphics rendering.

Data type:
C provides a variety of data types for representing variables and values, while OpenGL
provides data types specific to graphics rendering, such as vertex buffers, textures, and
shaders.

Library:
C provides a wide range of libraries for performing various tasks, while OpenGL itself is a
library that provides a set of functions and interfaces for rendering graphics.

Compatibility:
C code can be compiled to run on a wide variety of platforms and hardware architectures,
while OpenGL code depends on the hardware and operating system used and will need to be
modified to be compatible with a variety of platforms. There are cases.
CG LAB EXP-2

DDA Line DrawingAlgorithm


1. Calculate the slope of the line using the formula:
slope = (y2 - y1) / (x2 - x1)

2. Determine the number of steps required to draw the line. This can be done by taking
the maximum difference between the x-coordinates and the y-coordinates, and then
rounding up to the nearest integer:
steps = max(abs(x2 - x1), abs(y2 - y1))

3. Calculate the increment in x and y coordinates for each step using the formula:
dx = (x2 - x1) / steps
dy = (y2 - y1) / steps

4. Initialise the starting point of the line to (x1, y1) and increment the x and y
coordinates by dx and dy respectively for each step.

5. Round off the x and y coordinates to the nearest integer to get the pixel coordinates
for each step.

6. Plot the pixels along the line using the calculated pixel coordinates.

DDA Code

#include <stdio.h>
#include <GL/glut.h>
#include <math.h>

void display() {
float x1 = -0.7f, y1 = -0.7f;
float x2 = 0.7f, y2 = 0.7f;
float dx = x2 - x1;
float dy = y2 - y1;
float steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy);
float x_inc = dx / steps;
float y_inc = dy / steps;
float x = x1, y = y1;
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINES);

for (int i = 0; i <= steps; i++) {


glVertex2f(x, y);
x += x_inc;
y += y_inc;
}
glEnd();
glFlush();
}

int main(int argc, char** argv) {


glutInit(&argc, argv);
glutCreateWindow("DDA Line Drawing Algorithm");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

Output:
Bresenham Line Drawing Algorithm

1. Determine the endpoints of the line segment to be drawn: (x1, y1) and (x2, y2).

2. Calculate the differences between the endpoints in the x and y directions: dx = abs(x2
- x1) and dy = abs(y2 - y1).

3. Determine the sign of the differences: sx = sign(x2 - x1) and sy = sign(y2 - y1). The
sign function returns -1 if the value is negative, 0 if the value is zero, and 1 if the
value is positive.

4. Initialise the error term to zero: error = 0.

5. Loop from x1 to x2, and for each x value, calculate the corresponding y value using
the error term:

Calculate the pixel coordinates: plot(x, y).

If the error term is greater than or equal to dx, increment y by sy and subtract dx
from the error term. Otherwise, leave y unchanged and
add dy to the error term.

Increment x by sx.

6. Repeat step 5 for each value of x until x equals x2.

Bresenham Code

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

int x1, y1, x2, y2;

void myInit() {
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0.0, 0.0, 0.0, 1.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0, 500, 0, 500);
}
void draw_pixel(int x, int y) {
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
}

void draw_line(int x1, int x2, int y1, int y2) {


int dx, dy, i, e;
int incx, incy, inc1, inc2;
int x,y;

dx = x2-x1;
dy = y2-y1;

if (dx < 0) dx = -dx;


if (dy < 0) dy = -dy;
incx = 1;
if (x2 < x1) incx = -1;
incy = 1;
if (y2 < y1) incy = -1;
x = x1; y = y1;
if (dx > dy) {
draw_pixel(x, y);
e = 2 * dy-dx;
inc1 = 2*(dy-dx);
inc2 = 2*dy;
for (i=0; i<dx; i++) {
if (e >= 0) {
y += incy;
e += inc1;
}
else
e += inc2;
x += incx;
draw_pixel(x, y);
}

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

void myDisplay() {
draw_line(x1, x2, y1, y2);
glFlush();
}

void main(int argc, char **argv) {

printf( "Enter (x1, y1, x2, y2)\n");


scanf("%d %d %d %d", &x1, &y1, &x2, &y2);

glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(0, 0);
glutCreateWindow("Bresenham's Line Drawing");
myInit();
glutDisplayFunc(myDisplay);
glutMainLoop();
}
Output
CG LAB EXP-3

a) W.A.P to draw a simple circle.

Code:

#include <GL/glut.h>
#include <cmath>

using namespace std;

const int WINDOW_WIDTH = 640;


const int WINDOW_HEIGHT = 480;
float PI=3.14159;
void init() {
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0, WINDOW_WIDTH, 0.0, WINDOW_HEIGHT);
}

void Circle(float x, float y, float radius) {


int i;
int lineAmount = 100; //# of triangles used to draw circle

//GLfloat radius = 0.8f; //radius


GLfloat twicePi = 2.0f * PI;

glBegin(GL_LINE_LOOP);
for(i = 0; i <= lineAmount;i++) {
glVertex2f(
x + (radius * cos(i * twicePi / lineAmount)),
y + (radius* sin(i * twicePi / lineAmount))
);
}
glEnd();
}

void display() {
glClear(GL_COLOR_BUFFER_BIT);

glColor3f(1.0, 1.0, 1.0); // set color to white


Circle(WINDOW_WIDTH/2.0, WINDOW_HEIGHT/2.0, 100.0); // draw circle at
center of window

glFlush();
}

int main(int argc, char **argv) {


glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow("Simple Circle");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

Output:
b) W.A.P to draw a circle using Bresenham circle
drawing algorithm.

Algorithm:
1. Start

2. Declare x, y, r, x c, y c and d as variables, where (x c, y c) are coordinates of the


center.

3. Set x = 0, y = r and d = 3 - 2r

4. Plot point (x + x c, y + y c)

5. If x < y then set d = d + 4x + 6 and x = x + 1

6. Else set d = d + 4(y - x) + 10, x = x + 1 and y = y - 1

7. Go to step 4 until x > y

Code:

#include <GL/glut.h>
#include <cmath>

const int WINDOW_WIDTH = 640;


const int WINDOW_HEIGHT = 480;

void init() {
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0, WINDOW_WIDTH, 0.0, WINDOW_HEIGHT);
}

void plotCirclePoints(int centerX, int centerY, 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 drawCircle(int centerX, int centerY, int radius) {


int x = 0, y = radius;
int d = 3 - 2 * radius;
while (x <= y) {
plotCirclePoints(centerX, centerY, x, y);
if (d < 0) {
d += 4 * x + 6;
}
else {
d += 4 * (x - y) + 10;
y--;
}
x++;
}
}

void display() {
glClear(GL_COLOR_BUFFER_BIT);

glColor3f(1.0, 1.0, 1.0); // set color to white


drawCircle(WINDOW_WIDTH/2, WINDOW_HEIGHT/2, 100); // draw circle at
center of window

glFlush();
}

int main(int argc, char **argv) {


glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow("Bresenham Circle");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

Output:
c) W.A.P to draw a circle using the Midpoint circle
drawing algorithm.

Algorithm:

1. Start

2. Declare x, y, r as variables, where (x, y) are coordinates of the center and r is the
radius of the circle.

3. Set x = 0, y = r and p = 1 - r

4. Plot point (x + x c, y + y c)

5. If p < 0 then set p = p + 2x + 3 and x = x + 1

6. Else set p = p + 2(x - y) + 5, x = x + 1 and y = y - 1

7. Go to step 4 until x > y

Code:
#include <GL/glut.h>
#include <cmath>

const int WINDOW_WIDTH = 640;


const int WINDOW_HEIGHT = 480;

void init() {
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0, WINDOW_WIDTH, 0.0, WINDOW_HEIGHT);
}

void plotCirclePoints(int centerX, int centerY, 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 drawCircle(int centerX, int centerY, int radius) {


int x = 0, y = radius;
int d = 1 - radius;
while (x <= y) {
plotCirclePoints(centerX, centerY, x, y);
if (d < 0) {
d += 2 * x + 3;
}
else {
d += 2 * (x - y) + 5;
y--;
}
x++;
}
}

void display() {
glClear(GL_COLOR_BUFFER_BIT);

glColor3f(1.0, 1.0, 1.0); // set color to white


drawCircle(WINDOW_WIDTH/2, WINDOW_HEIGHT/2, 100); // draw circle at
center of window

glFlush();
}

int main(int argc, char **argv) {


glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow("Midpoint Circle");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
Output:
CG LAB EXP-4

W.A.P to draw a simple ellipse.

Code:

#include <GL/glut.h>
#include <cmath>

const int WINDOW_WIDTH = 640;


const int WINDOW_HEIGHT = 480;

void init() {
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0, WINDOW_WIDTH, 0.0, WINDOW_HEIGHT);
}

void plotEllipsePoints(int centerX, int centerY, 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);
glEnd();
}

void drawEllipse(int centerX, int centerY, int rx, int ry) {


int x = 0, y = ry;
int rxSquare = rx * rx;
int rySquare = ry * ry;
int twoRxSquare = 2 * rxSquare;
int twoRySquare = 2 * rySquare;
int p;
int px = 0;
int py = twoRxSquare * y;

plotEllipsePoints(centerX, centerY, x, y);


p = std::round(rySquare - rxSquare * ry + 0.25 * rxSquare);
while (px < py) {
x++;
px += twoRySquare;
if (p < 0) {
p += rySquare + px;
}
else {
y--;
py -= twoRxSquare;
p += rySquare + px - py;
}
plotEllipsePoints(centerX, centerY, x, y);
}

p = std::round(rySquare * (x + 0.5) * (x + 0.5) + rxSquare * (y - 1) * (y - 1) - rxSquare *


rySquare);
while (y > 0) {
y--;
py -= twoRxSquare;
if (p > 0) {
p += rxSquare - py;
}
else {
x++;
px += twoRySquare;
p += rxSquare - py + px;
}
plotEllipsePoints(centerX, centerY, x, y);
}
}

void display() {
glClear(GL_COLOR_BUFFER_BIT);

glColor3f(1.0, 1.0, 1.0); // set color to white


drawEllipse(WINDOW_WIDTH/2, WINDOW_HEIGHT/2, 200, 100); // draw ellipse at
center of window with radii 200 and 100 pixels

glFlush();
}

int main(int argc, char **argv) {


glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow("Ellipse");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

Output:
CG LAB EXP-5

Draw Line, Rectangle, Arc and Circle using inbuilt


functions.

1. Line

Code:

#include <GL/glut.h>

void display() {
glClear(GL_COLOR_BUFFER_BIT); // Clear the screen

glColor3f(1.0, 1.0, 1.0); // Set line color to white


glBegin(GL_LINES); // Begin drawing a line
glVertex2f(-0.5, -0.5); // Specify the starting point of the line
glVertex2f(0.5, 0.5); // Specify the ending point of the line
glEnd(); // End drawing the line

glFlush(); // Flush the drawing commands


}

int main(int argc, char** argv) {


glutInit(&argc, argv); // Initialize GLUT
glutCreateWindow("OpenGL Line"); // Create a window with the specified title
glutDisplayFunc(display); // Set the display callback function
glutMainLoop(); // Start the main loop
return 0;
}
Output:

2. Rectangle

Code:

#include <GL/glut.h>

void rect_display() {
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glColor3f(0.0, 0.0, 1.0); // set rectangle color to blue
glBegin(GL_QUADS); // begin drawing rectangle
glVertex2f(-0.5, -0.5); // set first point of rectangle
glVertex2f(0.5, -0.5); // set second point of rectangle
glVertex2f(0.5, 0.5); // set third point of rectangle
glVertex2f(-0.5, 0.5); // set fourth point of rectangle
glEnd(); // end drawing rectangle
glFlush(); // flush the buffer
}

int main(int argc, char** argv) {


glutInit(&argc, argv);
glutCreateWindow("Rectangle");
glutDisplayFunc(rect_display);
glutMainLoop();
return 0;
}

Output:
3. Arc

Code:
#include <GL/glut.h> // include the GLUT library
#include <math.h> // include the math library

void display()
{
glClear(GL_COLOR_BUFFER_BIT); // clear the color buffer
glColor3f(1.0, 1.0, 1.0); // set the color to white

glMatrixMode(GL_PROJECTION); // switch to projection matrix


glLoadIdentity(); // reset projection matrix
gluOrtho2D(-1.0, 1.0, -1.0, 1.0); // set up an orthographic view

const float PI = 3.14159265;


float angle1 = 45.0f; // start angle of arc in degrees
float angle2 = 135.0f; // end angle of arc in degrees
float radius = 0.5f; // radius of arc

glBegin(GL_LINE_STRIP); // start drawing line strip


for (float angle = angle1; angle <= angle2; angle += 0.1f) {
float x = radius * cos(angle * PI / 180.0f);
float y = radius * sin(angle * PI / 180.0f);
glVertex2f(x, y); // add vertex to line strip
}
glEnd(); // end drawing line strip

glFlush(); // flush drawing commands


}

int main(int argc, char **argv)


{
glutInit(&argc, argv); // initialize GLUT
glutCreateWindow("Arc"); // create a window
glutDisplayFunc(display); // register display callback function
glutMainLoop(); // enter main loop
return 0;
}
Output:

4. Circle

Code:

#include <GL/glut.h>
#include <math.h>

void display() {
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glColor3f(0.0, 1.0, 1.0); // set circle color to green
glBegin(GL_TRIANGLE_FAN); // begin drawing circle
glVertex2f(0.0, 0.0); // set center point of circle
float radius = 0.5; // set radius of circle
int num_segments = 50; // set number of segments for circle
for (int i = 0; i <= num_segments; i++) {
float angle = i * 2.0f * M_PI / num_segments;
float x = radius * cosf(angle);
float y = radius * sinf(angle);
glVertex2f(x, y);
}
glEnd(); // end drawing circle
glFlush(); // flush the buffer
}

int main(int argc, char** argv) {


glutInit(&argc, argv); // initialize GLUT
glutCreateWindow("Circle Drawing"); // create window
glutDisplayFunc(display); // set display callback function
glutMainLoop(); // enter main event loop
return 0;
}

Output:
CG LAB EXP-6

Boundary Fill

Boundary fill is a computer graphics algorithm used to fill a closed area (a region) with a
specific colour or pattern. The algorithm starts from a given point inside the region and
proceeds to fill the region with the specified colour or pattern until it reaches the boundary of
the region. The boundary is defined by a different colour or pattern, which is typically used to
distinguish the region from its surroundings. The boundary fill algorithm can be implemented
in different ways, such as the 4-connected approach, where pixels are considered neighbours
if they share a common edge, or the 8-connected approach, where pixels are considered
neighbours if they share a common edge or corner. The boundary fill algorithm is commonly
used in computer graphics applications such as drawing and painting programs, where it
allows users to quickly fill in areas of colour without having to manually colour each
individual pixel.

Algorithm:
1. Start by selecting a point inside the region to be filled.

2. Set the color of the selected pixel to the fill color.

3. Check the 8-connected neighbours of the selected pixel.

4. If a neighbour is not already filled and its color is not the boundary color, set its color
to the fill color and recursively repeat step 3 for this neighbour.

5. Repeat steps 3-4 for all 4/8-connected neighbours of the selected pixel.

6. Continue this process until all pixels within the region are filled.
Boundary Fill 4-connected

Code:
#include <GL/glut.h>

void boundaryFill4(int x, int y, float* fillColor, float* borderColor) {


float interiorColor[3];
glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, interiorColor);
if ((interiorColor[0] != borderColor[0] || interiorColor[1] != borderColor[1] ||
interiorColor[2] != borderColor[2]) &&
(interiorColor[0] != fillColor[0] || interiorColor[1] != fillColor[1] || interiorColor[2] !=
fillColor[2])) {
glColor3fv(fillColor);
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
boundaryFill4(x + 1, y, fillColor, borderColor);
boundaryFill4(x - 1, y, fillColor, borderColor);
boundaryFill4(x, y + 1, fillColor, borderColor);
boundaryFill4(x, y - 1, fillColor, borderColor);
}
}

void display() {
glClear(GL_COLOR_BUFFER_BIT);

// draw a square
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_LINE_LOOP);
glVertex2i(100, 100);
glVertex2i(200, 100);
glVertex2i(200, 200);
glVertex2i(100, 200);
glEnd();

// perform boundary fill at (150, 150)


float fillColor[] = { 1.0f, 1.0f, 1.0f };
float borderColor[] = { 0.0f, 1.0f, 1.0f };
boundaryFill4(150, 150, fillColor, borderColor);

glFlush();
}

int main(int argc, char** argv) {


glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowSize(400, 400);
glutInitWindowPosition(100, 100);
glutCreateWindow("Boundary Fill 4-Connected");
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
gluOrtho2D(0, 400, 0, 400);
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

Output:
Boundary Fill 8-connected

Code:
#include <GL/glut.h>
#include <stdlib.h>

#define WINDOW_WIDTH 640


#define WINDOW_HEIGHT 480

// Set the fill color


GLfloat fillColor[3] = {0.0, 0.0, 1.0}; // Blue

// Set the boundary color


GLfloat borderColor[3] = {1.0, 1.0, 1.0}; // Black

// Get the color of a pixel


void getPixelColor(int x, int y, GLfloat color[3]) {
glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, color);
}

// Set the color of a pixel


void setPixelColor(int x, int y, GLfloat color[3]) {
glColor3fv(color);
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
glFlush();
}

// Recursive function to fill the region


void boundaryFill8(int x, int y) {
GLfloat interiorColor[3];
getPixelColor(x, y, interiorColor);
if ((interiorColor[0] != borderColor[0]) &&
(interiorColor[1] != borderColor[1]) &&
(interiorColor[2] != borderColor[2]) &&
(interiorColor[0] != fillColor[0]) &&
(interiorColor[1] != fillColor[1]) &&
(interiorColor[2] != fillColor[2])) {
setPixelColor(x, y, fillColor);
boundaryFill8(x+1, y);
boundaryFill8(x-1, y);
boundaryFill8(x, y+1);
boundaryFill8(x, y-1);
boundaryFill8(x+1, y+1);
boundaryFill8(x+1, y-1);
boundaryFill8(x-1, y+1);
boundaryFill8(x-1, y-1);
}
}

// Display the window


void display() {
glClearColor(0.0, 0.0, 0.0, 0.0); // Set the background color to white
glClear(GL_COLOR_BUFFER_BIT);

// Draw the border of the region


glColor3fv(borderColor);
glRecti(100, 100, 300, 300);

// Call the boundary fill algorithm


boundaryFill8(150, 150);

glFlush();
}

// Initialize the window


void init() {
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0, WINDOW_WIDTH, 0, WINDOW_HEIGHT);
}

// Main function
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow("Boundary Fill 8 Connected Algorithm");
glutDisplayFunc(display);
init();
glutMainLoop();
return 0;
}
Output:

Flood Fill

Flood fill is a computer graphics algorithm used to fill a closed region with a specific color or
pattern. The algorithm works by selecting a starting point inside the region to be filled and
then colouring all the neighbouring pixels that are not part of the boundary until the entire
region is filled.The algorithm is named after the idea of "flooding" the region with color
starting from the initial point. It is commonly used in painting software, graphic design
applications, and video game development.The flood fill algorithm can be implemented in
either a recursive or iterative manner. Recursive implementation uses function calls to fill
neighbouring pixels while iterative implementation uses a stack or queue to keep track of
pixels to be filled.The flood fill algorithm can be modified to work with patterns, gradients,
or textures. It can also be used in combination with other algorithms such as edge detection to
create more complex effects.
Flood Fill algorithm
1. Choose a starting point inside the region to be filled.

2. Check the color of the starting point.

3. Set the color of the starting point to the fill colour.

4. Check the neighbouring pixels of the starting point.

5. If a neighbouring pixel has the same color as the starting point and is not already
filled, set its color to the fill color and add it to the list of pixels to check.

6. Repeat step 5 for all neighbouring pixels.

7. Continue this process until there are no more pixels to check.

Flood Fill 4-connected

Code:
#include <GL/glut.h>
#include <stdlib.h>

#define WINDOW_WIDTH 640


#define WINDOW_HEIGHT 480

// Set the fill color


GLfloat fillColor[3] = {0.0, 0.0, 1.0}; // Blue

// Set the boundary color


GLfloat borderColor[3] = {0.0, 0.0, 0.0}; // Black

// Get the color of a pixel


void getPixelColor(int x, int y, GLfloat color[3]) {
glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, color);
}

// Set the color of a pixel


void setPixelColor(int x, int y, GLfloat color[3]) {
glColor3fv(color);
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
glFlush();
}

// Recursive function to fill the region


void floodFill4(int x, int y) {
GLfloat interiorColor[3];
getPixelColor(x, y, interiorColor);
if ((interiorColor[0] != borderColor[0]) &&
(interiorColor[1] != borderColor[1]) &&
(interiorColor[2] != borderColor[2]) &&
(interiorColor[0] != fillColor[0]) &&
(interiorColor[1] != fillColor[1]) &&
(interiorColor[2] != fillColor[2])) {
setPixelColor(x, y, fillColor);
floodFill4(x+1, y);
floodFill4(x-1, y);
floodFill4(x, y+1);
floodFill4(x, y-1);
}
}

// Display the window


void display() {
glClearColor(1.0, 1.0, 1.0, 1.0); // Set the background color to white
glClear(GL_COLOR_BUFFER_BIT);

// Draw the border of the region


glColor3fv(borderColor);
glRecti(100, 100, 300, 300);

// Call the flood fill algorithm


floodFill4(150, 150);

glFlush();
}

// Initialize the window


void init() {
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0, WINDOW_WIDTH, 0, WINDOW_HEIGHT);
}

// Main function
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow("Flood Fill 4 Connected Algorithm");
glutDisplayFunc(display);
init();
glutMainLoop();
return 0;
}

Output:
Flood Fill 8-connected

Code:

#include <GL/glut.h>
#include <stdlib.h>

#define WINDOW_WIDTH 640


#define WINDOW_HEIGHT 480

// Set the fill color


GLfloat fillColor[3] = {0.0, 0.0, 1.0}; // Blue

// Set the boundary color


GLfloat borderColor[3] = {0.0, 0.0, 0.0}; // Black

// Get the color of a pixel


void getPixelColor(int x, int y, GLfloat color[3]) {
glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, color);
}

// Set the color of a pixel


void setPixelColor(int x, int y, GLfloat color[3]) {
glColor3fv(color);
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
glFlush();
}

// Recursive function to fill the region


void floodFill8(int x, int y) {
GLfloat interiorColor[3];
getPixelColor(x, y, interiorColor);
if ((interiorColor[0] != borderColor[0]) &&
(interiorColor[1] != borderColor[1]) &&
(interiorColor[2] != borderColor[2]) &&
(interiorColor[0] != fillColor[0]) &&
(interiorColor[1] != fillColor[1]) &&
(interiorColor[2] != fillColor[2])) {
setPixelColor(x, y, fillColor);
floodFill8(x+1, y);
floodFill8(x-1, y);
floodFill8(x, y+1);
floodFill8(x, y-1);
floodFill8(x+1, y+1);
floodFill8(x+1, y-1);
floodFill8(x-1, y+1);
floodFill8(x-1, y-1);
}
}

// Display the window


void display() {
glClearColor(1.0, 1.0, 1.0, 1.0); // Set the background color to white
glClear(GL_COLOR_BUFFER_BIT);

// Draw the border of the region


glColor3fv(borderColor);
glRecti(100, 100, 300, 300);

// Call the flood fill algorithm


floodFill8(150, 150);

glFlush();
}

// Initialize the window


void init() {
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0, WINDOW_WIDTH, 0, WINDOW_HEIGHT);
}

// Main function
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow("Flood Fill 8 Connected Algorithm");
glutDisplayFunc(display);
init();
glutMainLoop();
return 0;
}
Output:

You might also like