Advertisement
Shailrshah

Cohen Sutherland Line Clipping Algorithm

Oct 25th, 2014
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.01 KB | None | 0 0
  1. #include <graphics.h>
  2. #include <stdio.h>
  3. #include <conio.h>
  4. #define IN 0
  5. #define TOP 8
  6. #define BOTTOM 4
  7. #define RIGHT 2
  8. #define LEFT 1
  9.  
  10. float XMIN=20, XMAX=90, YMIN=20, YMAX=70, m;
  11. int ax=10, ay=10, bx=100, by = 90;
  12. int count=0;
  13. float f[2][2];
  14.  
  15. void startgraphics(){
  16.     int gd = DETECT, gm;
  17.     initgraph(&gd, &gm, "");
  18.     cleardevice();
  19. }
  20.  
  21. void clipit(float x, float y){
  22.     if(count==2) return;
  23.     f[count][0]=x;
  24.     f[count][1]=y;
  25.     count++;
  26. }
  27.  
  28. int getCode(float x, float y){
  29.     int code=IN;
  30.     if(x < XMIN) code |= LEFT;
  31.     else if(x > XMAX) code |= RIGHT;
  32.  
  33.     if(y < YMIN) code |= BOTTOM;
  34.     else if(y > YMAX) code |= TOP;
  35.  
  36.     return code;
  37. }
  38.  
  39. void calcF(int code){
  40.     if(code & TOP)
  41.         clipit(1/m*(YMAX-ay)+ax, YMAX);
  42.     else if(code & BOTTOM)
  43.         clipit(1/m*(YMIN-ay)+ax,YMIN);
  44.     else if(code & RIGHT)
  45.         clipit(XMAX, m*(XMAX-ax)+ay);
  46.     else if(code & LEFT)
  47.         clipit(XMIN, m*(XMIN-ax)+ay);
  48. }
  49.  
  50. void main(){
  51.     int codeA=0, codeB=0;
  52.     float xnew, ynew;
  53.     int i, j;
  54.     m=(float)(by-ay)/(bx-ax);
  55.     clrscr();
  56.  
  57.     printf("Windows: (%f, %f) and (%f, %f)\n", XMIN, YMIN, XMAX, YMAX);
  58.     printf("Line: (%d, %d) to (%d, %d)", ax, ay, bx, by);
  59.     codeA=getCode(ax, ay);
  60.     if(codeA==0) clipit((float)ax, (float)ay);
  61.     codeB=getCode(bx, by);
  62.     if(codeB==0) clipit((float)bx, (float)by);
  63.     printf("\ncodeA = %d\ncodeB = %d",codeA, codeB);
  64.  
  65.     if((codeA|codeB) == 0) printf("\n %d In!\n", codeA|codeB);
  66.     else if(codeA & codeB) printf("\nOut!\n");
  67.     else{
  68.         if(codeA)calcF(codeA);
  69.         if(codeB)calcF(codeB);
  70.         printf("\n\n%d/%d = m = %f", by-ay, bx-ax, m);
  71.         if(count>0){
  72.         printf("\nPartially Visible!\nThe clipping points are:-\n");
  73.         for(i=0; i<2; i++)
  74.                 printf("\n%f\t%f\n", f[i][0], f[i][1]);
  75.         } else printf("\nNot Visible!");
  76.     }
  77.     getch();
  78.  
  79.     startgraphics();
  80.     rectangle(XMIN, YMIN, XMAX, YMAX);
  81.     setcolor(GREEN);
  82.     line((int)ax, (int)ay, (int)bx, (int)by);
  83.     getch();
  84.  
  85.     cleardevice();
  86.     rectangle(XMIN, YMIN, XMAX, YMAX);
  87.     setcolor(RED);
  88.     line((int)f[0][0], (int)f[0][1], (int)f[1][0], (int)f[1][1]);
  89.     getch();
  90.  
  91.     closegraph();
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement