Cohen
- 1. #include<GL/glut.h>
#include<stdio.h>
#include<stdlib.h>
typedef unsigned int outcode;
int X0,X1,xmin,ymin,xmax,ymax,Y0,Y1;
enum{
TOP=0X1,
BOTTOM=0x2,
RIGHT=0x4,
LEFT=0x8
};
void Draw_Line(int X0,int Y0,int X1,int Y1)
{
glBegin(GL_LINES);
glColor3f(0,0,0.4);
glVertex2d(X0,Y0);
glVertex2d(X1,Y1);
glEnd();
}
void Draw_Rect(int xmin,int ymin,int xmax,int
ymax)
{
glBegin(GL_LINES);
glColor3f(0,2,0);
glVertex2d(xmin,ymin);
glVertex2d(xmax,ymin);
glVertex2d(xmax,ymin);
glVertex2d(xmax,ymax);
glVertex2d(xmax,ymax);
glVertex2d(xmin,ymax);
glVertex2d(xmin,ymax);
glVertex2d(xmin,ymin);
glEnd();
}
outcode CompOutCode(int x,int y,int xmin,int
xmax,int ymin,int ymax)
- 2. {
outcode code=0;
if(y>ymax)
code |=TOP;
else if(y<ymin)
code |=BOTTOM;
if(x>xmax)
code |=RIGHT;
else if(x<xmin)
code |=LEFT;
return code;
}
void cohen(int X0,int Y0,int X1,int Y1,int
xmin,int xmax,int ymin,int ymax)
{
outcode outcode0,outcode1,outcodeout;
int accept=0,done=0;
outcode0=CompOutCode(X0,Y0,xmin,xmax,ymin,ymax);
outcode1=CompOutCode(X1,Y1,xmin,xmax,ymin,ymax);
do
{
if(!(outcode0|outcode1))
{
accept=1;
done=1;
}
else if(outcode0 & outcode1)
done=1;
else
{
int x,y;
outcodeout=outcode0 ? outcode0:outcode1;
if(outcodeout & TOP)
{
x=X0+(X1-X0)*(ymax-Y0)/(Y1-Y0);
y=ymax;
}
else if(outcodeout & BOTTOM)
{
- 3. x=X0+(X1-X0)*(ymin-Y0)/(Y1-Y0);
y=ymin;
}
else if(outcodeout & RIGHT)
{
y=Y0+(Y1-Y0)*(xmax-X0)/(X1-X0);
x=xmax;
}
else
{
y=Y0+(Y1-Y0)*(xmin-X0)/(X1-X0);
x=xmin;
}
if(outcodeout==outcode0)
{
X0=x;
Y0=y;
outcode0=CompOutCode(X0,Y0,xmin,xmax,ymin,ymax);
}
else
{
X1=x;
Y1=y;
outcode1=CompOutCode(X1,Y1,xmin,xmax,ymin,ymax);
}
}
}while(done==0);
if(accept)
{
Draw_Line(X0+150,Y0,X1+150,Y1);
Draw_Rect(xmin+150,ymin,xmax+150,ymax);
}
}
void disp(void)
{
glClear(GL_COLOR_BUFFER_BIT);
Draw_Line(X0,Y0,X1,Y1);
Draw_Rect(xmin,ymin,xmax,ymax);
cohen(X0,Y0,X1,Y1,xmin,xmax,ymin,ymax);
- 4. glFinish();
}
void myInit()
{
glClearColor(0.8,0.8,0.4,0.1);
glLineWidth(2.0);
gluOrtho2D(0,400,0,400);
}
int main(int argc,char *argv[])
{
glutInit(&argc,argv);
glutInitWindowSize(640,480);
glutInitWindowPosition(200,100);
glutCreateWindow("lineclipping1");
glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE);
printf("enter the coordinates of line X0 &
Y0 n");
scanf("%d%d",&X0,&Y0);
printf("enter the coordinates of line X1 &
Y1 n");
scanf("%d%d",&X1,&Y1);
printf("n enter coordinates of rectangle in
order xmin ymin xmax ymaxn");
printf("xmin:");
scanf("%d%d%d%d",&xmin,&ymin,&xmax,&ymax);
myInit();
glutDisplayFunc(disp);
glutMainLoop();
return 0;
}