public V2d GetClosestPointOnLine(V2d p) { var d = P0 - P1; var l = d.LengthSquared; if (Fun.IsTiny(l)) { return(P0); //it does not matter which of the two points we choose } var t = (P0.Dot(d) - p.Dot(d)) / l; //parametric distance from P0 to P1, where closest point to p is if (t <= 0) { return(P0); } if (t >= 1) { return(P1); } return(P0 - t * d); }