-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeometry.pde
More file actions
47 lines (36 loc) · 1.67 KB
/
Geometry.pde
File metadata and controls
47 lines (36 loc) · 1.67 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
public static class Geometry {
public static boolean inLine(PVector p, PVector a, PVector b) {
final float EPSILON = 0.001f;
PVector ap = PVector.sub(p, a);
PVector ab = PVector.sub(b, a);
return PVector.angleBetween(ap, ab) <= EPSILON && ap.mag() < ab.mag();
}
public static PVector scalarProjection(PVector p, PVector a, PVector b) {
PVector ap = PVector.sub(p, a);
PVector ab = PVector.sub(b, a).normalize();
ab.mult(ap.dot(ab));
return PVector.add(a, ab);
}
public static PVector closerLinePoint(PVector p, PVector a, PVector b) {
PVector projection = scalarProjection(p, a, b);
float lineLength = a.dist(b);
if(projection.dist(b) > lineLength) return a;
if(projection.dist(a) > lineLength) return b;
return projection;
}
public static boolean inTriangle(PVector p, PVector t1, PVector t2, PVector t3) {
boolean b1 = Sign(p, t1, t2) < 0.0f;
boolean b2 = Sign(p, t2, t3) < 0.0f;
boolean b3 = Sign(p, t3, t1) < 0.0f;
return ((b1 == b2) && (b2 == b3));
}
private static float Sign(PVector p1, PVector p2, PVector p3) {
return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y);
}
private static PVector linesIntersection(PVector p1, PVector p2, PVector p3, PVector p4) {
float d = (p2.x - p1.x) * (p4.y - p3.y) - (p2.y - p1.y) * (p4.x - p3.x);
if(d == 0) return null;
float a = ((p3.x - p1.x) * (p4.y - p3.y) - (p3.y - p1.y) * (p4.x - p3.x)) / d;
return new PVector(p1.x + a * (p2.x - p1.x), p1.y + a * (p2.y - p1.y));
}
}