Updated copyright
[sixth-3d.git] / src / main / java / eu / svjatoslav / sixth / e3d / geometry / Polygon.java
1 /*
2  * Sixth 3D engine. Copyright ©2012-2019, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of version 3 of the GNU Lesser General Public License
6  * or later as published by the Free Software Foundation.
7  *
8  */
9
10 package eu.svjatoslav.sixth.e3d.geometry;
11
12 public class Polygon {
13
14     private static boolean intersectsLine(final Point2D point, Point2D p1,
15                                           Point2D p2) {
16
17         if (p1.y > p2.y) {
18             final Point2D tmp = p1;
19             p1 = p2;
20             p2 = tmp;
21         }
22
23         if (point.y < p1.y)
24             return false;
25         if (point.y > p2.y)
26             return false;
27
28         final double xp = p2.x - p1.x;
29         final double yp = p2.y - p1.y;
30
31         final double yp2 = point.y - p1.y;
32
33         final double crossX = p1.x + ((xp * yp2) / yp);
34
35         return point.x >= crossX;
36
37     }
38
39     public static boolean pointWithinPolygon(final Point2D point,
40                                              final Point2D p1, final Point2D p2, final Point2D p3) {
41
42         int intersectionCount = 0;
43
44         if (intersectsLine(point, p1, p2))
45             intersectionCount++;
46
47         if (intersectsLine(point, p2, p3))
48             intersectionCount++;
49
50         if (intersectsLine(point, p3, p1))
51             intersectionCount++;
52
53         return intersectionCount == 1;
54
55     }
56
57 }