Sie sind auf Seite 1von 43

DELHI TECHNOLOGICAL UNIVERSITY

COMPUTER GRAPHICS (CO 313)


PRACTICAL FILE

Submitted to: Submitted by:

Ms. Chyng-Mwan-Kym Kanika


2K17/CO/151
INDEX
S.No EXPERIMENT DATE SIGNATURE
1

10

11

12

13

14

15
Program-1
AIM:
Write a program to implement the DDA Line Algorithm.

THEORY:
In any 2D plane if we connect two points (x0, y0) and (x1, y1), we get a line segment. But in the case
of computer graphics we cannot directly join any two coordinate points, for that we should calculate
intermediate point’s coordinate and put a pixel for each intermediate point. For using graphics
functions, our output screen is treated as a coordinate system where the coordinate of the top-left
corner is (0, 0) and as we move down our y-ordinate increases and as we move right our x-ordinate
increases for any point (x, y).
Now, for generating any line segment we need intermediate points and for calculating them we have
can use a basic algorithm called DDA(Digital differential analyzer) line generating algorithm.

ALGORITHM
1. Calculate difference in x i.e. dx = (x2 – x1), difference in y i.e. dy = (y2 – y1)
2. Now calculate the slope of the line with given points and using dx and dy, i.e. m = (dy/dx)
3. Finding steps i.e. Steps = max(abs(dx), abs(dy))
4. Finding incremental value in ‘x’ and ‘y’. incX = (dx/Steps), incY = (dy/Steps)
5. Now for each step, increment X and Y by their increment value, set the pixel using putpixel

CODE:
#include <graphics.h>
#include <conio.h>
int main()
{
intgd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TurboC4\\TC\\BGI");

int X0 = 2, Y0 = 2, X1 = 14, Y1 = 16;


int dx = X1 - X0, dy = Y1 - Y0;
int steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy);
intincX = dx / steps;
intincY = dy / steps;

int X = X0, Y = Y0;

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


{
putpixel(X, Y, RED);
X += incX;
Y += incY;
}
getch();
return 0;
}
OUTPUT:

FINDINGS AND LEARNING:


We learnt about the basics of graphics.h library, initializing a graph, putting a pixel, and closing. We
also applied DDA algorithm to create a line between 2 coordinates.
Program-2
AIM:
Write a program to implement the Bresenham’s Line Algorithm.

THEORY:
Bresenham’s line drawing algorithm deals with the problems that occurred in DDA line drawing
algorithm. It does not takes the approx. values of coordinates, rather solves the problem with new
concept in form of variables known as Decision variable generally represented by ‘P’. With decision
variable we solve the case where it is to be decided that whether we should choose upper or lower
coordinate i.e. y+1 or y. Decision parameter finds the mid-point of two pixels and determines the
shortest distance of line from two pixels. Shortest distant pixel is chosen

ALGORITHM:
1. Input two coordinates – x1, y1 and x2, y2
2. Find the slope of the line i.e. m = (y2-y1)/(x2-x1) and P = 2.dy – dx and steps = max(abs(dy),
abs(dx))
3. If slope is less than one i.e. m < 1 and steps != 0
a. If P < 0
i. x = x + 1 and y = y
ii. P = P + 2.dy
b. Else
i. x = x + 1 and y = y + 1
ii. P = P + 2.dy – 2.dx
4. steps = steps – 1
5. Repeat and check again from step 4
6. If slope is greater than 1 i.e. m > 1 and steps != 0
a. If P < 0
i. y = y + 1 and x = x
ii. P = P + 2.dx
b. Else
i. x = x + 1 and y = y + 1
ii. P = P + 2.dx – 2.dy
7. steps = steps - 1
8. Repeat and check from Step 8
9. If slope is equal to 1 i.e. m = 1 and steps != 0
a. x = x + 1 and y = y + 1
10. Repeat and check from step 11

CODE:
#include <graphics.h>
#include <conio.h>
#include <iostream.h>
#include <math.h>

voidbresenham(int X0, int Y0, int X1, int Y1)


{
float m = (Y1 - Y0) / (float)(X1 - X0);
int dy, dx, pk, x = X0, y = Y0;
dy = abs(Y1 - Y0);
dx = abs(X1 - X0);

if (abs(m) < 1)
{
pk = 2 * dy - dx;
for (int i = 0; i < dx; i++)
{
x++;
if (pk< 0)
pk = pk + 2 * dy;
else
{
y++;
pk = pk + 2 * dy - 2 * dx;
}
putpixel(x, y, WHITE);
}
}
else
{
pk = 2 * dx - dy;
for (int i = 0; i < dy; i++)
{
x++;
if (pk< 0)
pk = pk + 2 * dx;
else
{
y++;
pk = pk + 2 * dx - 2 * dy;
}
putpixel(x, y, WHITE);
}
}
}

int main()
{
clrscr();
intgd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");

bresenham(20, 10, 200, 300);

getch();
return 0;
}
OUTPUT:

FINDING AND LEARNING:


We learnt about corrections of DDA made by Bresenham’s and wrote the Bresenham’s line drawing
algorithm using the decision variable.
Program-3
AIM:
Write a program to implement the Mid-Point Circle Drawing Algorithm.

THEORY:
Mid-point circle drawing algorithm uses the concept of 8-way symmetry property of the circle. In this
algorithm we find the coordinates of the first octant using the given radius and coordinates and place
the other corresponding symmetric points in other 7 octants. To solve the approximation problems
same as Bresenham’s algorithm, we use the concept of Decision parameter which is based upon the
concept that whether the mid-point of two possible pixels is in circle, on circle or outside the circle.

ALGORITHM
1. Input the radius “r” of the circle and centre of the circle (xc, yc).
2. Find the decision variable i.e. P = 1 – r;
3. The first coordinate is x = 0, y = r;
4. While x < y, repeat this step
5. Get temporary coordinatesby shifting by centre –
6. x = x + xc
7. y = y + yc
8. Plot (x,y), (-x,y), (x, -y), (-x, -y), (y, x), (-y, x), (y, -x) and (-y, -x).
9. If (P < 0)
a. P = P + 2.x + 3
b. Increment x
10. Else (P >= 0)
a. P = P + 2(x-y) + 5
b. Increment x and decrement y

CODE:
#include <graphics.h>
#include <conio.h>
#include <iostream.h>
#include <math.h>

voidmy_circle(int X0, int Y0, int r)


{
int x = 0, y = r;
int p = 1 - r;

while (x <= y)
{
putpixel(x + X0, y + Y0, WHITE);
putpixel(-x + X0, -y + Y0, WHITE);
putpixel(x + X0, -y + Y0, WHITE);
putpixel(-x + X0, y + Y0, WHITE);
putpixel(y + X0, x + Y0, WHITE);
putpixel(-y + X0, -x + Y0, WHITE);
putpixel(y + X0, -x + Y0, WHITE);
putpixel(-y + X0, x + Y0, WHITE);

if (p < 0)
{
x++;
p = p + 2 * x + 1;
}
else
{
x++;
y--;
p = p + 2 * x - 2 * y + 1;
}
}
}

int main()
{
clrscr();
intgd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");

my_circle(100, 100, 40);

getch();
return 0;
}

OUTPUT:

FINDING AND LEARNING:


We learnt about the 8-way symmetry property of circle and used it to plot the 7 other points
corresponding to one point in order to draw a full circle. We learnt about the mid-point circle
algorithm.
Program-4

AIM:
Write a program to implement the Mid-Point Ellipse Drawing Algorithm.

THEORY:
Midpoint ellipse algorithm plots(finds) points of an ellipse on the first quadrant by dividing the
quadrant into two regions. Each point(x, y) is then projected into other three quadrants (-x, y), (x, -y),
(-x, -y) i.e. it uses 4-way symmetry.

ALGORITHM:
1. Take input radius along x axis and y axis and obtain center of ellipse.
Initially, we assume ellipse to be centered at origin and the first point as : (x, y0)= (0, ry).
2. Obtain the initial decision parameter for region 1 as: p10=ry2+1/4rx2-rx 2ry
3. For every xk position in region 1 :
a. If p1k<0
i. then the next point along the is (xk+1 , yk)
ii. AND p1k+1=p1k+2ry2xk+1+ry2
b. Else
i. the next point is (xk+1, yk-1)
ii. AND p1k+1=p1k+2ry2xk+1– 2rx2yk+1+ry2
4. Obtain the initial value in region 2 using the last point (x0, y0) of region 1 as:
p20=ry2(x0+1/2)2+rx2(y0-1)2-rx2ry2
5. At each yk in region 2 starting at k =0 perform the following task.
a. If p2k<0
i. the next point is (xk, yk+1)
ii. and p2k+1=p2k-2rx2yk+1+rx2
b. Else
i. the next point is (xk+1, yk -1)
ii. and p2k+1=p2k+2ry2xk+1-2rx2yk+1+rx2
6. Now obtain the symmetric points in the three quadrants and plot the coordinate value as:
x=x+xc, y=y+yc
7. Repeat the steps for region 1 until 2ry2xgt=2rx2y

CODE:
#include <graphics.h>
#include <conio.h>
#include <iostream.h>
#include <math.h>
using namespace std;

void midEl(int rx, int ry, int xc, int yc)


{
floatdx, dy, d1, d2, x, y;
x = 0;
y = ry;
d1 = (ry * ry) - (rx * rx * ry) + (0.25 * rx * rx);
dx = 2 * ry * ry * x;
dy = 2 * rx * rx * y;

while(dx < dy)


{
cout << x + xc <<" , "<< y + yc << endl;
cout << -x + xc <<" , "<< y + yc << endl;
cout << x + xc <<" , "<< -y + yc << endl;
cout << -x + xc <<" , "<< -y + yc << endl;
if(d1 < 0)
{
x++;
dx = dx + (2 * ry * ry);
d1 = d1 + dx + (ry * ry);
}
else
{ x++;
y--;
dx = dx + (2 * ry * ry);
dy = dy - (2 * rx * rx);
d1 = d1 + dx - dy + (ry * ry);
}
}
d2 = ((ry * ry) * ((x + 0.5) * (x + 0.5))) + ((rx * rx) * ((y - 1) * (y - 1))) - (rx * rx * ry * ry);

while(y >= 0)
{
cout << x + xc <<" , "<< y + yc << endl;
cout << -x + xc <<" , "<< y + yc << endl;
cout << x + xc <<" , "<< -y + yc << endl;
cout << -x + xc <<" , "<< -y + yc << endl;
if(d2 > 0)
{
y--;
dy = dy - (2 * rx * rx);
d2 = d2 + (rx * rx) - dy;
}
else
{
y--;
x++;
dx = dx + (2 * ry * ry);
dy = dy - (2 * rx * rx);
d2 = d2 + dx - dy + (rx * rx);
}
}
}

int main()
{
midEl(10, 15, 50, 50);
return0;
}
OUTPUT:

LEARNING:
We learnt about the 4-way symmetry property of ellipse and used it to plot the 3 other points
corresponding to one point in order to draw a full ellipse. We learnt about the mid-point ellipse
algorithm.
Program-5

AIM:

To write a program and implement Flood Fill Algorithm

THEORY:

Sometimes we come across an object where we want to fill the area and its boundary with different colors.
We can paint such objects with a specified interior color instead of searching for particular boundary color as
in boundary filling algorithm.

Instead of relying on the boundary of the object, it relies on the fill color. In other words, it replaces the
interior color of the object with the fill color. When no more pixels of the original interior color exist, the
algorithm is completed.

In Flood Fill algorithm we start with some seed and examine the neighboring pixels, however pixels are
checked for a specified interior color instead of boundary color and is replaced by a new color. It can be done
using 4 connected or 8 connected region method.

ALGORITHM:

Step 1 − Initialize the value of seed point (seedx, seedy), fcolor and dcol.

Step 2 − Define the boundary values of the polygon.

Step 3 − Check if the current seed point is of default color, then repeat the steps 4 and 5 till the boundary
pixels reached.

Ifgetpixel(x, y)=dcol then repeat step 4and5

Step 4 − Change the default color with the fill color at the seed point.

setPixel(seedx, seedy, fcol)

Step 5 − Recursively follow the procedure with four neighborhood points.

FloodFill (seedx – 1, seedy, fcol, dcol)


FloodFill (seedx + 1, seedy, fcol, dcol)
FloodFill (seedx, seedy - 1, fcol, dcol)
FloodFill (seedx – 1, seedy + 1, fcol, dcol)
Step 6 − Exit

There is a problem with this technique. Consider the case as shown below where we tried to fill the entire
region. Here, the image is filled only partially. In such cases, 4-connected pixels technique cannot be used.

CODE:

#include<stdio.h>

#include<graphics.h>
#include<dos.h>

voidfloodFill(intx,inty,intoldcolor,intnewcolor)
{
if(getpixel(x,y) == oldcolor)
{
putpixel(x,y,newcolor);
floodFill(x+1,y,oldcolor,newcolor);
floodFill(x,y+1,oldcolor,newcolor);
floodFill(x-1,y,oldcolor,newcolor);
floodFill(x,y-1,oldcolor,newcolor);
}
}
//getpixel(x,y) gives the color of specified pixel

int main()
{
intgm,gd=DETECT,radius;
intx,y;

printf("Enter x and y positions for circle\n");


scanf("%d%d",&x,&y);
printf("Enter radius of circle\n");
scanf("%d",&radius);

initgraph(&gd,&gm,"c:\\turboc3\\bgi");
circle(x,y,radius);
floodFill(x,y,0,15);
delay(5000);
closegraph();

return 0;
}
OUTPUT:

LEARNING:

We can modify findFill() method to reduce storage requirements of the stack by filling horizontal pixel spans
,i.e., we stack only beginning positions for those pixel spans having oldcolour .In this modified version, starting
at the first position of each span, the pixel values are replaced until a value other than oldcolour is
encountered. We can also show an area bordered by several different color regions too.
Program-6

AIM:

To implement Boundary Fill Algorithm

THEORY:

The boundary fill algorithm works as its name. This algorithm picks a point inside an object and
starts to fill until it hits the boundary of the object. The color of the boundary and the color that we fill
should be different for this algorithm to work.
In this algorithm, we assume that color of the boundary is same for the entire object. The boundary
fill algorithm can be implemented by 4-connected pixels or 8-connected pixels.

ALGORITHM:

1. Create a function named as boundaryfill with 4 parameters (x,y,f_color,b_color).

void boundaryfill(int x,int y,int f_color,int


b_color)
{
if(getpixel(x,y)!=b_color &&
getpixel(x,y)!=f_color)
{
putpixel(x,y,f_color);
boundaryfill(x+1,y,f_color,b_color);
boundaryfill(x,y+1,f_color,b_color);
boundaryfill(x-1,y,f_color,b_color);
boundaryfill(x,y-1,f_color,b_color);
}
}

2. Call it recursively until the boundary pixels are reached.


3. Stop.
CODE:

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>
void fill_right(int x,int y);
void fill_left(int x,int y);
void main()
{
int gd=DETECT,gm,x,y,n,i;
clrscr();
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
printf("*** Boundary Fill algorithm ***");
/*- draw object -*/
line (50,50,200,50);
line (200,50,200,300);
line (200,300,50,300);
line (50,300,50,50);
/*- set seed point -*/
x=100; y=100;
fill_right(x,y);
fill_left(x-1,y);
getch();
}
void fill_right(int x,int y)
{
if((getpixel(x,y) != WHITE)&&(getpixel(x,y) != RED))
{
putpixel(x,y,RED);
fill_right(++x,y); x=x-1;
fill_right(x,y-1);
fill_right(x,y+1);
}
delay(1);
}
void fill_left(int x,int y)
{
if((getpixel(x,y) != WHITE)&&(getpixel(x,y) != RED))
{
putpixel(x,y,RED);
fill_left(--x,y); x=x+1;
fill_left(x,y-1);
fill_left(x,y+1);
}
delay(1);
}
OUTPUT:

LEARNING:

1. Boundary Fill is used for the coloring figures in computer graphics. Here, area gets colored
with pixels of a chosen color as boundary this giving the technique its name.
2. Boundary fill fills the chosen area with a color until the given colored boundary is found.
3. This algorithm is also recursive in nature as the function returns when the pixel to be colored is
the boundary color or is already the fill color.
Program-7

AIM:

Write a program to implement 2D Translation of an object.

THEORY:
A translation process moves every point a constant distance in a specified direction. It can be described as a
rigid motion. A translation can also be interpreted as the addition of a constant vector to every point, or as
shifting the origin of the coordinate system.

Suppose, If point P(X, Y) is to be translated by amount Dx and Dy to a new location P’(X’, Y’) then new
coordinates can be obtained by adding Dx to X and Dy to Y as:
X’ = Dx + X
Y’ = Dy + Y
Or
P’ = T + P
where P’ = [X’,Y’] ; T = [Dx,Dy]; P = [X,Y];

Algorithm:

1. Start
2. Initialize the graphics mode.
3. Construct a 2D object
4. Translation
a. Get the translation value tx, ty
b. Move the 2d object with tx, ty (x’=x+tx,y’=y+ty)
c. Plot (x’,y’)

Code:

#include<stdio.h>
#include<graphics.h>
#include<conio.h>
#include<dos.h>

void translateRectangle ( int P[][2], int T[])


{
/* init graph and rectangle() are used for
representing rectangle through graphical functions */
int gd = DETECT, gm, errorcode;
initgraph (&gd, &gm, "c://bgi");
setcolor (2);
// rectangle (Xmin, Ymin, Xmax, Ymax)
// original rectangle
rectangle (P[0][0], P[0][1], P[1][0], P[1][1]);

// calculating translated coordinates


P[0][0] = P[0][0] + T[0];
P[0][1] = P[0][1] + T[1];
P[1][0] = P[1][0] + T[0];
P[1][1] = P[1][1] + T[1];

translated rectangle (Xmin, Ymin, Xmax, Ymax)


setcolor(3);
rectangle (P[0][0], P[0][1], P[1][0], P[1][1]);
closegraph();
getch();
}

int main()
{
// Xmin, Ymin, Xmax, Ymax as rectangle
// coordinates of top left and bottom right points
int P[2][2] = {100, 100, 200, 200};
int T[] = {50, 70}; // translation factor
translateRectangle (P, T);
return 0;
}

Output:
Learning:

Translation can be achieved by any given factor by summation of the translation factor to the original
coordinates of the object.

Advantages:

● Useful for coordinate transformations.


● Used extensively while performing 2D and 3D transformations.
● Change of Basis.
Program-8

AIM:

Write a program to implement 2D Scaling of an object.

Description:

A scaling can be represented by a scaling matrix. To scale an object by a vector v = (vx, vy, vz), each point p =
(px, py, pz) would need to be multiplied with this scaling matrix:

As shown below, the multiplication will give the expected result:

Such a scaling changes the diameter of an object by a factor between the scale factors, the area by a factor
between the smallest and the largest product of two scale factors, and the volume by the product of all three.

The scaling is uniform if and only if the scaling factors are equal (vx = vy = vz). If all except one of the scale
factors are equal to 1, we have directional scaling.

In the case where vx = vy = vz = k, the scaling is also called an enlargement or dilation by a factor k, increasing
the area by a factor of k2 and the volume by a factor of k3.

A scaling in the most general sense is any affine transformation with a diagonalizable matrix. It includes the
case that the three directions of scaling are not perpendicular. It includes also the case that one or more scale
factors are equal to zero (projection), and the case of one or more negative scale factors. The latter
corresponds to a combination of scaling proper and a kind of reflection. Along lines in a particular direction we
take the reflection in the point of intersection with a plane that need not be perpendicular; therefore it is
more general than ordinary reflection in the plane.

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.

Algorithm:
1. For each vertex of the algorithm:
a. X = Sx*X
b. Y = Sy*Y
2. Redraw the polygon with new set of vertices.

Code:

#include <stdio.h>
#include <conio.h>
#include <stdio.h>
#include <conio.h>
#include <graphics.h>

#define ROUND(a) ((int)(a+0.5))


void thickline(int X0, int Y0, int X1, int Y1) {
// calculate dx & dy
int dx = X1 - X0;
int dy = Y1 - Y0;

// calculate steps required for generating pixels


int steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy);

// calculate increment in x & y for each steps


float Xinc = dx / (float) steps;
float Yinc = dy / (float) steps;

// Put pixel for each step


float X = X0;
float Y = Y0;
int i;
for (i = 0; i <= steps; i++) {
putpixel (ROUND(X),ROUND(Y),WHITE);// put pixel at (X,Y)
X += Xinc; // increment in x at each step
Y += Yinc; // increment in y at each step
delay(50); // for visualization of line-
// generation step by step
}
}

void scaling(int *x, int *y, int sx, int sy) {


*x =(*x)*sx;
*y = (*y)*sy;
}
int main() {
int x0 = 50, y0 = 50, x1 = 100, y1 = 100;

int gdriver = DETECT, gmode, errorcode;


initgraph(&gdriver, &gmode, "..\\");
errorcode = graphresult();

if(errorcode != grOk) {
printf("Graphics Error: %s\n",grapherrormsg(errorcode));
printf("Press key to halt");
getch();
exit(1);
}
thickline(x0,y0,x0,y1);
thickline(x0,y0,x1,y0);
thickline(x0,y1,x1,y1);
thickline(x1,y0,x1,y1);
delay(100);
closegraph();
clrscr();
scaling(&x0,&y0,2,2);
scaling(&x0,&y1,2,2);
scaling(&x1,&y0,2,2);
scaling(&x1,&y1,2,2);
gdriver = DETECT, gmode, errorcode;
initgraph(&gdriver, &gmode, "..\\");
errorcode = graphresult();

if(errorcode != grOk) {
printf("Graphics Error: %s\n",grapherrormsg(errorcode));
printf("Press key to halt");
getch();
exit(1);
}
thickline(x0,y0,x0,y1);
thickline(x0,y0,x1,y0);
thickline(x0,y1,x1,y1);
thickline(x1,y0,x1,y1);

getch();
closegraph();
return 0;
}

Output:

Before Scaling:

After Scaling:
Learning:

In projective geometry, often used in computer graphics, points are represented using homogeneous
coordinates. To scale an object by a vector v = (vx, vy, vz), each homogeneous coordinate vector p = (px, py,
pz, 1) would need to be multiplied with this projective transformation matrix:
Program-9
AIM:

Write a program to implement 2D Rotation of an object.

DESCRIPTION:
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.

Let us suppose you want to rotate it at the angle θ. After rotating it to a new location, you will get a new point
P’ (X’, Y’).

Using standard trigonometric the original coordinate of point P(X, Y) can be represented as −

X=rcosϕ......(1)

Y=rsinϕ......(2)

Same way we can represent the point P’ (X’, Y’) as −

x′=rcos(ϕ+θ)=rcosϕcosθ−rsinϕsinθ.......(3)

y′=rsin(ϕ+θ)=rcosϕsinθ+rsinϕcosθ.......(4)

Substituting equation (1) & (2) in (3) & (4) respectively, we will get

x′=xcosθ−ysinθ
y′=xsinθ+ycosθ

Representing the above equation in matrix form we have the Roation matrix R as,
ALGORITHM:

1. Start

2. Initialize the graphics mode.

3. Construct a 2D object (use DrawLine()) e.g. (x , y))

4. Rotation

a. Get the Rotation angle


b. Rotate the object by the angle ф

x’=x cos ф - y sin ф


y’=x sin ф - y cosф
c. Plot (x’,y’)

Code:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<graphics.h>
#include<math.h>

#define ROUND(a) ((int)(a+0.5))

void ddaline(int x1, int y1, int x2, int y2,int color)

{ float xsteps, ysteps, x=x1, y=y1;

int dx = x2-x1;
int dy = y2-y1;
int steps,k=1;

if(abs(dx)>=abs(dy))

steps=abs(dx);
else steps=abs(dy);

xsteps= dx/(float)steps;
ysteps= dy/(float)steps;

putpixel(ROUND(x),ROUND(y),color);
while(k<=steps)
{

x+=xsteps;
y+=ysteps;
putpixel(ROUND(x), ROUND(y),color);
k++;
}
}

void rotate(int x1, int y1, int x2, int y2, float theta)

{ int xtmp, ytmp;


float th = (3.14 * theta )/180;
xtmp = x1 + ROUND ((x2-x1)*cos(th) - (y2-y1)*sin(th));

ytmp = y1 + ROUND ((x2-x1)*sin(th) + (y2-y1)*cos(th));


ddaline(x1,y1,x2,y2,10);
ddaline(x1,y1,xtmp,ytmp,12);
}

int main()
{
int x1, x2, y1, y2;
float theta;

int gdriver = DETECT, gmode, errorcode;


initgraph(&gdriver, &gmode, "C:\\TURBOC3\\BGI");
errorcode = graphresult();

if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");

getch();
exit(1);
}
printf("Enter start point\n");
scanf("%d %d", &x1, &y1);
printf("Enter end point\n");
scanf("%d %d", &x2, &y2);
printf("Enter value of angle to rotate line about starting point\n");
scanf("%f", &theta);

rotate(x1, y1, x2, y2, theta);

getch();
closegraph();
return 0;
}

OUTPUT:

Learning:

● A rotation matrix is a matrix that is used to perform a rotation in Euclidean space. To perform the
rotation using a rotation matrix R, the position of each point must be represented by a column vector
v, containing the coordinates of the point. A rotated vector is obtained by using the matrix
multiplication Rv.
● Rotation of a complete object can viewed as rotation of all its constituent lines about a fixed point.
● Rotation matrices are square matrices, with real entries. More specifically, they can be characterized as
orthogonal matrices with determinant 1.
● Coordinate rotations are a natural way to express the orientation of a camera, or the attitude of a
spacecraft, relative to a reference axes-set. These are also used in various image editing software to
perform simple rotation of images.
Program-10

AIM:

To implement Cohen-Sutherland Line Clipping Algorithm

Description:

This algorithm uses the clipping window as shown in the following figure. The minimum coordinate for the
clipping region is (XWmin, YWmin) and the maximum coordinate for the clipping region is (XWmax, YWmax).

We will use 4-bits to divide the entire region. These 4 bits represent the Top, Bottom, Right, and Left of the
region as shown in the following figure. Here, the TOP and LEFT bit is set to 1 because it is the TOP-
LEFT corner.

There are 3 possibilities for the line −


● Line can be completely inside the window (This line should be accepted).
● Line can be completely outside of the window (This line will be completely removed from the region).
● Line can be partially inside the window (We will find intersection point and draw only that portion of
line that is inside region).

Algorithm:

1. Assign a region code for each endpoints.

2 − If both endpoints have a region code 0000 then accept this line.

3 − Else, perform the logical AND operation for both region codes.

3.1 − If the result is not 0000, then reject the line.

3.2 − Else you need clipping.

3.2.1 − Choose an endpoint of the line that is outside the window.

3.2.2 − Find the intersection point at the window boundary (base on region code).

3.2.3 − Replace endpoint with the intersection point and update the region code.

3.2.4 − Repeat step 2 until we find a clipped line either trivially accepted or trivially rejected.

4 − Repeat step 1 for other lines.

Code:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<graphics.h>
#include<dos.h>

typedef struct coordinate


{
int x,y;
char code[4];
}PT;

void drawwindow();
void drawline(PT p1,PT p2);
PT setcode(PT p);
int visibility(PT p1,PT p2);
PT resetendpt(PT p1,PT p2);

void main()
{
int gd=DETECT,v,gm;
PT p1,p2,p3,p4,ptemp;

printf("\nEnter x1 and y1\n");


scanf("%d %d",&p1.x,&p1.y);
printf("\nEnter x2 and y2\n");
scanf("%d %d",&p2.x,&p2.y);

initgraph(&gd,&gm,"c:\\turboc3\\bgi");
drawwindow();
delay(500);

drawline(p1,p2);
delay(500);
cleardevice();

delay(500);
p1=setcode(p1);
p2=setcode(p2);
v=visibility(p1,p2);
delay(500);

switch(v)
{
case 0: drawwindow();
delay(500);
drawline(p1,p2);
break;
case 1: drawwindow();
delay(500);
break;
case 2: p3=resetendpt(p1,p2);
p4=resetendpt(p2,p1);
drawwindow();
delay(500);
drawline(p3,p4);
break;
}

delay(5000);
closegraph();
}

void drawwindow()
{
line(150,100,450,100);
line(450,100,450,350);
line(450,350,150,350);
line(150,350,150,100);
}

void drawline(PT p1,PT p2)


{
line(p1.x,p1.y,p2.x,p2.y);
}

PT setcode(PT p) //for setting the 4 bit code


{
PT ptemp;

if(p.y<100)
ptemp.code[0]='1'; //Top
else
ptemp.code[0]='0';

if(p.y>350)
ptemp.code[1]='1'; //Bottom
else
ptemp.code[1]='0';

if(p.x>450)
ptemp.code[2]='1'; //Right
else
ptemp.code[2]='0';

if(p.x<150)
ptemp.code[3]='1'; //Left
else
ptemp.code[3]='0';

ptemp.x=p.x;
ptemp.y=p.y;

return(ptemp);
}

int visibility(PT p1,PT p2)


{
int i,flag=0;

for(i=0;i<4;i++)
{
if((p1.code[i]!='0') || (p2.code[i]!='0'))
flag=1;
}

if(flag==0)
return(0);

for(i=0;i<4;i++)
{
if((p1.code[i]==p2.code[i]) && (p1.code[i]=='1'))
flag='0';
}

if(flag==0)
return(1);

return(2);
}

PT resetendpt(PT p1,PT p2)


{
PT temp;
int x,y,i;
float m,k;

if(p1.code[3]=='1')
x=150;

if(p1.code[2]=='1')
x=450;

if((p1.code[3]=='1') || (p1.code[2]=='1'))
{
m=(float)(p2.y-p1.y)/(p2.x-p1.x);
k=(p1.y+(m*(x-p1.x)));
temp.y=k;
temp.x=x;

for(i=0;i<4;i++)
temp.code[i]=p1.code[i];

if(temp.y<=350 && temp.y>=100)


return (temp);
}

if(p1.code[0]=='1')
y=100;

if(p1.code[1]=='1')
y=350;

if((p1.code[0]=='1') || (p1.code[1]=='1'))
{
m=(float)(p2.y-p1.y)/(p2.x-p1.x);
k=(float)p1.x+(float)(y-p1.y)/m;
temp.x=k;
temp.y=y;

for(i=0;i<4;i++)
temp.code[i]=p1.code[i];

return(temp);
}
else
return(p1);
}

Result:

Before clipping:
After clipping:

Learning:

The algorithm divides a two-dimensional space into 9 regions and then efficiently determines the lines and
portions of lines that are visible in the central region of interest (the viewport).

Cohen Sutherland Line Clipping Algorithm is used to clip certain portions of the display according to a given
window.
Program-11

AIM:

Write a program to implement Liang Barsky Line Clipping algorithm.

Description:

● The Liang–Barsky algorithm uses the parametric equation of a line and inequalities describing the
range of the clipping window to determine the intersections between the line and the clip window.
With these intersections it knows which portion of the line should be drawn.
● This algorithm is significantly more efficient than Cohen–Sutherland.
● The idea of the Liang–Barsky clipping algorithm is to do as much testing as possible before computing
line intersections.

Algorithm:

1. Set tmin=0 and tmax=0


2. Calculate the values of tL, tR, tT, and tB (tvalues).
2.1 if t < tmin or t > tmax ignore it and go to the next edge
2.2 otherwise classify the tvalue as entering or exiting value (using inner product to classify)
2.3 if t is entering value set tmin = t ;
if t is exiting value set tmax = t
3. If tmin < tmax then draw a line from (x1 + dxtmin, y1 + dytmin) to (x1 + dxtmax, y1 + dytmax)
4. If the line crosses over the window, you will see (x1 + dxtmin, y1 + dytmin) and (x1 + dxtmax, y1 +
dytmax) are intersection between line and edge.

CODE:

#include<iostream.h>
#include<conio.h>
#include<graphics.h>

void main()

int gd = DETECT,gm;
initgraph(&gd,&gm,"C:\\TC\\BGI");
int x1,y1,x2,y2,xmax,xmin,ymax,ymin,xx1,yy1,xx2,yy2,dx,dy,i;

int p[4],q[4];

float t1,t2,t[4];
cout<<"Enter the lower co-ordinates of window";
cin>>xmin>>ymin;

cout<<"Enter the upper co-ordinates of window";

cin>>xmax>>ymax;

setcolor(RED);

rectangle(xmin,ymin,xmax,ymax);

cout<<"Enter x1:";

cin>>x1;

cout<<"Enter y1:";

cin>>y1;

cout<<"Enter x2:";

cin>>x2;

cout<<"Enter y2:";

cin>>y2;

line(x1,y1,x2,y2);

dx=x2-x1;

dy=y2-y1;

p[0]=-dx;

p[1]=dx;

p[2]=-dy;

p[3]=dy;

q[0]=x1-xmin;

q[1]=xmax-x1;

q[2]=y1-ymin;

q[3]=ymax-y1;

for(i=0;i < 4;i++)

{
if(p[i]!=0)

t[i]=(float)q[i]/p[i];
}

else

if(p[i]==0 && q[i] < 0)

cout<<"Line completely outside the window";

else

if(p[i]==0 && q[i] >= 0)

cout<<"Line completely inside the window";

if (t[0] > t[2]){

t1=t[0];

else{

t1=t[2];

if (t[1] < t[3]){

t2=t[1];

else{

t2=t[3];

if (t1 < t2){

xx1=x1+t1*dx;

xx2=x1+t2*dx;

yy1=y1+t1*dy;

yy2=y1+t2*dy;

cout<<"Line after clipping:";

setcolor(WHITE);

line(xx1,yy1,xx2,yy2);

}
else

cout<<"Line lies out of the window" }

getch();
}

Result:

Before Clipping:

After clipping:

Learning:

1. More efficient than other algorithms as line intersection with boundaries calculations are reduced.
2. Intersections of line are computed only once.

It can also be extended to 3-Dimensional Clipping. At most 4 parameter values are computed in Liang Barsky
Algorithm and it is a non-iterative algorithm.

Das könnte Ihnen auch gefallen