diff --git a/OpenNest.Engine.Tests/Jobs/FillStackCharacterizationTests.cs b/OpenNest.Engine.Tests/Jobs/FillStackCharacterizationTests.cs index 17f7f355..2f32dcbf 100644 --- a/OpenNest.Engine.Tests/Jobs/FillStackCharacterizationTests.cs +++ b/OpenNest.Engine.Tests/Jobs/FillStackCharacterizationTests.cs @@ -194,16 +194,16 @@ public class FillStackCharacterizationTests // --- interactive single-item fill --- [Theory] - [InlineData("Fill", "lshape", 52, "F1FB09254D935531")] + [InlineData("Fill", "lshape", 53, "C215C11EEBD3B59C")] [InlineData("Fill", "notched", 46, "32FB33C3C19FDCC8")] [InlineData("Fill", "arc", 40, "4E2F91AA3151E9E7")] - [InlineData("Strip", "lshape", 52, "F1FB09254D935531")] + [InlineData("Strip", "lshape", 53, "C215C11EEBD3B59C")] [InlineData("Strip", "notched", 46, "32FB33C3C19FDCC8")] [InlineData("Strip", "arc", 40, "4E2F91AA3151E9E7")] - [InlineData("Vertical Remnant", "lshape", 52, "F1FB09254D935531")] + [InlineData("Vertical Remnant", "lshape", 53, "C215C11EEBD3B59C")] [InlineData("Vertical Remnant", "notched", 46, "32FB33C3C19FDCC8")] [InlineData("Vertical Remnant", "arc", 40, "BBC5C583C3C7A9A7")] - [InlineData("Horizontal Remnant", "lshape", 52, "F1FB09254D935531")] + [InlineData("Horizontal Remnant", "lshape", 53, "C215C11EEBD3B59C")] [InlineData("Horizontal Remnant", "notched", 46, "32FB33C3C19FDCC8")] [InlineData("Horizontal Remnant", "arc", 40, "4E2F91AA3151E9E7")] public void FillItem_IrregularPart_PinnedLayout( diff --git a/OpenNest.Engine/Fill/PairFiller.cs b/OpenNest.Engine/Fill/PairFiller.cs index a585808b..c50323a9 100644 --- a/OpenNest.Engine/Fill/PairFiller.cs +++ b/OpenNest.Engine/Fill/PairFiller.cs @@ -99,7 +99,7 @@ namespace OpenNest.Engine.Fill this.comparer = comparer ?? new DefaultFillComparer(); this.dedup = dedup ?? new GridDedup(); this.candidateSelector = new PairCandidateSelector(plateSize, partSpacing); - this.remnantFiller = new PairRemnantFiller(partSpacing, this.comparer); + this.remnantFiller = new PairRemnantFiller(plate, this.comparer); } /// @@ -152,6 +152,7 @@ namespace OpenNest.Engine.Fill item.Drawing, workArea, targetCount, + bestFits, token, reportProgress ); @@ -174,6 +175,7 @@ namespace OpenNest.Engine.Fill Drawing drawing, Box workArea, int targetCount, + List bestFits, CancellationToken token, Action, string> reportProgress ) @@ -202,6 +204,7 @@ namespace OpenNest.Engine.Fill best?.Count ?? 0, maxUtilization, partArea, + bestFits, token ); @@ -244,6 +247,7 @@ namespace OpenNest.Engine.Fill int minCountToBeat, double maxUtilization, double partArea, + List bestFits, CancellationToken token ) { @@ -272,6 +276,7 @@ namespace OpenNest.Engine.Fill minCountToBeat, maxUtilization, partArea, + bestFits, token ); } @@ -410,6 +415,7 @@ namespace OpenNest.Engine.Fill /// The minCountToBeat /// The maxUtilization /// The partArea + /// The pairs the remnant strips are also filled with /// The token /// The private List EvaluateCandidate( @@ -419,6 +425,7 @@ namespace OpenNest.Engine.Fill int minCountToBeat, double maxUtilization, double partArea, + List bestFits, CancellationToken token ) { @@ -479,7 +486,7 @@ namespace OpenNest.Engine.Fill break; // sorted descending, so remaining are even smaller } - var remnantParts = remnantFiller.Fill(gridParts, drawing, workArea, token); + var remnantParts = remnantFiller.Fill(gridParts, drawing, workArea, token, bestFits); List total; if (remnantParts != null && remnantParts.Count > 0) { diff --git a/OpenNest.Engine/Fill/PairRemnantFiller.cs b/OpenNest.Engine/Fill/PairRemnantFiller.cs index 4ae1791a..b5c5bf30 100644 --- a/OpenNest.Engine/Fill/PairRemnantFiller.cs +++ b/OpenNest.Engine/Fill/PairRemnantFiller.cs @@ -1,6 +1,9 @@ +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; +using System.Linq; using System.Threading; +using OpenNest.Engine.BestFit; using OpenNest.Engine.Strategies; using OpenNest.Geometry; using OpenNest.Math; @@ -9,12 +12,22 @@ namespace OpenNest.Engine.Fill { /// /// Fills the leftover L-shaped area (top strip + right strip) around a pair grid - /// with the same drawing, caching results by drawing/box/spacing. + /// with the same drawing. Each strip is tried with single parts at 0 and 90 degrees and, + /// when a plate and best-fit pairs are given, with rows of pairs as the Row and Column + /// strategies lay them: a narrow strip can hold twice as many parts as pairs. /// public class PairRemnantFiller { private readonly double partSpacing; private readonly IFillComparer comparer; + private readonly Plate plate; + + /// + /// 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 = + new(); public PairRemnantFiller(double partSpacing, IFillComparer comparer) { @@ -22,6 +35,12 @@ namespace OpenNest.Engine.Fill this.comparer = comparer; } + public PairRemnantFiller(Plate plate, IFillComparer comparer) + : this(plate.PartSpacing, comparer) + { + this.plate = plate; + } + public int EstimateUpperBound( List gridParts, Box workArea, @@ -46,7 +65,8 @@ namespace OpenNest.Engine.Fill List gridParts, Drawing drawing, Box workArea, - CancellationToken token + CancellationToken token, + List bestFits = null ) { var gridBox = ((IEnumerable)gridParts).GetBoundingBox(); @@ -61,7 +81,7 @@ namespace OpenNest.Engine.Fill if (topLength >= minDim) { var topBox = new Box(workArea.X, topY, workArea.Length, topLength); - var parts = FillRemnantBox(drawing, topBox, token); + var parts = FillRemnantBox(drawing, topBox, bestFits, token); if (parts != null && parts.Count > (bestRemnant?.Count ?? 0)) bestRemnant = parts; } @@ -72,7 +92,7 @@ namespace OpenNest.Engine.Fill if (rightWidth >= minDim) { var rightBox = new Box(rightX, workArea.Y, rightWidth, workArea.Width); - var parts = FillRemnantBox(drawing, rightBox, token); + var parts = FillRemnantBox(drawing, rightBox, bestFits, token); if (parts != null && parts.Count > (bestRemnant?.Count ?? 0)) bestRemnant = parts; } @@ -80,7 +100,28 @@ namespace OpenNest.Engine.Fill return bestRemnant; } - private List FillRemnantBox(Drawing drawing, Box remnantBox, CancellationToken token) + private List FillRemnantBox( + Drawing drawing, + Box remnantBox, + List bestFits, + CancellationToken token + ) + { + var singles = FillSingles(drawing, remnantBox, token); + if (bestFits == null || plate == null) + return singles; + + // No layout holds more parts than the strip has room for by area. + var singleCount = singles?.Count ?? 0; + if (drawing.Area > 0 && singleCount + 1 > remnantBox.Area() / drawing.Area) + return singles; + + // Pairs replace the singles only when they place more; a tie keeps the singles. + var pairs = FillPairs(drawing, remnantBox, bestFits, token); + return pairs != null && pairs.Count > (singles?.Count ?? 0) ? pairs : singles; + } + + private List FillSingles(Drawing drawing, Box remnantBox, CancellationToken token) { var cachedResult = FillResultCache.Get(drawing, remnantBox, partSpacing); if (cachedResult != null) @@ -119,5 +160,65 @@ namespace OpenNest.Engine.Fill return null; } + + /// + /// 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. + /// + private List FillPairs( + Drawing drawing, + Box remnantBox, + List bestFits, + CancellationToken token + ) + { + var key = ( + System.Math.Round(remnantBox.Width, 6), + System.Math.Round(remnantBox.Length, 6) + ); + 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(); + pairStrips.TryAdd(key, normalized); + } + + if (normalized.Count == 0) + return null; + + var offset = remnantBox.Location; + return normalized.Select(p => p.CloneAtOffset(offset)).ToList(); + } + + /// + /// Fills the strip as the Row and Column strategies do: rows of pairs turned so a whole + /// number of them spans the strip, then singles beyond them. + /// + private List ComputePairs( + Drawing drawing, + Box area, + List bestFits, + CancellationToken token + ) + { + var context = new FillContext + { + Item = new NestItem { Drawing = drawing }, + WorkArea = area, + Plate = plate, + Token = token, + Policy = new FillPolicy(comparer), + }; + context.SharedState["BestFits"] = bestFits; + + // The stripe filler lays rows along both axes itself; its axis only names it. + var best = new StripeFiller(context, NestDirection.Horizontal).Fill(); + + Debug.WriteLine( + $"[PairFiller] Remnant pairs: {best?.Count ?? 0} parts in " + + $"{area.Width:F2}x{area.Length:F2}" + ); + return best; + } } } diff --git a/OpenNest.Tests/Fill/PairRemnantFillerTests.cs b/OpenNest.Tests/Fill/PairRemnantFillerTests.cs new file mode 100644 index 00000000..56a0653a --- /dev/null +++ b/OpenNest.Tests/Fill/PairRemnantFillerTests.cs @@ -0,0 +1,80 @@ +using OpenNest.Engine; +using OpenNest.Engine.BestFit; +using OpenNest.Engine.Fill; +using OpenNest.Geometry; +using OpenNest.Math; + +namespace OpenNest.Tests.Fill; + +public class PairRemnantFillerTests +{ + private const double Spacing = 0.25; + + private static Drawing MakeTriangleDrawing() => + new("triangle", TestHelpers.MakeClosedProgram( + new[] { new Vector(0, 0), new Vector(10, 0), new Vector(0, 4), new Vector(0, 0) })); + + /// + /// A pair grid ending 5.5 short of the work area's right edge and reaching its top, so only + /// the narrow right strip is left: one single fits across it, a pair of triangles laid as a + /// rectangle fits too, and pairs hold twice as many. + /// + private static (List Grid, Box WorkArea) GridLeavingNarrowStrip(Drawing drawing) + { + var workArea = new Box(0, 0, 21, 50); + var low = Part.CreateAtOrigin(drawing); + var high = Part.CreateAtOrigin(drawing); + high.Offset(new Vector(5.25, 46)); + high.UpdateBounds(); + return (new List { low, high }, workArea); + } + + [Fact] + public void Fill_NarrowStrip_PlacesRowsOfPairsWhenTheyHoldMore() + { + var drawing = MakeTriangleDrawing(); + var plate = new Plate { Size = new Size(60, 120), PartSpacing = Spacing }; + var bestFits = BestFitCache.GetOrCompute(drawing, 120, 60, Spacing); + var (grid, workArea) = GridLeavingNarrowStrip(drawing); + FillResultCache.Clear(); + + var singles = new PairRemnantFiller(Spacing, new DefaultFillComparer()) + .Fill(grid, drawing, workArea, CancellationToken.None); + var withPairs = new PairRemnantFiller(plate, new DefaultFillComparer()) + .Fill(grid, drawing, workArea, CancellationToken.None, bestFits); + + Assert.NotNull(singles); + Assert.NotNull(withPairs); + Assert.True(withPairs.Count > singles.Count, + $"pairs placed {withPairs.Count}, singles {singles.Count}"); + + var stripLeft = grid.Max(p => p.BoundingBox.Right) + Spacing; + foreach (var part in withPairs) + { + Assert.True(part.BoundingBox.Left >= stripLeft - Tolerance.Epsilon); + Assert.True(part.BoundingBox.Right <= workArea.Right + Tolerance.Epsilon); + Assert.True(part.BoundingBox.Bottom >= workArea.Bottom - Tolerance.Epsilon); + Assert.True(part.BoundingBox.Top <= workArea.Top + Tolerance.Epsilon); + } + + var check = new Plate { Size = new Size(60, 120), PartSpacing = Spacing }; + check.Parts.AddRange(withPairs); + Assert.False(check.HasOverlappingParts(out _)); + } + + [Fact] + public void Fill_WithoutBestFits_KeepsSingles() + { + var drawing = MakeTriangleDrawing(); + var plate = new Plate { Size = new Size(60, 120), PartSpacing = Spacing }; + var (grid, workArea) = GridLeavingNarrowStrip(drawing); + FillResultCache.Clear(); + + var singles = new PairRemnantFiller(Spacing, new DefaultFillComparer()) + .Fill(grid, drawing, workArea, CancellationToken.None); + var noPairs = new PairRemnantFiller(plate, new DefaultFillComparer()) + .Fill(grid, drawing, workArea, CancellationToken.None); + + Assert.Equal(singles?.Count ?? 0, noPairs?.Count ?? 0); + } +} diff --git a/docs/nesting-engines.md b/docs/nesting-engines.md index 29fdfaaf..be1fe8a3 100644 --- a/docs/nesting-engines.md +++ b/docs/nesting-engines.md @@ -16,7 +16,7 @@ in `OpenNest.Engine/NestingEngines//`, its tests in `OpenNest.Engine.Tests | Circles | Round parts: blanks, washers, flanges, gears by their tip circle | Each part packed as its minimum enclosing circle at centers tangent to two of walls, placed discs and clamp keep-outs, with hexagonal and square lattice seeds; bids only when every part is round; stock chosen as Rectangles does, plus whole-job runs preferring each stock and a tail re-plan | | Irregular | Irregular profiles | No-fit-polygon frontier packing with gap filling and best-fit pairs, six whole-job strategy variants and a tail re-plan, then grouped variants that pack like parts together, then a sheet-reduction pass that packs edge parts first and turns a key part by its contacts; under a time limit it keeps trying seeded variants until the limit | | FlatBar | Flat bar: parts about as wide as the bar | Each stock read as a bar and cut in one row: the CutList cut-list packer and a best-fill search on part lengths less their self-nesting gain, then a slide-left pass that nests shaped ends and refills freed length; stock chosen bar by bar by whole-plan cost | -| Lattice, Strip, Vertical Remnant, Horizontal Remnant | Many copies of a few parts | The fixed placement strategies behind interactive fill; Lattice is the multi-phase lattice fill (linear, pairs, rectangle best-fit, remainder), and the remnant strategies run it ranked to keep the largest drop. In whole jobs, all four place a plate with any fixed or bounded part rotation by the rotation-aware ordered placer instead | +| Lattice, Strip, Vertical Remnant, Horizontal Remnant | Many copies of a few parts | The fixed placement strategies behind interactive fill; Lattice is the multi-phase lattice fill (linear, pairs, rectangle best-fit, remainder; the pairs phase fills the strip its grid leaves with rows of pairs when they hold more than single parts), and the remnant strategies run it ranked to keep the largest drop. In whole jobs, all four place a plate with any fixed or bounded part rotation by the rotation-aware ordered placer instead | Each engine's plain description (`NestingEngineInfo.Description`) is shown beside its name in the desktop engine lists. The main-window selection also picks Fill Area's strategy; a selection that