CG Sample Codes
CG Sample Codes
A rectangle is inside a circle if all four corners of the rectangle lie inside the circle. Mathematically, a
point (x,y) is inside a circle centered at (Xc, Yc) with radius r if:
(x − Xc )2 + (y − Yc )2 <= r2
34 // Draw Rectangle
35 rectangle ( rectX , rectY , rectX + width , rectY + height ) ;
36
37 c h e c k R e c t a n g l e I n s i d e C i r c l e ( rectX , rectY , width , height , circleX , circleY ,
radius ) ;
38
39 getch () ;
40 closegraph () ;
41 return 0;
42 }
Listing 1: Check if the Rectangle is Inside the Circle
1
3
28 while (1) {
29 if (( code1 == 0) && ( code2 == 0) ) {
30 accept = 1; break ;
31 } else if ( code1 & code2 ) {
32 break ;
33 } else {
34 int x , y ;
35 int outcode = code1 ? code1 : code2 ;
36
37 if ( outcode & TOP ) {
38 x = x1 + ( x2 - x1 ) * ( Ymax - y1 ) / ( y2 - y1 ) ;
39 y = Ymax ;
40 } else if ( outcode & BOTTOM ) {
41 x = x1 + ( x2 - x1 ) * ( Ymin - y1 ) / ( y2 - y1 ) ;
42 y = Ymin ;
43 } else if ( outcode & RIGHT ) {
44 y = y1 + ( y2 - y1 ) * ( Xmax - x1 ) / ( x2 - x1 ) ;
45 x = Xmax ;
46 } else if ( outcode & LEFT ) {
47 y = y1 + ( y2 - y1 ) * ( Xmin - x1 ) / ( x2 - x1 ) ;
48 x = Xmin ;
49 }
50
51 if ( outcode == code1 ) {
52 x1 = x ; y1 = y ; code1 = computeCode ( x1 , y1 ) ;
53 } else {
54 x2 = x ; y2 = y ; code2 = computeCode ( x2 , y2 ) ;
55 }
56 }
57 }
58
59 if ( accept ) {
60 setcolor ( GREEN ) ;
61 line ( x1 * 50 , y1 * 50 , x2 * 50 , y2 * 50) ;
62 }
63 }
64
65 int main () {
66 int gd = DETECT , gm ;
2
67 initgraph (& gd , & gm , ( char *) " " ) ;
68
69 int Ax = 6 , Ay = 2 , Bx = 3 , By = 8 , Cx = 1 , Cy = 2 , Dx = 3 , Dy = 4;
70
71 printf ( " Region Codes :\ n " ) ;
72 printf ( " A (% d ,% d ) -> % d \ n " , Ax , Ay , computeCode ( Ax , Ay ) ) ;
73 printf ( " B (% d ,% d ) -> % d \ n " , Bx , By , computeCode ( Bx , By ) ) ;
74 printf ( " C (% d ,% d ) -> % d \ n " , Cx , Cy , computeCode ( Cx , Cy ) ) ;
75 printf ( " D (% d ,% d ) -> % d \ n " , Dx , Dy , computeCode ( Dx , Dy ) ) ;
76
77 setcolor ( RED ) ;
78 line ( Ax * 50 , Ay * 50 , Bx * 50 , By * 50) ;
79 line ( Cx * 50 , Cy * 50 , Dx * 50 , Dy * 50) ;
80
81 rectangle ( Xmin * 50 , Ymin * 50 , Xmax * 50 , Ymax * 50) ;
82
83 c oh e n Su t h er l a nd C l i p ( Ax , Ay , Bx , By ) ;
84 c oh e n Su t h er l a nd C l i p ( Cx , Cy , Dx , Dy ) ;
85
86 getch () ;
87 closegraph () ;
88 return 0;
89 }
Listing 2: Compute Region Codes and Clip Using Cohen-Sutherland Algorithm
3
35 initgraph (& gd , & gm , " " ) ;
36
37 thickBresenham (100 , 200 , 400 , 300 , 5) ;
38
39 getch () ;
40 closegraph () ;
41 return 0;
42 }
Listing 3: Thick Line using Bresenham’s Algorithm
4
13 for ( int i = 0; i <= steps ; i ++) {
14 int intensity = 255 - (255 * fabs ( y - round ( y ) ) ) ; // Anti - alias effect
15 putpixel ( round ( x ) , round ( y ) , COLOR ( intensity , intensity , intensity ) ) ;
16
17 x += xInc ;
18 y += yInc ;
19 }
20 }
21
22 int main () {
23 int gd = DETECT , gm ;
24 initgraph (& gd , & gm , " " ) ;
25