School of Computer Science and Engineering Winter Session 2020-21

You might also like

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

School of Computer Science and Engineering

Winter Session 2020-21

Course Name: Computer Graphics


Course Code: BTCS- 2401

Submitted By: Rishiv Kaushal

Admission No: 19SCSE1180124


Enrolment No: 19021130031
Section: AI&ML- 1

Submitted To: S. Deepica


List of Experiments

S. No Experiment Signature /
Remark

1. Study of basic graphics functions defined in “graphics.h”

2. To study and Implement DDA Algorithm

3. To study and Implement Bresenham's Algorithm

4. To implement Bresenham’s algorithms for Circle drawing.

5. To study and Implement Midpoint Circle Algorithm

6. To study and Implement 2D Translation

7. To study and Implement 2D Rotation

8. To study and Implement 2D Scaling

9. To implement Cohen-Sutherland 2-D Line clipping.

10. To study and Implement Polygon Clipping Algorithm using


SutherlandHodgman Algorithm.

11. To generate a smooth curve by using Bezier curve technique


for a given set of control points.

12. To generate an interpolation and approximation curve by


using B-Spline curve technique.

13. Write a program to implement Depth buffer Algorithm for


Hidden Surface removal.
Experiment: - 01
(Study of basic graphics functions defined in “graphics.h”)
Aim: - Getting knowledge of basic graphics functions defined in “graphics.h”
Pre- Requisite: - Knowledge of C language
Theory:

Function Description:

1. void initGraphics (int width, int height);

 Creates the graphics window on the screen. The first form creates a window with a
default size of 500x300; the second allows the client to specify the size of the
window.
 The call to initGraphics must precede any console output or calls to other functions
in this interface.

2. void drawArc(GRectangle bounds, double start, double sweep);

Usage:
 drawArc(bounds, start, sweep);
 drawArc(x, y, width, height, start, sweep);
3. void fillArc(GRectangle bounds, double start, double sweep);

Usage:
 fillArc(bounds, start, sweep);
 fillArc(x, y, width, height, start, sweep);
4. void setFont (string font);

 The font parameter is a string in the form family-style-size.


 In this string, family is the name of the font family; style is either missing
(indicating a plain font) or one of the strings Bold, Italic, or Bold Italic; and size is an
integer indicating the point size.

5. string getFont();

Usage:
 string font = getFont();

6. void setColor(string color);

 Sets the color used for drawing.


 The color parameter is usually one of the predefined color names from Java:

BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAG


ENTA, ORANGE, PINK, RED, WHITE, or YELLOW.

7. string getColor();

 Returns the current color as a string in the form "#rrggbb".


 In this string, the values rr, gg, and bb are two-digit hexadecimal values representing
the red, green, and blue components of the color, respectively.
Experiment: - 02
(Line Drawing Algorithms)
Aim: - To study and understand DDA Algorithms
Pre- Requisite: -
Knowledge of:

 Point Plotting Methods


 Graphics Initialization
 DDA Algorithms

Theory:
DDA Algorithm-
 In computer graphics, a digital differential analyser (DDA) is hardware or software used for
interpolation of variables over an interval between start and end point.

 DDAs are used for rasterization of lines, triangles and polygons.


 They can be extended to non-linear functions, such as perspective correct texture mapping,
quadratic curves, and traversing voxel.
In its simplest implementation for linear cases such as lines, the DDA algorithm interpolates
values in interval by computing for each xi the equations xi = xi−1 + 1, yi = yi−1 + m, where
m is the slope of the line.

This slope can be expressed in DDA as follows:

In fact, any two consecutive points (x, y) lying on this line segment should satisfy the
equation.
Algorithm:

Step 1: Start Algorithm


Step 2: Declare x1, y1, x2, y2, dx, dy, x, y as integer variables.
Step 3: Enter value of x1, y1, x2, y2.
Step 4: Calculate dx = x2-x1
Step 5: Calculate dy = y2-y1
Step 6: If ABS (dx) > ABS (dy)
Then step = abs (dx)
Else
Step 7: xinc=dx /step
yinc=dy /step
assign x = x1
assign y = y1
Step 8: Set pixel (x, y)
Step 9: x = x + xinc
y = y + yinc
Set pixels (Round (x), Round (y))
Step 10: Repeat step 9 until x = x2
Step 11: End Algorithm
Experiment: - 03
(Line Drawing Algorithm)

Aim: - To study and implement Bresenhams Algorithm


Pre- Requisite: -
Knowledge of:
 Point Plotting Methods

 Graphics Initialization
 Bresenhams Algorithm
Theory:
 This algorithm is used for scan converting a line. It was developed by Bresenham.
 It is an efficient method because it involves only integer addition, subtractions, and
multiplication operations.
 These operations can be performed very rapidly so lines can be generated quickly.In its
simplest implementation for linear cases such as lines, the DDA algorithm interpolates values
in interval by computing for each xi the equations xi = xi−1 + 1, yi = yi−1 + m, where m is
the slope of the line.

Program:
1. #include<stdio.h>
2. #include<graphics.h>
3. void drawline(int x0, int y0, int x1, int y1)
4. {
5. int dx, dy, p, x, y;
6. dx=x1-x0;
7. dy=y1-y0;
8. x=x0;
9. y=y0;
10. p=2*dy-dx;
11. while(x<x1)
12. {
13. if(p>=0)
14. {
15. putpixel(x,y,7);
16. y=y+1;
17. p=p+2*dy-2*dx;
18. }
19. else
20. {
21. putpixel(x,y,7);
22. p=p+2*dy;}
23. x=x+1;
24. }
25. }
26. int main()
27. {
28. int gdriver=DETECT, gmode, error, x0, y0, x1, y1;
29. initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi");
30. printf("Enter co-ordinates of first point: ");
31. scanf("%d%d", &x0, &y0);
32. printf("Enter co-ordinates of second point: ");
33. scanf("%d%d", &x1, &y1);
34. drawline(x0, y0, x1, y1);
35. return 0;
36. }

Output:
Experiment: - 04
(Circle Algorithm)
Aim: - To implement Bresenham’s algorithms for Circle drawing.
Pre- Requisite: -
Knowledge of:

 Point Plotting Methods


 Graphics Initialization
 Bresenhams Algorithm
Theory:
 In order to that we will use Bresenham’s Circle Algorithm for calculation of the locations
of the pixels in the first octant of 45 degrees. It assumes that the circle is centred on the
origin.
 So, for every pixel (x, y) it calculates, we draw a pixel in each of the 8 octants of the circle.
Now, we will see how to calculate the next pixel location from a previously known pixel
location (x, y).
 In Bresenham’s algorithm at any point (x, y) we have two option either to choose the next
pixel in the east i.e. (x+1, y) or in the south east i.e. (x+1, y-1).

Program:
1. #include <graphics.h>
2. #include <stdlib.h>
3. #include <stdio.h>
4. #include <conio.h>
5. #include <math.h>
6. void EightWaySymmetricPlot(int xc,int yc,int x,int y)
7. {
8. putpixel(x+xc,y+yc,RED);
9. putpixel(x+xc,-y+yc,YELLOW);
10. putpixel(-x+xc,-y+yc,GREEN);
11. putpixel(-x+xc,y+yc,YELLOW);
12. putpixel(y+xc,x+yc,12);
13. putpixel(y+xc,-x+yc,14);
14. putpixel(-y+xc,-x+yc,15);
15. putpixel(-y+xc,x+yc,6);
16. }
17. void BresenhamCircle(int xc,int yc,int r)
18. {
19. int x=0,y=r,d=3-(2*r);
20. EightWaySymmetricPlot(xc,yc,x,y);
21. while(x<=y)
22. {
23. if(d<=0)
24. {
25. d=d+(4*x)+6;
26. }
27. else
28. {
29. d=d+(4*x)-(4*y)+10;
30. y=y-1;
31. }
32. x=x+1;
33. EightWaySymmetricPlot(xc,yc,x,y);
34. }
35. }
36. int main(void)
37. {
38. /* request auto detection */
39. int xc,yc,r,gdriver = DETECT, gmode, errorcode;
40. /* initialize graphics and local variables */
41. initgraph(&gdriver, &gmode, "C:\\TURBOC3\\BGI");
42. /* read result of initialization */
43. errorcode = graphresult();
44. if (errorcode != grOk) /* an error occurred */
45. {
46. printf("Graphics error: %s\n", grapherrormsg(errorcode));
47. printf("Press any key to halt:");
48. getch();
49. exit(1); /* terminate with an error code */
50. }
51. printf("Enter the values of xc and yc :");
52. scanf("%d%d",&xc,&yc);
53. printf("Enter the value of radius :");
54. scanf("%d",&r);
55. BresenhamCircle(xc,yc,r);
56. getch();
57. closegraph();
58. return 0;
59. }

Output:
Experiment: - 05
(Circle Algorithm)
Aim: - To study and Implement Midpoint Circle Algorithm.
Pre- Requisite: -
Knowledge of:

 Point Plotting Methods


 Graphics Initialization
 Mid-Point Circle Drawing Algorithm
Theory:
 The mid-point circle drawing algorithm is an algorithm used to determine the points needed
for rasterizing a circle.
 We use the mid-point algorithm to calculate all the perimeter points of the circle in the first
octant and then print them along with their mirror points in the other octants. This will work
because a circle is symmetric about its centre

Program:
1. #include <graphics.h>
2. #include <stdlib.h>
3. #include <math.h>
4. #include <stdio.h>
5. #include <conio.h>
6. #include <iostream.h>
7. class bresen
8. {
9. float x, y,a, b, r, p;
10. public:
11. void get ();
12. void cal ();
13. };
14. void main ()
15. {
16. bresen b;
17. b.get ();
18. b.cal ();
19. getch ();
20. }
21. Void bresen :: get ()
22. {
23. cout<<"ENTER CENTER AND RADIUS";
24. cout<< "ENTER (a, b)";
25. cin>>a>>b;
26. cout<<"ENTER r";
27. cin>>r;
28. }
29. void bresen ::cal ()
30. {
31. /* request auto detection */
32. int gdriver = DETECT,gmode, errorcode;
33. int midx, midy, i;
34. /* initialize graphics and local variables */
35. initgraph (&gdriver, &gmode, " ");
36. /* read result of initialization */
37. errorcode = graphresult ();
38. if (errorcode ! = grOK) /*an error occurred */
39. {
40. printf("Graphics error: %s \n", grapherrormsg (errorcode);
41. printf ("Press any key to halt:");
42. getch ();
43. exit (1); /* terminate with an error code */
44. }
45. x=0;
46. y=r;
47. putpixel (a, b+r, RED);
48. putpixel (a, b-r, RED);
49. putpixel (a-r, b, RED);
50. putpixel (a+r, b, RED);
51. p=5/4)-r;
52. while (x<=y)
53. {
54. If (p<0)
55. p+= (4*x)+6;
56. else
57. {
58. p+=(2*(x-y))+5;
59. y--;
60. }
61. x++;
62. putpixel (a+x, b+y, RED);
63. putpixel (a-x, b+y, RED);
64. putpixel (a+x, b-y, RED);
65. putpixel (a+x, b-y, RED);
66. putpixel (a+x, b+y, RED);
67. putpixel (a+x, b-y, RED);
68. putpixel (a-x, b+y, RED);
69. putpixel (a-x, b-y, RED);
70. }
71. }

Output:
Experiment: - 06
(2-D Transformations - Translation)
Aim: - To study and Implement 2D Translation.
Pre- Requisite: -
Knowledge of:

 Point Plotting Methods


 Graphics Initialization
 2D Algorithms

Theory:
Transformation means changing some graphics into something else by applying rules. We
can have various types of transformations such as translation, scaling up or down, rotation,
shearing, etc. When a transformation takes place on a 2D plane, it is called 2D
transformation.

 Translation: A translation moves an object to a different position on the screen. You


can translate a point in 2D by adding translation coordinate (t x, ty) to the original
coordinate X,Y to get the new coordinate X′,Y′.

Program:

#include<graphics.h>

#include<stdlib.h>

#include<stdio.h>

#include<math.h>

void main()

int graphdriver=DETECT,graphmode,errorcode;

int i;

int x2,y2,x1,y1,x,y;

printf("Enter the 2 line end points:");


printf("x1,y1,x2,y2");

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

initgraph(&graphdriver,&graphmode,"c:\\tc\\bgi");

line(x1,y1,x2,y2);

printf("Enter translation co-ordinates ");

printf("x,y");

scanf("%d%d",&x,&y);

x1=x1+x;

y1=y1+y;

x2=x2+x;

y2=y2+y;

printf("translated line");

line(x1,y1,x2,y2);

getch();

closegraph();

Output:
Experiment: - 07
(2-D Transformations - Rotation)
Aim: - To study and Implement 2D Rotation.
Pre- Requisite: -
Knowledge of:

 Point Plotting Methods


 Graphics Initialization
 2D Algorithms
Theory:

 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.

Program:

#include<graphics.h>

#include<stdlib.h>

#include<stdio.h>

#include<math.h>

void main()

int graphdriver=DETECT,graphmode,errorcode;

int i;

int x2,y2,x1,y1,x,y,xn,yn;

double r11,r12,r21,r22,th;

clrscr();

printf("Enter the coordinates of line:");

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

initgraph(&graphdriver,&graphmode,"c:\\tc\\bgi");

line(x1,y1,x2,y2);

printf("\n\n\n[ Enter the angle");

scanf("%lf",&th);

r11=cos((th*3.1428)/180);

r12=sin((th*3.1428)/180);

r21=(-sin((th*3.1428)/180));

r22=cos((th*3.1428)/180);

//printf("%lf %lf %lf %lf",r11,r12,r21,r22);

xn=((x2*r11)-(y2*r12));

yn=((x2*r12)+(y2*r11));

line(x1,y1,xn,yn);

getch();

closegraph();

Output:
Experiment: - 08
(2-D Transformations - Scaling)
Aim: - To study and Implement 2D Scaling.
Pre- Requisite: -
Knowledge of:

 Point Plotting Methods


 Graphics Initialization
 2D Algorithms
Theory:

 Scaling: To change the size of an object, scaling transformation is used. In the scaling
process, you either expand or compress the dimensions of the object. Scaling can be
achieved by multiplying the original coordinates of the object with the scaling factor
to get the desired result.

Program:

#include<stdio.h>
#include<graphics.h>
// Matrix Multiplication to find new Coordinates.
// s[][] is scaling matrix. p[][] is to store
// points that needs to be scaled.
// p[0][0] is x coordinate of point.
// p[1][0] is y coordinate of given point.
void findNewCoordinate(int s[][2], int p[][1])
{
int temp[2][1] = { 0 };
for (int i = 0; i < 2; i++)
for (int j = 0; j < 1; j++)
for (int k = 0; k < 2; k++)
temp[i][j] += (s[i][k] * p[k][j]);

p[0][0] = temp[0][0];
p[1][0] = temp[1][0];
}
// Scaling the Polygon
void scale(int x[], int y[], int sx, int sy)
{
// Triangle before Scaling
line(x[0], y[0], x[1], y[1]);
line(x[1], y[1], x[2], y[2]);
line(x[2], y[2], x[0], y[0]);
// Initializing the Scaling Matrix.
int s[2][2] = { sx, 0, 0, sy };
int p[2][1];

// Scaling the triangle


for (int i = 0; i < 3; i++)
{
p[0][0] = x[i];
p[1][0] = y[i];
findNewCoordinate(s, p);
x[i] = p[0][0];
y[i] = p[1][0];
}
// Triangle after Scaling
line(x[0], y[0], x[1], y[1]);
line(x[1], y[1], x[2], y[2]);
line(x[2], y[2], x[0], y[0]);
}
// Driven Program
int main()
{
int x[] = { 100, 200, 300 };
int y[] = { 200, 100, 200 };
int sx = 2, sy = 2;
int gd, gm;
detectgraph(&gd, &gm);
initgraph(&gd, &gm," ");
scale(x, y, sx,sy);
getch();

return 0;
}

Output:
Experiment: - 09
(Cohen-Sutherland 2-D Line clipping)

Aim: - To implement Cohen-Sutherland 2-D Line clipping.

Pre- Requisite: -
Knowledge of:

 Point Plotting Methods


 Graphics Initialization

 Cohen-Sutherland Algorithm

Theory:
For a line segment with endpoints (x1, y1) and (x2, y2) and one or both end points outside the
clipping rectangle, the parametric representation is,

X =x1+u(x2-x1) Y=y1+u(y2-y1)

Program:

#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);
}

Output:
Experiment: - 10
(Polygon Clipping using Sutherland-Hodgman)

Aim: - To study and Implement Polygon Clipping Algorithm using Sutherland -Hodgman
Algorithm.
Pre- Requisite: -
Knowledge of:

 Point Plotting Methods


 Graphics Initialization
 Sutherland Hodgman Algorithm
Theory:

Sutherland-Hodgeman Polygon Clipping:

It is performed by processing the boundary of polygon against each window corner or edge.
First of all entire polygon is clipped against one edge, then resulting polygon is considered,
then the polygon is considered against the second edge, so on for all four edges.

Four possible situations while processing

1. If the first vertex is an outside the window, the second vertex is inside the window.
Then second vertex is added to the output list. The point of intersection of window
boundary and polygon side (edge) is also added to the output line.
2. If both vertexes are inside window boundary. Then only second vertex is added to the
output list.
3. If the first vertex is inside the window and second is an outside window. The edge
which intersects with window is added to output list.
4. If both vertices are the outside window, then nothing is added to output list.

Program:

#include<iostream.h>
#include<conio.h>
#include<graphics.h>
#define round(a) ((int)(a+0.5))
int k;
float xmin,ymin,xmax,ymax,arr[20],m;
void clipl(float x1,float y1,float x2,float y2)
{
if(x2-x1)
m=(y2-y1)/(x2-x1);
else
m=100000;
if(x1 >= xmin && x2 >= xmin)
{
arr[k]=x2;
arr[k+1]=y2;
k+=2;
}
if(x1 < xmin && x2 >= xmin)
{
arr[k]=xmin;
arr[k+1]=y1+m*(xmin-x1);
arr[k+2]=x2;
arr[k+3]=y2;
k+=4;
}
if(x1 >= xmin && x2 < xmin)
{
arr[k]=xmin;
arr[k+1]=y1+m*(xmin-x1);
k+=2;
}
}

void clipt(float x1,float y1,float x2,float y2)


{
if(y2-y1)
m=(x2-x1)/(y2-y1);
else
m=100000;
if(y1 <= ymax && y2 <= ymax)
{
arr[k]=x2;
arr[k+1]=y2;
k+=2;
}
if(y1 > ymax && y2 <= ymax)
{
arr[k]=x1+m*(ymax-y1);
arr[k+1]=ymax;
arr[k+2]=x2;
arr[k+3]=y2;
k+=4;
}
if(y1 <= ymax && y2 > ymax)
{
arr[k]=x1+m*(ymax-y1);
arr[k+1]=ymax;
k+=2;
}
}

void clipr(float x1,float y1,float x2,float y2)


{
if(x2-x1)
m=(y2-y1)/(x2-x1);
else
m=100000;
if(x1 <= xmax && x2 <= xmax)
{
arr[k]=x2;
arr[k+1]=y2;
k+=2;
}
if(x1 > xmax && x2 <= xmax)
{
arr[k]=xmax;
arr[k+1]=y1+m*(xmax-x1);
arr[k+2]=x2;
arr[k+3]=y2;
k+=4;
}
if(x1 <= xmax && x2 > xmax)
{
arr[k]=xmax;
arr[k+1]=y1+m*(xmax-x1);
k+=2;
}
}

void clipb(float x1,float y1,float x2,float y2)


{
if(y2-y1)
m=(x2-x1)/(y2-y1);
else
m=100000;
if(y1 >= ymin && y2 >= ymin)
{
arr[k]=x2;
arr[k+1]=y2;
k+=2;
}
if(y1 < ymin && y2 >= ymin)
{
arr[k]=x1+m*(ymin-y1);
arr[k+1]=ymin;
arr[k+2]=x2;
arr[k+3]=y2;
k+=4;
}
if(y1 >= ymin && y2 < ymin)
{
arr[k]=x1+m*(ymin-y1);
arr[k+1]=ymin;
k+=2;
}
}

void main()
{
int gdriver=DETECT,gmode,n,poly[20];
float xi,yi,xf,yf,polyy[20];
clrscr();
cout<<"Coordinates of rectangular clip window :\nxmin,ymin :";
cin>>xmin>>ymin;
cout<<"xmax,ymax :";
cin>>xmax>>ymax;
cout<<"\n\nPolygon to be clipped :\nNumber of sides :";
cin>>n;
cout<<"Enter the coordinates :";
for(int i=0;i < 2*n;i++)
cin>>polyy[i];
polyy[i]=polyy[0];
polyy[i+1]=polyy[1];
for(i=0;i < 2*n+2;i++)
poly[i]=round(polyy[i]);
initgraph(&gdriver,&gmode,"C:\\TC\\BGI");
setcolor(RED);
rectangle(xmin,ymax,xmax,ymin);
cout<<"\t\tUNCLIPPED POLYGON";
setcolor(WHITE);
fillpoly(n,poly);
getch();
cleardevice();
k=0;
for(i=0;i < 2*n;i+=2)
clipl(polyy[i],polyy[i+1],polyy[i+2],polyy[i+3]);
n=k/2;
for(i=0;i < k;i++)
polyy[i]=arr[i];
polyy[i]=polyy[0];
polyy[i+1]=polyy[1];
k=0;
for(i=0;i < 2*n;i+=2)
clipt(polyy[i],polyy[i+1],polyy[i+2],polyy[i+3]);
n=k/2;
for(i=0;i < k;i++)
polyy[i]=arr[i];
polyy[i]=polyy[0];
polyy[i+1]=polyy[1];
k=0;
for(i=0;i < 2*n;i+=2)
clipr(polyy[i],polyy[i+1],polyy[i+2],polyy[i+3]);
n=k/2;
for(i=0;i < k;i++)
polyy[i]=arr[i];
polyy[i]=polyy[0];
polyy[i+1]=polyy[1];
k=0;
for(i=0;i < 2*n;i+=2)
clipb(polyy[i],polyy[i+1],polyy[i+2],polyy[i+3]);
for(i=0;i < k;i++)
poly[i]=round(arr[i]);
if(k)
fillpoly(k/2,poly);
setcolor(RED);
rectangle(xmin,ymax,xmax,ymin);
cout<<"\tCLIPPED POLYGON";
getch();
closegraph();
}
Output:
Experiment: - 11
(Bezier Curve)

Aim: - To generate a smooth curve by using Bezier curve technique for a given set of
control points.
Pre- Requisite: -
Knowledge of:

 Point Plotting Methods


 Graphics Initialization
 Bezier Curve
Theory:

Bezier Curves

Bezier curve is discovered by the French engineer Pierre Bézier. These curves can be
generated under the control of other points. Approximate tangents by using control points are
used to generate curve. The Bezier curve can be represented mathematically as –

Where pipi is the set of points and Bni(t)Bin(t) represents the Bernstein polynomials which
are given by –

Where n is the polynomial degree, i is the index, and t is the variable.

Program:
#include<graphics.h>
#include<math.h>
#include<conio.h>
#include<stdio.h>
void main()
{
int x[4],y[4],i;
double put_x,put_y,t;
int gr=DETECT,gm;
initgraph(&gr,&gm,"C:\\TURBOC3\\BGI");
printf("\n****** Bezier Curve ***********");
printf("\n Please enter x and y coordinates ");
for(i=0;i<4;i++)
{
scanf("%d%d",&x[i],&y[i]);
putpixel(x[i],y[i],3); // Control Points
}

for(t=0.0;t<=1.0;t=t+0.001) // t always lies between 0 and 1


{
put_x = pow(1-t,3)*x[0] + 3*t*pow(1-t,2)*x[1] + 3*t*t*(1-t)*x[2] + pow(t,3)*x[3]; //
Formula to draw curve
put_y = pow(1-t,3)*y[0] + 3*t*pow(1-t,2)*y[1] + 3*t*t*(1-t)*y[2] + pow(t,3)*y[3];
putpixel(put_x,put_y, WHITE); // putting pixel
}
getch();
closegraph();
}
Output:
Experiment: - 12
(B – Spline Curve)

Aim: - To generate an interpolation and approximation curve by using B-Spline curve


technique.
Pre- Requisite: -
Knowledge of: -
 Point Plotting Methods
 Graphics Initializations
 Spline Curve Generation.

Theory:

The B Spline curve of order k (degree k−1) is a vector-valued piecewise polynomial function of the
form , 0 () () l i ik i P t PN t = = ∑ , 1 1 [,] k l ttt ∈ − + . where Pi denote the control points. Ni,k(t) are
the B Spline functions defined over the knot vector

The step in drawing the B Spline curves were as follows:

Step 1: Choose proper value N, M, compute the value n. Let B Spline curves change to integer
Eqs.(1), (4).

Step 2: From ( ) φ i and ϕ(i), i=0, 1, …, n. Compute φ and ϕ’s all order differences ak, bk at i=0.

Step 3: From Nx=φ(0)+z1, |z1|≤N/2 and My=ϕ(0) +q1, |qi|≤M/2, Compute first pixel point (x, y) and
z1, q1 at i=0.

Step 4: Draw the first pixel (x, y), and let xold=x, yold=y, xprev=x, yprev=y.

Step 5: For i=1, 2, …, n loop. Using Eqs.(2), (3) and difference formula, we compute xi+1, z i+1, y
i+1, q i+1. If ((|xi+1–xold| >1) or (|yi+1–yold | >1)) { Draw pixel (xprev, yprev), Let xold=xprev,
yold=yprev. } xprev=xi+1, yprev=yi+1.

Step 6: Draw the last point (x, y)..

Step 7: Stop

Program:

#include<stdio.h>
#include<math.h>
int i,j,k,ke,n,uj[50];
float u,t,nik[50][50];
int main()

{
int i,j,k,ke,umax;
printf("Enter the values of n and ke:\n");
scanf("%d %d",&n,&ke);
//Pyramid of Basis Functions; i.e Ni,k ;
printf ("\n The Pyramid of the basis function is as under:\n\n");
for (k=ke;k>=1;k--)
{
for(i=0;i<n+ke-k+1;i++)
printf("nik[%d][%d] ",i,k);
printf("\n\n");
}

printf("Range of j: 0<=j<= %d, \n i.e. There are %d knot Vectors \n Knot Vectors are :\n\n
",n+ke,n+ke+1);

for (j=0;j<=n+ke;j++)
{
if (j<ke)

uj[j]=0;

else if (j>=ke && j<=n)

uj[j]=j-ke+1;

else

uj[j]=n-ke+2;

printf("U%d = %d\n ",j ,uj[j]);


}
float denm1,num1,denm2,num2,u1,px[n],py[n],tempx,tempy;
printf("Enter the values of control points one by one\n");

for (j=0;j<=n;j++)
{
printf("px[%d],py[%d]=",j,j);
scanf("%f %f", &px[j],& py[j]);
}
abc:
printf("\nEnter the Step length required for U\n Smaller Numbers Give Higher Number of
Points on the Generated Curve.\n");
scanf("%f",&t);
if (t>0.5)
{
printf("\nEnter still Smaller Values of Step length of u\n");
goto abc;
}
else goto go;
go:
u1=0.0;
umax=n-ke+2;
while(u1<=umax)
{
printf("\n ");
for (j=0;j<n+ke;j++)
{
if(uj[j]==uj[j+1]) nik[j][1]=1;
if(u1>=uj[j] && u1<=uj[j+1]) nik[j][1]=1;
else nik[j][1]=0;

printf("nik[%d][1]=%1.2f\t for %d<=u<=%d\n = 0 \t elsewhere\n\n


",j,nik[j][1],uj[j],uj[j+1]);
}
printf("\n\n\n");

for(k=2;k<=ke;k++)
{
for (i=0;i<n+ke-k+1;i++)
{
denm1 = ((u1-uj[i])*nik[i][k-1]);
num1 = (uj[i+k-1]-uj[i]);
denm2 = ((uj[i+k]-u1)*nik[i+1][k-1]);
num2 = (uj[i+k]-uj[i+1]);
if(num1!=0 && num2!=0)
nik[i][k]=(denm1/num1) + (denm2/num2);
else if(num1!=0 && num2==0)
nik[i][k]=(denm1/num1);
else if(num2!=0 && num1==0)
nik[i][k]=(denm2/num2);
else nik[i][k]=0;

printf("nik[%d][%d]=%1.1f\n",i,k,nik[i][k]);
}
}

tempx=0;
tempy=0;
for(i=0;i<=n;i++)
{
tempx=tempx+px[i]*nik[i][ke];
tempy=tempy+py[i]*nik[i][ke];
}
printf("Px(u=%f)=%.3f\n",u1,tempx);
printf("Py(u=%f)=%.3f\n",u1,tempy);
u1=u1+t;
}
}

OUTPUT:
Experiment: - 13
(Depth Buffer Algorithm)

Aim: - Write a program to implement Depth buffer Algorithm for Hidden Surface
removal.

Pre- Requisite: -
Knowledge of: -
 Point Plotting Methods
 Graphics Initializations
 Depth Buffer Algorithm

Theory:
When viewing a picture containing non transparent objects and surfaces, it is not possible
to see those objects from view which are behind from the objects closer to eye. To get the
realistic screen image, removal of these hidden surfaces is must. The identification and
removal of these surfaces is called as the Hidden-surface problem.

Z-buffer, which is also known as the Depth-buffer method is one of the commonly used
method for hidden surface detection. It is an Image space method. Image space methods are
based on the pixel to be drawn on 2D. For these methods, the running time complexity is
the number of pixels times number of objects. And the space complexity is two times the
number of pixels because two arrays of pixels are required, one for frame buffer and the
other for the depth buffer.

The Z-buffer method compares surface depths at each pixel position on the projection
plane. Normally z-axis is represented as the depth. The algorithm for the Z-buffer method is
given below:

Algorithm:

Here is Z-buffer hidden surface algorithm: -


STEP 1. START
STEP 2. Set the frame buffer to the background intensity or color 2.
STEP 3. Set the z buffer to the minimum z value.
STEP 4. Scan converts each polygon in arbitrary order.
STEP 5. For each pixel (x,y) in the polygon, calculate the depth z(x,y) at that pixel.
STEP 6. Compare the depth z(x,y) with the value stored in the z buffeR at that location z
buffer(x,y) 6. If z(x,y) > z buffer(x,y) then write the polygon attributes to the frame buffer
and replace z.
STEP 7. Buffer (x,y) with z(x,y) otherwise “no action:”
STEP 8. Stop

Program:

/* vertices of cube about the origin */


GLfloat vertices[8][3] =
{{-1.0, -1.0, -1.0}, {1.0, -1.0, -1.0},
{1.0, 1.0, -1.0}, {-1.0, 1.0, -1.0}, {-1.0, -1.0, 1.0},
{1.0, -1.0, 1.0}, {1.0, 1.0, 1.0}, {-1.0, 1.0, 1.0}};
/* colors to be assigned to edges */
GLfloat colors[8][3] =
{{0.0, 0.0, 0.0}, {1.0, 0.0, 0.0},
{1.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 0.0, 1.0},
{1.0, 0.0, 1.0}, {1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}};
int main(int argc, char **argv)
{
glutInit(&argc, argv);
/* double buffering for smooth animation */
glutInitDisplayMode
(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGB);
... /* window creation and callbacks here */
glEnable(GL_DEPTH_TEST);
glutMainLoop();
return(0);
}
glutInitWindowSize(500, 500);
glutCreateWindow("cube");
glutReshapeFunc(myReshape);glutDisplayFunc(display);
glutIdleFunc(spinCube);
glutMouseFunc(mouse);
glutKeyboardFunc(keyboard);
void myReshape(int w, int h)
{
GLfloat aspect = (GLfloat) w / (GLfloat) h;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= h) /* aspect <= 1 */
glOrtho(-2.0, 2.0, -2.0/aspect, 2.0/aspect, -10.0, 10.0);
else /* aspect > 1 */
glOrtho(-2.0*aspect, 2.0*aspect, -2.0, 2.0, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
}
GLfloat theta[3] = {0.0, 0.0, 0.0};
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT
| GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glRotatef(theta[0], 1.0, 0.0, 0.0);
glRotatef(theta[1], 0.0, 1.0, 0.0);
glRotatef(theta[2], 0.0, 0.0, 1.0);colorcube(); glFlush();
glutSwapBuffers();
}
void colorcube(void)
{
face(0,3,2,1);
face(2,3,7,6);
face(0,4,7,3);
face(1,2,6,5);
face(4,5,6,7);
face(0,1,5,4);
}
void face(int a, int b, int c, int d)
{
glBegin(GL_POLYGON);
glColor3fv (colors[a]);
glVertex3fv(vertices[a]);
glColor3fv (colors[b]);
glVertex3fv(vertices[b]);
glColor3fv (colors[c]);
glVertex3fv(vertices[c]);
glColor3fv (colors[d]);
glVertex3fv(vertices[d]);
glEnd();
}GLfloat delta = 2.0;
GLint axis = 2;
void spinCube()
{
/* spin cube delta degrees about selected axis */
theta[axis] += delta;
if (theta[axis] > 360.0) theta[axis] -= 360.0;
/* display result */
glutPostRedisplay();
}
void mouse(int btn, int state, int x, int y)
{
if (btn==GLUT_LEFT_BUTTON
&& state == GLUT_DOWN) axis = 0;
if (btn==GLUT_MIDDLE_BUTTON
&& state == GLUT_DOWN) axis = 1;
if (btn==GLUT_RIGHT_BUTTON
&& state == GLUT_DOWN) axis = 2;
}
void keyboard(unsigned char key, int x, int y)
{
if (key==’q’ || key == ’Q’) exit(0);
if (key==’ ’) {stop = !stop;};
if (stop)
glutIdleFunc(NULL);else
glutIdleFunc(spinCube);
}

OUTPUT:

You might also like