EX NO: 11 COHEN-SUTHERLAND CLIPPING ALGORITHM
AIM:
To clip a line using Cohen-Sutherland clipping algorithm.
Algorithm:
The method speeds up the processing of line segments by performing initial tests that reduce the number of intersections that must be calculated.
1. Every line endpoint is assigned a four digit binary code, called region code, that identifies the location of the point relative to the boundaries of the clipping rectangle.
2. Each bit position in the region code is used to indicate one of the four relative coordinate positions of the point with respect to the clip window.
Bit 1: left
Bit 2: right
Bit 3: below
Bit 4: above
3. Bit values in the region code are determined by comparing endpoint coordinates values (x, y) with respect to the clip boundaries. eg.Bit 1 is set to 1 if x<xwmin
4. Once we have established region codes for all line endpoints, we can quickly determine which lines are completely outside or inside the clip window.
5. Lines that cannot be identified as completely inside or outside a clip window are checked for intersection with boundaries.
6. Intersection points with a clipping boundary can be calculated using the slope-intercept form of the line equation.
7. The y coordinate of the intersection point at vertical line
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<math.h>
float cxl,cxr,cyt,cyb;
code(float ,float);
void clip(float ,float,float,float);
void rect(float ,float,float,float);
main()
{
float x1,y1,x2,y2;
int g=0,d;
initgraph(&g,&d,"c:\\tc\\bin");
settextstyle(1,0,1);
outtextxy(40,15,"BEFORE CLIPPING");
printf("\n Please Enter Left,Bottom,Right,Top Of Clip Window");
scanf("%f%f%f%f",&cxl,&cyb,&cxr,&cyt);
rect(cxl,cyb,cxr,cyt);
getch();
printf("\n Enter The Line Coordinate");
scanf("%f%f%f%f",&x1,&y1,&x2,&y2);
line(x1,y1,x2,y2);
getch();
cleardevice();
settextstyle(1,0,1);
outtextxy(40,15,"AFTER CLIPPING");
clip(x1,y1,x2,y2);
getch();
closegraph();
}
void clip(float x1,float y1,float x2,float y2)
{
int c,c1,c2;
float x,y;
c1=code(x1,y1);
c2=code(x2,y2);
getch();
while((c1!=0)||(c2!=0))
{
if((c1&c2)!=0)
goto out;
c=c1;
if(c==0)
c=c2;
if((c&1)==1)
{
y=y1+(y2-y1)*(cxl-x1);
x=cxl;
}
else
if((c&2)==2)
{
y=y1+(y2-y1)*(cxl-x1)/(x2-x1);
x=cxr;
}
else
if((c&8)==8)
{
x=x1+(x2-x1)*(cyb-y1)/(y2-y1);
y=cyb;
}
else
if((c&4)==4)
{
x=x1+(x2-x1)*(cyt-y1)/(y2-y1);
y=cyt;
}
if(c==c1)
{
x1=x;
y1=y;
c1=code(x,y);
}
else
{
x2=x;
y2=y;
c2=code(x,y);
}
}
out:
rect(cxl,cyb,cxr,cyt);
line(x1,y1,x2,y2);
}
code(float x ,float y)
{
int c=0;
if(x<cxl) c=1;
else
if(x>cxr) c=2;
else
if(y<cyb) c=c|8;
else
if(y>cyt) c=c|4;
return c;
}
void rect(float xl,float yb,float xr,float yt)
{
line(xl,yb,xr,yb);
line(xr,yb,xr,yt);
line(xr,yt,xl,yt);
line(xl,yt,xl,yb);
}
OUTPUT
BEFORE CLIPPING
Please Enter Left , Bottom , Right , Top Of The Clip window
200
200
400
400
Please Enter The Line Coordinates (X1, Y1, X2, Y2)
150
300
400
450
RESULT : Thus the program is executed successfully.
0 comments:
Post a Comment