Search code examples
geometrytopology

how to determine if a line loops back on itself in 2d space, and finding points enclosed in that loop


This is a problem which is hard to explain in words, though I have it easily captured in my head. Let me know if my explanation below isn't clear.

Let's say that a user is drawing on a 2d surface. They are drawing curves, with, say a mouse or stylus. Just so I'm clear on the definition, I'll say that a curve consists of a start-point (the point where the stylus is initially put down), intermediate points (points where the stylus dragged over) and an end point (the final point, where the user lifts the stylus off the surface).

How can I detect if the users curve creates some enclosed shape? For example, if you blur your eyes and look at the below drawings ( '.' denotes points on the curve, '0' denotes points not on the curve), the first one does create an enclosed space, the second one doesn't.

0000000000000000
0000..0000000000
000.00.000000000
00.000.000000000
00.00.0000000000
000...0000000000
0000000000000000

000.000000000000
0000.00000000000
00000.0000000000
00000...00000000
0000000.00000000
00000000.0000000
0000000000000000

Additionally, given some point (x1,y1), how can I determine if that point is inside or outside of the enclosed space?


Solution

  • For your second question:

    the classical approach is to draw a line from x1,y1 to an edge of the screen and see how many times that line intersects your polygon. If the number is odd, its inside the shape, if its even then its outside. There are issues with the approach and single point edges, but I am sure you could find solutions/fixes online.