Files
OpenNest/OpenNest.Core/Geometry/Clearance.cs
T
ajandClaude Opus 5.5 4b61d249c0 fix(expand): let every selected part move and stop edges and clamps pinning parts
Expand Spacing kept the first selected part fixed and stalled on full plates.

- A pair of selected parts now shares each push (later part half, earlier
  part the rest, later part any remainder), so no selected part is an anchor.
  Both shares run to the full target, so a part between two short gaps no
  longer ping-pongs while its partners never move.
- Clamps act like the work-area edge: a part may close on the keep-out but
  never enter it, and the clamp gap neither chases the target spacing nor
  counts as the achieved spacing. Before, clamps held their full entry gap
  and a part resting just above one capped the whole search.
- A part flush on an edge can slide along it again. A push that leaned into
  the edge by rounding (parts turned a quarter or half) divided zero room by
  a tiny component and pinned every move.
- Faster search with identical layouts: per-part pair lists, clearances
  remembered at the positions measured, box-proven clamp pairs skipped,
  trial-move gaps measured only up to their threshold, the overlap clipping
  run only for outlines that touch, cross or nest, and ring distances
  measured at offsets without copying outlines. Clearance gains the bounded
  and offset distance used for this.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 08:45:31 -05:00

532 lines
21 KiB
C#

using System;
using System.Collections.Generic;
using OpenNest.Math;
namespace OpenNest.Geometry
{
/// <summary>
/// Signed clearance between two closed polygons, plus the unit direction that
/// increases it by moving the first polygon.
/// </summary>
public struct ClearanceResult
{
/// <summary>
/// &gt; 0: minimum boundary distance. 0: touching. &lt; 0: penetration depth
/// (the translation of <c>a</c> along <see cref="Direction"/> needed to end
/// contact).
/// </summary>
public double Distance;
/// <summary>
/// Unit direction for translating <c>a</c> away from <c>b</c>. For penetration
/// this is the minimum-translation direction. Never zero-length; degenerate
/// (coincident-centroid) penetration resolves to a deterministic axis.
/// </summary>
public Vector Direction;
public ClearanceResult(double distance, Vector direction)
{
Distance = distance;
Direction = direction;
}
}
/// <summary>
/// Omnidirectional clearance between two closed, lines-only polygons.
/// Complements <see cref="SpatialQuery.DirectionalDistance"/> (movement along a
/// fixed ray) with the all-directions minimum distance and separating direction,
/// and <see cref="Collision"/> (boolean overlap) with depth and direction.
/// <para>
/// Reference quality, not hot-loop quality: separation is a brute-force
/// segment-pair minimum with a bounding-box reject, penetration is a
/// separating-axis sweep over both polygons' edge normals. The overlap verdict
/// defers to <see cref="Collision.HasOverlap(Polygon, Polygon, List{Polygon}, List{Polygon})"/>
/// so callers that validate with Collision never see a disagreeing kernel.
/// Rings with holes are handled by the caller: pass every ring pair (a part's
/// material boundary is its outer ring plus its hole rings).
/// </para>
/// </summary>
public static class Clearance
{
public static ClearanceResult Between(Polygon a, Polygon b)
{
var linesA = a.ToLines();
var linesB = b.ToLines();
if (linesA.Count == 0 || linesB.Count == 0)
return new ClearanceResult(0, new Vector(1, 0));
if (Collision.HasOverlap(a, b))
return Penetration(linesA, linesB);
return Separation(linesA, linesB);
}
/// <summary>
/// Non-negative minimum boundary (edge-to-edge) distance between two rings
/// and the direction that translates <paramref name="a"/> away from
/// <paramref name="b"/> at the closest contact. Never tests overlap: a ring
/// contained in another (a part inside a cutout ring) still reports its true
/// gap. For signed material clearance use <see cref="Between"/>.
/// </summary>
public static ClearanceResult BoundaryDistance(Polygon a, Polygon b)
{
var linesA = a.ToLines();
var linesB = b.ToLines();
if (linesA.Count == 0 || linesB.Count == 0)
return new ClearanceResult(0, new Vector(1, 0));
return Separation(linesA, linesB);
}
/// <summary>
/// <see cref="BoundaryDistance(Polygon, Polygon)"/> for callers that only compare the
/// distance with thresholds under <paramref name="reach"/>: a distance under it is
/// exact (same value and direction), and anything at or beyond it reads as
/// <paramref name="reach"/>. Far segments are then never measured.
/// </summary>
public static ClearanceResult BoundaryDistance(Polygon a, Polygon b, double reach)
{
var linesA = a.ToLines();
var linesB = b.ToLines();
if (linesA.Count == 0 || linesB.Count == 0)
return new ClearanceResult(0, new Vector(1, 0));
var minDist = ClosestPoints(linesA, linesB, out var pa, out var pb, reach);
if (!(minDist < reach))
return new ClearanceResult(reach, new Vector(1, 0));
return Direction(minDist, pa, pb, linesA, linesB);
}
/// <summary>
/// <see cref="BoundaryDistance(Polygon, Polygon, double)"/> for rings given in local
/// frames: each vertex sits at its value plus the ring's offset, exactly as a copy
/// moved by <see cref="Polygon.Offset(Vector)"/> would, and segments join consecutive
/// vertices as <see cref="Polygon.ToLines"/> does. The result equals that call on the
/// moved copies, without making them. <paramref name="reach"/> may be
/// <see cref="double.MaxValue"/> for the exact distance.
/// </summary>
internal static ClearanceResult BoundaryDistance(
List<Vector> a, Vector offsetA, List<Vector> b, Vector offsetB, double reach)
{
if (a.Count < 2 || b.Count < 2)
return new ClearanceResult(0, new Vector(1, 0));
var minDist = ClosestPoints(a, offsetA, b, offsetB, out var pa, out var pb, reach);
if (reach < double.MaxValue && !(minDist < reach))
return new ClearanceResult(reach, new Vector(1, 0));
var dir = pa - pb;
var len = Magnitude(dir);
if (len > Tolerance.Epsilon)
return new ClearanceResult(minDist, dir / len);
return new ClearanceResult(minDist, CentroidAway(Moved(a, offsetA), Moved(b, offsetB)));
static List<Line> Moved(List<Vector> ring, Vector offset)
{
var lines = new List<Line>(ring.Count);
for (var i = 1; i < ring.Count; i++)
lines.Add(new Line(ring[i - 1].Offset(offset), ring[i].Offset(offset)));
return lines;
}
}
[ThreadStatic]
private static double[] segmentBoxes;
/// <summary>The list-of-lines ClosestPoints on rings at offsets, with the same segment
/// boxes, order and arithmetic, but no copies.</summary>
private static double ClosestPoints(List<Vector> a, Vector offsetA, List<Vector> b, Vector offsetB,
out Vector pa, out Vector pb, double reach)
{
var minDist = reach;
pa = Vector.Zero;
pb = Vector.Zero;
var countB = b.Count - 1;
var boxes = segmentBoxes;
if (boxes == null || boxes.Length < 4 * countB)
segmentBoxes = boxes = new double[System.Math.Max(4 * countB, 256)];
var (uLeft, uBottom, uRight, uTop) = (double.PositiveInfinity, double.PositiveInfinity,
double.NegativeInfinity, double.NegativeInfinity);
var last = b[0].Offset(offsetB);
for (var i = 0; i < countB; i++)
{
var next = b[i + 1].Offset(offsetB);
// As SegmentBox: a Box of (min, min, |dx|, |dy|), whose Right and Top add
// the extent back.
var left = System.Math.Min(last.X, next.X);
var bottom = System.Math.Min(last.Y, next.Y);
var right = left + System.Math.Abs(next.X - last.X);
var top = bottom + System.Math.Abs(next.Y - last.Y);
boxes[4 * i] = left;
boxes[4 * i + 1] = bottom;
boxes[4 * i + 2] = right;
boxes[4 * i + 3] = top;
uLeft = System.Math.Min(uLeft, left);
uBottom = System.Math.Min(uBottom, bottom);
uRight = System.Math.Max(uRight, right);
uTop = System.Math.Max(uTop, top);
last = next;
}
var a1 = a[0].Offset(offsetA);
for (var j = 1; j < a.Count; j++)
{
var a2 = a[j].Offset(offsetA);
var aLeft = System.Math.Min(a1.X, a2.X);
var aBottom = System.Math.Min(a1.Y, a2.Y);
var aRight = aLeft + System.Math.Abs(a2.X - a1.X);
var aTop = aBottom + System.Math.Abs(a2.Y - a1.Y);
if (!(aRight + minDist < uLeft || uRight + minDist < aLeft
|| aTop + minDist < uBottom || uTop + minDist < aBottom))
{
var b1 = b[0].Offset(offsetB);
for (var i = 0; i < countB; i++)
{
var b2 = b[i + 1].Offset(offsetB);
if (!(aRight + minDist < boxes[4 * i] || boxes[4 * i + 2] + minDist < aLeft
|| aTop + minDist < boxes[4 * i + 1] || boxes[4 * i + 3] + minDist < aBottom))
{
var d = SegmentDistance(a1, a2, b1, b2, out var qa, out var qb);
if (d < minDist)
{
minDist = d;
pa = qa;
pb = qb;
}
}
b1 = b2;
}
}
a1 = a2;
}
return minDist;
}
/// <summary>Distance from a closed boundary's segments to every segment
/// of an intentional open cutting path. Unlike polygonizing that path,
/// this retains segment interiors and disjoint subpaths.</summary>
internal static ClearanceResult BoundaryDistance(List<Line> closed, List<Line> open)
{
if (closed.Count == 0 || open.Count == 0)
return new ClearanceResult(0, new Vector(1, 0));
return Separation(closed, open);
}
/// <summary>
/// Minimum boundary distance between two non-overlapping rings and the
/// direction that translates <paramref name="linesA"/> away from
/// <paramref name="linesB"/> at the closest contact.
/// </summary>
private static ClearanceResult Separation(List<Line> linesA, List<Line> linesB)
{
var minDist = ClosestPoints(linesA, linesB, out var pa, out var pb);
return Direction(minDist, pa, pb, linesA, linesB);
}
private static ClearanceResult Direction(double minDist, Vector pa, Vector pb, List<Line> linesA, List<Line> linesB)
{
var dir = pa - pb;
var len = Magnitude(dir);
if (len <= Tolerance.Epsilon)
dir = CentroidAway(linesA, linesB);
else
dir = dir / len;
return new ClearanceResult(minDist, dir);
}
/// <summary>
/// Minimum boundary (edge-to-edge) distance between two rings and the point on each
/// boundary where it occurs. Like <see cref="BoundaryDistance(Polygon, Polygon)"/>, never
/// tests overlap. Infinity, with zero points, when either ring has no edges.
/// </summary>
public static double ClosestPoints(Polygon a, Polygon b, out Vector onA, out Vector onB)
{
var linesA = a.ToLines();
var linesB = b.ToLines();
if (linesA.Count == 0 || linesB.Count == 0)
{
onA = onB = Vector.Zero;
return double.PositiveInfinity;
}
return ClosestPoints(linesA, linesB, out onA, out onB);
}
/// <summary>
/// Minimum segment-to-segment distance, visiting segment pairs in order and keeping
/// the first pair that attains it. A pair is skipped only when its boxes prove it
/// cannot beat the best so far, so the result never depends on the skipping. With a
/// finite <paramref name="reach"/> the best starts there: a distance under it is
/// exactly the unbounded one (same points), and none under it returns
/// <paramref name="reach"/> with zero points.
/// </summary>
internal static double ClosestPoints(List<Line> linesA, List<Line> linesB, out Vector pa, out Vector pb,
double reach = double.MaxValue)
{
var minDist = reach;
pa = Vector.Zero;
pb = Vector.Zero;
var boxes = new Box[linesB.Count];
var (uLeft, uBottom, uRight, uTop) = (double.PositiveInfinity, double.PositiveInfinity,
double.NegativeInfinity, double.NegativeInfinity);
for (var i = 0; i < linesB.Count; i++)
{
var box = boxes[i] = SegmentBox(linesB[i]);
uLeft = System.Math.Min(uLeft, box.Left);
uBottom = System.Math.Min(uBottom, box.Bottom);
uRight = System.Math.Max(uRight, box.Right);
uTop = System.Math.Max(uTop, box.Top);
}
foreach (var la in linesA)
{
var boxA = SegmentBox(la);
// Every segment box of B lies inside B's box, so a segment of A out of
// reach of that box is out of reach of all of them.
if (boxA.Right + minDist < uLeft || uRight + minDist < boxA.Left
|| boxA.Top + minDist < uBottom || uTop + minDist < boxA.Bottom)
continue;
for (var i = 0; i < linesB.Count; i++)
{
if (!BoxesWithin(boxA, boxes[i], minDist))
continue;
var d = SegmentDistance(la, linesB[i], out var qa, out var qb);
if (d < minDist)
{
minDist = d;
pa = qa;
pb = qb;
}
}
}
return minDist;
}
/// <summary>
/// Penetration depth and minimum-translation direction along the separating-
/// axis candidates of both rings. Per candidate axis the true translation
/// depth is used (exit distance to the far side), so containment reports the
/// depth that actually ends contact, not the interval-intersection length.
/// Depth is reported as a negative clearance.
/// </summary>
private static ClearanceResult Penetration(List<Line> linesA, List<Line> linesB)
{
var ca = Centroid(linesA);
var cb = Centroid(linesB);
var bestDepth = double.MaxValue;
var bestDir = new Vector(1, 0);
var bestAxis = -1;
for (var axis = 0; axis < 2; axis++)
{
var lines = axis == 0 ? linesA : linesB;
foreach (var line in lines)
{
var edge = line.pt2 - line.pt1;
var n = new Vector(edge.Y, -edge.X);
var len = Magnitude(n);
if (len <= Tolerance.Epsilon)
continue;
n = n / len;
var (minA, maxA) = Project(linesA, n);
var (minB, maxB) = Project(linesB, n);
if (maxA <= minB || maxB <= minA)
continue; // separating axis found
// Depth pushing a away from b along ±n.
var forward = maxB - minA; // move a in +n until minA >= maxB
var backward = maxA - minB; // move a in -n until maxA <= minB
double depth;
Vector dir;
if (forward <= backward)
{
depth = forward;
dir = n;
}
else
{
depth = backward;
dir = -n;
}
if (depth < bestDepth - Tolerance.Epsilon || bestAxis < 0)
{
bestDepth = depth;
bestDir = dir;
bestAxis = axis;
}
}
}
if (bestAxis < 0)
{
// No candidate axis (degenerate rings): deterministic fallback.
var away = ca - cb;
var len = Magnitude(away);
bestDir = len > Tolerance.Epsilon ? away / len : new Vector(1, 0);
bestDepth = 0;
}
return new ClearanceResult(-bestDepth, bestDir);
}
private static Vector CentroidAway(List<Line> linesA, List<Line> linesB)
{
var away = Centroid(linesA) - Centroid(linesB);
var len = Magnitude(away);
return len > Tolerance.Epsilon ? away / len : new Vector(1, 0);
}
private static Vector Centroid(List<Line> lines)
{
var sum = Vector.Zero;
foreach (var line in lines)
{
sum += line.pt1;
sum += line.pt2;
}
return sum / (2 * lines.Count);
}
private static (double Min, double Max) Project(List<Line> lines, Vector n)
{
var min = double.MaxValue;
var max = double.MinValue;
foreach (var line in lines)
{
var d1 = line.pt1.DotProduct(n);
var d2 = line.pt2.DotProduct(n);
if (d1 < min)
min = d1;
if (d1 > max)
max = d1;
if (d2 < min)
min = d2;
if (d2 > max)
max = d2;
}
return (min, max);
}
/// <summary>
/// Minimum distance between two segments with the closest points.
/// Non-parallel segments use the classic clamped closest-point solve;
/// (near-)parallel segments fall back to the four endpoint-to-segment
/// distances, which is where the minimum always lies.
/// </summary>
private static double SegmentDistance(Line a, Line b, out Vector pa, out Vector pb) =>
SegmentDistance(a.pt1, a.pt2, b.pt1, b.pt2, out pa, out pb);
private static double SegmentDistance(Vector a1, Vector a2, Vector b1, Vector b2, out Vector pa, out Vector pb)
{
var p = a1;
var r = a2 - a1;
var q = b1;
var s = b2 - b1;
var rxr = r.DotProduct(r);
var sxs = s.DotProduct(s);
var rxs = r.DotProduct(s);
const double eps = 1e-12;
var denom = rxr * sxs - rxs * rxs;
if (denom > eps && rxr > eps && sxs > eps)
{
// Minimize |(p + r t) - (q + s u)|^2; setting both partials to
// zero and solving (Cramer) with d0 = p - q:
// t = ((r.s)(d0.s) - (d0.r)(s.s)) / (rr.ss - (r.s)^2)
// u = ((r.r)(d0.s) - (r.s)(d0.r)) / (rr.ss - (r.s)^2)
var d0 = p - q;
var d0r = d0.DotProduct(r);
var d0s = d0.DotProduct(s);
var t = Clamp((rxs * d0s - d0r * sxs) / denom, 0, 1);
var u = Clamp((rxs * t + d0s) / sxs, 0, 1); // nearest u on b for clamped t
t = Clamp((rxs * u - d0r) / rxr, 0, 1); // re-solve t for clamped u
pa = p + r * t;
pb = q + s * u;
return pa.DistanceTo(pb);
}
// Degenerate or parallel: the minimum is attained at an endpoint.
var bestPa = p;
var bestPb = q;
var best = double.MaxValue;
void Consider(Vector pt, Vector seg1, Vector seg2, bool ptOnA)
{
var d = seg2 - seg1;
var len2 = d.DotProduct(d);
var u = len2 <= eps ? 0 : Clamp((pt - seg1).DotProduct(d) / len2, 0, 1);
var on = seg1 + d * u;
var dist = pt.DistanceTo(on);
if (dist < best)
{
best = dist;
bestPa = ptOnA ? pt : on;
bestPb = ptOnA ? on : pt;
}
}
Consider(p, b1, b2, true);
Consider(a2, b1, b2, true);
Consider(q, a1, a2, false);
Consider(b2, a1, a2, false);
pa = bestPa;
pb = bestPb;
return best;
}
private static double Clamp(double v, double lo, double hi) =>
v < lo ? lo : (v > hi ? hi : v);
private static double Magnitude(Vector v) => System.Math.Sqrt(v.X * v.X + v.Y * v.Y);
private static Box SegmentBox(Line line)
{
return new Box(
System.Math.Min(line.pt1.X, line.pt2.X),
System.Math.Min(line.pt1.Y, line.pt2.Y),
System.Math.Abs(line.pt2.X - line.pt1.X),
System.Math.Abs(line.pt2.Y - line.pt1.Y)
);
}
/// <summary>Whether the boxes are no more than <paramref name="distance"/> apart on both axes.</summary>
internal static bool BoxesWithin(Box a, Box b, double distance)
{
return !(
a.Right + distance < b.Left
|| b.Right + distance < a.Left
|| a.Top + distance < b.Bottom
|| b.Top + distance < a.Bottom
);
}
}
}