// Stolen from: http://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment // Return minimum distance point on line segment vw minimizing the distance to point p PD nearestPointOnLineSegment(PD v, PD w, PD p) { if(epsEq(v, w)) return v; // v == w case. Avoid division by zero. double l2 = distSquared(v, w); // Consider the line extending the segment, parameterized as v + t (w - v). // We find projection of point p onto the line. // It falls where t = [(p-v) . (w-v)] / |w-v|^2 // We clamp t from [0,1] to handle points outside the segment vw. PD wv = w-v; double t = clamp01(dotProduct(p-v, wv) / l2); PD projection = v + (wv * t); // Projection falls on the segment return projection; }
double epsEq(PD a, PD b) { return epsEq(a.XX, b.XX) && epsEq(a.YY, b.YY); }
static int epsLteF(const float a, const float b) { return b > a || epsEq(a, b); // Not necessarily great numerically }