segmentDistanceSquared function
Squared distance from point to the closed segment start–end.
Implementation
double segmentDistanceSquared(
DiagramPoint point,
DiagramPoint start,
DiagramPoint end,
) {
final dx = end.x - start.x;
final dy = end.y - start.y;
final lengthSquared = dx * dx + dy * dy;
final t = lengthSquared == 0
? 0.0
: (((point.x - start.x) * dx + (point.y - start.y) * dy) / lengthSquared)
.clamp(0.0, 1.0);
final x = point.x - (start.x + dx * t);
final y = point.y - (start.y + dy * t);
return x * x + y * y;
}