Cohen Sutherland Line Clipping Algorithm in C
In this example you will get c graphics program code of cohen sutherland line clipping algorithm.
The Cohen-Sutherland line clipping algorithm is used in computer graphics to efficiently clip lines inside a rectangular window. It is developed by Ivan Sutherland and Daniel Cohen in 1967. It is less efficient than Liang Barsky Line Clipping Algorithm.
C Program code of Cohen Sutherland Line Clipping Algorithm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | #include<stdio.h> #include<graphics.h> #include<conio.h> typedef unsigned int outcode; enum { TOP=0x1, BOTTOM=0x2, RIGHT=0x4, LEFT=0x8 }; int calcode(float,float,float,float,float,float); void lineclip(float x0,float y0,float x1,float y1,float xwmin,float ywmin,float xwmax,float ywmax ) { int gd,gm; outcode code0,code1,codeout; int accept = 0, done=0; code0 = calcode(x0,y0,xwmin,ywmin,xwmax,ywmax); code1 = calcode(x1,y1,xwmin,ywmin,xwmax,ywmax); do{ if(!(code0 | code1)) { accept =1 ; done =1; } else if(code0 & code1) done = 1; else { float x,y; codeout = code0 ? code0 : code1; if(codeout & TOP) { x = x0 + (x1-x0)*(ywmax-y0)/(y1-y0); y = ywmax; } else if( codeout & BOTTOM) { x = x0 + (x1-x0)*(ywmin-y0)/(y1-y0); y = ywmin; } else if ( codeout & RIGHT) { y = y0+(y1-y0)*(xwmax-x0)/(x1-x0); x = xwmax; } else { y = y0 + (y1-y0)*(xwmin-x0)/(x1-x0); x = xwmin; } if( codeout == code0) { x0 = x; y0 = y; code0=calcode(x0,y0,xwmin,ywmin,xwmax,ywmax); } else { x1 = x; y1 = y; code1 = calcode(x1,y1,xwmin,ywmin,xwmax,ywmax); } } } while( done == 0); if(accept) line(x0,y0,x1,y1); rectangle(xwmin,ywmin,xwmax,ywmax); getch(); } /*--------------------------------------------------------------------*/ int calcode (float x,float y,float xwmin,float ywmin,float xwmax,float ywmax) { int code =0; if(y> ywmax) code |=TOP; else if( y<ywmin) code |= BOTTOM; else if(x > xwmax) code |= RIGHT; else if ( x< xwmin) code |= LEFT; return(code); } /*-------------------------------------------------*/ main() { float x2,y2,x1,y1,xwmin,ywmin,xwmax,ywmax; int gd,gm; detectgraph(&gd,&gm); initgraph(&gd,&gm,"C:\\TURBOC3\\BGI"); printf("\n\tEnter the co-ordinates of Line :"); printf("\n\tX1 Y1 : "); scanf("%f%f",&x1,&y1); printf("\n\tX2 Y2 : "); scanf("%f%f",&x2,&y2); printf("\n\tEnter the co_ordinates of window :\n "); printf("\n\txwmin , ywmin : "); scanf("%f%f",&xwmin,&ywmin); printf("\n\txwmax , ywmax : "); scanf("%f%f",&xwmax,&ywmax); line(x1,y1,x2,y2); rectangle(xwmin,ywmin,xwmax,ywmax); getch(); cleardevice(); lineclip(x1,y1,x2,y2,xwmin,ywmin,xwmax,ywmax ); getch(); closegraph(); } |
Output
Press any key…..