diff --git a/OpenNest.Engine.Tests/Fill/PatternCopySpacingTests.cs b/OpenNest.Engine.Tests/Fill/PatternCopySpacingTests.cs new file mode 100644 index 00000000..1129a58b --- /dev/null +++ b/OpenNest.Engine.Tests/Fill/PatternCopySpacingTests.cs @@ -0,0 +1,146 @@ +using OpenNest.CNC; +using OpenNest.Engine.BestFit; +using OpenNest.Engine.Fill; +using OpenNest.Engine.Jobs; +using OpenNest.Engine.Jobs.Adapters; +using OpenNest.Engine.Jobs.Placement; +using OpenNest.Engine.Tests.Jobs; +using OpenNest.Geometry; +using OpenNest.Math; + +namespace OpenNest.Engine.Tests.Fill; + +/// +/// A reported nest: the README gusset (an 8" right triangle with clipped corners) at 0.3" +/// spacing on a 60 x 120 sheet. Fill tiled a pair whose second gusset sits beside the first, +/// 0.26" higher: in the next column over, each gusset passes 0.04" above the one beside it. +/// Their bounding boxes do not overlap across the slide, so the copy distance never measured +/// that pair and the columns interlocked closer than the spacing. +/// +public class PatternCopySpacingTests +{ + private const double PartSpacing = 0.3; + + private static Drawing Gusset() + { + var program = new Program(); + program.MoveTo(3.7, 2.6); + program.ArcTo(new Vector(3.7, 2.6), new Vector(2.6, 2.6), RotationType.CCW); + program.MoveTo(0, 0); + foreach (var (x, y) in new[] { (8.0, 0.0), (8.0, 1.0), (1.0, 8.0), (0.0, 8.0), (0.0, 0.0) }) + program.LineTo(x, y); + return new Drawing("Gusset", program); + } + + private static Part PlacedAt(Drawing drawing, double degrees, double left, double bottom) + { + var part = Part.CreateAtOrigin(drawing, Angle.ToRadians(degrees)); + part.Offset(new Vector(left, bottom) - part.BoundingBox.Location); + part.UpdateBounds(); + return part; + } + + private static List SpacingViolations(Drawing drawing, List parts, Size size) => + NestLayoutCheck.Validate( + new() { (new Plate(size) { PartSpacing = PartSpacing }, parts) }, + new Dictionary { [drawing] = ("Gusset", parts.Count) }); + + [Theory] + [InlineData(NestDirection.Vertical)] + [InlineData(NestDirection.Horizontal)] + public void TilingKeepsSpacingFromAPartBesideTheNextCopysPath(NestDirection direction) + { + var drawing = Gusset(); + var vertical = direction == NestDirection.Vertical; + var pattern = new Pattern(); + pattern.Parts.Add(PlacedAt(drawing, vertical ? 90 : 270, 0, 0)); + pattern.Parts.Add(vertical + ? PlacedAt(drawing, 270, 8.3001, 0.2594) + : PlacedAt(drawing, 90, 0.2594, 8.3001)); + pattern.UpdateBounds(); + + var parts = new FillLinear(new Box(0, 0, 60, 60), PartSpacing + 1e-4).Fill(pattern, direction); + + Assert.True(parts.Count > 4, $"Tiled {parts.Count} parts"); + Assert.Empty(SpacingViolations(drawing, parts, new Size(60, 60))); + } + + /// + /// A column pair of D-shapes nested arc against arc, their bounding boxes 0.01 apart: the + /// next column's flat top passed 0.01 under the upper part's flat bottom. + /// + [Fact] + public void TilingKeepsSpacingFromAPartJustAboveTheNextCopysPath() + { + var drawing = new Drawing("arc", TestDrawingFactory.ArcPart()); + var pattern = new Pattern(); + pattern.Parts.Add(PlacedAt(drawing, 0, 0, 0)); + pattern.Parts.Add(PlacedAt(drawing, 180, 2.7693, 5.01)); + pattern.UpdateBounds(); + var plate = new Plate(new Size(40, 40)) { PartSpacing = 0.5 }; + var requirements = new Dictionary { [drawing] = ("arc", 100) }; + Assert.Empty(NestLayoutCheck.Validate(new() { (plate, pattern.Parts) }, requirements)); + + var parts = new FillLinear(new Box(0, 0, 40, 40), 0.5).Fill(pattern, NestDirection.Horizontal); + + Assert.True(parts.Count > 4, $"Tiled {parts.Count} parts"); + Assert.Empty(NestLayoutCheck.Validate(new() { (plate, parts) }, requirements)); + } + + /// The band Auto Nest asks for: 24 gussets in the sheet's 119.4 x 59 work area. + [Fact] + public void QuantityFillOfGussetsInALongBoxKeepsThePartSpacing() + { + var jobPart = DrawingJobMapper.FromDrawing("p", Gusset(), 24); + var drawing = DrawingJobMapper.CreateDrawing(jobPart); + var geometry = JobPartGeometry.TryRead(jobPart.Geometry)!; + List parts; + try + { + parts = PrivatePlateFill.Run(drawing, jobPart.Rotation, PartSpacing + 1e-4, 119.4, 59, 24, + CancellationToken.None); + } + finally + { + BestFitCache.Invalidate(drawing); + } + + Assert.Equal(24, parts.Count); + var poses = parts + .Select(p => new NestJobPlacement("p", 0, p.Location.X, p.Location.Y, Angle.NormalizeRad(p.Rotation))) + .ToArray(); + var close = new List(); + for (var i = 0; i < poses.Length; i++) + { + for (var k = i + 1; k < poses.Length; k++) + { + if (!NestLayoutCheck.Clears(geometry, poses[i], geometry, poses[k], PartSpacing)) + close.Add($"{i} at {poses[i].X:F3},{poses[i].Y:F3} and {k} at {poses[k].X:F3},{poses[k].Y:F3}"); + } + } + + Assert.Empty(close); + } + + /// Fill Plate on that sheet, whole and with the quantity set. + [Theory] + [InlineData(0, 154)] + [InlineData(24, 24)] + public void FillPlateOfGussetsKeepsThePartSpacing(int quantity, int expected) + { + var plate = new Plate(new Size(60, 120)) + { + PartSpacing = PartSpacing, + EdgeSpacing = new Spacing(0.3, 0.75, 0.3, 0.25), + }; + var drawing = Gusset(); + + var parts = PlateFillService.FillItem("Fill", plate, + new NestItem { Drawing = drawing, Quantity = quantity }, plate.WorkArea(), null, + CancellationToken.None); + + Assert.Empty(NestLayoutCheck.Validate(new() { (plate, parts) }, + new Dictionary { [drawing] = ("Gusset", parts.Count) })); + Assert.True(parts.Count >= expected, $"Placed {parts.Count} gussets"); + } +} diff --git a/OpenNest.Engine.Tests/Jobs/FillStackCharacterizationTests.cs b/OpenNest.Engine.Tests/Jobs/FillStackCharacterizationTests.cs index 2244896b..b1896aa1 100644 --- a/OpenNest.Engine.Tests/Jobs/FillStackCharacterizationTests.cs +++ b/OpenNest.Engine.Tests/Jobs/FillStackCharacterizationTests.cs @@ -45,6 +45,15 @@ namespace OpenNest.Engine.Tests.Jobs; /// herringbone-era pins came from Windows, whose runtime trig differs from Linux in the last /// bit, and the cross nested differently on each (Strip 23 there, 28 here). Both platforms /// now give these layouts, which pass the overlap and work-area checks. +/// The mixed Strip nest was re-captured when the pattern copy distance began measuring parts +/// beside the copy's path (PatternCopySpacingTests): its row of D-shapes used to come from +/// an Extents column pair tiled 0.01 apart, a layout that broke the part spacing and lost to the +/// columns on score. The row is now valid and denser than the columns, so the strip takes it. +/// The first remnant that layout leaves is a sliver along the top edge, too narrow for the single +/// rectangle, and the pack step used to stop there. It now goes on to the following remnants +/// (StripLeftoverPackTests), so the rectangle lands right of the row and the nest still +/// holds 35. No other pin changed, and the whole-plate nests are now checked with +/// NestLayoutCheck.Validate as they are solved. /// Not pinned: richer mixes that pair parallelogram, chevron or tee parts at oblique angles /// with other irregular items. Their Fill and Vertical Remnant nests vary between runs, most /// likely because best-fit pair candidates are gathered in a ConcurrentBag and equal @@ -282,7 +291,12 @@ public class FillStackCharacterizationTests { var plate = MakePlate(); var items = createItems(); + var demand = items.ToDictionary(i => i.Drawing, i => (i.Drawing.Name, i.Quantity)); var parts = PlateFillService.Nest(strategy, plate, items, null, CancellationToken.None); + Assert.Empty(NestLayoutCheck.Validate( + new List<(Plate, List)> { (plate, parts) }, + demand + )); // Remaining demand is part of the contract callers read back. var remaining = string.Join(",", items.Select(i => $"{i.Drawing.Name}={i.Quantity}")); return Layout(parts) + "\nremaining:" + remaining; @@ -290,7 +304,7 @@ public class FillStackCharacterizationTests [Theory] [InlineData("Fill", 34, "D3D54E9116D96ACF")] - [InlineData("Strip", 35, "55A0EE3EDF28E68E")] + [InlineData("Strip", 35, "E8735AC098986DBF")] [InlineData("Vertical Remnant", 35, "285AF7AF9B9573C5")] [InlineData("Horizontal Remnant", 30, "A0700052AE771E06")] public void Nest_MixedIrregularItems_PinnedLayout( diff --git a/OpenNest.Engine.Tests/Jobs/StripLeftoverPackTests.cs b/OpenNest.Engine.Tests/Jobs/StripLeftoverPackTests.cs new file mode 100644 index 00000000..7572f1b7 --- /dev/null +++ b/OpenNest.Engine.Tests/Jobs/StripLeftoverPackTests.cs @@ -0,0 +1,183 @@ +using System.Threading; +using OpenNest.Engine.Fill; +using OpenNest.Engine.Jobs; +using OpenNest.Engine.Jobs.Placement.Fillers; +using OpenNest.Geometry; + +namespace OpenNest.Engine.Tests.Jobs; + +/// +/// The Strip layout's pack step (): leftovers go to the +/// remnants in order, and a first remnant that holds none of them +/// (often a sliver along an edge, first because it touches the edge and is long) must not end +/// the search. The parts already on the plate are placed by hand here, so the remnants are known. +/// +public class StripLeftoverPackTests +{ + // Work area x 1..61, y 1..11. + private static Plate MakePlate() => + new(new Size(12, 62)) { EdgeSpacing = new Spacing(1, 1, 1, 1), PartSpacing = 0.5 }; + + private static Part Block(string name, double length, double width, double x, double y) => + new(new Drawing(name, TestDrawingFactory.Rectangle(length, width)), new Vector(x, y)); + + /// + /// Two blocks 8.5 high. They leave, in remnant order: a 60 x 1 sliver along the top edge, a + /// 4.5 x 10 remnant at the right edge and a 4.25 x 10 gap between the blocks. Each of the two + /// tall remnants holds at most three 4 x 2.5 rectangles at the 0.5 spacing. + /// + private static List TwoBlocks() => + [Block("block-a", 30, 8.5, 1, 1), Block("block-b", 19.75, 8.5, 36.25, 1)]; + + private static List Remnants(Plate plate, List placed) => + new RemnantFinder( + plate.WorkArea(), + placed.Select(part => part.BoundingBox.Offset(plate.PartSpacing)).ToList() + ).FindRemnants(); + + private static PlateFiller StripFiller(Plate plate) => + new(plate, PlateFillPolicy.Fill, PlateLayout.Strips); + + private static List Pack(Plate plate, List placed, List items) => + StripFiller(plate).PackLeftovers( + plate.WorkArea(), + placed, + items, + Array.Empty(), + null, + CancellationToken.None + ); + + private static bool Inside(Box area, Part part) + { + const double slack = 1e-6; + var box = part.BoundingBox; + return box.Left >= area.Left - slack + && box.Right <= area.Right + slack + && box.Bottom >= area.Bottom - slack + && box.Top <= area.Top + slack; + } + + private static void AssertValid(Plate plate, List placed, List packed) + { + var all = placed.Concat(packed).ToList(); + var requirements = all + .GroupBy(part => part.BaseDrawing) + .ToDictionary(group => group.Key, group => (group.Key.Name, group.Count())); + Assert.Empty(NestLayoutCheck.Validate(new List<(Plate, List)> { (plate, all) }, requirements)); + } + + private static string Poses(IEnumerable parts) => + string.Join( + "\n", + parts + .Select(p => $"{p.BaseDrawing.Name}@({p.Location.X:F6},{p.Location.Y:F6},{p.Rotation:F6})") + .Order(StringComparer.Ordinal) + ); + + [Fact] + public void LeftoverThatDoesNotFitTheFirstRemnant_IsPackedInALaterOne() + { + var plate = MakePlate(); + var placed = TwoBlocks(); + var leftover = new Drawing("leftover", TestDrawingFactory.Rectangle(4, 2.5)); + var items = new List { new() { Drawing = leftover, Quantity = 1 } }; + + var remnants = Remnants(plate, placed); + // The fixture only tests the change while the first remnant is the sliver. + Assert.Equal(1, remnants[0].Width, 6); + Assert.Empty(StripFiller(plate).PackArea(remnants[0], items, null, CancellationToken.None)); + + var packed = Pack(plate, placed, items); + + var part = Assert.Single(packed); + Assert.Same(leftover, part.BaseDrawing); + Assert.True(Inside(remnants[1], part), "the leftover belongs in the second remnant"); + Assert.Equal(1, items[0].Quantity); + AssertValid(plate, placed, packed); + } + + [Fact] + public void LeftoversOneRemnantCannotHold_GoOnToTheNextRemnant() + { + var plate = MakePlate(); + var placed = TwoBlocks(); + var leftover = new Drawing("leftover", TestDrawingFactory.Rectangle(4, 2.5)); + var items = new List { new() { Drawing = leftover, Quantity = 5 } }; + var remnants = Remnants(plate, placed); + + var packed = Pack(plate, placed, items); + + Assert.Equal(5, packed.Count); + Assert.Equal(3, packed.Count(part => Inside(remnants[1], part))); + Assert.Equal(2, packed.Count(part => Inside(remnants[2], part))); + AssertValid(plate, placed, packed); + } + + [Fact] + public void FirstRemnantThatHoldsEveryLeftover_PacksAsItAlwaysDid() + { + var plate = MakePlate(); + var placed = TwoBlocks(); + // 6 x 1 strips: all three lie in the top sliver, the first remnant. + var leftover = new Drawing("leftover", TestDrawingFactory.Rectangle(6, 1)); + var items = new List { new() { Drawing = leftover, Quantity = 3 } }; + var first = Remnants(plate, placed)[0]; + var expected = StripFiller(plate).PackArea(first, items, null, CancellationToken.None); + Assert.Equal(3, expected.Count); + + var packed = Pack(plate, placed, items); + + Assert.Equal(Poses(expected), Poses(packed)); + AssertValid(plate, placed, packed); + } + + [Fact] + public void EmptyPlate_PacksTheWholeWorkArea() + { + var plate = MakePlate(); + var leftover = new Drawing("leftover", TestDrawingFactory.Rectangle(4, 2.5)); + var items = new List { new() { Drawing = leftover, Quantity = 4 } }; + var expected = StripFiller(plate).PackArea(plate.WorkArea(), items, null, CancellationToken.None); + + var packed = Pack(plate, new List(), items); + + Assert.Equal(4, packed.Count); + Assert.Equal(Poses(expected), Poses(packed)); + } + + [Fact] + public void LeftoverNoRemnantHolds_IsLeftUnplaced() + { + var plate = MakePlate(); + var placed = TwoBlocks(); + var items = new List + { + new() { Drawing = new Drawing("too-big", TestDrawingFactory.Rectangle(8, 8)), Quantity = 2 }, + }; + + Assert.Empty(Pack(plate, placed, items)); + } + + /// End to end: a filled strip leaves the single part no room in the first remnant. + [Fact] + public void StripNest_PacksTheSinglePartBesideAFilledStrip() + { + var plate = MakePlate(); + var fill = new Drawing("fill", TestDrawingFactory.Rectangle(5, 8.5)); + var single = new Drawing("single", TestDrawingFactory.Rectangle(4, 2.5)); + var items = new List + { + new() { Drawing = fill, Quantity = 10 }, + new() { Drawing = single, Quantity = 1 }, + }; + var requirements = items.ToDictionary(i => i.Drawing, i => (i.Drawing.Name, i.Quantity)); + + var parts = StripFiller(plate).Nest(items, null, CancellationToken.None); + + Assert.Equal(10, parts.Count(part => ReferenceEquals(part.BaseDrawing, fill))); + Assert.Single(parts, part => ReferenceEquals(part.BaseDrawing, single)); + Assert.All(items, item => Assert.Equal(0, item.Quantity)); + Assert.Empty(NestLayoutCheck.Validate(new List<(Plate, List)> { (plate, parts) }, requirements)); + } +} diff --git a/OpenNest.Engine/Fill/FillLinear.cs b/OpenNest.Engine/Fill/FillLinear.cs index 15e7b8c9..f9f7be10 100644 --- a/OpenNest.Engine/Fill/FillLinear.cs +++ b/OpenNest.Engine/Fill/FillLinear.cs @@ -94,6 +94,16 @@ namespace OpenNest.Engine.Fill return direction == NestDirection.Horizontal ? WorkArea.Right : WorkArea.Top; } + /// + /// The gap between two boxes across the given axis; negative when they overlap there. + /// + private static double SideGap(Box a, Box b, NestDirection direction) + { + return direction == NestDirection.Horizontal + ? System.Math.Max(a.Bottom - b.Top, b.Bottom - a.Top) + : System.Math.Max(a.Left - b.Right, b.Left - a.Right); + } + private static NestDirection PerpendicularAxis(NestDirection direction) { return direction == NestDirection.Horizontal @@ -169,7 +179,10 @@ namespace OpenNest.Engine.Fill movingBoxes[i] = stationaryBoxes[i].Translate(offset); } + // The copy distance is the maximum over every pair. Pairs whose bboxes overlap + // across the push are kept apart from those only beside the copy's path: see below. var maxCopyDistance = 0.0; + var maxBesideDistance = 0.0; for (var j = 0; j < parts.Count; j++) { @@ -184,8 +197,13 @@ namespace OpenNest.Engine.Fill if (SpatialQuery.DirectionalGap(movingBox, stationaryBox, opposite) > 0) continue; - // Skip if bboxes can't overlap along the axis perpendicular to the push. - if (!SpatialQuery.PerpendicularOverlap(movingBox, stationaryBox, dirVec)) + // Skip a part the copy cannot come within the spacing of: one whose bbox + // lies beside the copy's path by the spacing or more. One nearer than + // that is measured even though the bboxes never overlap, or the copy + // would stop clear of the parts in its path and pass this one too close. + var sideGap = SideGap(movingBox, stationaryBox, direction); + var beside = sideGap > Tolerance.Epsilon; + if (beside && sideGap >= PartSpacing - Tolerance.Epsilon) continue; if (stationaryEntities[i] == null) @@ -214,16 +232,24 @@ namespace OpenNest.Engine.Fill var copyDist = startOffset - slideDistance; - if (copyDist > maxCopyDistance) - maxCopyDistance = copyDist; + if (beside) + maxBesideDistance = System.Math.Max(maxBesideDistance, copyDist); + else + maxCopyDistance = System.Math.Max(maxCopyDistance, copyDist); - // The copy distance is the maximum over every pair, so it can only grow. - if (maxCopyDistance > useful) + // Either maximum can only grow, and so can the distance they give. + if (maxCopyDistance > useful || maxBesideDistance > useful + Tolerance.Epsilon) return double.PositiveInfinity; } } - return maxCopyDistance; + // A part beside the path often meets the copy corner to corner at the very + // distance the parts in the path set, and that contact can measure up to + // Epsilon longer. Only one that needs more than that moves the copy. + if (maxBesideDistance > maxCopyDistance + Tolerance.Epsilon) + maxCopyDistance = maxBesideDistance; + + return maxCopyDistance > useful ? double.PositiveInfinity : maxCopyDistance; } /// diff --git a/OpenNest.Engine/Jobs/Placement/Fillers/LeftoverPacker.cs b/OpenNest.Engine/Jobs/Placement/Fillers/LeftoverPacker.cs new file mode 100644 index 00000000..9afa679e --- /dev/null +++ b/OpenNest.Engine/Jobs/Placement/Fillers/LeftoverPacker.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using OpenNest.Engine.Fill; +using OpenNest.Engine.NestingEngines.Rectangles; +using OpenNest.Geometry; +using OpenNest.Math; + +namespace OpenNest.Engine.Jobs.Placement.Fillers; + +/// +/// Packs what a plate's fills left unplaced into the room around the placed parts: the remnants +/// in order, each offered whatever is still unplaced. The first +/// remnant is often a sliver along an edge that holds none of them, so the first to take a part +/// is packed, the remnants are found again around what it took, and the search ends when no +/// remnant takes anything. +/// +internal static class LeftoverPacker +{ + /// + /// Returns the packed parts. are not changed: quantities are the + /// caller's to deduct. With nothing placed and no keep-outs the whole + /// is packed first. + /// + /// Rectangles treated as occupied (inflated clamp zones). + /// Packs one rectangular area with the items it is given. + internal static List Pack( + Box workArea, + double partSpacing, + IEnumerable placed, + IReadOnlyList items, + IReadOnlyList keepOuts, + Func, IProgress, CancellationToken, List> pack, + IProgress progress, + CancellationToken token + ) + { + var packed = new List(); + var remaining = items + .Where(item => item.Quantity > 0) + .Select(item => new NestItem + { + Drawing = item.Drawing, + Quantity = item.Quantity, + Priority = item.Priority, + StepAngle = item.StepAngle, + RotationStart = item.RotationStart, + RotationEnd = item.RotationEnd, + }) + .ToList(); + var sizes = remaining.ToDictionary( + item => item, + item => item.Drawing.Program.BoundingBox(), + ReferenceEqualityComparer.Instance + ); + var obstacles = placed.Select(part => part.BoundingBox.Offset(partSpacing)).ToList(); + obstacles.AddRange(keepOuts); + + while (remaining.Count > 0 && !token.IsCancellationRequested) + { + var areas = obstacles.Count > 0 + ? new RemnantFinder(workArea, obstacles).FindRemnants() + : new List { workArea }; + + List taken = null; + foreach (var area in areas) + { + if (token.IsCancellationRequested) + break; + if (area.Width <= 0 || area.Length <= 0) + continue; + if (!remaining.Any(item => CouldHold(area, sizes[item]))) + continue; + + var parts = pack(area, remaining, progress, token); + if (parts != null && parts.Count > 0) + { + taken = parts; + break; + } + } + + if (taken == null) + break; + + packed.AddRange(taken); + obstacles.AddRange(taken.Select(part => part.BoundingBox.Offset(partSpacing))); + var deducted = 0; + foreach (var item in remaining) + { + var count = taken.Count(part => ReferenceEquals(part.BaseDrawing, item.Drawing)); + item.Quantity -= count; + deducted += count; + } + remaining.RemoveAll(item => item.Quantity <= 0); + + // A pack function may answer with parts nobody asked for; without this the demand + // would never run out. + if (deducted == 0) + break; + } + + return packed; + } + + /// + /// False only when cannot lie in at 0 or 90 + /// degrees even with the overhang a packer allows at a work-area edge, so a remnant this + /// rules out is one would leave empty. + /// + private static bool CouldHold(Box area, Box size) + { + const double slack = SheetPacker.OverhangAllowance + Tolerance.Epsilon; + var length = area.Length + slack; + var width = area.Width + slack; + return (size.Length <= length && size.Width <= width) + || (size.Width <= length && size.Length <= width); + } +} diff --git a/OpenNest.Engine/Jobs/Placement/Fillers/PlateFiller.cs b/OpenNest.Engine/Jobs/Placement/Fillers/PlateFiller.cs index 7b28b389..11ea8c1c 100644 --- a/OpenNest.Engine/Jobs/Placement/Fillers/PlateFiller.cs +++ b/OpenNest.Engine/Jobs/Placement/Fillers/PlateFiller.cs @@ -21,7 +21,7 @@ internal enum PlateLayout /// /// Iterative shrink-fill strips (each strip ranked by a fresh remnant filler), then pack the - /// leftovers into the first remnant. + /// leftovers into the remnants, first to last, until none takes a part. /// Strips, } @@ -608,26 +608,8 @@ internal class PlateFiller } packItems = packItems.Where(item => item.Quantity > 0).ToList(); - if (packItems.Count > 0 && !token.IsCancellationRequested) - { - var packArea = workArea; - if (allParts.Count > 0 || clampKeepOuts.Count > 0) - { - var obstacles = allParts - .Select(part => part.BoundingBox.Offset(Plate.PartSpacing)) - .ToList(); - obstacles.AddRange(clampKeepOuts); - var finder = new RemnantFinder(workArea, obstacles); - var remnants = finder.FindRemnants(); - packArea = remnants.Count > 0 ? remnants[0] : new Box(0, 0, 0, 0); - } - - if (packArea.Width > 0 && packArea.Length > 0) - { - var packParts = PackArea(packArea, packItems, progress, token); - allParts.AddRange(packParts); - } - } + if (packItems.Count > 0) + allParts.AddRange(PackLeftovers(workArea, allParts, packItems, clampKeepOuts, progress, token)); foreach (var item in items) { @@ -641,6 +623,30 @@ internal class PlateFiller return allParts; } + /// + /// The Strip layout's pack step: go to the remnants + /// and the clamp keep-outs leave, first to last, through + /// . Returns the packed parts; quantities are the caller's to deduct. + /// + internal List PackLeftovers( + Box workArea, + List placed, + List packItems, + IReadOnlyList clampKeepOuts, + IProgress progress, + CancellationToken token + ) => + LeftoverPacker.Pack( + workArea, + Plate.PartSpacing, + placed, + packItems, + clampKeepOuts, + PackArea, + progress, + token + ); + private void RunPipeline(FillContext context) { var classification = PartClassifier.Classify(context.Item.Drawing); diff --git a/docs/geometry/directional-slides.md b/docs/geometry/directional-slides.md index fe9a9084..2bae3cb3 100644 --- a/docs/geometry/directional-slides.md +++ b/docs/geometry/directional-slides.md @@ -12,7 +12,7 @@ Open/incomplete chains and ambiguous contacts conservatively block. Loops are re - PlateView uses `SelectionManager.PushSelected` → `Compactor.Push`. On an outlined sheet the plate pushes also stop at the edge of its usable material (see [irregular stock](../irregular-stock.md)). The zero-spacing nudge-and-discard workaround is removed. Cutout contours on stationary obstacles are retained, and the plate entry's existing-overlap filter accounts for holes rather than relying solely on `Part.Intersects` (which compares outer perimeters). - With **Calculated distance** checked in Tools > Set Offset Increment, PlateView's arrow keys use `SelectionManager.StepSelected` → `Compactor.Step`. The step is the selection's linear-fill copy distance (`FillLinear.CopyDistance`) at the plate's part spacing, so a shape that nests into its own copy steps less than its size. That copy distance is the same in both directions along an axis. The move is not a slide: like a fixed nudge it always moves the full step, ignoring the work-area edge, clamps and other parts, because interlocked rows (staggered triangles, say) cannot slide straight past their neighbors to the next row. It can land off the plate or on a part; the layout check reports that as it does for any nudge. -- Linear fill inherits the shared native-entity query unchanged. Extents fill passes complete boundary loops instead of direction-filtered fragments. +- Linear fill inherits the shared native-entity query unchanged. Its pattern copy distance slides each part of the next copy against every part of the pattern whose bounding box is in the copy's path or beside it by less than the part spacing; a part beside the path by the spacing or more cannot come too close and is skipped. Skipping on bounding-box overlap alone let a copy pass a part 0.04 beside its path: columns of a gusset pair interlocked closer than the spacing (`PatternCopySpacingTests`). Extents fill passes complete boundary loops instead of direction-filtered fragments. - CPU best-fit batches prepare contact topology once and use all vertices plus curve/line interior and curve/curve tangency events. The old leading-half vertex filter cannot establish the next blocker after a skipped touch. - The best-fit pair search (`RotationSlideStrategy`) starts each slide from an offset on its step grid, then slides every resting position sideways, both ways, and keeps the new resting positions as extra candidates. A pair that locks in a corner (two interlocking channels) therefore closes to the part spacing on both axes instead of stopping up to a step short. This relies on leaving an existing contact being legal. - GPU kernels retain nearest-hit reduction and return unsnapped contact witnesses. The shared CPU classifier accepts a blocking witness or replays the full query after a nonblocking witness, preserving tied/later blockers. Both batch APIs honor active buffer lengths and refresh mutated/reused segment arrays. The GPU distance adapter sends only exact cardinal directions to the axis-only slide interface; arbitrary directions and native curves use the shared CPU path. diff --git a/docs/nesting-engines.md b/docs/nesting-engines.md index 4cd9b5ab..34e3c2aa 100644 --- a/docs/nesting-engines.md +++ b/docs/nesting-engines.md @@ -42,6 +42,11 @@ layout. The chosen pair then slides left and down against the true outlines arou one group. Trimming a fill to quantity keeps its interlocked pairs whole, so the spare space stays one usable cell rather than two half gaps. +Strip, in place of the two orders above, offers its leftovers to every remnant of the finished +layout (`LeftoverPacker`): the remnants in order, edge-touching first and then by area, the first +that takes a part packed as boxes at 0 or 90 degrees and the remnants found again around it, until +none takes a part. The first remnant is often a sliver along an edge that holds nothing. + Neither Irregular nor Rectangles wins every job, even within its own lane, so Default runs both rather than choosing by part shape; Rectangles adds little time and is also the fallback when an Irregular layout fails the check. Default runs Rectangles first, then Circles, then Irregular, so