我发现此代码用于计算线段和线段之间的距离。我们检查线段和线是否不平行,并找到参数方程的参数,其中线段和线之间的距离将最小。但我不明白我们是如何做到这一点的。
有人解释一下吗?或任何其他关于如何找到线段和线段之间距离的解释链接。
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;
}