I am working on a code concept (Java) in which the user will click on points to indicate points on the outline of a simple 2d structure.
My plan was to compose the shape of multiple line segments. I will then need to calculate the distance (overlap / vector magnitude) between this outlined "shape" (collection of line segments) and another single line segment (i.e. a ray) e.g. see image below. I thought I could heavily use line segment intersection* and have written this Java code:
/// calculate intersection of line segments
double p0X = 1; // line segment 1
double p0Y = 1;
double p1X = 3;
double p1Y = 2;
double p2X = 1; // line segment 2
double p2Y = 4;
double p3X = 2;
double p3Y = -1;
double s1X = p1X - p0X;
double s1Y = p1Y - p0Y;
double s2X = p3X - p2X;
double s2Y = p3Y - p2Y;
double s0 = (-s1Y*(p0X-p2X)+s1X*(p0Y-p2Y)) / (-s2X*s1Y+s1X*s2Y);
double t0 = (s2X*(p0Y-p2Y)+s1Y*(p0X-p2X)) / (-s2X*s1Y+s1X*s2Y);
if ((s0 >= 0) && (s0<= 1) && (t0 >= 0) && (t0 <= 1))
{
double xI = p0X + (t0 * s1X);
double yI = p0Y + (t0 * s1Y);
System.out.println("The line segments intersect at " + xI + ", " + yI);
}
else
{
System.out.println("The line segments don't intersect");
}
My issue is:
What to do about the distinct end points so there are no gaps between line segments on the shape outline? (Due to imperfect point placement by the user)
How to tell the algorithm line segments belong to the same shape.
For 1, I had thought I could use a threshold so that if two line segments have one end point within X pixels of each other then they "snap" to the same end point (e.g. either the average of both end points or using the end point values of one of the two line segments). E.g. See black shape in image below.
For 2, I thought I could then "tag" using an integer each line segment which belongs to the same "shape" (collection of line segments).
Is there any better solution to each of these issues?
*Note: I still need to handle/catch all the conditions in my code e.g. if the line segments are parallel, if the line segments intersect at (a shapes) line segment end point etc.
References:
1 https://en.wikipedia.org/wiki/Intersection_(Euclidean_geometry)#Two_line_segments