-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGraphics.cpp
More file actions
92 lines (79 loc) · 1.87 KB
/
Graphics.cpp
File metadata and controls
92 lines (79 loc) · 1.87 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
#include "Graphics.h"
#include <vector>
#include <cmath>
#include <algorithm>
namespace CG {
float dist(Point p, Point q)
{
float dx = p.x - q.x;
float dy = p.y - q.y;
return sqrt(dx*dx + dy*dy);
}
bool Point::operator<(Point p)
{
if (x < p.x) return true;
if (x == p.x && y < p.y) return true;
return false;
}
bool Point::operator==(Point p)
{
if (x == p.x && y == p.y) return true;
return false;
}
float LineSegment::length()
{
return dist(begin, end);
}
bool LineSegment::pointOnLeft(Point p)
{
float D = (end.x*p.y - p.x*end.y) - (begin.x*p.y - p.x*begin.y)
+ (begin.x*end.y - end.x*begin.y);
if (D > 0) return true;
return false;
}
bool LineSegment::pointOnRight(Point p)
{
float D = (end.x*p.y - p.x*end.y) - (begin.x*p.y - p.x*begin.y)
+ (begin.x*end.y - end.x*begin.y);
if (D < 0) return true;
return false;
}
bool LineSegment::pointOnLine(Point p)
{
float D = (end.x*p.y - p.x*end.y) - (begin.x*p.y - p.x*begin.y)
+ (begin.x*end.y - end.x*begin.y);
if (D == 0) return true;
return false;
}
bool LineSegment::pointInSegment(Point p)
{
if (abs(dist(begin, p) + dist(p, end) - length()) < EPSILON) return true;
return false;
}
bool LineSegment::intersects(LineSegment l)
{
Point p = intersection(l);
return p.x > -INFINITY && pointInSegment(p) && l.pointInSegment(p);
}
std::vector<float> LineSegment::equation()
{
float a = (end.y - begin.y);
float b = -(end.x - begin.x);
float c = begin.y*(end.x-begin.x)-begin.x*(end.y-begin.y);
std::vector<float> out = {a, b, c};
return out;
}
Point LineSegment::intersection(LineSegment l)
{
auto eq1 = equation();
auto eq2 = l.equation();
float D = eq1[0]*eq2[1] - eq2[0]*eq1[1];
float X = -INFINITY;
float Y = -INFINITY;
if (D) {
X = (eq1[1]*eq2[2] - eq2[1]*eq1[2])/D;
Y = (eq1[2]*eq2[0] - eq2[2]*eq1[0])/D;
}
return Point(X, Y);
}
}