public double DistToPoint(Point2D p, out Point2D footPos) { double minDist = this.points.Min(x => x.DistTo(p)); Point2D minPoint = this.points.First(x => x.DistTo(p) == minDist); if (minPoint == this.points.First()) { LineSeg seg1 = new LineSeg(this.points[0], this.points[1]); LineSegPointRelation relation1 = new LineSegPointRelation(seg1, p); if (relation1.Inner) { footPos = relation1.Foot; return(relation1.Dist); } else { footPos = minPoint; return(minDist); } } else if (minPoint == this.points.Last()) { int n = this.points.Count; LineSeg seg1 = new LineSeg(this.points[n - 2], this.points[n - 1]); LineSegPointRelation relation1 = new LineSegPointRelation(seg1, p); if (relation1.Inner) { footPos = relation1.Foot; return(relation1.Dist); } else { footPos = minPoint; return(minDist); } } else { int index = this.points.IndexOf(minPoint); LineSeg seg1 = new LineSeg(this.points[index - 1], this.points[index]); LineSeg seg2 = new LineSeg(this.points[index + 1], this.points[index]); LineSegPointRelation relation1 = new LineSegPointRelation(seg1, p); LineSegPointRelation relation2 = new LineSegPointRelation(seg2, p); if (relation1.Inner) { footPos = relation1.Foot; return(relation1.Dist); } else if (relation2.Inner) { footPos = relation2.Foot; return(relation2.Dist); } else { footPos = minPoint; return(minDist); } } }
public LineSegIntersect(LineSeg l1, LineSeg l2) { A = l1.p[0]; B = l1.p[1]; C = l2.p[0]; D = l2.p[1]; }
public LineSegPointRelation(LineSeg line, Point2D point) { A = line.p[0]; B = line.p[1]; C = point; if (line.IsPointOn(point)) { D = C; lambda = (A.x - C.x) / (C.x - B.x); if (double.IsNaN(lambda)) { lambda = (A.y - C.y) / (C.y - B.y); } } else { lambda = (-A.x * A.x + A.x * B.x + A.x * C.x - B.x * C.x - A.y * A.y + A.y * B.y + A.y * C.y - B.y * C.y) / (A.x * B.x - B.x * B.x - A.x * C.x + B.x * C.x + A.y * B.y - B.y * B.y - A.y * C.y + B.y * C.y); // from Mathematica D = line.GetDivPoint(lambda); } }