Saturday, August 25, 2012

C++ CODE FOR POLYGON CLIPPING

            C++ CODE FOR POLYGON CLIPPING

So here's my C++ code for Polygon Clipping.This program can clip ant polygon except rectangle and square.
Source code:
#include<iostream.h>
#include<conio.h>
#include<graphics.h>
void main(){ int gd=DETECT,gm;
initgraph(&gd,&gm,"C:\\TC\\BGI");
int p[20],xl,xh,yl,yh,i,n,t[20];
float m[10];
cout<<"Enter the lower window co-ordinates:";
cin>>xl>>yl;
cout<<"Enter the higher window co-ordinates:";
cin>>xh>>yh;
setcolor(BLUE);
rectangle(xl,yl,xh,yh);
cout<<"Enter no: of vertices for polygon:";
cin>>n;
int j=0;
do{
for(i=0;i<n;i++){
cout<<"\n x"<<i+1<<"& y"<<i+1<<":";
cin>>p[j];
j=j+1;
cin>>p[j];
j=j+1;}
} while(j<2*n);
p[2*n]=p[0];
p[2*n+1]=p[1];
cout<<"Before clipping:";
drawpoly(n+1,p);
getch();
int k=0;
for(i=0;i<2*n;i=i+2)
{m[i]=(float)(p[i+3]-p[i+1])/(p[i+2]-p[i]);
if(p[i]<xl || p[i]>xh || p[i+1]<yl || p[i+1]>yh)
{ if(p[i]<xl){
t[k+1]=p[i+1] +m[i]*(xl-p[i]);
t[k]=xl;}
else if(p[i]>xh){
t[k+1]=p[i+1]+m[i]*(xh-p[i]);
t[k]=xh;}
if(p[i+1]<yl)
{t[k]=p[i]+(yl-p[i+1])/m[i];
t[k+1]=yl;}
else if(p[i+1]>yh)
{t[k]=p[i]+(yh-p[i+1])/m[i];
t[k+1]=yh;} k=k+2;}
if(p[i]>=xl && p[i]<=xh && p[i+1]>=yl && p[i+1]<=yh)
{t[k]=p[i];
t[k+1]=p[i+1];
k=k+2;}
if(p[i+2]<xl || p[i+2]>xh || p[i+3]<yl || p[i+3]>yh)
{ if(p[i+2]<xl){
t[k+1]=p[i+3] +m[i]*(xl-p[i+2]);
t[k]=xl;}
else if(p[i+2]>xh){
t[k+1]=p[i+3]+m[i]*(xh-p[i+2]);
t[k]=xh;}
if(p[i+3]<yl)
{t[k]=p[i+2]+(yl-p[i+3])/m[i];
t[k+1]=yl;}
else if(p[i+3]>yh)
{t[k]=p[i+2]+(yh-p[i+3])/m[i];
t[k+1]=yh;}k=k+2;
}}
t[k]=t[0];
t[k+1]=t[1];
cout<<"\n After clipping:";
setcolor(WHITE);
drawpoly((k+2)/2,t);
getch();
}
OUTPUT:

No comments:

Post a Comment