diff --git a/OpenNest.Tests/BestFit/CrescentPairSpacingTests.cs b/OpenNest.Tests/BestFit/CrescentPairSpacingTests.cs new file mode 100644 index 00000000..3522363e --- /dev/null +++ b/OpenNest.Tests/BestFit/CrescentPairSpacingTests.cs @@ -0,0 +1,210 @@ +using OpenNest.CNC; +using OpenNest.Converters; +using OpenNest.Engine.BestFit; +using OpenNest.Geometry; +using OpenNest.Math; +using Xunit.Abstractions; + +namespace OpenNest.Tests.BestFit; + +/// +/// A crescent written the way a converted drawing is: coordinates rounded to 1e-6, the disc +/// split into two arcs away from a quadrant point, and the program origin outside the part, +/// so the program opens with a rapid across free space to the contour. That rapid is not +/// material. A spacing oracle that flattens every program entity measures from it and reports +/// pairs up to its length (0.2) too close, which is how this shape was once reported as a +/// slide defect. Measured on material alone, every pair the search builds keeps the spacing. +/// +public class CrescentPairSpacingTests +{ + private const double Spacing = 0.313; + private const double HalfSpacing = Spacing / 2; + private const double DiscRadius = 5.9687; + private const double BiteRadius = 3.3437; + private const double BiteDrop = 2.9245; + + // Disc center in program coordinates: the origin is 0.2 outside the disc. + private const double CenterX = 4.81058; + private const double CenterY = 3.861579; + + // Where the disc is split, as an angle from its center. + private const double SplitDegrees = 218.7549; + + private const double ChordTolerance = 0.0001; + + private readonly ITestOutputHelper _output; + + public CrescentPairSpacingTests(ITestOutputHelper output) + { + _output = output; + } + + private static Drawing Crescent() + { + var tipY = + (BiteRadius * BiteRadius - DiscRadius * DiscRadius - BiteDrop * BiteDrop) + / (2 * BiteDrop); + var tipX = System.Math.Sqrt(DiscRadius * DiscRadius - tipY * tipY); + var split = Angle.ToRadians(SplitDegrees); + + var start = Rounded( + CenterX + DiscRadius * System.Math.Cos(split), + CenterY + DiscRadius * System.Math.Sin(split) + ); + var rightTip = Rounded(CenterX + tipX, CenterY + tipY); + var leftTip = Rounded(CenterX - tipX, CenterY + tipY); + var center = new Vector(CenterX, CenterY); + var biteCenter = Rounded(CenterX, CenterY - BiteDrop); + + var program = new Program(); + program.MoveTo(start); + program.ArcTo(rightTip, center, RotationType.CW); + program.ArcTo(leftTip, biteCenter, RotationType.CCW); + program.ArcTo(start, center, RotationType.CW); + return new Drawing("crescent", program); + } + + private static Vector Rounded(double x, double y) => + new Vector(System.Math.Round(x, 6), System.Math.Round(y, 6)); + + /// + /// Two crescents hooked together, each with a horn in the other's bite. The first contact + /// is a horn's round spacing cap against the outside of the other disc: a small convex arc + /// against a large convex one, away from every vertex. + /// + [Fact] + public void HookedCrescents_StopWhereAHornCapMeetsTheOtherDisc() + { + var drawing = Crescent(); + var part1 = Part.CreateAtOrigin(drawing); + var template = Part.CreateAtOrigin(drawing, System.Math.PI); + var stationary = PartGeometry.GetOffsetPerimeterEntities(part1, HalfSpacing); + var moving = PartGeometry.GetOffsetPerimeterEntities(template, HalfSpacing); + var offset = new SlideOffset(-3, -24, 0, 1); + + var distance = new CpuDistanceComputer().ComputeDistances( + stationary, + moving, + new[] { offset } + )[0]; + + // External tangency of the stationary part's right-hand cap and the moving disc: + // their centers end one cap radius plus one disc radius apart. + var cap = stationary + .OfType() + .Where(a => System.Math.Abs(a.Radius - HalfSpacing) < 1e-9) + .OrderByDescending(a => a.Center.X) + .First(); + var disc = moving.OfType().OrderByDescending(a => a.Radius).First(); + var reach = cap.Radius + disc.Radius; + var across = cap.Center.X - (disc.Center.X + offset.Dx); + var expected = + cap.Center.Y + - System.Math.Sqrt(reach * reach - across * across) + - (disc.Center.Y + offset.Dy); + + _output.WriteLine($"slide {distance:R}, cap/disc tangency {expected:R}"); + Assert.Equal(expected, distance, 5); + + var part2 = Part.CreateAtOrigin(drawing, System.Math.PI); + part2.Location = new Vector( + template.Location.X + offset.Dx, + template.Location.Y + offset.Dy + distance + ); + + var gap = Gap(MaterialOutline(part1), MaterialOutline(part2)); + Assert.InRange(gap, Spacing - SpacingOutline.SpacingSlack, Spacing + 2 * ChordTolerance); + + // The same pair measured with the opening rapid counted as outline: the reading that + // was mistaken for a slide stopping inside the spacing. + var withRapid = Gap(EveryEntityOutline(part1), EveryEntityOutline(part2)); + _output.WriteLine($"material gap {gap:F5}, gap with the rapid counted {withRapid:F5}"); + Assert.True(withRapid < Spacing - 0.1, $"the rapid no longer sticks out: {withRapid:F5}"); + } + + [Theory] + [InlineData(0)] + [InlineData(54.5)] + [InlineData(109.38)] + [InlineData(180)] + [InlineData(234.5)] + public void EveryCandidateKeepsTheSpacing(double part2Degrees) + { + var drawing = Crescent(); + var candidates = new RotationSlideStrategy( + Angle.ToRadians(part2Degrees), + 1, + "crescent", + new CpuDistanceComputer() + ).GenerateCandidates(drawing, Spacing, stepSize: 0.25); + + Assert.NotEmpty(candidates); + + var outline1 = MaterialOutline(Part.CreateAtOrigin(drawing)); + var worst = double.MaxValue; + + foreach (var candidate in candidates) + { + var part2 = Part.CreateAtOrigin(drawing, candidate.Part2Rotation); + part2.Location = candidate.Part2Offset; + worst = System.Math.Min(worst, Gap(outline1, MaterialOutline(part2))); + } + + _output.WriteLine($"{candidates.Count} candidates, smallest gap {worst:F5}"); + Assert.True( + worst >= Spacing - SpacingOutline.SpacingSlack, + $"a pair is {worst:F5} apart, under the {Spacing} spacing" + ); + } + + /// The part's material outline as fine chords, independent of the slide solver. + private static List MaterialOutline(Part part) => + Flatten( + part, + ConvertProgram.ToGeometry(part.Program).Where(e => SpecialLayers.IsMaterial(e.Layer)) + ); + + private static List EveryEntityOutline(Part part) => + Flatten(part, ConvertProgram.ToGeometry(part.Program)); + + private static List Flatten(Part part, IEnumerable entities) + { + var shape = ShapeBuilder.GetShapes(entities.ToList())[0]; + var polygon = shape.ToPolygonWithTolerance(ChordTolerance); + polygon.Offset(part.Location); + return polygon.Vertices; + } + + private static double Gap(List a, List b) + { + var gap = double.MaxValue; + + foreach (var point in a) + for (var i = 0; i + 1 < b.Count; i++) + gap = System.Math.Min(gap, Distance(point, b[i], b[i + 1])); + + foreach (var point in b) + for (var i = 0; i + 1 < a.Count; i++) + gap = System.Math.Min(gap, Distance(point, a[i], a[i + 1])); + + return gap; + } + + private static double Distance(Vector point, Vector from, Vector to) + { + var dx = to.X - from.X; + var dy = to.Y - from.Y; + var lengthSquared = dx * dx + dy * dy; + var t = + lengthSquared < 1e-18 + ? 0 + : System.Math.Clamp( + ((point.X - from.X) * dx + (point.Y - from.Y) * dy) / lengthSquared, + 0, + 1 + ); + var x = from.X + t * dx - point.X; + var y = from.Y + t * dy - point.Y; + return System.Math.Sqrt(x * x + y * y); + } +} diff --git a/docs/geometry/directional-slides.md b/docs/geometry/directional-slides.md index c4155a38..7b11e71f 100644 --- a/docs/geometry/directional-slides.md +++ b/docs/geometry/directional-slides.md @@ -26,6 +26,8 @@ Open/incomplete chains and ambiguous contacts conservatively block. Loops are re `CompactorTests` covers the reported sequence (push left with spacing, then right/up/down), genuine zero-distance blocking, zero/nonzero-spacing later hooks, and inside-hole pushes through both direct and plate entry points. Physical spacing is measured from raw outlines rather than the inflated contours used by the solver. +`CrescentPairSpacingTests` covers an arc-only part with round spacing caps on two sharp tips: the first contact of a small convex cap against a large convex arc away from every vertex, and every pair the best-fit search builds at five part 2 rotations. Its spacing oracle flattens material entities only; counting a program's opening rapid as outline reports false violations (see [pair-spacing checks](pair-spacing.md)). + Verification commands: ```sh diff --git a/docs/geometry/pair-spacing.md b/docs/geometry/pair-spacing.md index fcfc821e..d5d98477 100644 --- a/docs/geometry/pair-spacing.md +++ b/docs/geometry/pair-spacing.md @@ -26,13 +26,14 @@ Measurements use raw material outlines tessellated at 1e-6 chord tolerance and i - Other angled candidates remain physically too close. Of 568 kept candidates in the corrected real-DXF probe, 49 had boundary distance below 0.25 minus 2e-6, including 48 below the existing 0.2495 spacing-slack threshold. The worst measured boundary gap was about 0.205618. Their cause is not established by this repair; CPU projection filtering and missing arc/line interior contact are separate suspects. - The offset-based layout check used to report 28 spacing violations in each corrected 70-part grid despite the independent fine-outline measurement above. The cause was its spacing outline, which circumscribes arcs by up to 0.001 each, more than the 0.0005 slack, so two arcs exactly at the spacing could overlap there. It now confirms each pair the outline flags on native contours flattened at a twentieth of the slack (`NativeContours`), as the pre-post review does, and both grids pass with no tolerance changed. +- A crescent (11.94 disc with a 6.69 round bite, two sharp horn tips) was reported as the same defect at 0.313 spacing: about 5% of kept candidates measuring under the spacing, the worst near 0.11. It is not a slide defect. That probe flattened every entity of the program, including the opening rapid from the program origin to the contour. On the converted part the origin is 0.2 outside the disc, so the rapid is a 0.2 spur on the "outline" and every pair resting near it reads up to 0.2 too close. Measured on material only (`SpecialLayers.IsMaterial`), all 4,700 candidates of that part (axis pushes plus the contact-loop positions then in progress) are at the spacing, the smallest 0.31290 at 0.0001 chords, as are 37,338 candidates of the exact-dimension crescent across 105 part 2 rotations. `CrescentPairSpacingTests` keeps the shape (1e-6 rounding, disc split off a quadrant point, origin outside), the hooked first contact of a horn's spacing cap against the other disc, and both readings of the gap. A spacing oracle must drop non-material entities before flattening. The 49-of-568 count above came from a different oracle and part and has not been re-measured. - Across the complete candidate probe, 42 tessellated polygons were invalid. Their boundary distances were recorded without silently repairing them, but intersection-area verdicts were omitted for those invalid polygons. This caveat does not apply to the top pair or the two reported grids. - Kept-pair acceptance still checks raw overlap, not requested clearance. Interactive fill/group paths can trust an invalid seed. This repair does not add a final spacing gate or repair existing user placements. - Serialized best-fit results have no algorithm-version invalidation. Loading previously saved candidates can retain old poses. The measurements above use newly imported drawings/fresh computation, not restored caches. Reimport/recompute when evaluating this fix; existing nests and DXFs are not rewritten. - A zero-demand `PlateFillService.Nest` probe returns no parts and is **not** evidence of a valid whole-job nest. The nonempty cases verified here are pair generation, pair fill, interactive fill, and the quantity-two shortcut. - GPU behavior and Windows desktop execution were not verified on this Linux host. -Next hardening should isolate the remaining angular contact defect with a first-contact regression, then address clearance-aware seed acceptance and cache compatibility as separate changes. Do not conflate those with the unrelated unchanged-row validation-reuse performance work. +Next hardening should re-measure the remaining angled candidates of the U-shaped part on material-only outlines and, if any are still too close, isolate the contact with a first-contact regression; then address clearance-aware seed acceptance and cache compatibility as separate changes. Do not conflate those with the unrelated unchanged-row validation-reuse performance work. ## Regression verification