|
|
IGNOU > IGNOU Assignments > MCA > MCA 2009 Assignments >Computer Graphics and Multimedia
IGNOU MCA Assignments
Question 2 Write a program in C/C++ to implement Cohen-Sutherland line clipping algorithm. In this implementation, consider two cases of a line: totally visible, totally invisible, against the rectangular clipping window.
Ans:
#include <stdio.h>
#include <conio.h>
#include<graphics.h>
void clipline(int,int,int,int);
void encode();
int accept();
int reject();
int xwmin=100,xwmax=350,ywmin=100,ywmax=350;
int x1,x2,y1,y2,x,y,a1,b1,a2,b2,temp,temp1;
int code1[4],code2[4],code3[4],code4[4];
int done=0,disp=0,k,c[4],i;
float m;
void main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
printf("enter the x1 & y1 coordinate:\n");
scanf("%d%d",&x1,&y1);
printf("Enter the x2 & y2 coordinate:\n");
scanf("%d%d",&x2,&y2);
getch();
clrscr();
cleardevice();
setcolor(6);
settextstyle(DEFAULT_FONT,HORIZ_DIR,3);
outtextxy(200,50,"BEFORE CLIPPING");
rectangle(xwmin,ywmin,xwmax,ywmax);
line(x1,y1,x2,y2);
line(a1,b1,a2,b2);
getch();
clrscr();
outtextxy(200,50,"AFTER CLIPPING");
rectangle(xwmin,ywmin,xwmax,ywmax);
clipline(x1,y1,x2,y2);
clipline(a1,b1,a2,b2);
getch();
closegraph();
}
void encode(int x,int y,int code[4])
{
if(x)
code[1]=1;
else
code[1]=0;
if(x>xwmax)
code[2]=1;
else
code[2]=0;
if(y)
code[3]=1;
else
code[3]=0;
if(x>xwmax)
code[4]=1;
else
code[4]=0;
}
int accept(int code1[],int code2[])
{
int k;
int accept1;
accept1=1;
for(k=1;k<=4;k++)
{
if(code1[k] || code2[k])
accept1=0;
}
return accept1;
}
int reject(int code1[],int code2[])
{
int k,reject1;
reject1=0;
for(k=1;k<=4;k++)
{
if(code1[k] && code2[k])
reject1=1;
}
return reject1;
}
void clipline(int x1,int y1,int x2,int y2)
{
int a,r;
a=r=0;
done=0;
disp=0;
while(!done)
{
encode(x1,y1,code1);
encode(x2,y2,code2);
a=(accept(code1,code2));
if(a)
{
done=1;
disp=1;
}
else
r=(reject(code1,code2));
if(r)
done=1;
else
{
if((x2xwmax)||(y2ywmax))
{
temp=x1;
x1=x2;
x2=temp;
temp1=y1;
y1=y2;
y2=temp1;
for(i=1;i<=4;i++)
c[i]=code1[i];
for(i=1;i<=4;i++)
code1[i]=code2[i];
for(i=1;i<=4;i++)
code2[i]=c[i];
}
}
m=(float)(y2-y1)/(float)(x2-x1);
if(code1[1])
{
y1=y1+(xwmin-x1)*m;
x1=xwmin;
}
else if(code1[2])
{
y1=y1+(xwmax-x1)*m;
x1=xwmax;
}
else
{
if(code1[3])
{
if(m=0)
x1=x;
else
{
x1=x1+(ywmin-y1)/m;
y1=ywmin;
}
}
if(code1[4])
{
if(m==0)
x1=x1;
else
{
x1=x1+(ywmax-y1)/m;
y1=ywmax;
}
}
}
}
if(disp==1)
line(x1,y1,x2,y2);
}
}
 
|
|