Judgment point is inside the polygon

1. Problem description

Given the point P(x,y) and the polygon polygon, determine whether the point P(x,y) is inside the polygon.

Two, the solution

X-ray method

With the point P as the endpoint, draw a ray L to the left. Since the polygon is bounded, the left end of the ray L must be outside the polygon. Consider moving from left to right along L from nowhere. When you encounter the first intersection point with the polygon, you enter the interior of the polygon. When you encounter the second intersection point, you leave the polygon. Therefore, when the intersection number C of L and the polygon is odd, P is inside the polygon, and if it is even, then P is outside the polygon.

The special case analysis is shown in the figure (a), (b), (c) and (d) below.

1 In Figure (a), L intersects with the vertices of the polygon, and only one intersection point can be calculated.

2 In figure (b), the intersection of L and the vertices of the polygon should not be calculated.

3 In Figures (c) and (d), L coincides with one side of the polygon, and this side should be ignored.

3. Code implementation

code analysis

Condition 1

((ploy[i].y <= pt.y) && (pt.y < poly[j].y)) || ((ploy[j].y <= pt.y) && (pt.y < poly[i].y))

Since the judgment process is mainly to judge whether there is an intersection point between the ray L and each side of the polygon, and the ray L is parallel to the X axis, condition 1 is equivalent to judging that the point P is between Pi and Pj in the vertical distance.

Condition 2

(pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y)/(poly[j].y - poly[i].y) + poly[i].x)

Condition 2 can be transformed into: (pt.x - poly[i].x) * (poly[j].y - poly[i].y) - (poly[j].x - poly[i].x) * (pt.y - poly[i].y) < 0, which is equivalent to the cross product of vector PiP and vector PiPj.

When the cross product of the vector PiP and the vector PiPj is less than 0, the vector PiP is in the counterclockwise direction of the vector PiPj, which means that the vector PiP is on the right side of the vector PiPj, and the ray L is emitted from the left side, and the point P is between Pi and Pj. The perpendicular distance between, therefore, the straddle condition of rays L and PiPj holds, intersects.

4. References


http://alienryderflex.com/polygon/

https://www.cnblogs.com/dwdxdy/p/3230647.html

Guess you like

Origin blog.csdn.net/beijingmake209/article/details/128564077