From d4103a3b9f3d0f251fc0da867c86cf7ece769638 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Tue, 17 Nov 2026 03:08:10 -0500 Subject: [PATCH] feat(fill): shift a tiling to fit parts of the copy before it A multi-part pattern tiles from the work area's leading edge, so the copy before the first one never fits whole. When the tiling leaves room at its far end, FillLinear now moves it forward by the smallest shift that fits the most parts of that previous copy and adds them. On an arch/cup herringbone this fits the cup row under the first arch row: 121 -> 132. Comparisons against the frozen fillers turn the new step off through an internal LeadingParts flag and check the default fill separately. Co-Authored-By: Claude Opus 5.5 --- OpenNest.Engine/Fill/FillLinear.cs | 107 +++++++++++++- .../Fill/FillLinearGeometryReuseTests.cs | 14 +- .../Fill/FillLinearLeadingPartsTests.cs | 131 ++++++++++++++++++ .../FillLinearValidationPerformanceTests.cs | 4 +- .../Fill/FillLinearValidationReuseTests.cs | 33 +++-- OpenNest.Tests/Strategies/FillHelpersTests.cs | 20 +-- docs/performance/fill-verification.md | 2 +- 7 files changed, 275 insertions(+), 36 deletions(-) create mode 100644 OpenNest.Tests/Fill/FillLinearLeadingPartsTests.cs diff --git a/OpenNest.Engine/Fill/FillLinear.cs b/OpenNest.Engine/Fill/FillLinear.cs index 761a0413..7d169e44 100644 --- a/OpenNest.Engine/Fill/FillLinear.cs +++ b/OpenNest.Engine/Fill/FillLinear.cs @@ -60,6 +60,13 @@ namespace OpenNest.Engine.Fill /// public int MaxParts { get; init; } + /// + /// When true (the default), a multi-part tiling may move off the work area's leading + /// edge to add parts of the copy before it (see ). Only + /// characterization against fillers frozen before that change turns it off. + /// + internal bool LeadingParts { get; init; } = true; + private static Vector MakeOffset(NestDirection direction, double distance) { return direction == NestDirection.Horizontal @@ -227,6 +234,83 @@ namespace OpenNest.Engine.Fill public double CopyDistance(Pattern pattern, NestDirection direction) => FindPatternCopyDistance(pattern, direction, new OffsetPerimeterCache(HalfSpacing)); + /// + /// Tiles a pattern along the given axis, returning the whole tiling: the pattern's own + /// parts first, then the copies. For multi-part patterns, also adds the parts of the + /// copies just before and after the whole ones that fit within the work area (see + /// ). The pattern's own parts are returned as given unless + /// leading parts moved the tiling. + /// + private List Tile( + Pattern basePattern, + NestDirection direction, + OffsetPerimeterCache cache, + int maxParts = 0 + ) + { + var tiling = new List(basePattern.Parts); + tiling.AddRange(TilePattern(basePattern, direction, cache, maxParts, out var copyDistance)); + if (LeadingParts && basePattern.Parts.Count > 1 && !(maxParts > 0 && tiling.Count >= maxParts) + && copyDistance > Tolerance.Epsilon && !double.IsPositiveInfinity(copyDistance)) + tiling = AddLeadingParts(basePattern, tiling, direction, copyDistance); + return tiling; + } + + /// + /// Adds the parts of the copies before the pattern that fit once the whole tiling moves + /// forward into the room left past its far end. A tiling always starts with the + /// pattern's leading edge on the work area's, so the copy before it never fits, though + /// some of its parts may: when an interlocked pair of reversed parts can only be tiled + /// with one row first, its partner row below it fits with that row raised slightly. The + /// tiling moves the least distance that adds the most parts; with none added it stays. + /// + private List AddLeadingParts( + Pattern basePattern, + List tiling, + NestDirection direction, + double copyDistance + ) + { + var start = GetStart(WorkArea, direction); + var end = double.MinValue; + foreach (var part in tiling) + end = System.Math.Max(end, GetStart(part.BoundingBox, direction) + + GetDimension(part.BoundingBox, direction)); + var room = GetLimit(direction) - end; + if (room < -Tolerance.Epsilon) + return tiling; + + var leading = new List<(Part Part, double Back, double Shift)>(); + foreach (var part in basePattern.Parts) + { + var ahead = GetStart(part.BoundingBox, direction) - start; + for (var copies = 1; ; copies++) + { + var back = copies * copyDistance; + var shift = back - ahead; + if (shift > room + Tolerance.Epsilon) + break; + leading.Add((part, back, shift)); + } + } + + if (leading.Count == 0) + return tiling; + + var move = 0.0; + foreach (var candidate in leading) + move = System.Math.Max(move, candidate.Shift); + move = System.Math.Min(move, System.Math.Max(room, 0)); + + var moved = new List(tiling.Count + leading.Count); + var offset = MakeOffset(direction, move); + foreach (var part in tiling) + moved.Add(move > 0 ? part.CloneAtOffset(offset) : part); + foreach (var (part, back, _) in leading) + moved.Add(part.CloneAtOffset(MakeOffset(direction, move - back))); + return moved; + } + /// /// Tiles a pattern along the given axis, returning the cloned parts /// (does not include the original pattern's parts). For multi-part @@ -237,10 +321,11 @@ namespace OpenNest.Engine.Fill Pattern basePattern, NestDirection direction, OffsetPerimeterCache cache, - int maxParts = 0 + int maxParts, + out double copyDistance ) { - var copyDistance = FindPatternCopyDistance(basePattern, direction, cache, + copyDistance = FindPatternCopyDistance(basePattern, direction, cache, UsefulCopyDistance(basePattern, direction, maxParts)); if (copyDistance <= 0 || double.IsPositiveInfinity(copyDistance)) @@ -314,10 +399,20 @@ namespace OpenNest.Engine.Fill var useful = GetLimit(direction) - GetStart(box, direction) - GetDimension(box, direction); var partial = basePattern.Parts.Count > 1 && !(maxParts > 0 && basePattern.Parts.Count >= maxParts); if (partial) + { + // A part of the copy before the pattern fits once the tiling moves forward + // into the room past the pattern, which only shrinks as copies are added. + var room = GetLimit(direction) - GetStart(box, direction) - GetDimension(box, direction); foreach (var part in basePattern.Parts) + { useful = System.Math.Max(useful, direction == NestDirection.Horizontal ? WorkArea.Right - part.BoundingBox.Right : WorkArea.Top - part.BoundingBox.Top); + if (LeadingParts) + useful = System.Math.Max(useful, + room + GetStart(part.BoundingBox, direction) - GetStart(WorkArea, direction)); + } + } return useful + 2 * Tolerance.Epsilon; } @@ -434,8 +529,7 @@ namespace OpenNest.Engine.Fill var rowIsVerified = false; // Step 1: Tile along primary axis - var row = new List(pattern.Parts); - row.AddRange(TilePattern(pattern, direction, cache)); + var row = Tile(pattern, direction, cache); if (pattern.Parts.Count > 1 && HasOverlappingParts(row, out var a1, out var b1)) { @@ -451,7 +545,7 @@ namespace OpenNest.Engine.Fill // If primary tiling didn't produce copies, just tile along perpendicular if (row.Count <= pattern.Parts.Count) { - row.AddRange(TilePattern(pattern, perpAxis, cache, MaxParts)); + row = Tile(pattern, perpAxis, cache, MaxParts); if (pattern.Parts.Count > 1 && HasOverlappingParts(row, out var a2, out var b2)) { @@ -474,8 +568,7 @@ namespace OpenNest.Engine.Fill rowPattern.Parts.AddRange(row); rowPattern.UpdateBounds(); - var gridResult = new List(rowPattern.Parts); - gridResult.AddRange(TilePattern(rowPattern, perpAxis, cache, MaxParts)); + var gridResult = Tile(rowPattern, perpAxis, cache, MaxParts); // Only the unchanged row is covered by Step 1's clean verdict: skip Step 2 // only when the perpendicular tiling appended zero parts, so gridResult diff --git a/OpenNest.Tests/Fill/FillLinearGeometryReuseTests.cs b/OpenNest.Tests/Fill/FillLinearGeometryReuseTests.cs index c5b266a3..46b15d9d 100644 --- a/OpenNest.Tests/Fill/FillLinearGeometryReuseTests.cs +++ b/OpenNest.Tests/Fill/FillLinearGeometryReuseTests.cs @@ -34,7 +34,7 @@ public class FillLinearGeometryReuseTests var drawing = Fixture(shape); var before = ProgramValues(drawing.Program); var area = new Box(3.1, -5.3, 42, 29); - var filler = new FillLinear(area, spacing); + var filler = new FillLinear(area, spacing) { LeadingParts = false }; var legacy = new LegacyFillLinear(area, spacing); var inputs = new[] { drawing.Program }; var expected = legacy.Fill(drawing, angle, direction); @@ -59,7 +59,7 @@ public class FillLinearGeometryReuseTests { var pattern = MakePattern(kind); var before = Snapshot(pattern); - var filler = new FillLinear(new Box(-7.1, 11.3, 52, 39), spacing); + var filler = new FillLinear(new Box(-7.1, 11.3, 52, 39), spacing) { LeadingParts = false }; var legacy = new LegacyFillLinear(filler.WorkArea, spacing); var inputs = pattern.Parts.Select(p => p.Program).ToArray(); var expected = legacy.Fill(pattern, direction); @@ -99,7 +99,7 @@ public class FillLinearGeometryReuseTests var area = new Box(3.1, 5.3, direction == NestDirection.Horizontal ? size : 10, direction == NestDirection.Vertical ? size : 8); var legacy = new LegacyFillLinear(area, spacing); - var filler = new FillLinear(area, spacing); + var filler = new FillLinear(area, spacing) { LeadingParts = false }; var expected = legacy.FillRow(drawing, 0, direction).Parts; counts.Add(expected.Count); AssertLayout(expected, filler.FillRow(drawing, 0, direction).Parts, new[] { drawing.Program }); @@ -126,14 +126,14 @@ public class FillLinearGeometryReuseTests fallback.AddRange((List)FillExtentsTests.Invoke(legacy, "TilePatternBbox", pattern, NestDirection.Horizontal)); var inputs = pattern.Parts.Select(p => p.Program).ToArray(); AssertLayout(fallback, legacy.Fill(pattern, NestDirection.Horizontal), inputs); - AssertLayout(fallback, new FillLinear(area, 0.5).Fill(pattern, NestDirection.Horizontal), inputs); + AssertLayout(fallback, new FillLinear(area, 0.5) { LeadingParts = false }.Fill(pattern, NestDirection.Horizontal), inputs); } [Fact] public void EmptyAndNoFit_MatchFrozenLegacy() { var area = new Box(3, 5, 1, 1); - var filler = new FillLinear(area, 0.5); + var filler = new FillLinear(area, 0.5) { LeadingParts = false }; var legacy = new LegacyFillLinear(area, 0.5); var drawing = Fixture("rectangle"); var pattern = MakePattern("rotated"); @@ -152,7 +152,7 @@ public class FillLinearGeometryReuseTests { var patterns = new[] { MakePattern("shared"), MakePattern("rotated"), MakePattern("built-pair") }; var before = patterns.Select(Snapshot).ToArray(); - var filler = new FillLinear(new Box(3.1, 5.3, 52, 39), 0.5); + var filler = new FillLinear(new Box(3.1, 5.3, 52, 39), 0.5) { LeadingParts = false }; var expected = patterns.Select(p => new[] { filler.Fill(p, NestDirection.Horizontal), filler.Fill(p, NestDirection.Vertical) }).ToArray(); Parallel.For(0, 48, new ParallelOptions { MaxDegreeOfParallelism = 4 }, i => @@ -245,7 +245,7 @@ public class FillLinearGeometryReuseTests var area = mode is "row" or "drawing" ? new Box(3, 5, 31.5, 17) : new Box(3, 5, 42.5, 25); var pattern = MakePattern(mode == "shared" ? "shared" : "rotated", drawing); var legacy = new LegacyFillLinear(area, 0.5); - var filler = new FillLinear(area, 0.5); + var filler = new FillLinear(area, 0.5) { LeadingParts = false }; PerfCounters.Reset(); try { diff --git a/OpenNest.Tests/Fill/FillLinearLeadingPartsTests.cs b/OpenNest.Tests/Fill/FillLinearLeadingPartsTests.cs new file mode 100644 index 00000000..8ef035a6 --- /dev/null +++ b/OpenNest.Tests/Fill/FillLinearLeadingPartsTests.cs @@ -0,0 +1,131 @@ +using System.Collections.Generic; +using System.Linq; +using OpenNest.CNC; +using OpenNest.Engine; +using OpenNest.Engine.Fill; +using OpenNest.Geometry; +using OpenNest.Math; + +namespace OpenNest.Tests.Fill; + +/// +/// A tiling starts with its pattern on the work area's leading edge, so the copy before it +/// never fits whole; once the tiling moves into the room left past its far end, some of +/// that copy's parts can. +/// +public class FillLinearLeadingPartsTests +{ + private static Drawing Rectangle(double length, double width) + { + var pgm = new Program(); + pgm.Codes.Add(new RapidMove(new Vector(0, 0))); + pgm.Codes.Add(new LinearMove(new Vector(length, 0))); + pgm.Codes.Add(new LinearMove(new Vector(length, width))); + pgm.Codes.Add(new LinearMove(new Vector(0, width))); + pgm.Codes.Add(new LinearMove(new Vector(0, 0))); + return new Drawing("rect", pgm); + } + + /// + /// A 10 x 8.5 arch: a band between a 5 radius and a 4.28 radius arc, its legs ending in + /// 0.125 radius rounds. Turned 180 degrees it is a cup, and a cup row drops 2.1 below + /// an arch row, each arch's legs inside two cups. + /// + private static Drawing Arch() + { + var pgm = new Program(); + pgm.Codes.Add(new RapidMove(new Vector(0, 0))); + pgm.Codes.Add(new ArcMove(new Vector(-0.1894982776, 0.1624029578), + new Vector(-0.0899707487, 0.0867770959), RotationType.CW)); + pgm.Codes.Add(new ArcMove(new Vector(-7.0081616203, 0.1624029578), + new Vector(-3.5988299489, 2.7529791426), RotationType.CCW)); + pgm.Codes.Add(new ArcMove(new Vector(-7.1976598979, 0), + new Vector(-7.1076891492, 0.0867770959), RotationType.CW)); + pgm.Codes.Add(new ArcMove(new Vector(0, 0), + new Vector(-3.5988299489, 3.4710838363), RotationType.CW)); + return new Drawing("arch", pgm); + } + + private static Pattern PatternOf(params Part[] parts) + { + var pattern = new Pattern(); + foreach (var part in parts) + { + part.UpdateBounds(); + pattern.Parts.Add(part); + } + pattern.UpdateBounds(); + return pattern; + } + + private static void AssertInside(Box area, List parts) + { + foreach (var part in parts) + { + var box = part.BoundingBox; + Assert.True(box.Left >= area.Left - Tolerance.Epsilon && box.Right <= area.Right + Tolerance.Epsilon + && box.Bottom >= area.Bottom - Tolerance.Epsilon && box.Top <= area.Top + Tolerance.Epsilon, + $"part at ({box.Left:F4},{box.Bottom:F4})-({box.Right:F4},{box.Top:F4}) is outside the area"); + } + } + + [Fact] + public void Tiling_MovesForwardToFitAPartOfTheCopyBeforeIt() + { + // Two 4 x 4 squares side by side, the right one 3 higher: copies stack 4.5 apart. + // In 20, three whole copies and the next copy's left square fit, leaving 2.5 at + // the top; raising the tiling 1.5 fits the previous copy's right square below. + var square = Rectangle(4, 4); + var pattern = PatternOf(new Part(square, new Vector(0, 0)), new Part(square, new Vector(5, 3))); + var area = new Box(0, 0, 9, 20); + + var parts = new FillLinear(area, 0.5).Fill(pattern, NestDirection.Vertical); + + Assert.Equal(8, parts.Count); + AssertInside(area, parts); + Assert.Equal(new[] { 1.5, 6, 10.5, 15 }, Bottoms(parts, left: true)); + Assert.Equal(new[] { 0, 4.5, 9, 13.5 }, Bottoms(parts, left: false)); + } + + [Fact] + public void Tiling_WithoutRoomForThePreviousCopy_StaysOnTheLeadingEdge() + { + // The same squares in 18.5: no room past the far end, so nothing moves. + var square = Rectangle(4, 4); + var pattern = PatternOf(new Part(square, new Vector(0, 0)), new Part(square, new Vector(5, 3))); + var area = new Box(0, 0, 9, 17.5); + + var parts = new FillLinear(area, 0.5).Fill(pattern, NestDirection.Vertical); + + Assert.Equal(7, parts.Count); + Assert.Equal(new[] { 0, 4.5, 9, 13.5 }, Bottoms(parts, left: true)); + Assert.Equal(new[] { 3, 7.5, 12 }, Bottoms(parts, left: false)); + } + + [Fact] + public void ArchesAndCups_FitTheCupRowBelowTheFirstArchRow() + { + // A cup resting on a row of arches tiles 10.3 along the row and 9.53 across it, but + // the pair starts with an arch row: in 58.375 it holds five pairs and a last arch + // row (121). The cup row of the pair before fits under it with the tiling raised + // 2.1, making twelve rows. + var arch = Arch(); + var cup = new Part(arch); + cup.Rotate(System.Math.PI); + cup.Location = new Vector(-2.047654897931384, 15.862226444770164); + var pattern = PatternOf(new Part(arch, new Vector(0, 0)), cup); + var area = new Box(0.3, 1.375, 119.4, 58.375); + + var parts = new FillLinear(area, 0.3).Fill(pattern, NestDirection.Horizontal); + + Assert.Equal(132, parts.Count); + AssertInside(area, parts); + Assert.Empty(PartOverlapChecker.FindOverlappingPairs(parts)); + } + + private static double[] Bottoms(List parts, bool left) => + parts.Where(p => p.BoundingBox.Left < 1 == left) + .Select(p => System.Math.Round(p.BoundingBox.Bottom, 6)) + .OrderBy(y => y) + .ToArray(); +} diff --git a/OpenNest.Tests/Fill/FillLinearValidationPerformanceTests.cs b/OpenNest.Tests/Fill/FillLinearValidationPerformanceTests.cs index 503d4235..16367b73 100644 --- a/OpenNest.Tests/Fill/FillLinearValidationPerformanceTests.cs +++ b/OpenNest.Tests/Fill/FillLinearValidationPerformanceTests.cs @@ -46,7 +46,7 @@ public class FillLinearValidationPerformanceTests var single = FillHelpers.BuildRotatedPattern(new List { first }, 0.37); var patterns = new[] { pair, pair, pair, pair, single }; var names = new[] { "horizontal-stripe", "vertical-stripe", "full-grid", "partial-only", "single-seed-stripe" }; - var counts = new[] { 8, 19, 36, 29, 8 }; + var counts = new[] { 8, 20, 36, 30, 8 }; var directions = new[] { NestDirection.Horizontal, NestDirection.Vertical, NestDirection.Horizontal, NestDirection.Vertical, NestDirection.Horizontal }; var areas = new[] @@ -83,7 +83,7 @@ public class FillLinearValidationPerformanceTests + "pair at 0/PI, second offset=(10.5,0), BuildRotatedPattern=0.37; spacing=0.5; origin=(0,0). " + "Stripe primary span=96, perpendicular span=exact pattern bbox; full-grid=(96,48); " + "vertical partial-only perpendicular span=1.8*pair.Length; single rotated seed H stripe. " - + "Counts in mode order=8,19,36,29,8; full-grid row=8+28; partial-only row=19+10."); + + "Counts in mode order=8,20,36,30,8; full-grid row=8+28; partial-only row=20+10."); output.WriteLine($"warmup=2 x {warmupCalls} calls/mode; measured={repetitions} x {callsPerBatch} calls/mode. " + "Mode order alternates forward/reverse in warmup and measurement. Real synchronous production Fill only; " + "setup, correctness assertions and output excluded. Geometry, tiling, overlap checks, GC, delegate/loop, " diff --git a/OpenNest.Tests/Fill/FillLinearValidationReuseTests.cs b/OpenNest.Tests/Fill/FillLinearValidationReuseTests.cs index 25d676d1..feabdc57 100644 --- a/OpenNest.Tests/Fill/FillLinearValidationReuseTests.cs +++ b/OpenNest.Tests/Fill/FillLinearValidationReuseTests.cs @@ -39,11 +39,12 @@ public class FillLinearValidationReuseTests var area = new Box(3.1, -5.3, 42, 29); var areaBefore = BoxBits(area); var expected = new PreStep3FillLinear(area, spacing).Fill(drawing, angle, direction); - var filler = new FillLinear(area, spacing); + var filler = new FillLinear(area, spacing) { LeadingParts = false }; AssertLayout(expected, filler.Fill(drawing, angle, direction), new[] { drawing.Program }); Assert.Equal(before, DrawingSnapshot(drawing)); AssertLayout(expected, filler.Fill(drawing, angle, direction), new[] { drawing.Program }); AssertValid(expected, area); + AssertDefaultAddsOnlyValidParts(expected, new FillLinear(area, spacing).Fill(drawing, angle, direction), area); Assert.Equal(before, DrawingSnapshot(drawing)); Assert.Equal(areaBefore, BoxBits(area)); Assert.Equal(areaBefore, BoxBits(filler.WorkArea)); @@ -153,7 +154,7 @@ public class FillLinearValidationReuseTests { var area = Area(size); var frozen = new PreStep3FillLinear(area, 0.5); - var filler = new FillLinear(area, 0.5); + var filler = new FillLinear(area, 0.5) { LeadingParts = false }; var expectedPattern = frozen.Fill(pattern, direction); var expectedDrawing = frozen.Fill(drawing, 0, direction); Assert.Equal(size == rejected ? 2 : 3, expectedPattern.Count); @@ -185,7 +186,7 @@ public class FillLinearValidationReuseTests PerfCounters.Reset(); try { - parts = new FillLinear(area, 0.5).Fill(pattern, direction); + parts = new FillLinear(area, 0.5) { LeadingParts = false }.Fill(pattern, direction); observedExact = PerfCounters.PartIntersects; observedPreparations = PerfCounters.OverlapPolygonPreparations; observedTriangulations = PerfCounters.PolygonTriangulations; @@ -226,7 +227,7 @@ public class FillLinearValidationReuseTests PerfCounters.Reset(); try { - parts = new FillLinear(area, 0.5).Fill(pattern, direction); + parts = new FillLinear(area, 0.5) { LeadingParts = false }.Fill(pattern, direction); observedExact = PerfCounters.PartIntersects; observedPreparations = PerfCounters.OverlapPolygonPreparations; observedTriangulations = PerfCounters.PolygonTriangulations; @@ -257,7 +258,7 @@ public class FillLinearValidationReuseTests PerfCounters.Reset(); try { - parts = new FillLinear(area, 0.5).Fill(pattern, direction); + parts = new FillLinear(area, 0.5) { LeadingParts = false }.Fill(pattern, direction); observed = PerfCounters.PartIntersects; Assert.Equal(exact, observed); Assert.NotEmpty(parts); @@ -284,7 +285,7 @@ public class FillLinearValidationReuseTests var before = PatternSnapshot(pattern); var area = new Box(0, 0, 35, 8.25); var frozen = new PreStep3FillLinear(area, 0.5) { Label = "invalid-frozen" }; - var filler = new FillLinear(area, 0.5) { Label = "invalid-production" }; + var filler = new FillLinear(area, 0.5) { LeadingParts = false, Label = "invalid-production" }; #if DEBUG using var listener = new FallbackListener(); Trace.Listeners.Add(listener); @@ -345,7 +346,7 @@ public class FillLinearValidationReuseTests public void EmptyNoFitAndMalformedInputs_PreserveResultsAndExceptionTypes(NestDirection direction) { var area = new Box(3, 5, 1, 1); - var filler = new FillLinear(area, 0.5); + var filler = new FillLinear(area, 0.5) { LeadingParts = false }; var frozen = new PreStep3FillLinear(area, 0.5); var drawing = MakeDrawing("rectangle"); var pattern = MakePattern("concave", "rotated"); @@ -386,7 +387,7 @@ public class FillLinearValidationReuseTests [Fact] public void ConcurrentIndependentCalls_OneFiller_MatchFrozenAndPreserveInputs() { - var filler = new FillLinear(new Box(3.1, -5.3, 52, 39), 0.5); + var filler = new FillLinear(new Box(3.1, -5.3, 52, 39), 0.5) { LeadingParts = false }; var frozen = new PreStep3FillLinear(filler.WorkArea, 0.5); var patterns = Enumerable.Range(0, 24).Select(i => MakePattern(i % 2 == 0 ? "concave" : "arc", i % 3 == 0 ? "shared" : i % 3 == 1 ? "rotated" : "single")).ToArray(); @@ -453,18 +454,32 @@ public class FillLinearValidationReuseTests Assert.False(FillHelpers.HasOverlappingParts(pattern.Parts)); var expected = new PreStep3FillLinear(area, spacing).Fill(pattern, direction); Assert.Equal(before, PatternSnapshot(pattern)); - var filler = new FillLinear(area, spacing); + var filler = new FillLinear(area, spacing) { LeadingParts = false }; var actual = filler.Fill(pattern, direction); AssertLayout(expected, actual, inputs); Assert.Equal(before, PatternSnapshot(pattern)); AssertLayout(expected, filler.Fill(pattern, direction), inputs); Assert.Equal(before, PatternSnapshot(pattern)); AssertValid(actual, area); + AssertDefaultAddsOnlyValidParts(expected, new FillLinear(area, spacing).Fill(pattern, direction), area); + Assert.Equal(before, PatternSnapshot(pattern)); Assert.Equal(areaBefore, BoxBits(area)); Assert.Equal(areaBefore, BoxBits(filler.WorkArea)); return actual; } + /// + /// The frozen fillers predate , so they are compared + /// with it off; with it on, a fill only adds parts of the copy before its pattern, never + /// holding fewer parts, and stays inside the area without overlaps. + /// + private static void AssertDefaultAddsOnlyValidParts(List frozen, List current, Box area) + { + Assert.True(current.Count >= frozen.Count, $"default fill holds {current.Count}, frozen {frozen.Count}"); + if (current.Count > 0) + AssertValid(current, area); + } + private static void AssertValid(List parts, Box area) { Assert.NotEmpty(parts); diff --git a/OpenNest.Tests/Strategies/FillHelpersTests.cs b/OpenNest.Tests/Strategies/FillHelpersTests.cs index 6cfb893d..78f58980 100644 --- a/OpenNest.Tests/Strategies/FillHelpersTests.cs +++ b/OpenNest.Tests/Strategies/FillHelpersTests.cs @@ -92,10 +92,10 @@ public class FillHelpersTests } [Theory] - [InlineData(5, 9, 8, 7)] - [InlineData(10, 4, 7, 8)] - [InlineData(5, 4, 3, 3)] - [InlineData(7, 6, 8, 8)] + [InlineData(5, 9, 10, 12)] + [InlineData(10, 4, 8, 8)] + [InlineData(5, 4, 4, 4)] + [InlineData(7, 6, 9, 8)] public void FillPattern_DefaultScoring_PreservesWinningLayoutAndInputs( double length, double width, int horizontalCount, int verticalCount) { @@ -308,12 +308,12 @@ public class FillHelpersTests } [Theory] - [InlineData(5, 9, 0, 2)] - [InlineData(5, 9, 1, 0)] - [InlineData(10, 4, 1, 0)] - [InlineData(5, 9, 2, 2)] + [InlineData(5, 9, 0, 2, 12)] + [InlineData(5, 9, 1, 0, 10)] + [InlineData(10, 4, 1, 0, 8)] + [InlineData(5, 9, 2, 2, 10)] public void FillPattern_ScoreWork_OnlyDefaultPathOrComparerComputesScores( - double length, double width, int comparerKind, long expectedComputations) + double length, double width, int comparerKind, long expectedComputations, int count) { var group = MakeGroup(); var workArea = new Box(3, 5, length, width); @@ -329,7 +329,7 @@ public class FillHelpersTests var result = FillHelpers.FillPattern(engine, group, angles, workArea, comparerKind == 0 ? null : comparer); - Assert.Equal(comparerKind == 0 ? 8 : 7, result.Count); + Assert.Equal(count, result.Count); Assert.Equal(comparerKind == 0 ? 0 : 1, comparer.Calls.Count); Assert.Equal(expectedComputations, PerfCounters.FillScoreComputations); } diff --git a/docs/performance/fill-verification.md b/docs/performance/fill-verification.md index a8c725b4..e2edb2d0 100644 --- a/docs/performance/fill-verification.md +++ b/docs/performance/fill-verification.md @@ -53,7 +53,7 @@ OPENNEST_RUN_FILL_PERF=1 dotnet test OpenNest.Tests/OpenNest.Tests.csproj -c Rel --logger 'console;verbosity=detailed' --logger 'trx;LogFileName=linear-validation-perf.trx' ``` -`FillLinearValidationPerformanceTests.cs` is self-contained against base APIs: byte-copy and hash the same file in both trees. It times complete production `Fill` calls (not frozen code or overlap-only helpers): horizontal/vertical stripes, full grid, partial-only additions, and single-seed stripe. The closed concave fixture gives counts **8 / 19 / 36 / 29 / 8**; grid is row 8 + 28 additions, partial-only is row 19 + 10 (no full row). Two 100-call warmups and seven 200-call batches per mode alternate forward/reverse mode order. Retain every raw tick/time/current-thread allocation row, including warmups; setup/assertions/output are excluded, count/last-result consumption is identical. No timing or reduced-work assertions belong in this baseline harness. +`FillLinearValidationPerformanceTests.cs` is self-contained against base APIs: byte-copy and hash the same file in both trees. It times complete production `Fill` calls (not frozen code or overlap-only helpers): horizontal/vertical stripes, full grid, partial-only additions, and single-seed stripe. The closed concave fixture gives counts **8 / 20 / 36 / 30 / 8**; grid is row 8 + 28 additions, partial-only is row 20 + 10 (no full row). Vertical-stripe and partial-only each gain a part of the copy before the pattern (`FillLinear.LeadingParts` moves a tiling into the room past its far end to fit them); the frozen-oracle comparisons and work-count assertions below turn it off and keep the earlier **8 / 19 / 36 / 29 / 8**, and every oracle fixture also checks that the default fill holds at least the frozen count, inside the area and without overlaps. Two 100-call warmups and seven 200-call batches per mode alternate forward/reverse mode order. Retain every raw tick/time/current-thread allocation row, including warmups; setup/assertions/output are excluded, count/last-result consumption is identical. No timing or reduced-work assertions belong in this baseline harness. `PreStep3FillLinear.cs` freezes production `FillLinear` at **1b23ad79f25d77fdd745bfea029de9dff2a91f6d**, separately from the older `LegacyFillLinear`. Reverse only the documented type/constructor rename, namespace/visibility/import additions, nullable directive and import formatting; retain a zero-diff comparison against `git show :OpenNest.Engine/Fill/FillLinear.cs` and SHA-256 hashes. Do not refactor the oracle or use it for before timings. `FillLinearValidationReuseTests` compares ordered IEEE-754 poses/bounds, CNC values/program sharing, drawing references and immutable inputs through both public `Fill` overloads, including concurrent calls on one filler. Valid fixtures assert closed positive-area material and no overlap. The separate invalid overlapping-seed case intentionally remains invalid; in Debug its listener confirms Step1 and Step2 fallback pair `(0,1)` with six parts at each step (zero perpendicular additions). It makes no claim that bbox fallback repairs the seeds.