COHEN
COHEN
h>
#include<conio.h>
#include<stdio.h>
#include<math.h>
void main()
{
int rcode_begin[4]={0,0,0,0},rcode_end[4]={0,0,0,0},region_code[4];
int W_xmax_AG,W_ymax_AG,W_xmin_AG,W_ymin_AG,flag=0;
float slope;
int x_AG,y_AG,x1_AG,y1_AG,i_AG, xc_AG,yc_AG;
int gr=DETECT,gm;
initgraph(&gr,&gm,"C:\\TURBOC3\\BGI");
printf("\n*** Cohen Sutherland Line Clipping algorithm ****");
printf("\n Now, enter XMin, YMin =");
scanf("%d %d",&W_xmin_AG,&W_ymin_AG);
printf("\n First enter XMax, YMax =");
scanf("%d %d",&W_xmax_AG,&W_ymax_AG);
printf("\n Please enter intial point x and y= ");
scanf("%d %d",&x_AG,&y_AG);
printf("\n Now, enter final point x1_AG and y1_AG= ");
scanf("%d %d",&x1_AG,&y1_AG);
cleardevice();
rectangle(W_xmin_AG,W_ymin_AG,W_xmax_AG,W_ymax_AG);
line(x_AG,y_AG,x1_AG,y1_AG);
line(0,0,600,0);
line(0,0,0,600);
if(y_AG>W_ymax_AG) {
rcode_begin[0]=1; // Top
flag=1 ;
}
if(y_AG<W_ymin_AG) {
rcode_begin[1]=1; // Bottom
flag=1;
}
if(x_AG>W_xmax_AG) {
rcode_begin[2]=1; // Right
flag=1;
}
if(x_AG<W_xmin_AG) {
rcode_begin[3]=1; //Left
flag=1;
}
if(x1_AG>W_xmax_AG){
rcode_end[2]=1; // Right
flag=1;
}
if(x1_AG<W_xmin_AG){
rcode_end[3]=1; //Left
flag=1;
}
if(flag==0)
{
printf("No need of clipping as it is already in window");
}
flag=1;
for(i_AG=0;i_AG<4;i_AG++){
region_code[i_AG]= rcode_begin[i_AG] && rcode_end[i_AG] ;
if(region_code[i_AG]==1)
flag=0;
}
if(flag==0)
{
printf("\n Line is completely outside the window");
}
else{
slope=(float)(y1_AG-y_AG)/(x1_AG-x_AG);
if(rcode_begin[2]==0 && rcode_begin[3]==1) //left
{
y_AG = y_AG+(float) (W_xmin_AG-x_AG)*slope ;
x_AG=W_xmin_AG;
}
if(rcode_begin[2]==1 && rcode_begin[3]==0) // right
{
y_AG=y_AG+(float) (W_xmax_AG-x_AG)*slope ;
x_AG=W_xmax_AG;
}
if(rcode_begin[0]==1 && rcode_begin[1]==0) // top
{
x_AG=x_AG+(float) (W_ymax_AG-y_AG)/slope ;
y_AG=W_ymax_AG;
}
if(rcode_begin[0]==0 && rcode_begin[1]==1) // bottom
{
x_AG=x_AG+(float) (W_ymin_AG-y_AG)/slope ;
y_AG=W_ymin_AG;
}
// end points
if(rcode_end[2]==0 && rcode_end[3]==1) //left
{
y1_AG=y1_AG+(float) (W_xmin_AG-x1_AG)*slope ;
x1_AG=W_xmin_AG;
}
if(rcode_end[2]==1 && rcode_end[3]==0) // right
{
y1_AG=y1_AG+(float) (W_xmax_AG-x1_AG)*slope ;
x1_AG=W_xmax_AG;
}
if(rcode_end[0]==1 && rcode_end[1]==0) // top
{
x1_AG=x1_AG+(float) (W_ymax_AG-y1_AG)/slope ;
y1_AG=W_ymax_AG;
}
if(rcode_end[0]==0 && rcode_end[1]==1) // bottom
{
x1_AG=x1_AG+(float) (W_ymin_AG-y1_AG)/slope ;
y1_AG=W_ymin_AG;
}
}
clearviewport();
rectangle(W_xmin_AG,W_ymin_AG,W_xmax_AG,W_ymax_AG);
line(0,0,600,0);
line(0,0,0,600);
setcolor(RED);
line(x_AG,y_AG,x1_AG,y1_AG);
getch();
closegraph();
}