-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCGEXP2.cpp
More file actions
100 lines (99 loc) · 2.69 KB
/
CGEXP2.cpp
File metadata and controls
100 lines (99 loc) · 2.69 KB
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
#include <iostream>
#include <graphics.h>
using namespace std;
static int LEFT = 1, RIGHT = 2, BOTTOM = 4, TOP = 8, xl, yl, xh, yh;
int getcode(int x, int y)
{
int code = 0;
// Perform Bitwise OR to get outcode
if (y > yh)
code |= TOP;
if (y < yl)
code |= BOTTOM;
if (x < xl)
code |= LEFT;
if (x > xh)
code |= RIGHT;
return code;
}
int main()
{
int gdriver = DETECT, gmode;
initgraph(&gdriver, &gmode, NULL);
setcolor(BLUE);
cout << "Enter bottom left and top right co-ordinates of window: ";
cin >> xl >> yl >> xh >> yh;
rectangle(xl, yl, xh, yh);
int x1, y1, x2, y2;
cout << "Enter the endpoints of the line: ";
cin >> x1 >> y1 >> x2 >> y2;
line(x1, y1, x2, y2);
getch();
int outcode1 = getcode(x1, y1), outcode2 = getcode(x2, y2);
int accept = 0; // decides if line is to be drawn
while (1)
{
float m = (float)(y2 - y1) / (x2 - x1);
// Both points inside. Accept line
if (outcode1 == 0 && outcode2 == 0)
{
accept = 1;
break;
}
// AND of both codes != 0.Line is outside. Reject line
else if ((outcode1 & outcode2) != 0)
{
break;
}
else
{
int x, y;
int temp;
// Decide if point1 is inside, if not, calculate intersection
if (outcode1 == 0)
temp = outcode2;
Else
temp = outcode1;
// Line clips top edge
if (temp & TOP)
{
x = x1 + (yh - y1) / m;
y = yh;
}
else if (temp & BOTTOM)
{ // Line clips bottom edge
x = x1 + (yl - y1) / m;
y = yl;
}
else if (temp & LEFT)
{ // Line clips left edge
x = xl;
y = y1 + m * (xl - x1);
}
else if (temp & RIGHT)
{ // Line clips right edge
x = xh;
y = y1 + m * (xh - x1);
}
// Check which point we had selected earlier as temp, and replace
ordinates if (temp == outcode1)
{
x1 = x;
y1 = y;
outcode1 = getcode(x1, y1);
}
else
{
x2 = x;
y2 = y;
outcode2 = getcode(x2, y2);
}
}
}
setcolor(WHITE);
cout << "After clipping:";
if (accept)
line(x1, y1, x2, y2);
return 0;
closegraph();
}