Liang Barksy

#include
#include
double xmin = 100, ymin = 100, xmax = 200, ymax = 200; // clipping window
double x0, y0, x1, y1, t, t1 = 0.0, t2 = 1.0;
int cliptest(double p,double q)
{
	double t = q/p;
	if(p  t1) t1 = t;
		if(t > t2) return(false);
	}
	else if(p > 0.0)
	{
		if(t < t2) t2=t;
		if(t < t1) return(false);
	}
	else if(p == 0.0)
	{
		if(q < 0.0) return(false);
	}
	return(true);
}

void LiangBarsky(double x1,double y1,double x2,double y2)
{
	int i;
	double p[4], q[4];

	p[0] = -(x2-x1);
	p[1] = (x2-x1);
	p[2] = -(y2-y1);
	p[3] = (y2-y1);
	q[0] = (x1-xmin);
	q[1] = (xmax-x1);
	q[2] = (y1-ymin);
	q[3] = (ymax-y1);

	if(cliptest(p[0],q[0]))
		if(cliptest(p[1],q[1]))
			if(cliptest(p[2],q[2]))
				if(cliptest(p[3],q[3]))
				{
					if(t20.0)
					{
						x1=x1+t1*p[1];
						y1=y1+t1*p[3];
					}

					glColor3f(1.0,0.0,0.0);		// Set red colour
					glBegin(GL_LINES);			// Display clipped line in red
					glVertex2d(x1,y1);
					glVertex2d(x2,y2);
					glEnd();
				}
}

void display()
{
	glClear(GL_COLOR_BUFFER_BIT);
	glColor3f(1.0,1.0,1.0);
	glBegin(GL_LINES);				// Display line
	glVertex2d(x0,y0);
	glVertex2d(x1,y1);
	glEnd();
	glColor3f(1.0,1.0,0.0);
	glBegin(GL_LINE_LOOP);			// Display Clipping Window
	glVertex2f(xmin,ymin);
	glVertex2f(xmax,ymin);
	glVertex2f(xmax,ymax);
	glVertex2f(xmin,ymax);
	glEnd();
	LiangBarsky(x0,y0,x1,y1);
	glFlush();
}

void myinit()
{
	glClearColor(0.0,0.0,0.0,1.0);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0.0,300.0,0.0,300.0);
}

int main(int argc, char ** argv)
{
	printf("Enter the end points of the line: ");
	scanf("%lf%lf%lf%lf", &x0,&y0,&x1,&y1);
	glutInit(&argc,argv);
	glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
	glutInitWindowSize(500,500);
	glutInitWindowPosition(0,0);
	glutCreateWindow("Liang-Barsky Line Clipping");
	glutDisplayFunc(display);
	myinit();
	glutMainLoop();
	return 0;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s