Tuesday, 17 March 2015

Liang Barsky Clipping Algorithm

                                                               

/* This routine performs 2D clipping. It is assumed that user  
/* will supply window and line co-ordinates.                  
/* For the window only two co-ordinates are needed: left-bottom
/* and the right-top corner co-ordinates respectively.        
                                                           

/******************************************************************/


#include<stdio.h>

#define n 4

struct point {float x; float y;};
struct point EndPt[2], WinPt[2], NewPt[2];

float p[n], q[n];

main()
{
 int i;
 float t, tmin, tmax;

 for(i=0;i<2;i++)
   {
    printf("\nGive input line end point[%d]:",i);
    scanf("%f %f", &EndPt[i].x, &EndPt[i].y);
   }
 for(i=0;i<2;i++)
   {
    printf("\nGive Window corner point[%d]:",i);
    scanf("%f %f", &WinPt[i].x, &WinPt[i].y);
   }

 p[0] = EndPt[0].x - EndPt[1].x; q[0] =  EndPt[0].x - WinPt[0].x;
 p[1] = EndPt[1].x - EndPt[0].x; q[1] =  WinPt[1].x - EndPt[0].x;
 p[2] = EndPt[0].y - EndPt[1].y; q[2] =  EndPt[0].y - WinPt[0].y;
 p[3] = EndPt[1].y - EndPt[0].y; q[3] =  WinPt[1].y - EndPt[0].y;
 tmin=1.0; tmax=0.0;

 for(i=0;i<n;i++)
 {
  if(p[i]==0.0) //line parallel to i-th clipping boundary
    if(q[i]<0.0) continue; //line completely invisible

  if(p[i]<0.0)
   {
    t=q[i]/p[i];
    if(t>tmax) tmax=t;
   }
  if(p[i]>0.0)
   {
    t=q[i]/p[i];
    if(t<tmin) tmin=t;
   }
  printf("%d) %4.2f %4.2f %4.2f %4.2f\n", i, p[i], q[i], tmin, tmax);
 }
 if(tmax<tmin)
  { 
   if(tmin<=1.0)
    {
     NewPt[1].x = EndPt[0].x + tmin * p[1];
     NewPt[1].y = EndPt[0].y + tmin * p[3];
    }
   if(tmax>=0.0)
    {
     NewPt[0].x = EndPt[0].x + tmax * p[1];
     NewPt[0].y = EndPt[0].y + tmax * p[3];
    }
  }
   //line(round(NewPt[0].x),round(NewPt[0].y),round(NewPt[1].x),round(NewPt[1].y));
   printf("%4.2f %4.2f, %4.2f %4.2f\n", NewPt[0].x, NewPt[0].y, NewPt[1].x, NewPt[1].y);
}

/* Instructions are used for text mode outputs only. Readers may convert it into a graphics mode program.                    
/*******************************************************************/

No comments:

Post a Comment