I found this code for calculate distance between line and line segment. We are check if segment and line are not parallel and find parameters for parametric equation where distance between segment and line will be minimal. But i dont understand how we are doing this.
Сan someone explain this? Or any other explanation link of how to find distance between line and segment.
Result operator()(Line<N, Real> const& line, Segment<N, Real> const& segment)
{
Result result;
Vector<N, Real> segCenter, segDirection;
Real segExtent;
segment.GetCenteredForm(segCenter, segDirection, segExtent);
Vector<N, Real> diff = line.origin - segCenter;
Real a01 = -Dot(line.direction, segDirection);
Real b0 = Dot(diff, line.direction);
Real s0, s1;
if (std::fabs(a01) < (Real)1)
{
// The line and segment are not parallel.
Real det = (Real)1 - a01 * a01;
Real extDet = segExtent * det;
Real b1 = -Dot(diff, segDirection);
s1 = a01 * b0 - b1;
if (s1 >= -extDet)
{
if (s1 <= extDet)
{
// Two interior points are closest, one on the line
// and one on the segment.
s0 = (a01 * b1 - b0) / det;
s1 /= det;
}
else
{
// The endpoint e1 of the segment and an interior
// point of the line are closest.
s1 = segExtent;
s0 = -(a01 * s1 + b0);
}
}
else
{
// The endpoint e0 of the segment and an interior point
// of the line are closest.
s1 = -segExtent;
s0 = -(a01 * s1 + b0);
}
}
else
{
// The line and segment are parallel. Choose the closest pair
// so that one point is at segment origin.
s1 = (Real)0;
s0 = -b0;
}
result.parameter[0] = s0;
result.parameter[1] = s1;
result.closestPoint[0] = line.origin + s0 * line.direction;
result.closestPoint[1] = segCenter + s1 * segDirection;
diff = result.closestPoint[0] - result.closestPoint[1];
result.sqrDistance = Dot(diff, diff);
result.distance = std::sqrt(result.sqrDistance);
return result;
}