isInsidePolygon method Null safety

bool isInsidePolygon(
  1. Point<num> point,
  2. List<Point<num>> polygon
)

Check if a point is inside the polygon

Implementation

static bool isInsidePolygon(Point point, List<Point> polygon) {
  assert(polygon.length >= 3);
  if (polygon.any((p) => p == point)) return true;

  if (point.x < getMostLeftPoint(polygon).x) return false;
  if (point.y < getBottomPoint(polygon).y) return false;
  if (point.x > getMostRightPoint(polygon).x) return false;
  if (point.y > getTopPoint(polygon).y) return false;

  final sides = getPolygonSides(polygon);

  if (sides.any((s) => LineUtils.isPointBelongToLineSegment(point, s))) {
    return true;
  }

  final ray = Line(point, Point(getMostRightPoint(polygon).x + 2, point.y));
  int intersects = 0;

  for (var s in sides) {
    if (LineUtils.isTwoLineSegmentsIntersect(ray, s)) {
      intersects++;
    }
  }

  return intersects % 2 != 0;
}