Академический Документы
Профессиональный Документы
Культура Документы
Lab Manual
Prepared by,
SE COMP
CG Lab Manual SE COMP, Sem-II, 2018-19
2. Problem analysis: Identify, formulate, research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools, including prediction and modeling to complex engineering activities,
with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.
Course Objectives:
1. To acquaint the learner with the basic concepts of Computer Graphics
2. To learn the various algorithms for generating and rendering graphical figures
3. To get familiar with mathematics behind the graphical transformations
4. To understand and apply various methods and techniques regarding projections,
animation, shading, illumination and lighting
Course Outcomes:
On completion of the course, student will be able to–
1. Apply mathematics and logic to develop Computer programs for elementary graphic
operations
2. Develop scientific and strategic approach to solve complex problems in the domain of
Computer Graphics
3. Develop the competency to understand the concepts related to Computer Vision and
Virtual reality
4. Apply the logic to develop animation and gaming programs
CG Lab Manual SE COMP, Sem-II, 2018-19
CG Lab Manual SE COMP, Sem-II, 2018-19
CG Lab Manual SE COMP, Sem-II, 2018-19
INDEX
CG Lab Manual SE COMP, Sem-II, 2018-19
3 3A Write C++ program to draw 2-D object and perform 1,3 1,6
following basic transformations,
a) Scaling
b) Translation
c) Rotation
Use operator overloading.
3B Write C++ program to implement translation, sheer, rotation 1,3 1,6
and scaling transformations on equilateral triangle and
rhombus.
3C Write a program to implement scaling, translation on 3-D 1,3 1,6
cube using OpenGL.
4 7 Write C++ program for line drawing using DDA algorithm 1,2 1
with patterns such as solid, dotted, dashed, dash dot and
thick.
5 8 Write Java program to draw a convex polygon and fill it 1,3 1,4
with desired color using Seed fill algorithm. Use mouse
interfacing to draw polygon.
CG Lab Manual SE COMP, Sem-II, 2018-19
6 9 Write C++ program to fill polygon using scan line 1,2 1,4
algorithm.
7 10 Write C++ program to implement Cohen-Sutherland line 1,2,3 1
clipping algorithm for given window.
8 11 Write C++/Java program to draw any object such as flower/ 1,2 1,2
waves using any curve generation techniques
9 12 Write C++/Java/OpenGL program to generate fractal 1,2 1,7
patterns by using Koch curves.
10 13 Write C++ program to simulate any one of or similar scene- 1,4 1,3,6
Clock with pendulum
National Flag hoisting
Vehicle/boat locomotion
Water drop falling into the water and generated
waves after impact
Use Object oriented programming concepts to implement the problem statements. Implement
programs by using C++ /Java/OpenGL programming language.
Software Required:
1. 64 bit open source operating system
2. Geany, Qt creator
3. Eclipse version 3.8
Write-ups must include:
Group:
Assignment No.
Title
Problem Statement
Prerequisites
Course Objectives
Course Outcomes
Theory(in brief)
Algorithm
Test Cases
Conclusion
FAQs:
ASSIGNMENT NO: 1
AIM: To learn Basic Graphics primitives.
PREREQUISITES:
COURSE OBJECTIVE:
THEORY:
● Text Editor:
A text editor is a type of program used for editing plain text files.
Text editors are often provided with operating systems or software development packages,
and can be used to change configuration files and programming language source code.
● Graphics Editor :
A raster graphics editor is a computer program that allows users to paint and edit pictures
interactively on the computer screen and save them in one of many popular "bitmap" or
"raster" formats such as JPEG, PNG, GIF and TIFF. Usually an image viewer is preferred
over a raster graphics editor for viewing images .Some editors specialize in the editing of
photo-realistic images such as the popular Adobe Photoshop, while others are more geared to
artist-created illustrations.
Graphics mode Initialization :
First of all we have to call the initgraph function that will initialize the graphics mode on the
computer. Initigraph have the following prototype.
void initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver);
Initgraph initializes the graphics system by loading a graphics driver from disk (or validating a
registered driver) then putting the system into graphics mode.Initgraph also resets all graphics
settings(color, palette current position, viewport)to their defaults, then resets graphresult to 0.
CG Lab Manual SE COMP, Sem-II, 2017-18
*graphdriver Integer that specifies the graphics driver to be used. You can give graphdriver a
value using a constant of the graphics_drivers enumeration type.
*graphmode Integer that specifies the initial graphics mode(unless *graphdriver = DETECT).
If *graphdriver = DETECT, initgraph sets *graphmode to the highest resolution available for the
detected driver. You can give *graphmode a value using a constant of the graphics_modes
enumeration type.
*pathtodriver Specifies the directory path where initgraph looks for graphics drivers
(*.BGI) first.
*graphdriver and *graphmode must be set to valid graphics_drivers and graphics_mode values or
you'll get unpredictable results. (The exception is graphdriver = DETECT.)
Graphics Primitives:
Function Description
It initializes the graphics system by loading the passed graphics driver
then changing the system into graphics mode.
initgraph int gd,gm;
gd=DETECT;
initgraph(&gd,&gm,NULL);
It returns the maximum X & Y coordinate in current graphics mode and
getmaxx driver.
getmaxy Syntax: int getmaxx()
int getmaxy()
It changes the current drawing colour. Default colour is white. Each color
is assigned a number, like BLACK is 0 and RED is 4. Here we are using
setcolor
colour constants defined inside graphics.h header file.
setcolor(int color)
It is used to get intensity of current pixel
getpixel int getpixel(int x, int y)
Function Description
WIDE_DOT_FILL 10 Widely spaced dot fill
CLOSE_DOT_FILL 11 Closely spaced dot fill
USER_FILL 12 User-defined fill pattern
It is used to fill a closed area with current fill pattern and fill color. It
floodfill takes any point inside closed area and color of the boundary as input.
floodfill(int x, int y, int color)
It clears the screen, and sets current position to (0, 0).
cleardevice
cleardevice();
It is used to determine whether a key is pressed or not. It returns a non-
kbhit zero value if a key is pressed otherwise zero.
Kbhit()
It is used to suspend execution of a program for a M milliseconds.
delay
delay(miliseconds)
It unloads the graphics drivers and sets the screen back to text mode.
closegraph
closegraph();
CG Lab Manual SE COMP, Sem-II, 2017-18
PROBLEM STATEMENT A. Write C++/Java program to draw line using DDA and
Bresenham‘s algorithm. Inherit pixel class and Use function overloading.
PROBLEM STATEMENT B. Write C++/Java program to draw the following pattern using any Line
drawing algorithms.
PREREQUISITES:
COURSE OBJECTIVE:
1. Apply mathematics and logic to develop Computer programs for elementary graphic
operations
THEORY:
Line is denoted by two points P1(x1, y1) and P2(x2,y2). Mathematical equation for line is
y=mx+b where m is slope and b is intercept.
4 Δx=(x2-x1)/length ; Δy=(y2-y1)/length
5 x=x1+0.5*Sign(Δx)
6 y=y1+0.5 *Sign(Δy)
7 plot pixel(x,y)
8 while(i<length)
x=x+Δx
y=y+Δy
plot(x,y)
i=i+1
end while
9 Stop
1. It is the simplest algorithm and it does not require special skills for implementation.
2. It is a faster method for calculating pixel positions than the direct use of equation y=mx + b. It
eliminates the multiplication in the equation by making use of raster characteristics, so that
appropriate increments are applied in the x or y direction to find the pixel positions along the line
path.
Algorithm :
2 Calculate the delta X and delta Y as delta Dx=|x2-x1| and delta Dy=|y2-y1|
7 If we are using octant symmetry property to plot the pixel then until (i<=delta x) we have
to perform following steps
while(e>=0)
Increase y by 1
Update e by e=e-2*delta x
}
increase x by 1
Update e by e=e+2*delta y
Advantages of Bresenham’s Line Drawing algorithm
1. Bresenham’s algorithm does not round off but takes the incremental value in its
operation.
CG Lab Manual SE COMP, Sem-II, 2017-18
2. Bresenham’s algorithm is less expensive than DDA algorithm as it uses only addition
and subtraction.
3. Bresenham’s algorithm is faster than DDA algorithm in line drawing because it
performs only addition and subtraction in its calculation and uses only integer arithmetic
so it runs significantly faster.
Test Cases
T_ID T_Name Condition to test Expected outcome Pass/Fail
T_P1 End point Given end points are Out will be displayed on
Checking within X max and Y the screen
max of screen
Given end points are Output will not be
beyond X max and Y displayed
max of screen
CONCLUSION: Hence we have studied and implemented Bresenham’s and DDA line drawing
algorithms. Bresenhams line drawing algorithm is faster and produce smooth line.
FAQ’s
1. Compare DDA and Bresenham’s Line Drawing Algorithms
CG Lab Manual SE COMP, Sem-II, 2017-18
Ans :
DDA Bresenham’s
Arithmetic DDA algorithm uses floating Bresenhams algorithm uses
points i.e. Real Arithmetic. fixed points i.e. Integer
Arithmetic.
Operations DDA algorithm uses Bresenhams algorithm uses
multiplication and division in only subtraction and addition
its operations. in its operations.
Round Off DDA algorithm round off the Bresenhams algorithm does
coordinates to integer that is not round off but takes the
nearest to the line. incremental value in its
operation.
Expensive DDA algorithm uses an Bresenhams algorithm is less
enormous number of floating- expensive than DDA algorithm
point multiplications so it is as it uses only addition and
expensive. subtraction.
2. What is Aliasing?
Ans: Stair case or jagged line effect is called aliasing. Minimizing aliasing effect is called
antialiasing. Super sampling and area sampling are techniques for antialiasing.
3. Use of Floor and ceil function in DDA algorithm
Ans: The C library function double floor(double x) returns the largest integer value less than or
equal to x.
The C library function double ceil(double x) returns the smallest integer value greater than or
equal to x.
4. What is Antialising?
Ans: In computer graphics, antialiasing is a technique for minimizing jaggies- stairstep-like.
Aliasing is staircase or jagged line effect.
5. Rasterize the points for line (4,9) to (7,7) using DDA line drawing algorithm.
6. Rasterize the points for line (4,4) to (-12,-9) using DDA line drawing algorithm.
7. Rasterize the points for line (4,9) to (7,7) using Bresenhams line drawing algorithm.
8. Rasterize the points for line (4,4) to (12,9) using Bresenhams line drawing algorithm.
PREREQUISITES:
COURSE OBJECTIVE:
1. To acquaint the learner with the basic concepts of Computer Graphics
2. To learn the various algorithms for generating and rendering graphical figures
COURSE OUTCOME:
1. Apply mathematics and logic to develop Computer programs for elementary graphic
operations
THEORY:
Circle
We can reduce our calculation drastically (8th fraction ) by making use of the fact that a circle has
8 way symmetry. Thus after calculating a pixel position (x,y) to be plotted, we get 7 other points
on the circle corresponding to it. These are:
(x,y);(x,-y);(-x,y);(-x,-y);(y,x);(y,-x);(-y,x);(-y,-x);
CG Lab Manual SE COMP, Sem-II, 2017-18
1. Accept radius and center co-ordinates from user and plot first point on circumference of
circle (x,y) = (0,r)
3.If we are using octant symmetry property to plot the pixel then until (x<y) we have to
If(d<=0)
Update d by d=d+4x+6 and increase x by 1
Else
Update d by d=d+4(x-y)+10 and increase x by 1
and decrease y by 1
5. Move and calculate the pixel position (x,y) on to the circular path .
Test Cases
T_ID T_Name Condition to test Expected outcome Pass/Fail
T_C1 Center input center is origin Complete circle will not
testing be displayed
Center is shifted to Complete circle will be
mid point displayed
CONCLUSION: Circle can be drawn using eight way symmetry. Midpoint & Bresenham’s
circle algorithms are implemented.
FAQ’s :
Ans: Circle can be drawn by drawing 1/8th part. Eight pixels can be drawn by one pixel only.
6. Rasterize the points for circle having center (0,0) radius=3 using Bresenhams circle
drawing algorithm.
7. Rasterize the points for circle having center (0,0) radius=3 using Midpoint circle drawing
algorithm.
OUTPUT: Printout of program with output.
GROUP: A
CG Lab Manual SE COMP, Sem-II, 2017-18
ASSIGNMENT NO: 3
AIM: To apply the basic 2D transformations such as translation, Scaling, Rotation for
a given 2D object.
PROBLEM STATEMENT A : Write C++/Java program to draw 2-D object and perform
following basic transformations,
a) Scaling
b) Translation
c) Rotation
Use operator overloading.
PREREQUISITES:
COURSE OBJECTIVE:
1. To acquaint the learner with the basic concepts of Computer Graphics
2. To get familiar with mathematics behind the graphical transformations
COURSE OUTCOME:
1. Develop scientific and strategic approach to solve complex problems in the domain of
Computer Graphics
THEORY:
A. Transformations:
Transformations allow us to uniformly alter the entire picture. The geometric transformations
considered here - translation, scaling and rotation are expressed in terms of matrix multiplication.
Example:
CG Lab Manual SE COMP, Sem-II, 2017-18
Homogenous Coordinates
To perform a sequence of transformation such as translation followed by rotation and scaling, we
need to follow a sequential process −
To shorten this process, we have to use 3×3 transformation matrix instead of 2×2 transformation
matrix. To convert a 2×2 matrix to 3×3 matrix, we have to add an extra dummy coordinate W.
In this way, we can represent the point by 3 numbers instead of 2 numbers, which is called
Homogenous Coordinate system. In this system, we can represent all the transformation
equations in matrix multiplication.
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.
Scaling can be achieved by multiplying the original coordinates of the object with the scaling
factor to get the desired result.
The scaling factor SX, SY scales the object in X and Y direction respectively. The above
equations can also be represented in matrix form as below −
X’ X Sx 0
Y’ = Y
0 Sy
scaling is performed about the origin (0,0) not about the center of the line/polygon/whatever
uniform scaling: Sx = Sy
differential scaling Sx != Sy -> alters proportions
CG Lab Manual SE COMP, Sem-II, 2017-18
If we provide values less than 1 to the scaling factor S, then we can reduce the size of the object.
If we provide values greater than 1, then we can increase the size of the object.
Rotation
In rotation, we rotate the object at particular angle θ (theta) from its origin. From the following
figure, we can see that the point P(X, Y) is located at angle φ from the horizontal X coordinate
with distance r from the origin.
Using standard trigonometric the original coordinate of point P(X, Y) can be represented as −
X = r cosϕ ......(1)
Y = r sinϕ ......(2)
Same way we can represent the point P’ (X’, Y’) as −
x′ = r cos(ϕ+θ) = r cosϕ cosθ − r sinϕ sinθ .......(3)
y′ = r sin(ϕ+θ) = r cosϕ sinθ + r sinϕ cosθ.......(4)
Substituting equation (1) & (2) in (3) & (4) respectively, we will get
x′ = x cosθ –y sinθ
y′ = x sinθ + y cosθ
Representing the above equation in matrix form,
X’ X’ cos θ sin θ
Y’ = Y’ -sin θ cos θ
0 Sy
OR P’ = P . R
Where R is the rotation matrix
cos θ sin θ
R= -sin θ cos θ
R=
Translation
A translation moves an object to a different position on the screen. You can translate a point in
2D by adding translation coordinate (tx, ty) to the original coordinate (X, Y) to get the new
coordinate (X’, Y’).
Translation Distance: It is nothing but by how much units we should shift the object from one
location to another along x, y-axis.
X’ = X + tx
Y’ = Y + ty
The pair (tx, ty) is called the translation vector or shift vector. The above equations can also be
represented using the column vectors.
P = [X] / [Y]
p' = [X′] / [Y′]
T = [tx] / [ty]
We can write it as - P’ = P + T
Shear
A transformation that slants the shape of an object is called the shear transformation. There are
two shear transformations X-Shear and Y-Shear. One shifts X coordinates values and other shifts
Y coordinate values. However; in both the cases only one coordinate changes its coordinates and
other preserves its values. Shearing is also termed as Skewing.
X-Shear
CG Lab Manual SE COMP, Sem-II, 2017-18
The X-Shear preserves the Y coordinate and changes are made to X coordinates, which causes
the vertical lines to tilt right or left as shown in below figure.
1 0 0
Shx 1 0
Xsh =
0 0 1
X' = X + Shx . Y
Y’ = Y
Y-Shear
The Y-Shear preserves the X coordinates and changes the Y coordinates which causes the
horizontal lines to transform into lines which slopes up or down as shown in the following
figure.
0 1 0
Ysh =
0 0 1
Y’ = Y + Shy . X
X’ = X
Reflection
Reflection in computer graphics is used to emulate reflective objects like mirrors and shiny
surfaces.
Homogeneous Matrices:
Translation Scaling
Sx 0 0
1 0 0
0 Sy 0
0 1 0
0 0 1
Tx Ty 1
cosθ sinθ 0 -1 0 0
0 -1 0
-sinθ cosθ 0
0 0 1
0 0 1
X- Shear Y-Shear
1 0 0 1 Shy 0
Shx 1 0 0 1 0
0 0 1 0 0 1
CG Lab Manual SE COMP, Sem-II, 2017-18
B. OpenGL
Point Primitives: This will cause OpenGL to interpret each individual vertex in the stream as a
point.
GL_POINTS
Line Primitives:
There are 3 kinds of line primitives, based on different interpretations of a vertex stream.
CG Lab Manual SE COMP, Sem-II, 2017-18
Algorithm:
1. Read input object in the form of matrix
2. Multiply input matrix with transformation matrix
3. Repeat same for all transformations
4. Display transformed object
5. stop
OOP’s concepts used
2. Class
3. Operator Overloading
PROBLEM STATEMENT: Write C++/Java program for line drawing using DDA or
Bresenhams algorithm with patterns such as solid, dotted, dashed, dash dot and thick.
PREREQUISITES:
COURSE OBJECTIVE:
COURSE OBJECTIVE:
THEORY:
There are different line styles like thin line, thick line, dotted line and dashed line.
Solid line
Thick line
Dotted line
Dashed line
Dash_ Dotted line
Thick Line:
To produce thick line we have to run to line drawing algorithms in parallel to find pixel along the
line edges.
Wy
CG Lab Manual SE COMP, Sem-II, 2017-18
Algorithm:
Where,
Wy=(w-1)/2 [((x2-x1)2+(y2-y1)2 )]1/2/|x2-x1|
We have left boundary between the points (x1-wx, y1) and (x2-wx, y2) and right boundary
between (x1+wx, y1) and (x2+wx, y2)
Algorithm for Dot line: We can draw dotted line by alternatively ploting pixels in DDA line
drawing algorithm.
If (i%2)==0 then
{} //Do not plot pixel
Else
Plot pixel
Algorithm for Dash line: We can draw dashed line by skipping pixels after plotting some
constant no. of pixels in DDA line drawing algorithm.
4. Stop
Algorithm for Dash-Dot line: We can draw dashed-Dotted line by combining logic of dashed-
dotted line by in DDA line drawing algorithm.
1 2 3 4 5 6 7 8 9
skip skip
CG Lab Manual SE COMP, Sem-II, 2017-18
To plot dash –dot pattern we have to skip 7th and 9th pixel position as shown in above figure.
CONCLUSION: Different Line style drawn using DDA line drawing algorithm
FAQ:
1)What is thickness of thin line?
Ans:Thickness of thin line is one pixel
2)What is thickness of thick line?
Ans: Thickness of thick line is more than one pixel
3) What is refresh rate?
Ans: The refresh rate is the number of frames per second the television can display. Its unit is a
Hertz, which is equal to 1/second. 120Hz means it can draw 120 images per second. The refresh
rate of televisions is misleading and is mixed with marketing lies.
4) What is gentle slope and sharp slope?
Ans : Gentle slope : Whether columns are more than rows; i.e. Dx > Dy
Sharp slope : Whether rows are more than columnss; i.e. Dx < Dy
5) What is slope of horizontal line, vertical line and diagonal (linear) line?
Ans :Slop of Horizontal line =0 Vertical line=∞ Diagonal line=1;
PROBLEM STATEMENT: Write Java program to draw a convex polygon and fill it with
desired color using Seed fill algorithm. Use mouse interfacing to draw polygon.
PREREQUISITES:
COURSE OBJECTIVE:
COURSE OUTCOME:
1. Develop scientific and strategic approach to solve complex problems in the domain of
Computer Graphics
THEORY:
Seed Fill: In this method a particular seed point is picked and we start filling upwards and
downwards pixels until boundary is reached. Seed fill method is of two types: Boundary fill and
Flood fill.
1) Boundary fill algorithm: In Boundary filling a seed point is fixed, and then neighboring
pixels are checked to match with the boundary color. Then, color filling is done until boundary is
reached. A region may be 4 connected or 8 connected:
4-Connected Polygon
In this technique 4-connected pixels are used as shown in the figure. We are putting the pixels
above, below, to the right, and to the left side of the current pixels and this process will continue
until we find a boundary with different color.
CG Lab Manual SE COMP, Sem-II, 2017-18
8-Connected Polygon
In this technique 8-connected pixels are used as shown in the figure. We are putting pixels
above, below, right and left side of the current pixels as we were doing in 4-connected technique.
In addition to this, we are also putting pixels in diagonals so that entire area of the current pixel
is covered. This process will continue until we find a boundary with different color.
Algorithm:
void BoundaryFill4(int x, int y, color newcolor, color edgecolor)
{
int current;
current = ReadPixel(x, y);
if(current != edgecolor && current != newcolor)
{
BoundaryFill4(x+1, y, newcolor, edgecolor);
BoundaryFill4(x-1, y, newcolor, edgecolor);
BoundaryFill4(x, y+1, newcolor, edgecolor);
BoundaryFill4(x, y-1, newcolor, edgecolor);
}
}
There are some cases where the boundary color is different than the fill color. For situations like
these Flood fill algorithm is used. Here the process is started in a similar way by examining the
colors of neighboring pixels. But instead of matching it with a boundary color a specified color is
matched.
Algorithm:
void FloodFill4(int x, int y, color newcolor, color oldColor)
{
if(ReadPixel(x, y) == oldColor)
{
FloodFill4(x+1, y, newcolor, oldColor);
FloodFill4(x-1, y, newcolor, oldColor);
FloodFill4(x, y+1, newcolor, oldColor);
FloodFill4(x, y-1, newcolor, oldColor);
}
}
CG Lab Manual SE COMP, Sem-II, 2017-18
Test Cases
T_ID T_Name Condition to test Expected outcome Pass/Fail
T_F1 Seed point Selected pixel is Polygon will fill with given
checking inside the polygon color
Selected pixel is Polygon will not fill
outside the polygon
T_F2 Polygon Polygon of small Get filled
Size testing size
Polygon of large Due to recursive fall
size system error will occur
CONCLUSION: Polygon is drawn by mouse click event. Seed fill algorithms are used for
polygon filling. Analysis of flood fill and boundary fill is done.
FAQ’s
1. What is advantage of flood fill over boundary fill?
Ans: Flood fill works when boundary colors are different
2. What is limitation of seed fill?
Ans: Seed point is selected manually
3. Compare Seed fill and Scan line
Ans: Any polygon(convex, concave) with bigger size can be filled with with scan line. Only
small size convex polygons are filled with seed fill.
4. Compare 4-connected and 8-connected
Ans: 8-connected gives better filling result but 4-connected is faster
5. What is disadvantage of recursive call?
Ans: Processor Stack gets overflow
6. Name various polygon filling algorithms.
Ans: Seed fill, Scan line, Fence fill
Applet: A Java applet is a small application which is written in Java and delivered to users in the
form of bytecode. The user launches the Java applet from a web page, and the applet is then
executed within a Java Virtual Machine (JVM) in a process separate from the web browser itself.
Awt: Abstract Window Toolkit (AWT) is a set of application program interfaces ( API s) used
by Java programmers to create graphical user interface ( GUI ) objects, such as buttons, scroll
bars, and windows. AWT is part of the Java Foundation Classes ( JFC ) from Sun Microsystems,
the company that originated Java.
When AWT invokes this method, the Graphics object parameter is pre-configured with the
appropriate state for drawing on this particular component:
Programs must use this Graphics object (or one derived from it) to render output. They are free
to change the state of the Graphics object as necessary.
Here is a simple example of a paint callback which renders a filled circle in the bounds of a
component:
public void paint(Graphics g)
{
// Dynamically calculate size information
Dimension size = getSize(); // diameter
int d = Math.min(size.width, size.height);
int x = (size.width - d)/2;
int y = (size.height - d)/2;// draw circle (color already set to foreground)g.fillOval(x, y, d, d);
g.setColor(Color.black);
g.drawOval(x, y, d, d);
}
Events:
CG Lab Manual SE COMP, Sem-II, 2017-18
The Event Model framework is really very simple in and of itself, consisting of three classes
(one abstract) and an interface. Most of all it consists of naming conventions that the
programmer must obey. The framework is depicted in the image on the right.
Speaking in terms of classes and interfaces, the most important parts of the framework are the
java.util.EventObject abstract class and the java.util.EventListener
interface. These two types are the centerpieces of the rules and conventions of the Java Platform
Event Model, which are:
A class that has to be notified when an event occurs, is called an event listener. An event
listener has one distinct method for each type of event notification that it is interested in.
Event notification method declarations are grouped together into categories. Each
category is represented by an event listener interface, which must extend
java.util.EventListener. By convention an event listener interface is named <Event
category name>Listener. Any class that will be notified of events must implement at least
one listener interface.
Any and all state related to an event occurrence will be captured in a state object. The
class of this object must be a subclass of java.util.EventObject and must record at least
which object was the source of the event. Such a class is called an event class and by
convention is named <Event category name>Event.
Usually (but not necessarily!) an event listener interface will relate to a single event class.
An event listener may have multiple event notification methods that take the same event
class as an argument.
An event notification method usually (but not necessarily!) has the conventional
signature public void <specific event>(<Event category name>Event evt).
A class that is the source of events must have a method that allows for the registration of
listeners, one for each possible listener interface type. These methods must by convention
have the signature public void add<Event category name>Listener(<Event category
name>Listener listener).
CG Lab Manual SE COMP, Sem-II, 2017-18
A class that is the source of events may have a method that allows for the deregistration
of listeners, one for each possible listener interface type. These methods must by
convention have the signature public void remove<Event category
name>Listener(<Event category name>Listener listener).
PROBLEM STATEMENT: Write C++/Java program to fill polygon using scan line algorithm.
Use mouse interfacing to draw polygon.
PREREQUISITES:
COURSE OBJECTIVE:
COURSE OUTCOME:
1. Develop scientific and strategic approach to solve complex problems in the domain of
Computer Graphics
2. Develop the competency to understand the concepts related to Computer Vision and
Virtual reality
THEORY:
Polygon: polygon is a diagram in which start point and end point is connected.
Convex Polygons: In a convex polygon, any line segment joining any two inside points lies
inside the polygon.
Concave Polygons: In a concave polygon, a line segment connecting any two points may or may
not lie inside the polygon.
CG Lab Manual SE COMP, Sem-II, 2017-18
● For each scan lines crossing a polygon are then sorted from left to right, and the
corresponding frame buffer positions between each intersection pair are set to the
specified color.
● These intersection points are then sorted from left to right , and the corresponding frame
buffer positions between each intersection pair are set to specified color
● Some scan-Line intersections at polygon vertices require special handling:
CONCLUSION: Scan Line algorithm can be used for filling the simple as well as complex
polygon efficiently.
FAQs
1. What are active edges?
Ans: Edges that are inserted by current scan line are called active edges.
2. What is scan line?
Ans: Horizontal line across the y axix
3. What is span?
Ans: pixels between to active edges
4. What is complex polygon?
Ans: intersecting or overlapping polygons
5. Why to sort ymax and y min of polygon edges?
Ans: So algorithm will start at ymin or ymax of polygon instead of ymin and ymax of window.
6. Why to sort xmin and xmax?
Ans: To make pair for filling per active edge
PREREQUISITES:
Knowledge of windowing
COURSE OBJECTIVE:
COURSE OUTCOME:
1. Develop scientific and strategic approach to solve complex problems in the domain of
Computer Graphics
2. Develop the competency to understand the concepts related to Computer Vision and
Virtual reality
THEORY:
Clipping :
1. Accept (and draw) lines that have both endpoints inside the region
2. Reject (and don’t draw) lines that have both endpoints less than xmin or ymin or
greater than xmax or ymax
3. Clip the remaining lines at a region boundary and repeat steps 1 and 2 on the
clipped line segments
if(outcode(P)OR outcode(Q)==0000)
accept
else if(outcode(P)And outcode(Q))!=0)
reject
else test further
FAQ:
1. What are types clipping algorithms?
Ans: Point clipping, Line Clipping, Polygon Clipping and Text Clipping
2. What is viewing transformation?
Ans: Mapping of picture coordinates to display coordinates is viewing transformation
3. What is windowing?
Ans: The process of selecting and viewing the picture with different views is called windowing.
4. What is window?
Ans: To perform viwing transformation we select a finite world co-ordinate area for display
called a windowing.
5. What is viewport?
Ans: An area on divice to which window is mapped
6. Name polygon clipping algorithm
Ans: Sudherland Hodgman polygon clipping algorithm
PROBLEM STATEMENT: Write C++/Java program to draw any object such as flower/ waves
using any curve generation techniques Types of Curves
PREREQUISITES:
COURSE OBJECTIVE:
COURSE OUTCOME:
1. Develop the competency to understand the concepts related to Computer Vision and
Virtual reality
THEORY:
A curve is an infinitely large set of points. Each point has two neighbors except endpoints.
Bezier Curves
Bezier curve is discovered by the French engineer Pierre Bézier. These curves can be generated
under the control of other points.
They generally follow the shape of the control polygon, which consists of the segments
joining the control points.
They always pass through the first and last control points.
They are contained in the convex hull of their defining control points.
The degree of the polynomial defining the curve segment is one less that the number of
defining polygon point. Therefore, for 4 control points, the degree of the polynomial is 3, i.e.
cubic polynomial.
The direction of the tangent vector at the end points is same as that of the vector determined
by first and last segments.
The convex hull property for a Bezier curve ensures that the polynomial smoothly follows
the control points.
No straight line intersects a Bezier curve more times than it intersects its control polygon.
Bezier curves exhibit global control means moving a control point alters the shape of the
whole curve.
A given Bezier curve can be subdivided at a point t=t0 into two Bezier segments which join
together at the point corresponding to the parameter value t=t0.
B-Spline Curves
The Bezier-curve produced by the Bernstein basis function has limited flexibility.
First, the number of specified polygon vertices fixes the order of the resulting polynomial
which defines the curve.
The second limiting characteristic is that the value of the blending function is nonzero for
all parameter values over the entire curve.
The B-spline basis contains the Bernstein basis as the special case. The B-spline basis is non-
global.
Basis Function:
k is the order of the polynomial segments of the B-spline curve. Order k means that the
curve is made up of piecewise polynomial segments of degree k - 1,
CG Lab Manual SE COMP, Sem-II, 2017-18
The sum of the B-spline basis functions for any parameter value is 1.
Each basis function is positive or zero for all parameter values.
Each basis function has precisely one maximum value, except for k=1.
The maximum order of the curve is equal to the number of vertices of defining polygon.
B-spline allows the local control over the curve surface because each vertex affects the shape
of a curve only over a range of parameter values where its associated basis function is
nonzero.
Any affine transformation can be applied to the curve by applying it to the vertices of
defining polygon.
The curve line within the convex hull of its defining polygon.
Algorithm
CA
A
ABCD
BA
A
AA
A
Xab=(Xa+Xb)/2
Yab=(Ya+Yb)/2
Xbc=(Xb+Xc)/2
Ybc=(Yb+Yc)/2
Xcd=(Xd+Xc)/2
Ycd=(Yd+Yc)/2
Xabc=(Xab+Xbc)/2
Yabc=(Yab+Ybc)/2
Xbcd=(Xbc+Xcd)/2
Ybcd=(Ybc+Ycd)/2
Xabcd=(Xabc+Xbcd)/2
Yabcd=(Yabc+Ybcd)/2
3. Repeat the step 2 for section A, AB, ABC, ABCD and section ABCD,BCD,CD and D
6. Stop
Ans : The degree of the polynomial defining the curve segment is one less that the number of
defining polygon point in Bezier and The degree of B-spline polynomial is independent on the
number of vertices of defining polygon in B-Spline.
5. How to represent curve mathematically?
Ans: Curve can be represented by Trigonometric and polynomial equation.
OUTPUT: Printout with output
GROUP: C
ASSIGNMENT NO: 9
AIM: To study fractals
PREREQUISITES:
COURSE OBJECTIVE:
1. Develop the competency to understand the concepts related to Computer Vision and
Virtual reality
THEORY:
Fractals : Fractals are very complex pictures generated by a computer from a single formula.
They are created using iterations. This means one formula is repeated with slightly different
values over and over again, taking into account the results from the previous iteration.
Others − For depicting clouds, coastline and borderlines, data compression, diffusion, economy,
fractal art, fractal music, landscapes, special effect, etc.
Koch curve :
The Koch curve is also known as snowflake curve. It is drawn by dividing line into 4 equal
segments with scaling factor 1/3 & middle 2 segments are so adjusted that they form adjacent
sides of equilateral triangle. Repeat same process for each of the 4 segments. Each repetition
increases length by factor 4/3.
CG Lab Manual SE COMP, Sem-II, 2017-18
Fractal dimension:
4=3D
D= log34= log 4/ log 3 = 1.2618
Therefore for Koch curve topological dimension is 1, but fractal dimension is 1.2618 hence Koch
curve is fractal.
Algorithm
1. Divide line into 4 equal segments with scaling factor 1/3.
2. Adjust middle 2 segments that they form adjacent sides of equilateral triangle.
5. Stop
FAQs:
GROUP: C
ASSIGNMENT NO: 10
AIM: To implement simple animation
PROBLEM STATEMENT: Write C++/Java program to simulate any one of or similar scene-
Vehicle/boat locomotion
Water drop falling into the water and generated waves after impact
PREREQUISITES:
COURSE OBJECTIVE:
COURSE OUTCOME:
THEORY:
Animation means giving life to any object in computer graphics. Computer-assisted animation
and computer-generated animation are two categories of computer animation. It can be presented
via film or video.
The basic idea behind animation is to play back the recorded images at the rates fast enough to
fool the human eye into interpreting them as continuous motion. Animation can be used in many
areas like entertainment, computer aided-design, scientific visualization, training, education, e-
commerce, and computer art.
CG Lab Manual SE COMP, Sem-II, 2017-18
Animation Techniques
Animators have invented and used a variety of different animation techniques. Basically there
are six animation techniques which we would discuss one by one in this section.
Traditionally most of the animation was done by hand. All the frames in an animation had to be
drawn by hand. Since each second of animation requires 24 frames (film), the amount of efforts
required to create even the shortest of movies can be tremendous.
2. Keyframing
In this technique, a storyboard is laid out and then the artists draw the major frames of the
animation. Major frames are the ones in which prominent changes take place. They are the key
points of animation. Keyframing requires that the animator specifies critical or key positions for
the objects. The computer then automatically fills in the missing frames by smoothly
interpolating between those positions.
3. Procedural
In a procedural animation, the objects are animated by a procedure − a set of rules − not by
keyframing. The animator specifies rules and initial conditions and runs simulation. Rules are
often based on physical rules of the real world expressed by mathematical equations.
4. Behavioral
In behavioral animation, an autonomous character determines its own actions, at least to a certain
extent. This gives the character some ability to improvise, and frees the animator from the need
to specify each detail of every character's motion.
Another technique is Motion Capture, in which magnetic or vision-based sensors record the
actions of a human or animal object in three dimensions. A computer then uses these data to
animate the object.
This technology has enabled a number of famous athletes to supply the actions for characters in
sports video games. Motion capture is pretty popular with the animators mainly because some of
the commonplace human actions can be captured with relative ease. However, there can be
serious discrepancies between the shapes or dimensions of the subject and the graphical
character and this may lead to problems of exact execution.
CG Lab Manual SE COMP, Sem-II, 2017-18
Unlike key framing and motion picture, simulation uses the laws of physics to generate motion
of pictures and other objects. Simulations can be easily used to produce slightly different
sequences while maintaining physical realism. Secondly, real-time simulations allow a higher
degree of interactivity where the real person can maneuver the actions of the simulated character.
In contrast the applications based on key-framing and motion select and modify motions form a
pre-computed library of motions. One drawback that simulation suffers from is the expertise and
time required to handcraft the appropriate controls systems.
Algorithm:
1. Draw object using basic graphics primitives
2. Create animation by increasing or decreasing in x direction or y direction
3. Keep delay of predefined milliseconds
4. stop
PREREQUISITES:
COURSE OBJECTIVE:
THEORY:
Blender is a professional free and open-source 3D computer graphics software product used for
creating animated films, visual effects, art, 3D printed models, interactive 3D applications and
video games. Blender's features include 3D modeling, UV unwrapping, texturing, raster graphics
editing, rigging and skinning, fluid and smoke simulation, particle simulation, soft body
simulation, sculpting, animating, match moving, camera tracking, rendering, video editing and
compositing.
Features
Official releases of Blender for Microsoft Windows, Mac OS X, and Linux, as well as a port for
FreeBSD, are available in both 32-bit and 64-bit versions.
Support for a variety of geometric primitives, including polygon meshes, fast subdivision
surface modeling, Bezier curves, NURBS surfaces, metaballs, multi-res digital sculpting
(including dynamic topology, maps baking, remeshing, resymetrize, decimation..),
outline font, and a new n-gon modeling system called B-mesh.
Keyframed animation tools including inverse kinematics, armature (skeletal), hook, curve
and lattice-based deformations, shape keys (morph target animation), non-linear
animation, constraints, and vertex weighting
Algorithm:
1) Take UVSphere on Mesh from Add-> Mesh->UVSphere toolbar
2) Add key frame style movement to the ball. With the ball selected press i to insert a
location key frame. Now press the up arrow we will see the number of key frames
increase on the bottom of the screen 51 represents the number of frames. Go up to 75 key
frames so that the ball has a smooth 3 second bounce.
3) Save the location of ball in every keyframe, press s.
4) Run the Animation ,click on start button or Press P Button from Keyboard
CONCLUSION:
Blender is free and open-source 3D computer graphics software product used for
creating animations.
Ans: Maya 3D animation, modeling, simulation and rendering software offers artists a
comprehensive creative tool set.
2. List Open Source Software for creating Animation
Pencil
Synfig Studios
Stykz
CreaToon
Ajax Animator
Blender
Bryce
DAZ Studio
Clara.io
3. What is animation?
4. What is fps?