Implementation of Cohen-Sutherland 2D Clipping [CS1255 - Graphics and Multimedia Lab]


AIM:
                To write a "C++" program for the implementation of Cohen-Sutherland 2D Clipping in CS1255 - Graphics and Multimedia Lab.

SOURCE CODE:

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

class clips
{
private:
int x1[10],y1[10],x2[10],y2[10];
int xmin,ymin,xmax,ymax;
int i,j,l,m,n,x,y;
int a1[5],b1[5],c1[5],d1[5];
int a2[5],b2[5],c2[5],d2[5];
public:
void input();
void call();
};

void clips::input()
{
cout<<"Enter the value of window:\n";
cin>>xmin>>ymin>>xmax>>ymax;
rectangle(xmin,ymin,xmax,ymax);
cout<<"Enter the no of lines:\n";
cin>>n;
for(i=1;i<=n;i++)
{
cin>>x1[i]>>y1[i]>>x2[i]>>y2[i];
line(x1[i],y1[i],x2[i],y2[i]);
}
getch();
}

void clips::call()
{
cout<<"The clipped image";
rectangle(xmin,ymin,xmax,ymax);
for(i=1;i<=n;i++)
{
if(x1[i]>xmin)
a1[i]=0;
else
a1[i]=1;
if(x1[i]<xmax)
b1[i]=0;
else
b1[i]=1;
if(y1[i]>ymin)
c1[i]=0;
else
c1[i]=1;
if(y1[i]<ymax)
d1[i]=0;
else
d1[i]=1;
if(x2[i]>xmin)
a2[i]=0;
else
a2[i]=1;
if(x2[i]<xmax)
b2[i]=0;
else
b2[i]=1;
if(y2[i]>ymin)
c2[i]=0;
else
c2[i]=1;
if(y2[i]<ymax)
d2[i]=0;
else
d2[i]=1;
if(a1[i]==0&&b1[i]==0&&c1[i]==0&&d1[i]==0&&a2[1]==0&&b2[i]==0&&c2[i]==0&&d2[i]==0)
line(x1[i],y1[i],x2[i],y2[i]);
else if((a1[i]&&b1[i]&&c1[i]&&d1[i]==1)&&(a2[1]&&b2[i]&&c2[i]&&d2[i])==1)
cout<<" ";
else
{
j=y2[i]-y1[i];
l=x2[i]-x1[i];
m=j/l;
if(a1[i]==0&&b1[i]==0&&c1[i]==0&&d1[i]==0)
{
if(x2[i]<xmin)
{
x=xmin;
y=y1[i]+(m*(xmin-x1[i]));
}
else if(x2[i]>xmax)
{
x=xmax;
y=y1[i]+(m*(xmax-x1[i]));
}
else if(y2[i]<ymin)
{
y=ymin;
x=x1[i]+((ymin-y1[i])/m);
}
else if(y2[i]>ymax)
{
y=ymax;
x=x1[i]+((ymax-y1[i])/m);
}
line(x,y,x1[i],y1[i]);
}
else if(a2[i]==0&&b2[i]==0&&c2[i]==0&&d2[i]==0)
{
if(x1[i]<xmin)
{
x=xmin;
y=y1[i]+(m*(xmin-x1[i]));
}
else if(x1[i]>xmax)
{
x=xmax;
y=y1[i]+(m*(xmax-x1[i]));
}
else if(y1[i]<ymin)
{
y=ymin;
x=x1[i]+((ymin-y1[i])/m);
}
else if(y1[i]>ymax)
{
y=ymax;
x=x1[i]+((ymax-y1[i])/m);
}
line(x,y,x2[i],y2[i]);
}
}
}
}

void main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,"c:\\tc\\bgi");
clips clip;
clip.input();
clearviewport();
clip.call();
getch();
closegraph();
}

OUTPUT:


Previous
Next Post »

Still not found what you are looking for? Try again here.