//Header Files #include #include #include //Clipping Coordinates int ymin,ymax,xmin,xmax; //point structure struct point { int x,y; point():x(0),y(0){} }; //swap function void swap(int &a,int &b) { int rep=a; a=b; b=rep; } //check 4 bit code int code(point p) { int code = 0; if(p.xxmax) code=(code|0x2); //for right if(p.yymax) code=(code|0x8); // for above return code; } //clip the line according to clipping window void clipline(point p1,point p2) { int draw=0; float slope; int code1,code2; while(1) { code1=code(p1); code2=code(p2); if(!(code1|code2)) { draw = 1; break; } else if(code1&code2) { break; } else { if(!code1) { swap(p1.x,p2.x); swap(p1.y,p2.y); swap(code1,code2); } if(p2.x!=p1.x) { slope=(float)(p2.y-p1.y)/(float)(p2.x-p1.x); } if(code1&0x1) //for left { p1.y=p1.y+(xmin-p1.x)*slope; p1.x=xmin; } else if(code1&0x2)//for right { p1.y=p1.y+(xmax-p1.x)*slope; p1.x=xmax; } else if(code1&0x4) // for bottom { if(p1.x != p2.x) p1.x=p1.x+(ymin-p1.y)/slope; p1.y=ymin; } if(code1&0x8) // for above { if(p1.x != p2.x) p1.x=p1.x+(ymax-p1.y)/slope; p1.y=ymax; } } } if(draw) line(p1.x,p1.y,p2.x,p2.y); } //Main Function void main() { int d,m,i; detectgraph(&d,&m); initgraph(&d,&m,"f:\\tc\\bgi"); cout<<"Enter Clipping Points:"; cin>>xmin>>ymin>>xmax>>ymax; rectangle(xmin,ymin,xmax,ymax); point p1,p2; randomize(); for(i=0;i<100;i++) { //point 1 p1.x=random(600); p1.y=random(400); //poing 2 p2.x=random(600); p2.y=random(400); //clip the line with respect to clipping window clipline(p1,p2); } getch(); } /****************************************************************/