2 * Sixth 3D engine. Author: Svjatoslav Agejenko.
3 * This project is released under Creative Commons Zero (CC0) license.
5 package eu.svjatoslav.sixth.e3d.geometry;
8 * Utility class for polygon operations.
10 public class Polygon {
14 * Checks if point is on the right side of the line.
15 * @param point point to check
16 * @param lineP1 line start point
17 * @param lineP2 line end point
18 * @return true if point is on the right side of the line
20 private static boolean intersectsLine(final Point2D point, Point2D lineP1,
23 // Sort line points by y coordinate.
24 if (lineP1.y > lineP2.y) {
25 final Point2D tmp = lineP1;
30 // Check if point is within line y range.
31 if (point.y < lineP1.y)
33 if (point.y > lineP2.y)
36 // Check if point is on the line.
37 final double xp = lineP2.x - lineP1.x;
38 final double yp = lineP2.y - lineP1.y;
40 final double yp2 = point.y - lineP1.y;
42 final double crossX = lineP1.x + ((xp * yp2) / yp);
44 return point.x >= crossX;
48 public static boolean pointWithinPolygon(final Point2D point,
49 final Point2D p1, final Point2D p2, final Point2D p3) {
51 int intersectionCount = 0;
53 if (intersectsLine(point, p1, p2))
56 if (intersectsLine(point, p2, p3))
59 if (intersectsLine(point, p3, p1))
62 return intersectionCount == 1;