Find us on Google+ Kill the code: Line Clipping Algorithm in C

Monday, 9 April 2012

Line Clipping Algorithm in C



#include<stdio.h>

#include<conio.h>

#include<graphics.h>



void main()

{

 int x1, y1, x2, y2, a1, a2, a3, a4, b1, b2, b3, b4, xmin, ymin, xmax, ymax, qa, qb;

 int gd=DETECT, gm, c1, c2, c3, c4, xint1, yint1, xint2,  yint2;

 float m;

 clrscr();

 printf("enter end-points of line : ");

 scanf("%d %d %d %d", &x1, &y1, &x2, &y2);

 printf("enter co-ord. of screen : ");

 scanf("%d %d %d %d", &xmin, &ymin, &xmax, &ymax);

 if(x1<xmin)

 {

  a3 = 0; a4 = 1;

 }

 if(x1>xmin && x1<xmax)

 {

  a3 = 0; a4 = 0;

 }

 if(x1>xmax)

 {

  a3 = 1; a4 = 0;

 }

 if(y1<ymin)

 {

  a1 = 0; a2 = 1;

 }

 if(y1>ymin && y1<ymax)

 {

  a1 = 0; a2 = 0;

 }

 if(y1>ymax)

 {

  a1 = 1; a2 = 0;

 }

 if(x2<xmin)

 {

  b3 = 0; b4 = 1;

 }

 if(x2>xmin && x2<xmax)

 {

  b3 = 0; b4 = 0;

 }

 if(x2>xmax)

 {

  b3 = 1; b4 = 0;

 }

 if(y2<ymin)

 {

  b1 = 0; b2 = 1;

 }

 if(y2>ymin && y2<ymax)

 {

  b1 = 0; b2 = 0;

 }

 if(y2>ymax)

 {

  b1 = 1; b2 = 0;

 }

 if(a1 == 0 && a2 == 0 && a3 == 0 && a4 == 0)

 {

  qa = 5;

 }

 if(b1 == 0 && b2 == 0 && b3 == 0 && b4 == 0)

 {

  qb = 5;

 }

 initgraph(&gd, &gm, "c://tc//bgi");

 c1 = a1&b1;

 c2 = a2&b2;

 c3 = a3&b3;

 c4 = a4&b4;

 if(c1 == 0 && c2 == 0 && c3 == 0 && c4 == 0)

 {

  if(a1 == 0 && a2 == 0 && a3 == 0 && a4 == 0 && b1 == 0 && b2 == 0 && b3 == 0 && b4 == 0)

   printf("line is completely inside");

  else

   printf("line is partially inside");

 }

 else

  printf("line is completely outside");







if(x2-x1 == 0 || y2-y1 == 0)

{

 if(x2 - x1 == 0)

 {

  if(qa == 5)

   line(x1, y1, x1, ymax);



  if(qb == 5)

   line(x1, ymin, x2, y2);



  if(y1<=ymin && y2>=ymax)

   line(x1,ymin, x2, ymax);



 }

 if(y2 - y1 == 0)

 {



  if(qa == 5)

   line(x1, y1, xmax, y2);



  if(qb == 5)

   line(xmin, y1, x2, y2);



  if(x1<=xmin && x2>=xmax)

   line(xmin, y1, xmax, y2);



 }

}

else

{

 xint1 = ((x2-x1)*(ymin-y1)/(y2-y1))+x1;

 xint2 = ((x2-x1)*(ymax-y1)/(y2-y1))+x1;

 yint1 = ((xmin-x1)*(y2-y1)/(x2-x1))+y1;

 yint2 = ((xmax-x1)*(y2-y1)/(x2-x1))+y1;



 if(qa == 5 || qb == 5)

 {

  if(qa == 5)

  {

   if(xint2<=xmax)

   line(x1, y1, xint2, ymax);

   if(yint2<=ymax)

   line(x1, y1, xmax, yint2);

  }

  if(qb == 5)

  {

   if(xint1>=xmin)

   line(xint1, ymin, x2, y2);

   if(yint1>=ymin)

   line(xmin, yint1, x2, y2);

  }

 }

 else

 {

  if(xint1>=xmin && xint1<=xmax)

  {

   if(xint2>=xmin && xint2<=xmax)

    line(xint1, ymin, xint2, ymax);



   if(yint2>=ymin && yint2<=ymax)

    line(xint1, ymin, xmax, yint2);



  }

  if(yint1>=ymin && yint1<=ymax)

  {

   if(xint2>=xmin && xint2<=xmax)

    line(xmin, yint1, xint2, ymax);



   if(yint2>=ymin && yint2<=ymax)

    line(xmin, yint1, xmax, yint2);



  }

 }

}



 rectangle(xmin, ymin, xmax, ymax);

 getch();

}

1 comment:

  1. excellent code... very helpful
    thax a lot...

    ReplyDelete