Computer graphics programs
Computer graphics program - Cohen-sutherland Line clipping algorithm
Cohen-sutherland Line clipping algo.
Cohen-sutherland Line clipping algorithm program
Code
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
int el,er,et,eb;
int *code(int a,int b)
{
int *x,i;
x=(int*)malloc(sizeof(int)*4);
for(i=0;i<4;i++)
x[i]=1;
if(a>=el)
x[0]=0;
if(a<=er)
x[1]=0;
if(b<=eb)
x[2]=0;
if(b>=et)
x[3]=0;
return x;
}
int count (int *e)
{
int i,cnt=0;
for(i=0;i<4;i++)
if(e[i]==0)
cnt++;
return cnt;
}
int intersect(int x1,int y1,int cp,float m,int *p)
{
int x,y,*e,c;
switch(cp)
{
case 0: y=y1+m*(el-x1);
x=el;
break;
case 1: y=y1+m*(er-x1);
x=er;
break;
case 3: x=x1+(et-y1)/m;
y=et;
break;
case 4: x=x1+(eb-y1)/m;
y=eb;
}
e=code(x,y);
c=count(e);
if(c==4)
{
p[0]=x;
p[1]=y;
cp=4;
}
else
cp++;
return cp;
}
main()
{
int gd=DETECT,gm;
int cp=0,cnt1,x,y,x1,x2,y1,y2,i,p,cnt=0,p1[2]={-1,-1},p2[2]={-1,-1};
int *b,*d;
float m;
initgraph(&gd,&gm,"c:\\tc\\bgi");
cleardevice();
setbkcolor(15);
setcolor(8);
printf("enter the boundaries of the clip window:");
scanf("%d %d %d %d",&el,&er,&et,&eb); // boundaries of clip window
printf("enter the co-ordinates1:");
scanf("%d %d",&x1,&y1);
b=code(x1,y1);
printf("enter the co-ordinates2:");
scanf("%d%d",&x2,&y2);
d=code(x2,y2);
cleardevice();
line(el,et,er,et);
line(el,eb,er,eb);
line(el,et,el,eb);
line(er,et,er,eb);
line(x1,y1,x2,y2);
getch();
cleardevice();
line(el,et,er,et);
line(el,eb,er,eb);
line(el,et,el,eb);
line(er,et,er,eb);
cnt=count(b);
cnt1=count(d);
m=1.0*(y2-y1)/(x2-x1);
if(cnt==4 && cnt1==4)
{
line(x1,y1,x2,y2);
getch();
exit(1);
}
if(b[0]*d[0]!=0 || b[1]*d[1]!=0 ||b[2]*d[2]!=0 ||b[3]*d[3]!=0 )
{
printf("line invisible");
getch();
exit(1);
}
if(cnt==4)
{
p1[0]=x1;
p1[1]=y1;
}
else
{
while(cp<=3)
{
if(b[cp]==1)
cp=intersect(x1,y1,cp,m,p1);
else
cp++;
}
}
getch();
cp=0;
if(cnt1==4)
{
p2[0]=x2;
p2[1]=y2;
}
else
{
while(cp<=3)
{
if(d[cp]==1)
cp=intersect(x1,y1,cp,m,p2);
else
cp++;
}
}
if(p1[0]!=-1 && p1[1]!=-1)
line(p1[0],p1[1],p2[0],p2[1]);
else
printf("line invisible");
getch();
return 0;
}