diff --git a/src/Base/Vector3D.cpp b/src/Base/Vector3D.cpp index 4054ccb6e..fbc197f55 100644 --- a/src/Base/Vector3D.cpp +++ b/src/Base/Vector3D.cpp @@ -218,6 +218,28 @@ _Precision Vector3<_Precision>::DistanceToLine (const Vector3<_Precision> &rclBa return (_Precision) fabs((rclDirect % Vector3(*this - rclBase)).Length() / rclDirect.Length()); } +template +Vector3<_Precision> Vector3<_Precision>::DistanceToLineSegment (const Vector3& rclP1, + const Vector3& rclP2) const +{ + Vector3<_Precision> dir = rclP2-rclP1; + Vector3<_Precision> beg = *this-rclP1; + Vector3<_Precision> end = beg+dir; + + Vector3<_Precision> proj, len; + proj.ProjToLine(beg, dir); + len = proj + beg; + if (len * dir < 0 || len.Length() > dir.Length()) { + if (beg.Length() < end.Length()) + return beg; + else + return end; + } + else { + return proj; + } +} + template Vector3<_Precision>& Vector3<_Precision>::ProjToLine (const Vector3<_Precision> &rclPoint, const Vector3<_Precision> &rclLine) diff --git a/src/Base/Vector3D.h b/src/Base/Vector3D.h index 57418d359..395d5afe6 100644 --- a/src/Base/Vector3D.h +++ b/src/Base/Vector3D.h @@ -180,6 +180,12 @@ public: _Precision DistanceToPlane (const Vector3 &rclBase, const Vector3 &rclNorm) const; /// Computes the distance from this point to the line given by \a rclBase and \a rclDirect. _Precision DistanceToLine (const Vector3 &rclBase, const Vector3 &rclDirect) const; + /** Computes the vector from this point to the point on the line segment with the shortest + * distance. The line segment is defined by \a rclP1 and \a rclP2. + * Note: If the projection of this point is outside the segment then the shortest distance + * to \a rclP1 or \a rclP2 is computed. + */ + Vector3 DistanceToLineSegment (const Vector3& rclP1, const Vector3& rclP2) const; //@} };