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

cg writeup

Uploaded by

dusanesanika7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

cg writeup

Uploaded by

dusanesanika7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

ASSIGNMENT NO.

TITLE : Polygon filling using scan line algorithm :

PROBLEM STATEMENT: Write C++ program to draw a concave polygon and fill it with desired color
using scan fill algorithm. Apply the concept of inheritance.

OBJECTIVE:

1. To understand scan line algorithm to fill polygon.

2. To understand the implementation of Inheritance.

THEORY:

Inheritance in C++:-

The capability of a class to derive properties and characteristics from another class is called Inheritance.
Inheritance is one of the most important feature of Object Oriented Programming.

Sub Class: The class that inherits properties from another class is called Sub class or Derived class.

Super Class:The class whose properties are inherited by sub class is called Base Class or Super class.

Implementing inheritance in C++: For creating a sub-class which is inherited from the base class we have
to follow the below syntax.

Syntax:

class subclass_name : access_mode base_class_name

//body of subclass

};

Here, subclass_name is the name of the sub class, access_mode is the mode in which you want
to inherit this sub class for example: public, private etc. and base_class_name is the name of the
base class from which you want to inherit the sub class.

Note: A derived class doesn’t inherit access to private data members.

However, it does inherit a full parent object, which contains any private members which that class
declares.

filter_none

edit

play_arrow

brightness_4

// C++ program to demonstrate implementation of Inheritance


#include <bits/stdc++.h>

using namespace std;

//Base class

class Parent

public:

int id_p;

};

// Sub class inheriting from Base Class(Parent)

class Child : public Parent

public:

int id_c;

};

//main function

int main()

Child obj1;

// An object of class child has all data members and member functions of class parent

obj1.id_c = 7;

obj1.id_p = 91;

cout << "Child id is " << obj1.id_c << endl;

cout << "Parent id is " << obj1.id_p << endl;

return 0;

Scan line:-
The scan line fill algorithm is an ingenious way of filling in irregular polygons. The algorithm begins with a
set of points. Each point is connected to the next, and the line between them is considered to be an edge
of the polygon. The points of each edge are adjusted to ensure that the point with the
smaller y value appears first. Next, a data structure is created that contains a list of edges that begin
on each scan line of the image. The program progresses from the first scan line upward. For
each line, any pixels that contain an intersection between this scan line and an edge of the polygon

are filled in. Then, the algorithm progresses along the scan line, turning on when it reaches a polygon pixel
and turning off when it reaches another one, all the way across the scan line.

The basic scan-line algorithm is as follows:

Find the intersections of the scan line with all active edges of the polygon

Sort the intersections by increasing x coordinate

Fill in all pixels between pairs of intersections that lie interior to the polygon

Process involved:

The scan-line polygon-filling algorithm involves

• the horizontal scanning of the polygon from its lowermost to its topmost vertex,

• identifying which edges intersect the scan-line,

• finally drawing the interior horizontal lines with the specified fill color process.

Algorithm

CONCLUSION: Thus we have implemented scan line algorithm to fill

polygon successfully.
ASSIGNMENT NO. 2

TITLE : Line clipping using Cohen-Sutherland algorithm.

PROBLEM STATEMENT : Write C++ program to implement Cohen Southerland line clipping
algorithm.

OBJECTIVE:

1. To understand line clipping algorithm.

2. To understand intersection and outcode concepts.

THEORY:

The Cohen-Sutherland line clipping algorithm quickly detects and dispenses with two common and trivial
cases. To clip a line, we need to consider only its endpoints. If both endpoints of a line lie inside the
window, the entire line lies inside the window. It is trivially accepted and needs no clipping. On the other
hand, if both endpoints of a line lie entirely to one side of the window, the line must lie entirely outside
of the window. It is trivially rejected and needs to be neither clipped nor displayed
ALGORITHM:

CONCLUSION: Thus, we have successfully implemented line clipping algorithm.


ASSIGNMENT NO. 3

TITLE : Program to draw a given pattern using any line and circle drawing algorithm.

PROBLEM STATEMENT : Write C++ program to draw the following pattern. Use DDA line and
Bresenham‘s circle drawing algorithm. Apply the concept of encapsulation

OBJECTIVE:

1. To understand the concept and use of line drawing algorithms.

2. To understand the concept and use of circle drawing algorithms

THEORY:

Line Drawing Algorithms:

DDA (Digital Differential Analyzer): Scan conversion line algorithm based on ∆ x or ∆ y. Sample
the line at unit interval in one co-ordinate and determine corresponding integer value. Faster
method than y= mx+ b using but may specifies inaccurate pixel section. Rounding off operations
and floating point arithmetic operations are time consuming. DDA is used in drawing straight
line to form a line, triangle or polygon in computer graphics.

DDA analyzes samples along the line at regular interval of one coordinate as the integer and for the
other coordinate it rounds off the integer that is nearest to the line. Therefore as the line progresses
it scan the first integer coordinate and round the second to nearest integer. Therefore a line drawn using
DDA for x coordinate it will be x0 to x1 but for y coordinate it will be y=ax+ b and to draw function it will
be fn(x, y rounded off).
Bresenham’s:

It is much accurate and much more efficient than DDA. An algorithm which determines which order to
form a close approximation to a straight line between two given points. It is commonly used to draw lines
on a computer screen, as it uses only integer addition, subtraction and bit shifting, all of which are very
cheap operations in standard computer architectures. It scans the coordinates but instead of rounding
them off it takes the incremental value in account by adding or subtracting and therefore can be
used for drawing circle and curves.

Therefore if a line is to be drawn between two points x and y then next coordinates will be( xa+1, ya)
and (xa+1, ya+1) where a is the incremental value of the next coordinates and difference between
these two will be calculated by subtracting or adding the equations formed by them.

Bresenham’s circle generation algorithm:

This algorithm does only integer arithmetic which makes it faster than floating point. We are
creating only one octant i.e. from 90 to 45 degree. We derive other seven octants of circle by symmetry
property

The circle is generated by considering center point as origin with radius ‘r’.

The algorithm calculates one new pixel per step.

To draw Circle :

Now, consider a very small continuous arc of the circle interpolated below, passing by the

discrete pixels as shown. At any point (x,y), we have two choices – to choose the pixel on east of it, i.e.
N(x+1,y) or the south-east pixel S(x+1,y-1). To choose the pixel, we determine the errors involved with
both N & S which are f(N) and f(S) respectively and whichever gives the lesser error, we choose that pixel.
Let di = f(N) + f(S), where d can be called as “decision parameter”.

if (di<=0), then, N(x+1,y) is to be chosen as next pixel i.e. xi+1 = xi+1 and yi+1 = yi , and

if (di>0), then, S(x+1,y-1) is to be chosen as next pixel i.e. xi+1 = xi+1 and yi+1 = yi -1.

We know that for a circle, the equation of circle is

x2+ y2 = r2

Where

x = x-coordinate

y = y-coordinate

r = radius of the circle

Errors can be represented as

if (di<=0), then

di+1 = di + 4xi + 6

if (di>0),

di+1 = di + 4(xi - yi ) + 10

ALGORITHM:

Line Drawing Algorithm:

Circle Drawing Algorithm:

CONCLUSION: Thus pattern drawing using line and circle drawing algorithms are successfully
implemented.
ASSIGNMENT NO. 4

TITLE : Performing 2D transformations

PROBLEM STATEMENT :

Write C++ program to draw 2-D object and perform following basic transformations, Scaling

Translation, Rotation. Apply the concept of operator overloading.

OBJECTIVE:

1. To understand 2D transformations

2. To understand matrix calculations

THEORY:

We have to perform 2D transformations on 2D objects. Here we perform transformations on a line


segment.

The 2D transformations are:

1. Translation

2. Scaling

3. Rotation

1. Translation: Translation is defined as moving the object from one position to another position Along
straight line path.

We can move the objects based on translation distances along x and y axis. tx denotes translation

distance along x-axis and ty denotes translation distance along y axis.


Translation Distance: It is nothing but by how much units we should shift the object from one

location to another along x, y-axis. Consider (x,y) are old coordinates of a point. Then the new

coordinates of that same point (x’,y’) can be obtained as follows:

X’=x+tx

Y’=y+ty

We denote translation transformation as P. we express above equations in matrix form as:

2. Scaling: scaling refers to changing the size of the object either by increasing or decreasing. We

Will increase or decrease the size of the object based on scaling factors along x and y-axis.

If (x, y) are old coordinates of object, then new coordinates of object after applying scaling

transformation are obtained as:

x’=x*sx

y’=y*sy.

sx and sy are scaling factors along x-axis and y-axis. we express the above equations in matrix

form as:
3. Rotation: A rotation repositions all points in an object along a circular path in the plane

centered at the pivot point. We rotate an object by an angle theta. New coordinates after rotation

depend on both x and y

x’ = xcosθ -y sinθ

y’ = xsinθ+ ycosθ

or in matrix form:

ALGORITHM:

CONCLUSION: Thus we have obtained scaled, translated and rotated object (line) by using matrix
calculations.
ASSIGNMENT NO. 5

TITLE: Fractals Generation

PROBLEM STATEMENT : Write a C++ program to generate fractals .

OBJECTIVE: To understand the concept of Fractals and to implement in C++ language

THEORY:

Koch Curve:

The Koch curve fractal was first introduced in 1904 by Helge von Koch. It was one of the first fractal objects
to be described.

To create a Koch curve Create a line and divide it into three parts.

The second part is now rotated by 60°. Add another part which goes from the end of part 2 to the
beginning of part Repeat step 1 to step 3 with each part of the line.

We will get following Koch curve as number of iteration goes on increasing

Step 1: In Iteration 0, we have a horizontal line.

Step 2: In Iteration 1, line is divided into 3 equal parts. Middle part of a line is rotated in 600 , because it
forms a perfect an equilateral triangle as shown below:
Here, (x1,y1) and (x2, y2) is accepted from user.

Now, we can see line is divided into 3 equal segments:

segment((x1,y1),(x3,y3)), segment((x3,y3),(x4,y4)),segment((x4,y4),(x2,y2)) in above figure.

Coordinates of middle two points will be calculated as follows:

x3 = (2*x1+x2)/3;

y3 = (2*y1+y2)/3;

x4 = (x1+2*x2)/3;

y4 = (y1+2*y2)/3;

In our curve, middle segment((x3,y3),(x4,y4)) will not be drawn. Now, in order to find out
coordinates of the top vertex (x,y) of equilateral triangle, we have rotate point (x4,y4) with respect to
arbitrary point (x3,y3) by angle of 60 degree in anticlockwise direction. After performing this rotation, we
will get rotated coordinates (x, y) as:

x=x3+(x4-x3)*cosθ+(y4-y3)*sinθ

y=y3+(x4-x3)*sinθ+(y4-y3)*cosθ

Step 3: In iteration 2, you will repeat step 2 for every segment obtained in iteration1. In this way, you
can generate Koch curve for any number of iterations.

ALGORITHM:

CONCLUSION: Thus we have implemented C++ program to generate fractals successfully


ASSIGNMENT NO. 6

TITLE: Simulation using OpenGL (Stack or queue /3-D Cube/Sunrise & sunset)

PROBLEM STATEMENT :

OBJECTIVE: To understand and implement OpenGL concepts.

THEORY:

Open Graphics Library (OpenGL) is a cross-language (language independent), cross-platform


(platform independent) API for rendering 2D and 3D Vector Graphics (use of polygons to represent
image). OpenGL is a low-level, widely supported modeling and rendering software package,

available across all platforms. It can be used in a range of graphics applications, such as
games, CAD design, or modeling. OpenGL API is designed mostly in hardware.

Getting started with OpenGL

Overview of an OpenGL program

 Main
 Open window and configure frame buffer (using GLUT for example)
 Initialize GL states and display (Double buffer, color mode, etc.)
 Loop
 Check for events

if window event (resize, unhide, maximize etc.)

modify the viewport

and Redraw

else if input event (keyboard and mouse etc.)

handle the event (such as move the camera or change the state)

and usually draw the scene

 Redraw
 Clear the screen (and buffers e.g., z-buffer)
 Change states (if desired)
 Render
 Swap buffers (if double buffer)

OpenGL Syntax

All functions have the form: gl*

glVertex3f() – 3 means that this function take three arguments, and f means that the type of those
arguments is float.
glVertex2i() – 2 means that this function take two arguments, and i means that the type of those
arguments is integer

All variable types have the form: GL*

In OpenGL program it is better to use OpenGL variable types

(portability)

Glfloat instead of float

Glint instead of int

Writing an OpenGL Program with GLUT

An OpenGL program using the three libraries listed above must include the appropriate headers. This
requires the following three lines:

#include <GL/gl.h>

#include <GL/glu.h>

#include <GL/glut.h>

Before OpenGL rendering calls can be made, some initialization has to be done. With GLUT, this consists
of initializing the GLUT library, initializing the display mode, creating the window, and setting up
callback functions.

The following lines initialize a full color, double buffered display:

glutInit(&argc, argv);

glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);

Double buffering means that there are two buffers, a front buffer and a back buffer. The front buffer is
displayed to the user, while the back buffer is used for rendering operations. This prevents flickering
that would occur if we rendered directly to the front buffer.

Next, a window is created with GLUT that will contain the viewport which displays the OpenGL front
buffer with the following three lines:

glutInitWindowPosition(px, py);

glutInitWindowSize(sx, sy);

glutCreateWindow(name);

To register callback functions, we simply pass the name of the function that

handles the event to the appropriate GLUT function.

glutReshapeFunc(reshape);
glutDisplayFunc(display);

Here, the functions should have the following prototypes:

void reshape(int width, int height);

void display();

In this example, when the user resizes the window, reshape is called by GLUT, and when the display
needs to be refreshed, the display function is called. For animation, an idle event handler that takes
no arguments can be created to call the display function to constantly redraw the scene with
glutIdleFunc. Once all the callbacks have been set up, a call to glutMainLoop allows the program to
run.

In the display function, typically the image buffer is cleared, primitives are rendered to it, and the results
are presented to the user. The following line clears the image buffer, setting each pixel color to the
clear color, which can be configured to be any color:

glClear(GL_COLOR_BUFFER_BIT);

The next line sets the current rendering color to blue. OpenGL behaves like a state machine, so certain
state such as the rendering color is saved by OpenGL and used automatically later as it is needed.

glColor3f(0.0f, 0.0f, 1.0f);

To render a primitive, such as a point, line, or polygon, OpenGL requires that a call to glBegin is
made to specify the type of primitive being rendered.

glBegin(GL_LINES);

Only a subset of OpenGL commands is available after a call to glBegin. The main command that is used is
glVertex, which specifies a vertex position.

In GL LINES mode, each pair of vertices define endpoints of a line segment.

In this case, a line would be drawn from the point at ( x0, y0) to (x1,y1).

glVertex2f(x0, y0); glVertex2f(x1, y1);

A call to glEnd completes rendering of the current primitive.

glEnd();

Finally, the back buffer needs to be swapped to the front buffer that the user will see, which GLUT can
handle for us:

glutSwapBuffers();

ALGORITHM:
CONCLUSION: Thus, we have successfully implemented the C++ program for Simulation using OpenGL

You might also like