From 4b3d7d57aa65e4a2b911c250ae150e77a6d25f89 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Sat, 21 Nov 2026 14:21:25 -0500 Subject: [PATCH] feat(fill): fill the J-bar strip with whole-pair grids and grid-end inserts Fill placed 30 J-shaped bars (30 x 7.5, 0.3 spacing) on a 48 x 96 sheet where 33 fit by hand. With pairs settled tight (07f30c12), two columns leave a 30.2" strip, but the grid topped its last column up with single halves of pairs and took that strip. The work that reached 33 was done on 2026-11-09 and left uncommitted; this ports it onto master. - PairFiller also tiles each pair grid with whole pairs only (FillLinear PartialCopies = false), after the others, and refills the strip it leaves; that grid wins only by placing more parts. Only fills without a quantity try it: in Auto Nest's capped fills it ended N26-2ER's sheet at 103.83 instead of 103.08. The cutout lattice turns it off, since it crops its fill. - GridEndInserter completes a strip's densest pair grid: it moves the grid to each corner, slides copies of its parts in from the open sides and fills the strip beyond. The J-bar strip takes three pairs stood on end, one more bar beside them and a pair underneath: 33 parts, as laid out by hand. Corpus: the J-bar fill places 33 (baseline 30), N26-29X keeps 136, and every auto-nest nest keeps its saved layout. Co-Authored-By: Claude Opus 5.5 --- OpenNest.Engine.Tests/Fill/JBarFillTests.cs | 73 ++++ OpenNest.Engine/Fill/FillLinear.cs | 15 +- OpenNest.Engine/Fill/GridEndInserter.cs | 319 ++++++++++++++++++ OpenNest.Engine/Fill/PairFiller.cs | 133 +++++--- OpenNest.Engine/Fill/PairRemnantFiller.cs | 62 +++- .../Jobs/Cutouts/CutoutLatticeFill.cs | 3 +- .../Jobs/Placement/Fillers/PlateFiller.cs | 9 + .../Jobs/Placement/PrivatePlateFill.cs | 5 +- OpenNest.Engine/Strategies/FillContext.cs | 6 + .../Strategies/PairsFillStrategy.cs | 1 + docs/nesting-engines.md | 25 ++ 11 files changed, 587 insertions(+), 64 deletions(-) create mode 100644 OpenNest.Engine.Tests/Fill/JBarFillTests.cs create mode 100644 OpenNest.Engine/Fill/GridEndInserter.cs diff --git a/OpenNest.Engine.Tests/Fill/JBarFillTests.cs b/OpenNest.Engine.Tests/Fill/JBarFillTests.cs new file mode 100644 index 00000000..121ce7a5 --- /dev/null +++ b/OpenNest.Engine.Tests/Fill/JBarFillTests.cs @@ -0,0 +1,73 @@ +using OpenNest.CNC; +using OpenNest.Engine.BestFit; +using OpenNest.Engine.Jobs; +using OpenNest.Engine.Jobs.Placement; +using OpenNest.Geometry; + +namespace OpenNest.Engine.Tests.Fill; + +/// +/// A reported nest: 30 x 7.5 J-shaped bars (a 3.6" bar with a 2" leg at one end) on a 48 x 96 +/// plate. Pairs stack bar on bar with each leg tucked just past the other bar's end. Best fit +/// sampled the pair's offset along the bars a quarter inch apart and landed 0.2" short of the +/// leg's contact, so two columns of pairs left a 29.8" strip, too short for a 30" bar: Fill +/// placed 30. With the pair settled against both contacts the strip is 30.2" and holds nine +/// more, as laid out by hand (33): three pairs stood on end, one more bar dropped 2.3" beside +/// them so its leg passes under its neighbor's, and a pair lying under all seven. +/// +public class JBarFillTests +{ + private static Plate JBarPlate() => + new(new Size(48, 96)) + { + PartSpacing = 0.3, + EdgeSpacing = new Spacing(0.3, 0.75, 0.3, 0.25), + }; + + /// The reported drawing's outline, in absolute coordinates. + private static Drawing JBar() + { + var program = new Program(); + program.MoveTo(-2.21875, -2.5126780932); + program.LineTo(-2.21875, 0.625); + program.ArcTo(new Vector(-1.96875, 0.875), new Vector(-1.96875, 0.625), RotationType.CW); + program.LineTo(27.53125, 0.875); + program.ArcTo(new Vector(27.78125, 0.625), new Vector(27.53125, 0.625), RotationType.CW); + program.LineTo(27.78125, -5.625); + program.ArcTo(new Vector(25.78125, -5.625), new Vector(26.78125, -5.625), RotationType.CW); + program.LineTo(25.78125, -0.875); + program.LineTo(25.71875, -0.875); + program.LineTo(25.71875, -2.5126780932); + program.ArcTo(new Vector(25.46875, -2.7626780932), new Vector(25.46875, -2.5126780932), RotationType.CW); + program.LineTo(-1.96875, -2.7626780932); + program.ArcTo(new Vector(-2.21875, -2.5126780932), new Vector(-1.96875, -2.5126780932), RotationType.CW); + return new Drawing("J-Bar", program); + } + + [Fact] + public void BestFitSettlesThePairAgainstBothContacts() + { + var fits = new BestFitFinder(48, 96).FindBestFits(JBar(), spacing: 0.3); + + // Leg 2" + spacing 0.3" past a 30" bar: 32.3" end to end, not 32.5". + var tightest = fits + .Where(f => f.Keep && System.Math.Min(f.BoundingWidth, f.BoundingHeight) < 8) + .Min(f => System.Math.Max(f.BoundingWidth, f.BoundingHeight)); + Assert.Equal(32.3, tightest, 4); + } + + [Fact] + public void FillLeavesAStripThatHoldsNineMore() + { + var plate = JBarPlate(); + var drawing = JBar(); + + var parts = PlateFillService.FillItem("Fill", plate, + new NestItem { Drawing = drawing, Quantity = 0 }, plate.WorkArea(), null, + CancellationToken.None); + + Assert.Equal(33, parts.Count); + Assert.Empty(NestLayoutCheck.Validate(new() { (plate, parts) }, + new Dictionary { [drawing] = ("J-Bar", 33) })); + } +} diff --git a/OpenNest.Engine/Fill/FillLinear.cs b/OpenNest.Engine/Fill/FillLinear.cs index f9f7be10..18d01d08 100644 --- a/OpenNest.Engine/Fill/FillLinear.cs +++ b/OpenNest.Engine/Fill/FillLinear.cs @@ -67,6 +67,13 @@ namespace OpenNest.Engine.Fill /// internal bool LeadingParts { get; init; } = true; + /// + /// When true (the default), a multi-part pattern whose next copy does not fit whole + /// still places the parts of that copy that do. False keeps whole copies only, so the + /// strip beyond the grid stays free for a remnant fill. + /// + public bool PartialCopies { get; init; } = true; + private static Vector MakeOffset(NestDirection direction, double distance) { return direction == NestDirection.Horizontal @@ -276,7 +283,8 @@ namespace OpenNest.Engine.Fill { 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) + if (PartialCopies && LeadingParts && basePattern.Parts.Count > 1 + && !(maxParts > 0 && tiling.Count >= maxParts) && copyDistance > Tolerance.Epsilon && !double.IsPositiveInfinity(copyDistance)) tiling = AddLeadingParts(basePattern, tiling, direction, copyDistance); return tiling; @@ -388,7 +396,7 @@ namespace OpenNest.Engine.Fill // next copy that didn't fit as a whole. This handles cases where // e.g. a 2-part pair only partially fits — one part may still be // within the work area even though the full pattern exceeds it. - if (basePattern.Parts.Count > 1 && !Full()) + if (PartialCopies && basePattern.Parts.Count > 1 && !Full()) { var offset = MakeOffset(direction, copyDistance * count); @@ -423,7 +431,8 @@ namespace OpenNest.Engine.Fill { var box = basePattern.BoundingBox; var useful = GetLimit(direction) - GetStart(box, direction) - GetDimension(box, direction); - var partial = basePattern.Parts.Count > 1 && !(maxParts > 0 && basePattern.Parts.Count >= maxParts); + var partial = PartialCopies && 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 diff --git a/OpenNest.Engine/Fill/GridEndInserter.cs b/OpenNest.Engine/Fill/GridEndInserter.cs new file mode 100644 index 00000000..816b3a83 --- /dev/null +++ b/OpenNest.Engine/Fill/GridEndInserter.cs @@ -0,0 +1,319 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using OpenNest.Geometry; +using OpenNest.Math; + +namespace OpenNest.Engine.Fill +{ + /// + /// Completes a grid of pairs that leaves slack in its area. The grid is moved to each corner + /// of the area, copies of its parts are slid in from the open sides, and the strip left + /// beyond them is filled. A part whose pair no longer fits can still tuck beside the grid's + /// last pair, offset across the row so it clears its neighbor: J-shaped bars stood on end + /// in a 30.2" strip hold three pairs and one more bar dropped 2.3" beside them, with a pair + /// lying under all seven. + /// + /// + /// Every insert is a push, so the parts keep the part spacing and + /// stay in the area by construction; an insert is kept only when it stops inside the area. + /// + internal static class GridEndInserter + { + /// Positions across the row a copy is first slid in from, per template. + private const int CoarseSamples = 24; + + /// Most positions tried around the best coarse landing. + private const int FineSamples = 24; + + /// Most copies slid in from one side. + private const int MaxInserts = 4; + + /// + /// The most parts found among the grid moved to each corner of , + /// with and without copies slid in from its open sides, each with the strip left beyond + /// them filled by ; null when none places more than + /// parts or the grid alone. A strip is filled only when the + /// parts it could hold by (the part's true area) could beat + /// the best so far, since each fill lays out the strip with pairs. + /// + public static List Complete( + List grid, + Box area, + double spacing, + double partArea, + int toBeat, + Func> fillStrip, + CancellationToken token + ) + { + if (grid == null || grid.Count == 0 || !(partArea > 0)) + return null; + + // Nothing beyond the grid's own box can hold more parts than its area allows. + if (grid.Count + (int)((area.Area() - grid.GetBoundingBox().Area()) / partArea) <= toBeat) + return null; + + var gridBox = grid.GetBoundingBox(); + var slackX = area.Right - gridBox.Right; + var slackY = area.Top - gridBox.Top; + var baseX = area.Left - gridBox.Left; + var baseY = area.Bottom - gridBox.Bottom; + + var templates = grid + .GroupBy(p => (p.BaseDrawing, System.Math.Round(p.Rotation, 9))) + .Select(g => g.First()) + .ToList(); + + List best = null; + var floor = System.Math.Max(toBeat, grid.Count); + foreach (var toRight in new[] { false, true }) + { + if (toRight && slackX <= Tolerance.Epsilon) + continue; + + foreach (var toTop in new[] { false, true }) + { + if (toTop && slackY <= Tolerance.Epsilon) + continue; + + token.ThrowIfCancellationRequested(); + var offset = new Vector(baseX + (toRight ? slackX : 0), baseY + (toTop ? slackY : 0)); + var placed = grid.Select(p => p.CloneAtOffset(offset)).ToList(); + + // Moved to another corner without inserts, the grid leaves the same strips + // mirrored, which hold the same parts. + if (!toRight && !toTop) + Consider(WithStrip(placed, area, spacing, partArea, Floor(), fillStrip)); + + var inserted = new List(placed); + InsertMany(inserted, templates, area, spacing, + toRight ? PushDirection.Right : PushDirection.Left, token); + InsertMany(inserted, templates, area, spacing, + toTop ? PushDirection.Up : PushDirection.Down, token); + if (inserted.Count > placed.Count) + Consider(WithStrip(inserted, area, spacing, partArea, Floor(), fillStrip)); + } + } + + return best; + + int Floor() => System.Math.Max(floor, best?.Count ?? 0); + + void Consider(List candidate) + { + if (candidate != null && candidate.Count > Floor()) + best = candidate; + } + } + + /// + /// and the most parts places in one + /// of the strips between their bounds and the area's edges, or + /// alone when no strip could lift the total above by area. + /// + private static List WithStrip( + List parts, + Box area, + double spacing, + double partArea, + int toBeat, + Func> fillStrip + ) + { + var box = parts.GetBoundingBox(); + var strips = new (double X, double Y, double Length, double Width)[] + { + (area.Left, box.Top + spacing, area.Length, area.Top - box.Top - spacing), + (area.Left, area.Bottom, area.Length, box.Bottom - spacing - area.Bottom), + (box.Right + spacing, area.Bottom, area.Right - box.Right - spacing, area.Width), + (area.Left, area.Bottom, box.Left - spacing - area.Left, area.Width), + }; + + List bestStrip = null; + foreach (var (x, y, length, width) in strips) + { + if (width <= Tolerance.Epsilon || length <= Tolerance.Epsilon) + continue; + + var room = (int)(length * width / partArea); + if (parts.Count + room <= System.Math.Max(toBeat, parts.Count + (bestStrip?.Count ?? 0))) + continue; + + var filled = fillStrip(new Box(x, y, length, width)); + if (filled != null && filled.Count > (bestStrip?.Count ?? 0)) + bestStrip = filled; + } + + if (bestStrip == null) + return parts; + + var result = new List(parts.Count + bestStrip.Count); + result.AddRange(parts); + result.AddRange(bestStrip); + return result; + } + + /// Slides copies in along until none fits. + private static void InsertMany( + List parts, + List templates, + Box area, + double spacing, + PushDirection slide, + CancellationToken token + ) + { + for (var i = 0; i < MaxInserts; i++) + { + token.ThrowIfCancellationRequested(); + var next = InsertOne(parts, templates, area, spacing, slide); + if (next == null) + return; + + parts.Add(next); + } + } + + /// + /// A copy slid in along from beyond the area, at the position + /// across the slide that strays least outside the parts' band (so the strip beyond stays + /// whole), then travels deepest; null when no position leaves it inside the area. Each + /// slide pushes against every part, so positions are swept coarsely first, then at half + /// the spacing within one coarse step of the best coarse landing. + /// + private static Part InsertOne( + List parts, + List templates, + Box area, + double spacing, + PushDirection slide + ) + { + var horizontal = slide == PushDirection.Left || slide == PushDirection.Right; + var band = parts.GetBoundingBox(); + var direction = SpatialQuery.DirectionToOffset(slide, 1.0); + var obstacles = new Compactor.ObstacleSet(parts, spacing); + var moving = new List(1); + var fine = System.Math.Max(spacing / 2, Tolerance.Epsilon); + + Part best = null; + Part bestTemplate = null; + var bestAcross = 0.0; + var bestStray = double.MaxValue; + var bestDepth = double.MaxValue; + + void Try(Part template, double across) + { + var copy = StartBeyond(template, area, spacing, slide, across, horizontal); + moving.Clear(); + moving.Add(copy); + if (Compactor.Push(moving, area, direction, obstacles) <= 0) + return; + + var landed = copy.BoundingBox; + if (!Inside(landed, area)) + return; + + var stray = horizontal + ? System.Math.Max(0, band.Bottom - landed.Bottom) + System.Math.Max(0, landed.Top - band.Top) + : System.Math.Max(0, band.Left - landed.Left) + System.Math.Max(0, landed.Right - band.Right); + var depth = LeadingEdge(landed, slide); + if (stray < bestStray - Tolerance.Epsilon + || (stray < bestStray + Tolerance.Epsilon && depth < bestDepth - Tolerance.Epsilon)) + { + bestStray = stray; + bestDepth = depth; + best = copy; + bestTemplate = template; + bestAcross = across; + } + } + + (double Lo, double Hi) Range(Part template) + { + var box = template.BoundingBox; + var size = horizontal ? box.Width : box.Length; + return (horizontal ? area.Bottom : area.Left, (horizontal ? area.Top : area.Right) - size); + } + + var coarse = fine; + foreach (var template in templates) + { + var (lo, hi) = Range(template); + if (hi < lo - Tolerance.Epsilon) + continue; + + var samples = System.Math.Clamp((int)System.Math.Ceiling((hi - lo) / fine), 1, CoarseSamples); + coarse = System.Math.Max(coarse, (hi - lo) / samples); + for (var i = 0; i <= samples; i++) + Try(template, lo + (hi - lo) * i / samples); + } + + if (bestTemplate != null && coarse > fine + Tolerance.Epsilon) + { + var (lo, hi) = Range(bestTemplate); + var from = System.Math.Max(lo, bestAcross - coarse); + var to = System.Math.Min(hi, bestAcross + coarse); + var samples = System.Math.Clamp((int)System.Math.Ceiling((to - from) / fine), 1, FineSamples); + for (var i = 0; i <= samples; i++) + Try(bestTemplate, from + (to - from) * i / samples); + } + + return best; + } + + /// + /// A copy of just beyond the area edge the slide starts from, + /// its lower bound across the slide at . + /// + private static Part StartBeyond( + Part template, + Box area, + double spacing, + PushDirection slide, + double across, + bool horizontal + ) + { + var box = template.BoundingBox; + var gap = spacing + 1.0; + double dx, dy; + if (horizontal) + { + dy = across - box.Bottom; + dx = slide == PushDirection.Left + ? area.Right + gap - box.Left + : area.Left - gap - box.Right; + } + else + { + dx = across - box.Left; + dy = slide == PushDirection.Down + ? area.Top + gap - box.Bottom + : area.Bottom - gap - box.Top; + } + + var copy = template.CloneAtOffset(new Vector(dx, dy)); + copy.UpdateBounds(); + return copy; + } + + /// How far the copy got: smaller is deeper along the slide. + private static double LeadingEdge(Box box, PushDirection slide) => + slide switch + { + PushDirection.Left => box.Left, + PushDirection.Right => -box.Right, + PushDirection.Down => box.Bottom, + _ => -box.Top, + }; + + private static bool Inside(Box box, Box area) => + box.Left >= area.Left - Tolerance.Epsilon + && box.Right <= area.Right + Tolerance.Epsilon + && box.Bottom >= area.Bottom - Tolerance.Epsilon + && box.Top <= area.Top + Tolerance.Epsilon; + } +} diff --git a/OpenNest.Engine/Fill/PairFiller.cs b/OpenNest.Engine/Fill/PairFiller.cs index ae14d01b..2c88f3f4 100644 --- a/OpenNest.Engine/Fill/PairFiller.cs +++ b/OpenNest.Engine/Fill/PairFiller.cs @@ -112,6 +112,12 @@ namespace OpenNest.Engine.Fill init => remnantFiller.StripeConvergence = value; } + /// + /// When true (the default), each pair grid is also tiled with whole pairs only, after the + /// others, and the strip it leaves refilled; that layout wins only by placing more parts. + /// + public bool WholePairGrids { get; init; } = true; + /// /// The Fill /// @@ -170,6 +176,7 @@ namespace OpenNest.Engine.Fill parts = EvaluateHerringbones( item.Drawing, workArea, + targetCount, parts, candidates, bestFits, @@ -189,6 +196,7 @@ namespace OpenNest.Engine.Fill private List EvaluateHerringbones( Drawing drawing, Box workArea, + int targetCount, List best, List candidates, List bestFits, @@ -219,6 +227,7 @@ namespace OpenNest.Engine.Fill drawing, workArea, minCountToBeat, + targetCount, maxUtilization, partArea, bestFits, @@ -295,6 +304,7 @@ namespace OpenNest.Engine.Fill batchStart, batchEnd, best?.Count ?? 0, + targetCount, maxUtilization, partArea, bestFits, @@ -368,6 +378,7 @@ namespace OpenNest.Engine.Fill int batchStart, int batchEnd, int minCountToBeat, + int targetCount, double maxUtilization, double partArea, List bestFits, @@ -397,6 +408,7 @@ namespace OpenNest.Engine.Fill drawing, workArea, minCountToBeat, + targetCount, maxUtilization, partArea, bestFits, @@ -539,6 +551,7 @@ namespace OpenNest.Engine.Fill /// The drawing /// The workArea /// The minCountToBeat + /// The quantity the fill needs, or zero for as many as fit /// The maxUtilization /// The partArea /// The pairs the remnant strips are also filled with @@ -549,6 +562,7 @@ namespace OpenNest.Engine.Fill Drawing drawing, Box workArea, int minCountToBeat, + int targetCount, double maxUtilization, double partArea, List bestFits, @@ -559,6 +573,18 @@ namespace OpenNest.Engine.Fill // work, waits until the ranking or Phase 2 needs its outcome (see CompareByCount). var grids = new List(); var engine = new FillLinear(workArea, partSpacing) { Label = "Pairs" }; + + // A grid tops its last column or row up with the halves of pairs that do not fit + // whole, which can take a strip that would hold more parts: J-shaped bar pairs end a + // 48 x 96 sheet with a column of single halves where four more pairs fit. The pair + // turned 180 degrees would leave that strip, but it has the same bounding box, so the + // grid dedup never tiles it. The grid of whole pairs is tried too, after the others, + // leaving the strip to the remnant fill. Only a fill without a quantity tries it: a + // capped fill (Auto Nest's) ranks its layouts by more than count, and a whole-pair grid + // that wins there by one part can end its sheet later (N26-2ER). + var wholeGrids = new List>(); + var wholeEngine = new FillLinear(workArea, partSpacing) { Label = "Pairs", PartialCopies = false }; + foreach (var (pattern, dir) in claimed) { token.ThrowIfCancellationRequested(); @@ -566,8 +592,19 @@ namespace OpenNest.Engine.Fill var grid = engine.FillDeferred(pattern, dir); if (grid.IsPending && (grid.Count == 0 || grid.FallbackCount == 0)) grid.Resolve(); - if (grid.IsPending || grid.Count > 0) - grids.Add(grid); + if (!grid.IsPending && grid.Count == 0) + continue; + + grids.Add(grid); + + if (WholePairGrids && targetCount <= 0 && pattern.Parts.Count > 1) + { + // Against the grid's tiled count: a whole-pair grid as large holds no + // partial copies, so it is that grid, already tried. + var wholeParts = wholeEngine.Fill(pattern, dir); + if (wholeParts != null && wholeParts.Count > 0 && wholeParts.Count < grid.Count) + wholeGrids.Add(wholeParts); + } } if (grids.Count == 0) @@ -576,62 +613,62 @@ namespace OpenNest.Engine.Fill // Sort by count descending so we try the best grids first SortByCount(grids); - // Early abort: if the best grid + optimistic remnant can't beat the global best, skip Phase 2 - if (minCountToBeat > 0) + int Bound(List gridParts) => + gridParts.Count + remnantFiller.EstimateUpperBound(gridParts, workArea, maxUtilization, partArea); + + List WithRemnant(List gridParts) { - var topParts = grids[0].Resolve(); - var topCount = topParts.Count; - var optimisticRemnant = remnantFiller.EstimateUpperBound( - topParts, - workArea, - maxUtilization, - partArea + var remnantParts = remnantFiller.Fill(gridParts, drawing, workArea, token, bestFits); + if (remnantParts == null || remnantParts.Count == 0) + return gridParts; + + var total = new List(gridParts.Count + remnantParts.Count); + total.AddRange(gridParts); + total.AddRange(remnantParts); + return total; + } + + List best = null; + + // Early abort: if the best grid + optimistic remnant can't beat the global best, skip Phase 2 + var topBound = minCountToBeat > 0 ? Bound(grids[0].Resolve()) : int.MaxValue; + if (topBound <= minCountToBeat) + { + Debug.WriteLine( + $"[PairFiller] Skipping candidate grids: best grid + estimate {topBound} <= best {minCountToBeat}" ); - if (topCount + optimisticRemnant <= minCountToBeat) + } + else + { + // Phase 2: try remnant for each grid, skip if grid is too far behind + foreach (var grid in grids) { - Debug.WriteLine( - $"[PairFiller] Skipping candidate: grid {topCount} + estimate {optimisticRemnant} <= best {minCountToBeat}" - ); - return null; + token.ThrowIfCancellationRequested(); + + var gridParts = grid.Resolve(); + + // If this grid + max possible remnant can't beat current best, skip + if (best != null && Bound(gridParts) <= best.Count) + break; // sorted descending, so remaining are even smaller + + var total = WithRemnant(gridParts); + if (comparer.IsBetter(total, best, workArea)) + best = total; } } - // Phase 2: try remnant for each grid, skip if grid is too far behind - List best = null; - - foreach (var grid in grids) + // A whole-pair grid replaces the best only by placing more parts than it and the + // global best: it exists to free a strip, and its bound is not monotone in its size. + foreach (var wholeParts in wholeGrids) { token.ThrowIfCancellationRequested(); - var gridParts = grid.Resolve(); + var toBeat = System.Math.Max(best?.Count ?? 0, minCountToBeat); + if (Bound(wholeParts) <= toBeat) + continue; - // If this grid + max possible remnant can't beat current best, skip - if (best != null) - { - var remnantBound = remnantFiller.EstimateUpperBound( - gridParts, - workArea, - maxUtilization, - partArea - ); - if (gridParts.Count + remnantBound <= best.Count) - break; // sorted descending, so remaining are even smaller - } - - var remnantParts = remnantFiller.Fill(gridParts, drawing, workArea, token, bestFits); - List total; - if (remnantParts != null && remnantParts.Count > 0) - { - total = new List(gridParts.Count + remnantParts.Count); - total.AddRange(gridParts); - total.AddRange(remnantParts); - } - else - { - total = gridParts; - } - - if (comparer.IsBetter(total, best, workArea)) + var total = WithRemnant(wholeParts); + if (total.Count > toBeat && comparer.IsBetter(total, best, workArea)) best = total; } diff --git a/OpenNest.Engine/Fill/PairRemnantFiller.cs b/OpenNest.Engine/Fill/PairRemnantFiller.cs index a5be01e9..dcadfd40 100644 --- a/OpenNest.Engine/Fill/PairRemnantFiller.cs +++ b/OpenNest.Engine/Fill/PairRemnantFiller.cs @@ -26,7 +26,7 @@ namespace OpenNest.Engine.Fill /// Pair fills of a strip by strip size, normalized to the origin. Per filler, because /// they depend on the best-fit list it fills from. /// - private readonly ConcurrentDictionary<(double Width, double Length), List> pairStrips = + private readonly ConcurrentDictionary<(double Width, double Length, bool Complete), List> pairStrips = new(); /// Pairs tried when tiling a strip with one pair as a grid. @@ -35,6 +35,13 @@ namespace OpenNest.Engine.Fill /// Grid candidates tried in a row without improvement before giving up. private const int GridStaleLimit = 10; + /// + /// How many of a strip's densest grids completes. Each + /// completion slides copies against every part of the grid, so more grids cost much more: + /// on a 60 x 120 sheet of small parts, three took the fill 23% longer. + /// + private const int MaxCompletedGrids = 1; + private readonly ConcurrentDictionary minimumWidths = new(ReferenceEqualityComparer.Instance); @@ -125,7 +132,8 @@ namespace OpenNest.Engine.Fill Drawing drawing, Box remnantBox, List bestFits, - CancellationToken token + CancellationToken token, + bool complete = true ) { var singles = FillSingles(drawing, remnantBox, token); @@ -138,7 +146,7 @@ namespace OpenNest.Engine.Fill return singles; // Pairs replace the singles only when they place more; a tie keeps the singles. - var pairs = FillPairs(drawing, remnantBox, bestFits, token); + var pairs = FillPairs(drawing, remnantBox, bestFits, token, complete); return pairs != null && pairs.Count > (singles?.Count ?? 0) ? pairs : singles; } @@ -185,22 +193,26 @@ namespace OpenNest.Engine.Fill /// /// The strip filled with rows of pairs, or null when none fit. Computed once per strip /// size: the layout depends only on the size, so it is laid out at the origin and moved. + /// With , the densest pair grid is also completed with + /// , whose own strips are filled without it. /// private List FillPairs( Drawing drawing, Box remnantBox, List bestFits, - CancellationToken token + CancellationToken token, + bool complete ) { var key = ( System.Math.Round(remnantBox.Width, 6), - System.Math.Round(remnantBox.Length, 6) + System.Math.Round(remnantBox.Length, 6), + complete ); if (!pairStrips.TryGetValue(key, out var normalized)) { var origin = new Box(0, 0, remnantBox.Length, remnantBox.Width); - normalized = ComputePairs(drawing, origin, bestFits, token) ?? new List(); + normalized = ComputePairs(drawing, origin, bestFits, token, complete) ?? new List(); pairStrips.TryAdd(key, normalized); } @@ -219,7 +231,8 @@ namespace OpenNest.Engine.Fill Drawing drawing, Box area, List bestFits, - CancellationToken token + CancellationToken token, + bool complete ) { var context = new FillContext @@ -238,10 +251,25 @@ namespace OpenNest.Engine.Fill var best = new StripeFiller(context, NestDirection.Horizontal).Fill(); // A grid replaces the stripes only when it places more; a tie keeps the stripes. - var grid = TilePairs(drawing, area, bestFits, token); + var grid = TilePairs(drawing, area, bestFits, token, out var denseGrids); if (grid != null && grid.Count > (best?.Count ?? 0)) best = grid; + // The densest grid may leave slack where a lone part tucks in beside the last pair and + // a strip beyond that holds more; a completion replaces the best only when it places + // more. A strip already holding as many parts as its area allows has nothing to gain. + if (complete && drawing.Area > 0 && (best?.Count ?? 0) + 1 <= area.Area() / drawing.Area) + { + foreach (var dense in denseGrids) + { + var completed = GridEndInserter.Complete(dense, area, partSpacing, drawing.Area, + best?.Count ?? 0, + strip => FillRemnantBox(drawing, strip, bestFits, token, complete: false), token); + if (completed != null && completed.Count > (best?.Count ?? 0)) + best = completed; + } + } + Debug.WriteLine( $"[PairFiller] Remnant pairs: {best?.Count ?? 0} parts in " + $"{area.Width:F2}x{area.Length:F2}" @@ -258,7 +286,8 @@ namespace OpenNest.Engine.Fill Drawing drawing, Box area, List bestFits, - CancellationToken token + CancellationToken token, + out List> denseGrids ) { var shortSide = System.Math.Min(area.Width, area.Length); @@ -271,6 +300,7 @@ namespace OpenNest.Engine.Fill var engine = new FillLinear(area, partSpacing) { Label = "Pairs-Remnant" }; List best = null; var sinceImproved = 0; + var tiled = new List<(List Parts, double Density)>(); foreach (var fit in candidates) { token.ThrowIfCancellationRequested(); @@ -288,7 +318,13 @@ namespace OpenNest.Engine.Fill foreach (var dir in new[] { NestDirection.Horizontal, NestDirection.Vertical }) { var parts = engine.Fill(pattern, dir); - if (parts == null || parts.Count == 0 || !comparer.IsBetter(parts, best, area)) + if (parts == null || parts.Count == 0) + continue; + + if (parts.Count > 1 && drawing.Area > 0) + tiled.Add((parts, parts.Count * drawing.Area / parts.GetBoundingBox().Area())); + + if (!comparer.IsBetter(parts, best, area)) continue; best = parts; @@ -299,6 +335,12 @@ namespace OpenNest.Engine.Fill sinceImproved = improved ? 0 : sinceImproved + 1; } + // Stable, so equally dense grids keep the order they were tiled in. + denseGrids = tiled + .OrderByDescending(t => t.Density) + .Select(t => t.Parts) + .Take(MaxCompletedGrids) + .ToList(); return best; } diff --git a/OpenNest.Engine/Jobs/Cutouts/CutoutLatticeFill.cs b/OpenNest.Engine/Jobs/Cutouts/CutoutLatticeFill.cs index c10ee5ae..8b7f95bd 100644 --- a/OpenNest.Engine/Jobs/Cutouts/CutoutLatticeFill.cs +++ b/OpenNest.Engine/Jobs/Cutouts/CutoutLatticeFill.cs @@ -151,8 +151,9 @@ internal static class CutoutLatticeFill var drawing = DrawingJobMapper.CreateDrawing(insert); try { + // The lattice is shifted and cropped to the hole, so it keeps the regular pair grid. var parts = PrivatePlateFill.Run(drawing, insert.Rotation, spacing, - bounds.Length + 2 * step, bounds.Width + 2 * step, 0, token); + bounds.Length + 2 * step, bounds.Width + 2 * step, 0, token, wholePairGrids: false); token.ThrowIfCancellationRequested(); var left = bounds.Left - step; var bottom = bounds.Bottom - step; diff --git a/OpenNest.Engine/Jobs/Placement/Fillers/PlateFiller.cs b/OpenNest.Engine/Jobs/Placement/Fillers/PlateFiller.cs index 11ea8c1c..23688720 100644 --- a/OpenNest.Engine/Jobs/Placement/Fillers/PlateFiller.cs +++ b/OpenNest.Engine/Jobs/Placement/Fillers/PlateFiller.cs @@ -83,6 +83,14 @@ internal class PlateFiller /// internal bool StopAtQuantity { get; init; } + /// + /// When true (the default), the pairs phase also tiles each pair grid with whole pairs only + /// and refills the strip it leaves (). A caller that + /// crops the fill to another shape turns it off: that layout fills the box but is less + /// regular, so fewer of its parts survive the crop. + /// + internal bool WholePairGrids { get; init; } = true; + public virtual List BuildAngles( NestItem item, ClassificationResult classification, @@ -461,6 +469,7 @@ internal class PlateFiller PreferredDirection ), MaxQuantity = StopAtQuantity ? System.Math.Max(0, item.Quantity) : 0, + WholePairGrids = WholePairGrids, }; RunPipeline(context); diff --git a/OpenNest.Engine/Jobs/Placement/PrivatePlateFill.cs b/OpenNest.Engine/Jobs/Placement/PrivatePlateFill.cs index b2b46223..e7c7dae4 100644 --- a/OpenNest.Engine/Jobs/Placement/PrivatePlateFill.cs +++ b/OpenNest.Engine/Jobs/Placement/PrivatePlateFill.cs @@ -19,8 +19,9 @@ internal static class PrivatePlateFill /// X extent of the plate and work area. /// Y extent of the plate and work area. /// Copies wanted; zero fills the whole area. + /// See . internal static List Run(Drawing drawing, RotationPolicy rotation, double spacing, - double length, double width, int quantity, CancellationToken token) + double length, double width, int quantity, CancellationToken token, bool wholePairGrids = true) { var plate = new Plate(new Size(width, length)) { PartSpacing = spacing }; // The drawing is private: stabilize this cache entry before Fill's candidate pruning. @@ -34,7 +35,7 @@ internal static class PrivatePlateFill fits.AddRange(sorted); // A positive quantity lets supporting strategies avoid surplus rows. Zero still // fills the whole area (the cutout lattice caller requires an uncapped lattice). - var filler = new PlateFiller(plate) { StopAtQuantity = true }; + var filler = new PlateFiller(plate) { StopAtQuantity = true, WholePairGrids = wholePairGrids }; return filler.Fill(new NestItem { Drawing = drawing, diff --git a/OpenNest.Engine/Strategies/FillContext.cs b/OpenNest.Engine/Strategies/FillContext.cs index 2bac4c55..b4d51918 100644 --- a/OpenNest.Engine/Strategies/FillContext.cs +++ b/OpenNest.Engine/Strategies/FillContext.cs @@ -22,6 +22,12 @@ namespace OpenNest.Engine.Strategies /// many (see ). Zero fills the whole work area. /// public int MaxQuantity { get; init; } + + /// + /// Whether the pairs phase also tries its grids with whole pairs only + /// (). + /// + public bool WholePairGrids { get; init; } = true; public PartType PartType { get; set; } /// diff --git a/OpenNest.Engine/Strategies/PairsFillStrategy.cs b/OpenNest.Engine/Strategies/PairsFillStrategy.cs index b3b8fbf5..f02e53f4 100644 --- a/OpenNest.Engine/Strategies/PairsFillStrategy.cs +++ b/OpenNest.Engine/Strategies/PairsFillStrategy.cs @@ -31,6 +31,7 @@ namespace OpenNest.Engine.Strategies var filler = new PairFiller(context.Plate, comparer, dedup) { StripeConvergence = StripeConvergenceCache.GetOrCreate(context.SharedState), + WholePairGrids = context.WholePairGrids, }; var result = filler.Fill( context.Item, diff --git a/docs/nesting-engines.md b/docs/nesting-engines.md index 11347b81..01e8ba9f 100644 --- a/docs/nesting-engines.md +++ b/docs/nesting-engines.md @@ -194,6 +194,31 @@ area, not their bounding box. An 8" gusset on a 16.85 x 60 strip fills 20 that w along their hypotenuse in an 8.75" column, and eight gussets at 45 degrees zigzagging up the strip beside it, against 14 in a 10.35" column of seven pairs. +A grid tops its last column or row up with the parts of a pair that does not fit whole, which can +fill a strip that would hold more parts. The pair turned 180 degrees has the same bounding box, so +the grid dedup never tiles it to leave that strip open. The pairs phase therefore also tiles each +pair grid with whole pairs only, after the others, and refills the strip it leaves; that grid wins +only by placing more parts. Only fills without a quantity (Fill Plate, Fill Area) try it: in a +capped fill, such as Auto Nest's, the grid that wins by a part can end the sheet later. The cutout +lattice turns it off: it shifts its fill and crops it to the hole, and a regular grid keeps more +parts through the crop than a fuller but irregular one. Best-fit pairs are found by pushing one part +against the other from cross offsets a step apart (0.25"), so a pair held by two contacts at once +lands up to a step short of the second. Each landed pair also slides across its push, both ways, to +the next contact less than a step away. Two columns of 30" J-shaped bars, stacked bar on bar with +each leg tucked past the other bar's end, take 64.9" of a 96" sheet that way rather than 65.3", +leaving a 30.2" strip, where Fill had placed 30. + +A strip's densest pair grid is also completed (`GridEndInserter`): the grid is moved to each corner +of the strip, copies of its parts slide in from the open sides at the position that strays least +outside the grid's band, then travel deepest, and the strip beyond is filled with singles and pairs +(without completing again). A completion replaces the strip's layout only when it places more. Each +slide pushes against every part of the grid, so positions are swept coarsely, then finely near the +best; a strip, a grid or a leftover strip is skipped when the parts its area could hold cannot beat +the best so far. Completing the three densest grids made a 60 x 120 sheet of small parts fill 23% +slower; one adds about 3%. The 30.2" strip above holds three bar pairs stood on end and one more bar +dropped 2.3" beside them so its leg passes under its neighbor's, with a pair lying under all seven: +33 parts, as laid out by hand. + Lattice's last strategy, TiltedRemnant, adds tilted parts beside the best layout when the room left past it on the right or top is too narrow for the part at 0 or 90 degrees, such as a long part beside a grid of the same part turned 90 degrees. It moves the layout flush to the low end