Polygon Clipping

Write a program to implement Polygon Clipping.


#include<stdio.h>
#include<conio.h>
#include<graphics.h>
int cx1,cx2,cy1,cy2,i;
float x[50],y[50],xt[50],yt[50];
void check(float x1,float y1,float x2,float y2,int side);
int gd=DETECT,gm;
int nt=0,k=0,g,h,n;
void display()
{
	int i;
	for(i=0;i<n-1;i++)
		line(x[i],y[i],x[i+1],y[i+1]);
	line(x[i],y[i],x[0],y[0]);
	getch();
}
void main()
{
	int p,j;
	initgraph(&gd,&gm,"c:\\tc\\bgi");
	printf("\nEnter values for cx1,cy1,cx2,cy2\t:");
	scanf("%d%d%d%d",&cx1,&cy1,&cx2,&cy2);
	printf("\nEnter value of n\t:");
	scanf("%d",&n);

	putpixel(0,0,WHITE);
	putpixel(639,479,WHITE);
	for(p=0;p<n;p++)
	{
		printf("enter x[%d],y[%d]\t:",p+1,p+1);
		scanf("%f%f",&x[p],&y[p]);
	}
	g=x[n-1];h=y[n-1];
	setcolor(5);
	rectangle(cx1,cy1,cx2,cy2);
	getch();
	display();
	for(j=1;j<=4;j++)
	{
		k=0;
		i=0;
		for(i=0;i<n-1;)
		{
			check(x[i],y[i],x[i+1],y[i+1],j);
			i++;
		}
		check(x[i],y[i],x[0],y[0],j);
		n=k;
		for(p=0;p<nt;p++)
		{
			x[p]=xt[p];
			y[p]=yt[p];

		}
	}
	setcolor(WHITE);
	rectangle(cx1,cy1,cx2,cy2);
	setcolor(WHITE);
	display();
}
void check(float x1,float y1,float x2,float y2,int side)
{
	float m;
	  //int i=0;
	if(x1!=x2)
	m=(y2-y1)/(x2-x1);
	switch(side)
	{
		case 1:if(x1<cx1&&x2>cx1)
		{
			xt[k]=cx1;
			yt[k]=m*(cx1-x1)+y1;
			k++;
			xt[k]=x2;
			yt[k]=y2;
			k++;

		}
		else if(x1>=cx1&&x2>=cx1)
		{
			xt[k]=x2;
			yt[k]=y2;
			k++;
		}
		else if(x1>cx1&&x2<cx1)
		{
			xt[k]=cx1;
			yt[k]=m*(cx1-x1)+y1;
			k++;
		}
		break;
		case 2:if(x1>cx2&&x2<cx2)
		{
			xt[k]=cx2;
			yt[k]=m*(cx2-x1)+y1;
			k++;
			xt[k]=x2;
			yt[k]=y2;
			k++;
		}
		else if(x1<cx2&&x2>cx2)
		{
			xt[k]=cx2;
			yt[k]=m*(cx2-x1)+y1;
			k++;
		}
		else if(x1<=cx2&&x2<=cx2)
		{
			xt[k]=x2;
			yt[k]=y2;k++;
		}
		break;
		case 3:if(y1>cy2&&y2<cy2)
		{
			yt[k]=cy2;
			if(x1==x2)
				xt[k]=x1;
			else
				xt[k]=(cy2-y2)/m+x2;
			k++;
			xt[k]=x2;
			yt[k]=y2;
			k++;
		}
		else if(y1<=cy2&&y2<=cy2)
		{
			xt[k]=x2;
			yt[k]=y2;
			k++;
		}
		else if(y1<cy2&&y2>cy2)
		{
			yt[k]=cy2;
			if(x1==x2)
				xt[k]=x1;
			else
			xt[k]=(cy2-y2)/m+x2;
			k++;
		}
		break;
		case 4:if(y1<cy1&&y2>cy1)
		{
			yt[k]=cy1;
			if(x1==x2)
				xt[k]=x1;
			else
			xt[k]=(cy1-y1)/m+x1;
			k++;
			xt[k]=x2;
			yt[k]=y2;
			k++;
		}
		else if(y1>cy1&&y2<cy1)
		{
			yt[k]=cy1;
			if(x1==x2)
				xt[k]=x1;
			else
			xt[k]=(cy1-y2)/m+x2;
			k++;
		}
		else if(y1>=cy1&&y2>=cy1)
		{
			yt[k]=y2;
			xt[k]=x2;
			k++;
		}
		break;
	}
	nt=k;
}


Output
1

Leave a Reply

Your email address will not be published. Required fields are marked *