Sutherland Hodgeman Polygon Clipping: Exp No: 9 DATE: 29-02-2012
Sutherland Hodgeman Polygon Clipping: Exp No: 9 DATE: 29-02-2012
ALGORITHM
1. 2. 3. 4. Start Input polygon co-ordinates Input clipping window co-ordinates for i := 1 to 4 do //for 4 sides of clipping window a. for j := 1 to N do //for polygon with N sides i. if first end point is outside clipping window and second end point is inside clipping window, clip the first point and keep the second point ii. if both end points are inside clipping window, then keep the second point iii. if first end point is inside and second end point is outside clipping window, then clip the second point b. assign the newly obtained co-ordinates to actual polygon co-ordinates 5. Display the clipped polygon 6. Stop
PROGRAM
#include<stdio.h> #include<graphics.h>
void check(float,float,float,float,int);
int i; for(i=0;i<n-1;i++) line(x[i],y[i],x[i+1],y[i+1]); //DRAW EDGES 1 TO N-1 line(x[i],y[i],x[0],y[0]); //DRAW EDGE N getch(); }
printf(" Enter the co ordinate of the top left corner of the clipping window: "); scanf("%d%d",&cx1,&cy1); printf(" Enter the co ordinate of the bottom right corner of the clipping window: "); scanf("%d%d",&cx2,&cy2);
g=x[n-1]; h=y[n-1];
setcolor(5); clearviewport(); rectangle(cx1,cy1,cx2,cy2); //SHOW CLIPPING WINDOW getch(); display(); //SHOW POLYGON
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]; } }
clearviewport(); setcolor(5); rectangle(cx1,cy1,cx2,cy2); //SHOW CLIPPING WINDOW setcolor(3); display(); //SHOW RESULTING POLYGON }
void check(float x1,float y1,float x2,float y2,int side){ float m; if(x1!=x2) m=(y2-y1)/(x2-x1);
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
RESULT
The program is executed and output is verified.