diff --git a/OpenNest.Core/Geometry/Clearance.cs b/OpenNest.Core/Geometry/Clearance.cs
index 5fec515c..7fbf22ad 100644
--- a/OpenNest.Core/Geometry/Clearance.cs
+++ b/OpenNest.Core/Geometry/Clearance.cs
@@ -80,6 +80,134 @@ namespace OpenNest.Geometry
return Separation(linesA, linesB);
}
+ ///
+ /// for callers that only compare the
+ /// distance with thresholds under : a distance under it is
+ /// exact (same value and direction), and anything at or beyond it reads as
+ /// . Far segments are then never measured.
+ ///
+ 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);
+ }
+
+ ///
+ /// for rings given in local
+ /// frames: each vertex sits at its value plus the ring's offset, exactly as a copy
+ /// moved by would, and segments join consecutive
+ /// vertices as does. The result equals that call on the
+ /// moved copies, without making them. may be
+ /// for the exact distance.
+ ///
+ internal static ClearanceResult BoundaryDistance(
+ List a, Vector offsetA, List 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 Moved(List ring, Vector offset)
+ {
+ var lines = new List(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;
+
+ /// The list-of-lines ClosestPoints on rings at offsets, with the same segment
+ /// boxes, order and arithmetic, but no copies.
+ private static double ClosestPoints(List a, Vector offsetA, List 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;
+ }
+
/// 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.
@@ -98,7 +226,11 @@ namespace OpenNest.Geometry
private static ClearanceResult Separation(List linesA, List 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 linesA, List linesB)
+ {
var dir = pa - pb;
var len = Magnitude(dir);
@@ -129,20 +261,43 @@ namespace OpenNest.Geometry
return ClosestPoints(linesA, linesB, out onA, out onB);
}
- internal static double ClosestPoints(List linesA, List linesB, out Vector pa, out Vector pb)
+ ///
+ /// 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 the best starts there: a distance under it is
+ /// exactly the unbounded one (same points), and none under it returns
+ /// with zero points.
+ ///
+ internal static double ClosestPoints(List linesA, List linesB, out Vector pa, out Vector pb,
+ double reach = double.MaxValue)
{
- var minDist = 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++)
- boxes[i] = SegmentBox(linesB[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))
@@ -281,12 +436,15 @@ namespace OpenNest.Geometry
/// (near-)parallel segments fall back to the four endpoint-to-segment
/// distances, which is where the minimum always lies.
///
- private static double SegmentDistance(Line a, Line b, out Vector pa, out Vector pb)
+ 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 = a.pt1;
- var r = a.pt2 - a.pt1;
- var q = b.pt1;
- var s = b.pt2 - b.pt1;
+ var p = a1;
+ var r = a2 - a1;
+ var q = b1;
+ var s = b2 - b1;
var rxr = r.DotProduct(r);
var sxs = s.DotProduct(s);
@@ -319,12 +477,12 @@ namespace OpenNest.Geometry
var bestPb = q;
var best = double.MaxValue;
- void Consider(Vector pt, Line seg, bool ptOnA)
+ void Consider(Vector pt, Vector seg1, Vector seg2, bool ptOnA)
{
- var d = seg.pt2 - seg.pt1;
+ var d = seg2 - seg1;
var len2 = d.DotProduct(d);
- var u = len2 <= eps ? 0 : Clamp((pt - seg.pt1).DotProduct(d) / len2, 0, 1);
- var on = seg.pt1 + d * u;
+ 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)
{
@@ -334,10 +492,10 @@ namespace OpenNest.Geometry
}
}
- Consider(p, b, true);
- Consider(a.pt2, b, true);
- Consider(q, a, false);
- Consider(b.pt2, a, false);
+ Consider(p, b1, b2, true);
+ Consider(a2, b1, b2, true);
+ Consider(q, a1, a2, false);
+ Consider(b2, a1, a2, false);
pa = bestPa;
pb = bestPb;
diff --git a/OpenNest.Engine.Tests/Fill/ExpanderCutoffQuadrantTests.cs b/OpenNest.Engine.Tests/Fill/ExpanderCutoffQuadrantTests.cs
index ed095573..c0bdda84 100644
--- a/OpenNest.Engine.Tests/Fill/ExpanderCutoffQuadrantTests.cs
+++ b/OpenNest.Engine.Tests/Fill/ExpanderCutoffQuadrantTests.cs
@@ -49,12 +49,14 @@ public class ExpanderCutoffQuadrantTests
}
Vector end;
+ Vector anchorEnd;
int violations;
if (expand)
{
var result = Expander.Expand(new List { anchor, mover }, plate,
new Expander.Options { MaxSpacing = 3 });
end = mover.Location;
+ anchorEnd = anchor.Location;
violations = result.Violations.Count;
Assert.True(result.AchievedSpacing >= 2.99,
$"spacing={result.AchievedSpacing:R}; end=({end.X:R},{end.Y:R})");
@@ -63,6 +65,7 @@ public class ExpanderCutoffQuadrantTests
{
var result = Expander.Separate(new List { anchor, mover }, plate, 3);
end = result.Positions[1];
+ anchorEnd = result.Positions[0];
violations = result.Violations.Count;
Assert.True(result.Converged,
$"unchanged=({end.X:R},{end.Y:R}), violations={violations}");
@@ -70,12 +73,15 @@ public class ExpanderCutoffQuadrantTests
Assert.Equal(moverPose.Y, mover.Location.Y);
}
- // Two units of negative-axis motion opens the selected gap 1 -> 3.
- // The parallel open cutoff remains eight units away throughout.
- Assert.True(verticalMotion ? end.Y <= moverPose.Y - 1.999 : end.X <= moverPose.X - 1.999);
+ // Two units of relative motion along the axis open the selected gap
+ // 1 -> 3; both selected parts share it. The parallel open cutoff
+ // remains several units away throughout.
+ var opened = (end - anchorEnd) - (moverPose - anchorPose);
+ Assert.True(verticalMotion ? opened.Y <= -1.999 : opened.X <= -1.999,
+ $"opened=({opened.X:R},{opened.Y:R})");
Assert.Equal(0, violations);
- Assert.Equal(anchorPose.X, anchor.Location.X);
- Assert.Equal(anchorPose.Y, anchor.Location.Y);
+ Assert.Equal(0, verticalMotion ? end.X - moverPose.X : end.Y - moverPose.Y, 9);
+ Assert.Equal(0, verticalMotion ? anchorEnd.X - anchorPose.X : anchorEnd.Y - anchorPose.Y, 9);
if (cutoff)
{
plate.RegenerateCutOffs(new CutOffSettings());
diff --git a/OpenNest.Engine.Tests/Fill/ExpanderFinalQualityTests.cs b/OpenNest.Engine.Tests/Fill/ExpanderFinalQualityTests.cs
index cde01ec5..595d1983 100644
--- a/OpenNest.Engine.Tests/Fill/ExpanderFinalQualityTests.cs
+++ b/OpenNest.Engine.Tests/Fill/ExpanderFinalQualityTests.cs
@@ -92,8 +92,9 @@ public class ExpanderFinalQualityTests
var result = Expander.Expand(new List { anchor, mover }, plate,
new Expander.Options { MaxSpacing = 3 });
- Assert.True(mover.Location.X >= 6 - 1e-4 && result.AchievedSpacing >= 2.99,
- $"Remote cutoff pinned horizontal move: x={mover.Location.X:R}, achieved={result.AchievedSpacing:R}, violations={result.Violations.Count}");
+ var opened = mover.Location.X - anchor.Location.X;
+ Assert.True(opened >= 5 - 1e-4 && result.AchievedSpacing >= 2.99,
+ $"Remote cutoff pinned horizontal move: opened={opened:R}, achieved={result.AchievedSpacing:R}, violations={result.Violations.Count}");
Assert.Equal(0, cutPart.Location.X);
Assert.Equal(0, cutPart.Location.Y);
plate.RegenerateCutOffs(settings);
diff --git a/OpenNest.Engine.Tests/Fill/ExpanderPatternTests.cs b/OpenNest.Engine.Tests/Fill/ExpanderPatternTests.cs
index 2246d0be..f59bfc5d 100644
--- a/OpenNest.Engine.Tests/Fill/ExpanderPatternTests.cs
+++ b/OpenNest.Engine.Tests/Fill/ExpanderPatternTests.cs
@@ -242,7 +242,8 @@ public class ExpanderPatternTests
var result = Expander.Expand(parts, plate);
Assert.False(result.KeptPattern);
- Assert.Equal(new Vector(5, 5), parts[0].Location); // the pair search's anchor
+ Assert.False(result.PatternMoved);
+ Assert.True(result.AchievedSpacing > 0.5, $"achieved={result.AchievedSpacing:R}");
}
[Fact]
diff --git a/OpenNest.Engine.Tests/Fill/ExpanderQualityReviewTests.cs b/OpenNest.Engine.Tests/Fill/ExpanderQualityReviewTests.cs
index 53f7909c..35f0ca4c 100644
--- a/OpenNest.Engine.Tests/Fill/ExpanderQualityReviewTests.cs
+++ b/OpenNest.Engine.Tests/Fill/ExpanderQualityReviewTests.cs
@@ -64,19 +64,21 @@ public class ExpanderQualityReviewTests
[Fact]
public void EdgeLimitedConvexOverlap_ShouldRetainCertifiedPartialImprovement()
{
- var plate = MakePlate(11.5);
- var anchor = AddSquare(plate, 5, 4, 4);
- var mover = AddSquare(plate, 7, 4, 4);
+ // The anchor sits on the low edge, so only the mover can open the overlap.
+ var plate = MakePlate(6.5);
+ var anchor = AddSquare(plate, 0, 4, 4);
+ var mover = AddSquare(plate, 2, 4, 4);
var result = Expander.Expand(
new List { anchor, mover }, plate, new Expander.Options { MaxSpacing = 1 }
);
- // Along x in [7,7.5], penetration is 9-x and strictly decreases.
+ // Along x in [2,2.5], penetration is 4-x and strictly decreases.
Assert.True(
- mover.Location.X >= 7.49,
- $"Lost safe partial-overlap improvement: x={mover.Location.X:R}; expected edge at 7.5"
+ mover.Location.X >= 2.49,
+ $"Lost safe partial-overlap improvement: x={mover.Location.X:R}; expected edge at 2.5"
);
Assert.NotEmpty(result.Violations);
- Assert.True(mover.Location.X + 4 <= 11.5 + 1e-9);
+ Assert.Equal(0, anchor.Location.X);
+ Assert.True(mover.Location.X + 4 <= 6.5 + 1e-9);
}
[Fact]
@@ -86,8 +88,9 @@ public class ExpanderQualityReviewTests
var anchor = AddSquare(plate, 5, 4, 4);
var mover = AddSquare(plate, 7, 4, 4);
var result = Expander.Separate(new List { anchor, mover }, plate, -1);
- Assert.True(result.Converged, $"Signed target -1 was not reached; x={result.Positions[1].X:R}");
- Assert.True(result.Positions[1].X >= 8);
+ var opened = result.Positions[1].X - result.Positions[0].X;
+ Assert.True(result.Converged, $"Signed target -1 was not reached; opened={opened:R}");
+ Assert.True(opened >= 3 - 1e-6, $"opened={opened:R}");
Assert.Equal(7, mover.Location.X);
}
}
diff --git a/OpenNest.Engine.Tests/Fill/ExpanderRemoteObliquePathTests.cs b/OpenNest.Engine.Tests/Fill/ExpanderRemoteObliquePathTests.cs
index eaa446be..7cf44328 100644
--- a/OpenNest.Engine.Tests/Fill/ExpanderRemoteObliquePathTests.cs
+++ b/OpenNest.Engine.Tests/Fill/ExpanderRemoteObliquePathTests.cs
@@ -53,11 +53,13 @@ public class ExpanderRemoteObliquePathTests
// First line is y=.64*x+20.48. The anchor's nearest corner (40,42)
// has exact gap 4.08/sqrt(1+.64^2)>3; mover (43,42) >5.
Vector end;
+ Vector anchorEnd;
if (expand)
{
var result = Expander.Expand(new List { anchor, mover }, plate,
new Expander.Options { MaxSpacing = 2 });
end = mover.Location;
+ anchorEnd = anchor.Location;
Assert.True(result.AchievedSpacing >= 1.99,
$"Remote cutoff pinned mover: spacing={result.AchievedSpacing:R}, violations={result.Violations.Count}");
}
@@ -65,13 +67,16 @@ public class ExpanderRemoteObliquePathTests
{
var result = Expander.Separate(new List { anchor, mover }, plate, 2);
end = result.Positions[1];
+ anchorEnd = result.Positions[0];
Assert.True(result.Converged,
$"Remote cutoff pinned mover: end=({end.X:R},{end.Y:R}), violations={result.Violations.Count}");
Assert.Equal(moverPose.X, mover.Location.X);
Assert.Equal(moverPose.Y, mover.Location.Y);
}
- Assert.True(transpose ? end.Y >= moverPose.Y + 0.999 : end.X >= moverPose.X + 0.999);
- Assert.Equal(anchorPose.X, anchor.Location.X);
- Assert.Equal(anchorPose.Y, anchor.Location.Y);
+ // Both selected parts share the opening along the pair's axis.
+ var opened = (end - anchorEnd) - (moverPose - anchorPose);
+ Assert.True(transpose ? opened.Y >= 0.999 : opened.X >= 0.999,
+ $"opened=({opened.X:R},{opened.Y:R})");
+ Assert.Equal(0, transpose ? opened.X : opened.Y, 9);
}
}
diff --git a/OpenNest.Engine.Tests/Fill/ExpanderSpecRegressionTests.cs b/OpenNest.Engine.Tests/Fill/ExpanderSpecRegressionTests.cs
index 925fbb9b..746dfabb 100644
--- a/OpenNest.Engine.Tests/Fill/ExpanderSpecRegressionTests.cs
+++ b/OpenNest.Engine.Tests/Fill/ExpanderSpecRegressionTests.cs
@@ -72,6 +72,5 @@ public class ExpanderSpecRegressionTests
$"native gap={nativeGap:R}; achieved={result.AchievedSpacing:R}; violations={result.Violations.Count}");
Assert.True(result.AchievedSpacing >= 2.9);
Assert.Empty(result.Violations);
- Assert.Equal(7, a.Location.X);
}
}
diff --git a/OpenNest.Engine.Tests/Fill/ExpanderTests.cs b/OpenNest.Engine.Tests/Fill/ExpanderTests.cs
index d3cfd068..fa104de5 100644
--- a/OpenNest.Engine.Tests/Fill/ExpanderTests.cs
+++ b/OpenNest.Engine.Tests/Fill/ExpanderTests.cs
@@ -78,7 +78,7 @@ public class ExpanderTests
}
[Fact]
- public void Expand_TwoSquares_GrowUntilEdgeFloor_AndAnchorStaysPut()
+ public void Expand_TwoSquares_BothMoveToTheEdgeFloors()
{
var plate = MakePlate(24, 24);
var a = AddSquare(plate, 6, 10);
@@ -86,14 +86,16 @@ public class ExpanderTests
var result = Expander.Expand(new List { a, b }, plate);
- // Max gap: B flush against the right edge floor (23.5): 23.5 - 14 - 4 + gap base...
- // A stays (anchor); B slides to x=19.5 -> gap 9.5.
- Assert.Equal(6, a.Location.X, 6);
+ // Neither part is an anchor: A slides to the left edge floor (0.5) and
+ // B to the right one (23.5 - 4 = 19.5), so the gap is 15.
+ Assert.Equal(0.5, a.Location.X, 1);
Assert.Equal(10, a.Location.Y, 6);
- Assert.Equal(9.5, b.Location.X - (a.Location.X + 4), 1);
- Assert.True(result.AchievedSpacing >= 9.4, $"achieved {result.AchievedSpacing}");
- Assert.True(result.AchievedSpacing <= 9.6, $"achieved {result.AchievedSpacing}");
+ Assert.Equal(19.5, b.Location.X, 1);
+ Assert.Equal(10, b.Location.Y, 6);
+ Assert.True(result.AchievedSpacing >= 14.9, $"achieved {result.AchievedSpacing}");
+ Assert.True(result.AchievedSpacing <= 15.1, $"achieved {result.AchievedSpacing}");
AssertNoOverlaps(plate);
+ Assert.True(a.BoundingBox.Left >= 0.5 - 1e-6);
Assert.True(b.BoundingBox.Right <= 23.5 + 1e-6);
}
@@ -187,7 +189,7 @@ public class ExpanderTests
}
[Fact]
- public void Expand_ThreeInRow_FirstSelectedNeverMoves_AndOracleConfirmsSpacing()
+ public void Expand_ThreeInRow_OracleConfirmsSpacing()
{
var plate = MakePlate(60, 14);
var a = AddSquare(plate, 5, 5);
@@ -200,8 +202,8 @@ public class ExpanderTests
new Expander.Options { MaxSpacing = 8 }
);
- Assert.Equal(5, a.Location.X, 6); // anchor: never the later index of any pair
Assert.True(result.AchievedSpacing >= 7.9);
+ Assert.True(a.Location.X < 5, $"first selected part stayed at {a.Location.X:R}"); // no anchor
// Independent oracle: every pair clears the reported spacing.
var parts = new List { a, b, c };
@@ -360,10 +362,14 @@ public class ExpanderTests
new List { anchor, mover }, plate, spacing: 3
);
- // One unit from the wall at entry: closing it to help the other pair
- // would trade one gap for another.
+ // One unit from the wall and from the anchor at entry: the 3-unit target
+ // does not fit, and neither gap may close below its one-unit entry gap
+ // to help the other. The parts may still spend the edge's slack.
Assert.False(converged);
- Assert.Equal(new Vector(4, 4), positions[1]);
+ Assert.True(positions[1].X - (positions[0].X + 2) >= 1 - 1e-6, $"selected gap at {positions[1].X:R}");
+ Assert.True(7 - (positions[1].X + 2) >= 1 - 1e-6, $"wall gap at {positions[1].X:R}");
+ Assert.True(positions[0].X >= -1e-9);
+ Assert.Equal(4, positions[1].Y);
}
[Fact]
@@ -393,17 +399,15 @@ public class ExpanderTests
var (converged, positions, violations) = Expander.Separate(selected, plate, spacing: 2);
Assert.True(converged, $"remaining: {violations.Count}");
Assert.Empty(violations);
- Assert.Equal(5, positions[0].X);
- Assert.True(positions[1].X >= 11 - 1e-4);
+ Assert.True(positions[1].X >= positions[0].X + 6 - 1e-4);
Assert.True(positions[2].X >= positions[1].X + 6 - 1e-4);
Assert.Equal(10, middle.Location.X); // Separate is scratch-only.
Assert.Equal(14, last.Location.X);
var result = Expander.Expand(selected, plate, new Expander.Options { MaxSpacing = 2 });
Assert.True(result.AchievedSpacing >= 1.99, $"achieved {result.AchievedSpacing}");
- Assert.True(middle.Location.X >= 11 - 1e-4);
+ Assert.True(middle.Location.X >= first.Location.X + 6 - 1e-4);
Assert.True(last.Location.X >= middle.Location.X + 6 - 1e-4);
- Assert.Equal(5, first.Location.X);
}
[Fact]
@@ -500,7 +504,7 @@ public class ExpanderTests
Assert.True(converged, $"remote zone pinned growth: {violations.Count} violations, " +
$"poses {poses[0].X:R},{poses[1].X:R}; " +
string.Join("; ", violations.Select(v => $"{v.A.BaseDrawing.Name}/{v.B.BaseDrawing.Name}={v.Achieved:R}")));
- Assert.True(poses[1].X >= 6 - 1e-4);
+ Assert.True(poses[1].X - poses[0].X >= 5 - 1e-4, $"opened {poses[1].X - poses[0].X:R}");
Assert.Equal(4, moving.Location.X);
}
@@ -735,4 +739,96 @@ public class ExpanderTests
Assert.True(result.AchievedSpacing >= 0.25 - 1e-3, $"achieved {result.AchievedSpacing}");
AssertNoOverlaps(plate);
}
+
+ [Fact]
+ public void Expand_PartMayCloseOnAClamp_LikeAnEdge()
+ {
+ // The clamp keep-out is a hard boundary: B may slide right up to it
+ // (its entry gap is not a floor), and the gap to it is not a part gap.
+ var plate = MakePlate(30, 12, edge: 0);
+ plate.ClampZones.Add(new ClampZone("clamp", new Box(20, 0, 1, 1)));
+ var a = AddSquare(plate, 1, 0, 2);
+ var b = AddSquare(plate, 4, 0, 2);
+
+ var result = Expander.Expand(new List { a, b }, plate);
+
+ Assert.Empty(result.Violations);
+ Assert.True(a.Location.X <= 1e-3, $"a at {a.Location.X:R}");
+ Assert.True(b.BoundingBox.Right <= 20 + 1e-6, $"b entered the clamp: right={b.BoundingBox.Right:R}");
+ Assert.True(b.BoundingBox.Right >= 20 - 0.01, $"b stopped short of the clamp: right={b.BoundingBox.Right:R}");
+ Assert.True(result.AchievedSpacing >= 15.9, $"achieved {result.AchievedSpacing:R}");
+ AssertNoOverlaps(plate);
+ }
+
+ [Fact]
+ public void Expand_PartJustAboveAClamp_IsNotTheSmallestGap()
+ {
+ // A part resting 0.005 above a clamp neither caps the spacing at that gap
+ // nor has to climb off the clamp to the target spacing.
+ var plate = MakePlate(30, 12, edge: 0);
+ plate.ClampZones.Add(new ClampZone("clamp", new Box(2, 0, 1, 1)));
+ var a = AddSquare(plate, 1, 1.005, 4);
+ var b = AddSquare(plate, 5.5, 1.005, 4);
+
+ var result = Expander.Expand(new List { a, b }, plate, new Expander.Options { MaxSpacing = 2 });
+
+ Assert.Empty(result.Violations);
+ Assert.True(result.AchievedSpacing >= 1.99, $"achieved {result.AchievedSpacing:R}");
+ Assert.Equal(1.005, a.Location.Y, 6);
+ Assert.Equal(1.005, b.Location.Y, 6);
+ AssertNoOverlaps(plate);
+ }
+
+ [Fact]
+ public void Separate_SqueezedMiddlePart_PartnersShareTheShortfall()
+ {
+ // A column like N26-2J3 plate 2's: 3.75 x 9 parts, gaps 0.25 then 0.257,
+ // selected out of stacking order. A half push lands a part between two
+ // short gaps just past the trigger; unless its partners take their share
+ // too, the next pair pushes it straight back and the column stalls.
+ var plate = MakePlate(20, 60, edge: 0);
+ var stack = new List();
+ var y = 0.002;
+ foreach (var gap in new[] { 0.25, 0.257, 0.257, 0.257, 0.257, 0.0 })
+ {
+ stack.Add(AddRectangle(plate, 5, y, 3.75, 9));
+ y += 9 + gap;
+ }
+ var selected = new List { stack[1], stack[0], stack[3], stack[2], stack[5], stack[4] };
+
+ var (converged, positions, violations) = Expander.Separate(selected, plate, spacing: 0.3);
+
+ Assert.True(converged, string.Join("; ", violations.Select(v => $"{v.A.BaseDrawing.Name}/{v.B?.BaseDrawing.Name}={v.Achieved:R}")));
+ var tops = selected.Select((part, i) => (Part: part, Y: positions[i].Y)).OrderBy(e => e.Y).ToList();
+ for (var i = 1; i < tops.Count; i++)
+ Assert.True(tops[i].Y - tops[i - 1].Y - 9 >= 0.3 - 1e-6, $"gap {i}: {tops[i].Y - tops[i - 1].Y - 9:R}");
+ }
+
+ [Fact]
+ public void Expand_PartFlushOnTheBottomEdge_StillSlidesAlongIt()
+ {
+ // Parts turned a quarter and a half carry rounding in their vertices, so the
+ // push between these two leans into the bottom edge by about 3e-15, as
+ // on N26-2J3's plates. Zero room below the right part must not pin its move
+ // along the edge: before the fix this pair could not open at all.
+ var plate = MakePlate(60, 20, edge: 0.25);
+ Part Turned(double length, double angle, double left)
+ {
+ var part = new Part(new Drawing($"turned{plate.Parts.Count}", Rectangle(length, 5.302)));
+ part.Rotate(angle);
+ part.Offset(new Vector(left - part.BoundingBox.Left, 0.25 - part.BoundingBox.Bottom));
+ plate.Parts.Add(part);
+ return part;
+ }
+ var leftPart = Turned(12.5, System.Math.PI / 2, 0.25);
+ var rightPart = Turned(12.5, System.Math.PI, leftPart.BoundingBox.Right + 0.285);
+
+ var result = Expander.Expand(new List { leftPart, rightPart }, plate,
+ new Expander.Options { MaxSpacing = 2 });
+
+ Assert.True(result.AchievedSpacing >= 1.99, $"achieved {result.AchievedSpacing:R}");
+ Assert.True(rightPart.BoundingBox.Bottom >= 0.25 - 1e-6);
+ AssertNoOverlaps(plate);
+ }
}
+
diff --git a/OpenNest.Engine/Fill/Expander.cs b/OpenNest.Engine/Fill/Expander.cs
index 6fe9096c..04b73b2f 100644
--- a/OpenNest.Engine/Fill/Expander.cs
+++ b/OpenNest.Engine/Fill/Expander.cs
@@ -20,9 +20,9 @@ namespace OpenNest.Engine.Fill
/// Plate edges retain their EdgeSpacing floor.
///
///
- /// Anchor policy: within a violated selected pair only its later-indexed
- /// selected part moves. Nonselected parts never move; there is no counterpart
- /// fallback when the prescribed mover is blocked.
+ /// Mover policy: both parts of a violated selected pair move apart, sharing
+ /// the push, and either takes the rest when the other is blocked, so no
+ /// selected part is an anchor. Nonselected parts never move.
///
///
/// A selection that repeats on a lattice skips the pair search: its lattice
@@ -348,6 +348,11 @@ namespace OpenNest.Engine.Fill
}
}
+ /// How far past its trigger a push carries: absorbs the clearance
+ /// kernel's tessellation error so the applied spacing holds against the
+ /// production validators.
+ private const double Margin = 0.002;
+
private static double MinimumPairClearance(
SeparationContext context, List positions, CancellationToken token)
{
@@ -356,9 +361,13 @@ namespace OpenNest.Engine.Fill
foreach (var pair in context.Pairs)
{
token.ThrowIfCancellationRequested();
- if (context.ProvesClearance(pair, positions, min))
+ // A clamp keep-out is a hard edge, not a part gap: only material
+ // inside it lowers the spacing.
+ if (context.ProvesClearance(pair, positions, pair.Clamp ? 0 : min))
continue;
var (distance, _) = context.PairClearance(pair.IndexA, pair.IndexB, positions);
+ if (pair.Clamp && distance >= 0)
+ continue;
if (distance < min)
min = distance;
}
@@ -379,10 +388,6 @@ namespace OpenNest.Engine.Fill
var violations = new List();
var epsMove = 1e-4;
- // Internal margin absorbs the clearance kernel's tessellation error so
- // the applied spacing holds against the production validators.
- var target = spacing + 0.002;
-
var iterationLimit = maxIterations < 1 ? 1 : maxIterations;
for (var iteration = 0; iteration < iterationLimit; iteration++)
@@ -398,7 +403,8 @@ namespace OpenNest.Engine.Fill
{
if (token.IsCancellationRequested)
return (false, start, violations);
- if (context.ProvesClearance(pair, positions, spacing))
+ var pairSpacing = pair.SpacingAt(spacing);
+ if (context.ProvesClearance(pair, positions, pairSpacing))
continue;
var (distance, directionA) = context.PairClearance(
pair.IndexA,
@@ -412,61 +418,36 @@ namespace OpenNest.Engine.Fill
// spacing) would oscillate forever. The margin only sets how
// far past the trigger a push carries, absorbing tessellation
// error in the measurement.
- if (distance >= spacing)
+ if (distance >= pairSpacing)
continue;
- var need = target - distance;
-
- // Anchor policy (decided): only the later-indexed selected
- // part of a violated pair moves. Counterparts and walls
- // never do — a pair whose anchor mover cannot reach the
- // target is a violation, not an invitation to drift the
- // anchor.
- var moverIndex = pair.Mover;
-
- // Clearance direction translates A away from B; a mover on
- // the B side travels the opposite way.
- var direction = moverIndex == pair.IndexA ? directionA : -directionA;
-
- // A zero-distance hole contact can have an ambiguous nearest-
- // boundary fallback. Only if the normal candidate makes no
- // safe progress, retry its opposite through the same path,
- // floor and active-improvement checks. Never move the anchor.
- var attempt = ProposeMove(context, positions, pair, distance, direction, need, spacing, epsMove);
- if (attempt.Applied <= 0 && distance <= 1e-7)
+ // Mover policy: a selected/nonselected pair moves its selected
+ // part; nonselected parts are walls. A pair of selected parts
+ // shares the push: the later part takes half, the earlier part
+ // the rest, and the later part any rest its partner had no room
+ // for. So no selected part is an anchor, and the selection opens
+ // about its middle instead of away from its first part.
+ // Partial progress keeps the pair live: its blockers may move
+ // away in later iterations and unblock the rest. The final sweep
+ // remeasures all pairs. Every share runs until the pair reaches its
+ // full target, not just the trigger: a half push lands just past the
+ // trigger, and stopping there would leave a part squeezed between two
+ // short gaps to ping-pong while its partners never move.
+ foreach (var (moverIndex, share) in Shares(pair))
{
- var opposite = ProposeMove(context, positions, pair, distance, -direction, need, spacing, epsMove);
- if (opposite.Applied > attempt.Applied)
- attempt = opposite;
+ var applied = Push(context, positions, pair, moverIndex, distance, directionA,
+ (pairSpacing + Margin - distance) * share, spacing, epsMove);
+ if (applied > 0)
+ {
+ moved += applied;
+ observer?.Invoke(Checkpoint.AfterScratchMove);
+ if (token.IsCancellationRequested)
+ return (false, start, violations);
+ (distance, directionA) = context.PairClearance(pair.IndexA, pair.IndexB, positions);
+ }
+ if (distance >= pairSpacing + Margin - epsMove)
+ break;
}
- var applied = attempt.Applied;
- if (applied > 0)
- {
- positions[moverIndex] = attempt.Proposal;
- moved += applied;
- observer?.Invoke(Checkpoint.AfterScratchMove);
- if (token.IsCancellationRequested)
- return (false, start, violations);
- }
-
- // A pair fully separated to the user target (the internal margin
- // absorbs tessellation slack) is satisfied even if not to target.
- if (applied > 0)
- {
- var (finalDistance, _) = context.PairClearance(
- pair.IndexA,
- pair.IndexB,
- positions
- );
- if (finalDistance >= spacing)
- continue;
- // Partial progress: keep the pair live — its blockers may
- // move away in later iterations and unblock the rest.
- continue;
- }
-
- // No progress now; a later part may unblock this pair on
- // the next pass. The final sweep remeasures all pairs.
}
observer?.Invoke(Checkpoint.AfterPairPass);
@@ -486,7 +467,8 @@ namespace OpenNest.Engine.Fill
{
if (token.IsCancellationRequested)
return (false, start, violations);
- if (context.ProvesClearance(pair, positions, spacing))
+ var pairSpacing = pair.SpacingAt(spacing);
+ if (context.ProvesClearance(pair, positions, pairSpacing))
continue;
var (distance, directionA) = context.PairClearance(
pair.IndexA,
@@ -494,23 +476,22 @@ namespace OpenNest.Engine.Fill
positions
);
- if (distance >= spacing)
+ if (distance >= pairSpacing)
continue;
- var direction = pair.Mover == pair.IndexA ? directionA : -directionA;
- var need = target - distance;
- var attempt = ProposeMove(context, positions, pair, distance, direction, need, spacing, epsMove);
- if (attempt.Applied <= 0 && distance <= 1e-7)
- {
- var opposite = ProposeMove(context, positions, pair, distance, -direction, need, spacing, epsMove);
- if (opposite.Applied > attempt.Applied)
- attempt = opposite;
- }
+ var need = pairSpacing + Margin - distance;
// Only an actual first work-area limit is an edge blocker.
// An available move at the iteration budget, or a part/floor
- // limiting first, is not evidence of an edge obstruction.
- var blockedByEdge = attempt.EdgeLimited && !attempt.PartLimited
- && attempt.Applied < need - epsMove;
+ // limiting first, is not evidence of an edge obstruction. A
+ // shared pair is edge-blocked only when each of its movers is.
+ var blockedByEdge = true;
+ foreach (var moverIndex in pair.Shared ? new[] { pair.IndexB, pair.IndexA } : new[] { pair.Mover })
+ {
+ var attempt = Attempt(context, positions, pair, moverIndex, distance, directionA, need,
+ spacing, epsMove);
+ blockedByEdge &= attempt.EdgeLimited && !attempt.PartLimited
+ && attempt.Applied < need - epsMove;
+ }
violations.Add(
new Violation
{
@@ -526,11 +507,61 @@ namespace OpenNest.Engine.Fill
return (violations.Count == 0, positions, violations);
}
+ // Shares of a pair's shortfall, in order: a lone mover takes it all; a pair of
+ // selected parts splits it, then the later part retries what is left.
+ private static readonly (bool Later, double Share)[] SharedShares =
+ { (true, 0.5), (false, 1.0), (true, 1.0) };
+
+ private static IEnumerable<(int Mover, double Share)> Shares(Pair pair)
+ {
+ if (!pair.Shared)
+ {
+ yield return (pair.Mover, 1.0);
+ yield break;
+ }
+ foreach (var (later, share) in SharedShares)
+ yield return (later ? pair.IndexB : pair.IndexA, share);
+ }
+
+ /// Moves away from its partner by up to
+ /// on the scratch positions; returns the distance moved.
+ private static double Push(
+ SeparationContext context, List positions, Pair pair, int mover,
+ double distance, Vector directionA, double need, double spacing, double epsMove)
+ {
+ if (need <= epsMove)
+ return 0;
+ var attempt = Attempt(context, positions, pair, mover, distance, directionA, need, spacing, epsMove);
+ if (attempt.Applied > 0)
+ positions[mover] = attempt.Proposal;
+ return attempt.Applied;
+ }
+
+ private static (double Applied, Vector Proposal, bool EdgeLimited, bool PartLimited) Attempt(
+ SeparationContext context, List positions, Pair pair, int mover,
+ double distance, Vector directionA, double need, double spacing, double epsMove)
+ {
+ // Clearance direction translates A away from B; a mover on the B side
+ // travels the opposite way.
+ var direction = mover == pair.IndexA ? directionA : -directionA;
+
+ // A zero-distance hole contact can have an ambiguous nearest-boundary
+ // fallback. Only if the normal candidate makes no safe progress, retry
+ // its opposite through the same path, floor and active-improvement checks.
+ var attempt = ProposeMove(context, positions, pair, mover, distance, direction, need, spacing, epsMove);
+ if (attempt.Applied <= 0 && distance <= 1e-7)
+ {
+ var opposite = ProposeMove(context, positions, pair, mover, distance, -direction, need, spacing, epsMove);
+ if (opposite.Applied > attempt.Applied)
+ attempt = opposite;
+ }
+ return attempt;
+ }
+
private static (double Applied, Vector Proposal, bool EdgeLimited, bool PartLimited) ProposeMove(
- SeparationContext context, List positions, Pair pair,
+ SeparationContext context, List positions, Pair pair, int mover,
double distance, Vector direction, double need, double spacing, double epsMove)
{
- var mover = pair.Mover;
var start = positions[mover];
var edgeRoom = context.ClipToWorkArea(mover, start, direction, need);
var room = context.ClipToMaterial(mover, positions, direction, edgeRoom);
@@ -558,22 +589,38 @@ namespace OpenNest.Engine.Fill
: (0, start, edgeLimited, true);
}
- /// One constrained part↔part pair with its anchor mover.
+ /// One constrained part↔part pair and the part that moves for it.
private sealed class Pair
{
public int IndexA;
public int IndexB;
+
+ /// The selected part of a pair with a wall; the later part of a shared pair.
public int Mover;
+
+ /// True when both parts are selected, so both move apart.
+ public bool Shared;
public double EntryFloor;
/// True for a pair of parts, whose wide entry gap may close
- /// to the target. Cut-offs and clamps always keep their entry gap.
+ /// to the target. Cut-offs always keep their entry gap.
public bool Yields;
+ /// True for a part and a clamp wall. The wall already holds the
+ /// clamp clearance, so like the work-area edge it is a hard boundary:
+ /// a part may close on it but never enter it, and its gap neither
+ /// chases the target spacing nor counts as the achieved spacing.
+ public bool Clamp;
+
/// Lowest clearance this pair may reach at a target spacing.
- public double FloorAt(double spacing) => Yields
- ? System.Math.Min(EntryFloor, System.Math.Max(0, spacing))
- : EntryFloor;
+ public double FloorAt(double spacing) => Clamp
+ ? System.Math.Min(EntryFloor, 0)
+ : Yields
+ ? System.Math.Min(EntryFloor, System.Math.Max(0, spacing))
+ : EntryFloor;
+
+ /// The clearance this pair must reach at a target spacing.
+ public double SpacingAt(double spacing) => Clamp ? 0 : spacing;
}
///
@@ -594,6 +641,28 @@ namespace OpenNest.Engine.Fill
public readonly List Pairs = new();
public readonly double SpacingCap;
+ /// Each part's pairs, in order, so a trial
+ /// move rechecks only the pairs of the part it moves.
+ private List[] pairsOf;
+
+ ///
+ /// Measured clearances, keyed by the ordered index pair and remembered at
+ /// the exact two positions they were measured at. A clearance depends only
+ /// on those positions, so a hit is the same answer recomputed: pairs whose
+ /// parts did not move since are never measured again, within a probe or
+ /// across the probes that each restart from the entry layout. Two slots
+ /// per pair keep the committed pose when a trial pose is measured.
+ ///
+ private readonly Dictionary<(int, int), ClearanceSlots> clearances = new();
+
+ private sealed class ClearanceSlots
+ {
+ public Vector A0, B0, A1, B1;
+ public (double Distance, Vector Direction) Value0, Value1;
+ public int Filled; // 0, 1 or 2 slots in use
+ public bool NewestIsOne;
+ }
+
private sealed class RingSet
{
public Polygon Outer;
@@ -678,6 +747,7 @@ namespace OpenNest.Engine.Fill
{
token.ThrowIfCancellationRequested();
pair.EntryFloor = context.PairClearance(pair.IndexA, pair.IndexB, entry).Distance;
+ pair.Clamp = pair.IndexB >= clampStart;
pair.Yields = pair.IndexB < clampStart
&& !context.parts[pair.IndexA].BaseDrawing.IsCutOff
&& !context.parts[pair.IndexB].BaseDrawing.IsCutOff;
@@ -795,12 +865,21 @@ namespace OpenNest.Engine.Fill
{
IndexA = a,
IndexB = b,
- // Anchor policy: the later-index mover moves.
Mover = bMover ? b : a,
+ Shared = aMover && bMover,
}
);
}
}
+
+ pairsOf = new List[parts.Count];
+ for (var i = 0; i < parts.Count; i++)
+ pairsOf[i] = new List();
+ foreach (var pair in Pairs)
+ {
+ pairsOf[pair.IndexA].Add(pair);
+ pairsOf[pair.IndexB].Add(pair);
+ }
}
public bool IsMover(int index) => index < moverCount;
@@ -827,6 +906,18 @@ namespace OpenNest.Engine.Fill
///
public bool ProvesClearance(Pair pair, List positions, double floor)
{
+ if (pair.Clamp)
+ {
+ // A clamp pair's floor is at most zero, so a part whose bounds
+ // clear the exact keep-out rectangle cannot reach it. Only a
+ // part near a clamp needs its material tested.
+ var part = shapes[pair.IndexA].Bounds;
+ if (part == null || parts[pair.IndexA].BaseDrawing.IsCutOff)
+ return false;
+ var gap = BoxGap(part, positions[pair.IndexA], clampBoxes[pair.IndexB - clampStart], Vector.Zero)
+ - BoundsSlack;
+ return double.IsFinite(gap) && gap > 0 && gap >= floor;
+ }
if (pair.IndexB >= clampStart
|| parts[pair.IndexA].BaseDrawing.IsCutOff
|| parts[pair.IndexB].BaseDrawing.IsCutOff)
@@ -880,6 +971,61 @@ namespace OpenNest.Engine.Fill
int indexB,
List positions
)
+ {
+ var a = positions[indexA];
+ var b = positions[indexB];
+ if (!clearances.TryGetValue((indexA, indexB), out var slots))
+ clearances[(indexA, indexB)] = slots = new ClearanceSlots();
+ if (slots.Filled > 0 && Same(slots.A0, a) && Same(slots.B0, b))
+ return slots.Value0;
+ if (slots.Filled > 1 && Same(slots.A1, a) && Same(slots.B1, b))
+ return slots.Value1;
+
+ var value = MeasurePairClearance(indexA, indexB, positions);
+ // Replace the older slot, so the newest two poses stay remembered.
+ if (slots.Filled == 0 || (slots.Filled == 2 && slots.NewestIsOne))
+ {
+ (slots.A0, slots.B0, slots.Value0) = (a, b, value);
+ slots.NewestIsOne = false;
+ }
+ else
+ {
+ (slots.A1, slots.B1, slots.Value1) = (a, b, value);
+ slots.NewestIsOne = true;
+ }
+ slots.Filled = System.Math.Min(2, slots.Filled + 1);
+ return value;
+
+ static bool Same(Vector slot, Vector position) => slot.X == position.X && slot.Y == position.Y;
+ }
+
+ ///
+ /// for a caller that compares the clearance only
+ /// with thresholds under : a clearance under it is
+ /// exact, anything at or beyond it may read as . A
+ /// remembered clearance is used when the pose matches; a new pose is
+ /// measured without remembering it, since trial poses rarely repeat.
+ ///
+ public double PairClearanceWithin(int indexA, int indexB, List positions, double reach)
+ {
+ var a = positions[indexA];
+ var b = positions[indexB];
+ if (clearances.TryGetValue((indexA, indexB), out var slots))
+ {
+ if (slots.Filled > 0 && slots.A0.X == a.X && slots.A0.Y == a.Y && slots.B0.X == b.X && slots.B0.Y == b.Y)
+ return slots.Value0.Distance;
+ if (slots.Filled > 1 && slots.A1.X == a.X && slots.A1.Y == a.Y && slots.B1.X == b.X && slots.B1.Y == b.Y)
+ return slots.Value1.Distance;
+ }
+ return MeasurePairClearance(indexA, indexB, positions, reach).Distance;
+ }
+
+ private (double Distance, Vector Direction) MeasurePairClearance(
+ int indexA,
+ int indexB,
+ List positions,
+ double reach = double.MaxValue
+ )
{
var setA = shapes[indexA];
var setB = shapes[indexB];
@@ -964,28 +1110,30 @@ namespace OpenNest.Engine.Fill
if (setA.Outer == null || setB.Outer == null)
return (0, new Vector(1, 0));
- var outerA = CloneAt(setA.Outer, offsetA);
- var outerB = CloneAt(setB.Outer, offsetB);
-
- var holesA = setA.Holes.Count == 0 ? null : CloneAll(setA.Holes, offsetA);
- var holesB = setB.Holes.Count == 0 ? null : CloneAll(setB.Holes, offsetB);
-
- if (Collision.HasOverlap(outerA, outerB, holesA, holesB))
+ if (OutersMayShareMaterial(setA.Outer, offsetA, setB.Outer, offsetB))
{
- var penetration = Clearance.Between(outerA, outerB);
- if (penetration.Distance < 0)
- return (penetration.Distance, penetration.Direction);
- // Hole subtraction resolved what the outers overlap: touching.
- return (0, penetration.Direction);
+ // Moved copies only for the overlap kernel, which needs polygons.
+ var outerA = CloneAt(setA.Outer, offsetA);
+ var outerB = CloneAt(setB.Outer, offsetB);
+ if (Collision.HasOverlap(outerA, outerB,
+ setA.Holes.Count == 0 ? null : CloneAll(setA.Holes, offsetA),
+ setB.Holes.Count == 0 ? null : CloneAll(setB.Holes, offsetB)))
+ {
+ var penetration = Clearance.Between(outerA, outerB);
+ if (penetration.Distance < 0)
+ return (penetration.Distance, penetration.Direction);
+ // Hole subtraction resolved what the outers overlap: touching.
+ return (0, penetration.Direction);
+ }
}
- double best = double.MaxValue;
+ // A ring pair can only matter when it beats the best so far, so the
+ // best bounds each measurement; it starts at the caller's reach.
+ var best = reach;
var bestDir = new Vector(1, 0);
foreach (var ringA in setA.Rings)
{
- Polygon worldA = null;
-
foreach (var ringB in setB.Rings)
{
// Boundaries are never closer than their boxes, so a ring
@@ -993,9 +1141,10 @@ namespace OpenNest.Engine.Fill
if (BoxGap(ringA.BoundingBox, offsetA, ringB.BoundingBox, offsetB) - 1e-9 >= best)
continue;
- worldA ??= CloneAt(ringA, offsetA);
- var worldB = CloneAt(ringB, offsetB);
- var clearance = Clearance.BoundaryDistance(worldA, worldB);
+ // Measured on the prepared rings at their offsets: the same
+ // result as on moved copies, without making them.
+ var clearance = Clearance.BoundaryDistance(
+ ringA.Vertices, offsetA, ringB.Vertices, offsetB, best);
if (clearance.Distance < best)
{
@@ -1014,17 +1163,41 @@ namespace OpenNest.Engine.Fill
return (best, bestDir);
}
+ ///
+ /// False when two outer rings cannot share material: their boundaries stay
+ /// apart and neither holds a vertex of the other. Material shared at
+ /// positive area needs crossing boundaries or one ring inside the other, so
+ /// the overlap kernel's clipping, the costly part of a measurement, runs only
+ /// for rings that touch, cross or nest.
+ ///
+ private static bool OutersMayShareMaterial(Polygon a, Vector offsetA, Polygon b, Vector offsetB)
+ {
+ const double Apart = 1e-3;
+ if (a.Vertices.Count == 0 || b.Vertices.Count == 0)
+ return true;
+ if (Clearance.BoundaryDistance(a.Vertices, offsetA, b.Vertices, offsetB, Apart).Distance < Apart)
+ return true;
+ // Containment in local frames: a vertex of one ring placed in the other's.
+ return b.ContainsPoint(a.Vertices[0] + offsetA - offsetB)
+ || a.ContainsPoint(b.Vertices[0] + offsetB - offsetA);
+ }
+
///
/// Largest α ≤ need such that translating the part by direction·α keeps
/// its AABB inside the work area.
///
public double ClipToWorkArea(int index, Vector position, Vector direction, double need)
{
+ // Each side gets the same allowance InsideWorkArea accepts. A part
+ // flush on an edge (no room at all) otherwise pins every move whose
+ // direction leans into that edge by rounding, such as (1, -1e-17)
+ // along the bottom edge: zero room over a tiny component is zero.
+ const double Allowance = 1e-9;
var box = localBoxes[index];
- var left = position.X + box.Left - workArea.Left;
- var right = workArea.Right - (position.X + box.Right);
- var bottom = position.Y + box.Bottom - workArea.Bottom;
- var top = workArea.Top - (position.Y + box.Top);
+ var left = position.X + box.Left - workArea.Left + Allowance;
+ var right = workArea.Right - (position.X + box.Right) + Allowance;
+ var bottom = position.Y + box.Bottom - workArea.Bottom + Allowance;
+ var top = workArea.Top - (position.Y + box.Top) + Allowance;
var max = need;
if (direction.X > 0)
@@ -1383,6 +1556,10 @@ namespace OpenNest.Engine.Fill
/// Check active improvement and every affected pair against
/// its floor at the target spacing on scratch positions.
+ /// A reach safely past , and past the
+ /// 0.002 band in which a curved pair's gap reads as uncertain.
+ private static double WithinReach(double threshold) => System.Math.Max(threshold, 0) + 0.01;
+
public bool MaintainsValidity(
int index, Vector trial, List positions, Pair active, double activeDistance,
double spacing)
@@ -1394,17 +1571,18 @@ namespace OpenNest.Engine.Fill
positions[index] = trial;
try
{
- var improved = PairClearance(active.IndexA, active.IndexB, positions).Distance;
+ // Only comparisons with a threshold follow, so each clearance is
+ // measured just past it (WithinReach): far segments are skipped.
+ var improved = PairClearanceWithin(active.IndexA, active.IndexB, positions,
+ WithinReach(activeDistance + 1e-7));
if (!double.IsFinite(improved) || improved <= activeDistance + 1e-7)
return false;
- foreach (var pair in Pairs)
+ foreach (var pair in pairsOf[index])
{
- if (pair.IndexA != index && pair.IndexB != index)
- continue;
var floor = pair.FloorAt(spacing) - FloorTolerance;
if (ProvesClearance(pair, positions, floor))
continue;
- var clearance = PairClearance(pair.IndexA, pair.IndexB, positions).Distance;
+ var clearance = PairClearanceWithin(pair.IndexA, pair.IndexB, positions, WithinReach(floor));
if (!double.IsFinite(clearance) || clearance < floor)
return false;
// Once an initial overlap is cleared, never reintroduce it.
diff --git a/OpenNest.Tests/Geometry/ClearanceTests.cs b/OpenNest.Tests/Geometry/ClearanceTests.cs
index a070fdbe..7757648b 100644
--- a/OpenNest.Tests/Geometry/ClearanceTests.cs
+++ b/OpenNest.Tests/Geometry/ClearanceTests.cs
@@ -305,4 +305,72 @@ public class ClearanceTests
}
}
}
+
+ [Fact]
+ public void BoundaryDistance_AtOffsetsAndWithinReach_MatchesMovedCopies()
+ {
+ // The Expander measures prepared rings at offsets, often only up to a reach.
+ // Both must give exactly what the moved copies give: same distance and the
+ // same direction, including parallel edges where many points tie.
+ var random = new Random(1234);
+ Polygon Ring()
+ {
+ var points = new List();
+ var count = random.Next(3, 12);
+ for (var i = 0; i < count; i++)
+ {
+ var angle = 2 * System.Math.PI * i / count;
+ var radius = 1 + random.NextDouble();
+ points.Add(new Vector(radius * System.Math.Cos(angle), radius * System.Math.Sin(angle)));
+ }
+ var ring = new Polygon { Vertices = points };
+ ring.Close();
+ ring.UpdateBounds();
+ return ring;
+ }
+
+ Polygon Moved(Polygon ring, Vector offset)
+ {
+ var copy = (Polygon)ring.Clone();
+ copy.UpdateBounds();
+ copy.Offset(offset);
+ return copy;
+ }
+
+ var shapes = new List { Square(0, 0, 2, 2), Square(0, 0, 3, 1) };
+ for (var i = 0; i < 40; i++)
+ shapes.Add(Ring());
+
+ for (var trial = 0; trial < 400; trial++)
+ {
+ var a = shapes[random.Next(shapes.Count)];
+ var b = shapes[random.Next(shapes.Count)];
+ var offsetA = new Vector(random.NextDouble() * 10, random.NextDouble() * 10);
+ var offsetB = offsetA + new Vector(random.NextDouble() * 8 - 4, random.NextDouble() * 8 - 4);
+ var expected = Clearance.BoundaryDistance(Moved(a, offsetA), Moved(b, offsetB));
+
+ var atOffsets = Clearance.BoundaryDistance(a.Vertices, offsetA, b.Vertices, offsetB, double.MaxValue);
+ Assert.Equal(expected.Distance, atOffsets.Distance);
+ Assert.Equal(expected.Direction.X, atOffsets.Direction.X);
+ Assert.Equal(expected.Direction.Y, atOffsets.Direction.Y);
+
+ var reach = random.NextDouble() * 3;
+ foreach (var bounded in new[]
+ {
+ Clearance.BoundaryDistance(a.Vertices, offsetA, b.Vertices, offsetB, reach),
+ Clearance.BoundaryDistance(Moved(a, offsetA), Moved(b, offsetB), reach),
+ })
+ {
+ if (expected.Distance < reach)
+ {
+ Assert.Equal(expected.Distance, bounded.Distance);
+ Assert.Equal(expected.Direction.X, bounded.Direction.X);
+ Assert.Equal(expected.Direction.Y, bounded.Direction.Y);
+ }
+ else
+ Assert.Equal(reach, bounded.Distance);
+ }
+ }
+ }
}
+
diff --git a/docs/geometry/expand-spacing.md b/docs/geometry/expand-spacing.md
index 459d96ec..4b5bdfb0 100644
--- a/docs/geometry/expand-spacing.md
+++ b/docs/geometry/expand-spacing.md
@@ -1,17 +1,23 @@
# Expand Spacing
-`Plate > Expand Spacing` moves selected parts by translation only. The first selected part is the anchor for selected pairs; the later selected member moves, and nonselected parts remain fixed. The plate retains its own `EdgeSpacing` floor; the command does not change `PartSpacing` or `EdgeSpacing`. To push apart only the parts the overlap check flags, use [Fix Spacing](fix-spacing.md).
+`Plate > Expand Spacing` moves selected parts by translation only. Any selected part may move: a pair of selected parts shares each push (the later part takes half, the earlier part the rest, and the later part whatever its partner has no room for), so the selection opens about its middle and a part on the edge leaves the push to its partner. A selected part pushes away from a nonselected part alone, and nonselected parts remain fixed. The search probes ever wider spacings (doubling, then bisecting between the last spacing that converged and the first that failed) and applies the widest one that converged. The plate retains its own `EdgeSpacing` floor; the command does not change `PartSpacing` or `EdgeSpacing`. To push apart only the parts the overlap check flags, use [Fix Spacing](fix-spacing.md).
## Repeating patterns
A selection that repeats on a lattice, such as a fill, is stretched as one pattern instead of going through the pair search below. Parts of one drawing at one rotation form a motif group, and every group must sit on the same two lattice translations (one for a single row) to within 2% of a pitch. Each group needs at least two parts, and one group needs at least three for a row or four for a grid, because any two or three points fit some lattice. A single-drawing selection that fits no one lattice also counts when it forms rows along X (or Y): at least two rows of at least two parts, one of at least three, whose steps along the row are whole multiples of one shared pitch. Such rows may stack at any spacing and offset, as when staggered rows are topped by straight ones, and each part then stretches on its own. Cut-offs, overlapping selections and selections that start outside the work area always use the pair search.
-The lattice is scaled along X, then along Y, about its center, and each part moves by the displacement of its motif copy's lattice point, so interlocked pairs and other multi-part motifs stay rigid. Along each axis the largest scale is used whose stretched selection fits the work area and keeps every floor: no selected gap closes below the smallest selected gap at entry, a gap to a nonselected part closes no further than that, and cut-offs and clamps keep their entry gaps. A part may not pass through a nonselected part, cut-off or clamp on its straight way from the entry layout. The stretched selection is tried centered on where it was, then held at its low edge, then at its high edge. An axis with no room keeps its pitch, so a fill whose rows run edge to edge along X only opens its rows along Y: the row gap stays and the diagonal gap grows. The status bar reads "Spread the repeating pattern" with the smallest gap, or says the pattern has no room to spread.
+The lattice is scaled along X, then along Y, about its center, and each part moves by the displacement of its motif copy's lattice point, so interlocked pairs and other multi-part motifs stay rigid. Along each axis the largest scale is used whose stretched selection fits the work area and keeps every floor: no selected gap closes below the smallest selected gap at entry, a gap to a nonselected part closes no further than that, cut-offs keep their entry gaps and no part enters a clamp keep-out. A part may not pass through a nonselected part, cut-off or clamp on its straight way from the entry layout. The stretched selection is tried centered on where it was, then held at its low edge, then at its high edge. An axis with no room keeps its pitch, so a fill whose rows run edge to edge along X only opens its rows along Y: the row gap stays and the diagonal gap grows. The status bar reads "Spread the repeating pattern" with the smallest gap, or says the pattern has no room to spread.
-Every selected/selected and selected/nonselected pair has a clearance floor, measured against material with cutouts subtracted. A pair of parts may close to the spacing being tried but never below its own starting gap when that gap is already smaller, so a wide gap can be spent evenly across a layout and a tight one cannot shrink. A cut-off or clamp always keeps its full starting gap. A later move may reuse slack opened by an earlier move. Existing overlaps are accepted for attempted separation; a remaining overlap is reported as a violation, not a successful positive gap. Geometry whose material side is unresolved at sub-scale is conservatively reported as a violation when native extents intersect; that negative marker is not a measured penetration depth. An unchanged selected part already outside the work area also yields an edge violation and zero credited spacing. Temporarily blocked pairs are retried after another part moves, while a pass without positive movement stops the relaxation. An individual violation's `BlockedByEdge` flag is true only when the work-area edge is the first limiting cause; the desktop status currently displays a blocked-pair count, not those individual causes.
+Every selected/selected and selected/nonselected pair has a clearance floor, measured against material with cutouts subtracted. A pair of parts may close to the spacing being tried but never below its own starting gap when that gap is already smaller, so a wide gap can be spent evenly across a layout and a tight one cannot shrink. A cut-off always keeps its full starting gap. A clamp is a hard edge, like the work-area edge: its keep-out (the zone grown by the clamp clearance) may be approached until a part touches it but never entered, and the gap to it neither has to reach the spacing being tried nor counts toward the reported spacing. A later move may reuse slack opened by an earlier move. Existing overlaps are accepted for attempted separation; a remaining overlap is reported as a violation, not a successful positive gap. Geometry whose material side is unresolved at sub-scale is conservatively reported as a violation when native extents intersect; that negative marker is not a measured penetration depth. An unchanged selected part already outside the work area also yields an edge violation and zero credited spacing. Temporarily blocked pairs are retried after another part moves, while a pass without positive movement stops the relaxation. An individual violation's `BlockedByEdge` flag is true only when the work-area edge is the first limiting cause; the desktop status currently displays a blocked-pair count, not those individual causes.
+
+A part flush on a work-area edge still slides along that edge and away from it; only a move that would carry it past the edge is clipped. Each side of the work area is given the same 1e-9 allowance the inside-the-work-area check accepts, because a push between two parts can lean into the edge by a rounding-sized amount (parts turned a quarter or half carry rounding in their vertices), and zero room over that tiny component would otherwise pin every move.
Probes run on scratch poses. Each trial translation is clipped against blocking material along its entire straight path, including cutout walls and regenerated open cut-off paths; a remote cut-off does not pin an unrelated move. Entry floors for open cut-offs use nearest points on every native segment, not a program endpoint or a fictional closing chord. Open paths that strictly enter part material stay as violations even at zero target; boundary contact and paths wholly inside holes remain legal. An open path's broad box is not a blocker when its real segments miss the part. Initially overlapping convex line profiles and complete native disks can take a certified direct separating path, including a safe partial move when the plate edge prevents a full exit; unsupported or ambiguous overlap paths stay put and remain reported. Complete native disks use analytic clearance rather than interpreting a shallow arc overlap as a positive polygon gap. For other curved pairs, a polygon gap inside the combined 0.002-unit chord band is uncertain and conservatively reported as a violation rather than proof of clear material. When a part touches a cutout wall and the usual nearest-boundary direction makes no safe progress, the tool tries the opposite direction through the same checks. Tiny clamp keep-outs use tolerance-free material occupancy and a conservative native-bound motion limit when tolerant geometry cannot certify them. Cancellation before application leaves the live layout unchanged; `Separate` never changes it. A bounded search reports the spacing it found, not an optimum. See [directional slides](directional-slides.md) for directional contact behavior.
## Canceling a long search
On a complex layout the search can run for minutes. The desktop command runs it on a worker thread; if it is still running after about 0.3 seconds, a small Expand Spacing window opens with an elapsed time and a Cancel button, and the rest of the application waits behind it. Cancel, Escape and the window's close box all request cancellation. The window then shows "Canceling..." and stays open until the search stops at its next pair check, which took under 0.3 seconds on the real jobs measured. A canceled search moves no part, and the status bar reads "Expand Spacing canceled - no parts were moved". A search that finishes before the cancellation takes effect applies its result normally. While Auto Nest or a fill is still running on the nest, the command refuses with "Finish or cancel the current nesting or fill before Expand Spacing." because those operations can still add parts to the plate the search reads. The command does not save automatically.
+
+## Search cost
+
+The pair table is built once per run: every selected part with every other part and clamp, each with its starting gap as its floor, and with each part's own pairs listed so a trial move rechecks only the moved part's pairs. A measured clearance is remembered at the exact two positions it was measured at, so a pair is never measured again until one of its parts moves, including across the probes that each restart from the entry layout. Pairs whose bounding boxes are farther apart than the spacing being checked are skipped without measuring, and a clamp is skipped when the part's box clears its keep-out. A trial move only compares gaps with thresholds, so its gaps are measured just past the threshold and far outline segments are never visited; the overlap kernel's clipping runs only for outlines that touch, cross or nest. None of this changes a result: a skipped measurement is one whose answer is already known, and a measurement stopped short still answers its comparison exactly.