Write a program to clip a line using Cohen – Sutherland line clipping algorithm.


#include<stdio.h>
#include<conio.h>
#include<graphics.h>

#define ROUND(a)    ( (int) a+0.5 )
#define ACCEPT(a,b) (!(a|b))
#define REJECT(a,b) (a&b)
#define INSIDE(a)   (!a)

#define LEFT   0x1
#define RIGHT  0x2
#define BOTTOM 0x4
#define TOP    0x8

#define TRUE  1
#define FALSE 0

int xMin, xMax, yMin, yMax;

void clip(int, int, int, int);
char encode(int, int);

void  main()
{
   int gdriver = DETECT, gmode;
   int x1,y1,x2,y2;

   initgraph(&gdriver,&gmode,"c:\\tc\\bgi");

   cleardevice();

   clip(x1,y1,x2,y2);

   getch();
   closegraph();
}

char encode(int x, int y)
{
   char code = 0x00;

   if(x < xMin)
         code = code | LEFT;
   if(x > xMax)
         code = code | RIGHT;
   if(y < yMin)
         code = code | BOTTOM;
   if(y > yMax)
         code = code | TOP;

   return(code);
}

void clip(int x1, int y1, int x2, int y2)
{
   char code1, code2;
   int done = FALSE, draw = FALSE;
   float m;

   while( !done )
   {
         code1 = encode(x1,y1);
         code2 = encode(x2,y2);

         if( ACCEPT(code1, code2) )
         {
               done = TRUE;
               draw = TRUE;
         }
         else if( REJECT(code1, code2) )
               done = TRUE;
         else if( INSIDE(code1) )
               swap(x1,y1,x2,y2,code1,code2);

         if( x2 != x1)
               m = (float) (y2 -y1) / (x2 - x1);
         if(code1 & LEFT)
         {
               y1 = (xMin - x1) * m;
               x1 = xMin;
         }
         else if(code1 & RIGHT)
         {
               y1 = (xMax - x1) * m;
               x1 = xMax;
         }
         else if(code1 & BOTTOM)
         {
               y1 = yMin;
               x1 = (yMin - y1) / m;
         }
         else if(code1 & TOP)
         {
               y1 = yMax;
               x1 = (yMax - y1) / m;
         }
   }
   if(draw)
         line( ROUND(x1), ROUND(y1), ROUND(x2), ROUND(y2) );
}

Related Posts Plugin for WordPress, Blogger...

Engineering material

GTU IDP/ UDP PROJECT

GTU IDP/ UDP PROJECT

Patel free software download

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP