Polygon-Point Containment
Table of contents
# Usage
This algorithm is to determine if a given point is in a given polygon, on the polygon or outside of the polygon.
# Algorithm
Let the polygon , point , a edge of the polygon .
Let vectors from to vertices of , (a.y < b.y).
# A point is on a polygon
is on when the predicate below is true.
is in when the predicate below is true.
# Code
N-polygon
Spec of return value.
- 2: in
- 1: on
- 0: outside
Int contains(Vector2 polygon[], int N, Vector2 &point) {
bool in = false;
loop(n,0,N) {
Vector2 a = polygon[n] - point;
Vector2 b = polygon[(n+1) % N] - point;
if (fabs(a.cross(b)) < EPS && a.dot(b) < EPS) return 1;
if (a.y > b.y) swap(a, b);
if (a.y < EPS && b.y > EPS && a.cross(b) > EPS) in = !in;
}
return in ? 2 : 0;
}
Shun
Remote freelancer. A web and mobile application enginner.
Traveling around the world based on East Asia.
I'm looking forward to your job offers from all over the world!