Sunday, November 27, 2011

Implementation of Cohen-Sutherland Line clipping Algorithm

#include<graphics.h>
#include<conio.h>
#include<iostream.h>
const int t=1, b=2, r=4, l=8 ;
float xmin,ymin,xmax,ymax;
int calcode (float x,float y)
{ int code =0;
  if(y> ymax) code |=t;
  else if(y<ymin) code |= b;
  else if(x>xmax) code |= r;
  else if(x<xmin) code |= l;
  return(code);
}

void lineclip(float x1,float y1,float x2,float y2)
{ unsigned int code1,code2,codeout;
  int accept = 0, done=0;
  code1 = calcode(x1,y1);
  code2 = calcode(x2,y2);
  do{ if(!(code1 | code2))
    { accept =1 ; done =1; }
    else if(code1 & code2) done = 1;
    else
    { float x,y;
       codeout = code1 ? code1 : code2;
       if(codeout & t)
    { x = x1 + (x2-x1)*(ymax-y1)/(y2-y1);y = ymax;}
       else if(codeout & b)
    {x=x1+(x2-x1)*(ymin-y1)/(y2-y1);y=ymin;}
       else if (codeout & r)
      {y=y1+(y2-y1)*(xmax-x1)/(x2-x1);x=xmax;}
       else
     {y=y1+(y2-y1)*(xmin-x1)/(x2-x1);x=xmin;}
       if(codeout == code1)
      {x1 = x; y1 = y;
      code1=calcode(x1,y1);}
       else
    {x2 = x; y2 = y;
     code2 = calcode(x2,y2);}
   }
  } while( done == 0);
  if(accept)
    line(x1,y1,x2,y2);
    rectangle(xmin,ymin,xmax,ymax);
}

main()
{ float x1,y1,x2,y2;
  int gd=DETECT,gm;
  clrscr();
  initgraph(&gd,&gm,"");
  cout<<"\n\n\t:::Enter the co-ordinates of Line::::\n\tx1 :";cin>>x1;
  cout<<"\n\ty1 :";cin>>y1;
  cout<<"\n\tx2 :";cin>>x2;
  cout<<"\n\ty2 :";cin>>y2;
  cout<<"\n\t:::Enter the co_ordinates of window:::\n ";
  cout<<"\n\txmin :";cin>>xmin;
  cout<<"\n\tymin :";cin>>ymin;
  cout<<"\n\txmax :";cin>>xmax;
  cout<<"\n\tymax :";cin>>ymax;
  clrscr();
  line(x1,y1,x2,y2);
  rectangle(xmin,ymin,xmax,ymax);
  getch();
  clrscr();
  lineclip(x1,y1,x2,y2);
  getch();
  closegraph();
  return 0;
}