From 197a1ac760baab177eb58b93c5c7ddfc94c4cefe Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Sun, 29 Nov 2026 14:38:32 -0500 Subject: [PATCH] perf(fill): fill past the clamps first and skip pair grids that cannot win Interactive Fill on a plate with clamps took over five minutes on a 1240-part sheet. Every progress report certified all the parts again, and the pair phase checked grids for overlaps whose count could not beat the best so far. - Fill the clamp-free strip first, then the whole work area with clamp hits dropped; a tie keeps the strip layout. - Certify a preview only when its layout changed, and cache each part's material geometry for the certification. - Resolve a whole-pair grid only when its outcome can change a decision, and drop a candidate without sorting when none of its grids can beat the count to beat. Layouts are unchanged. Co-Authored-By: Claude Fable 5.2 --- .../Jobs/ClampZoneInteractiveFillTests.cs | 20 ++++ OpenNest.Engine/Fill/FillLinear.cs | 13 +++ OpenNest.Engine/Fill/PairFiller.cs | 46 ++++++-- OpenNest.Engine/Jobs/InteractiveClamps.cs | 94 ++++++++++------ .../Jobs/Placement/PlateFillService.cs | 104 +++++++++++++----- docs/nesting-engines.md | 19 ++-- 6 files changed, 211 insertions(+), 85 deletions(-) diff --git a/OpenNest.Engine.Tests/Jobs/ClampZoneInteractiveFillTests.cs b/OpenNest.Engine.Tests/Jobs/ClampZoneInteractiveFillTests.cs index 54d82994..03a2347c 100644 --- a/OpenNest.Engine.Tests/Jobs/ClampZoneInteractiveFillTests.cs +++ b/OpenNest.Engine.Tests/Jobs/ClampZoneInteractiveFillTests.cs @@ -340,6 +340,26 @@ public class ClampZoneInteractiveFillTests AssertClearOfClamps(parts, ZoneA, ZoneB); } + [Fact] + public void ClampedFillFillsPastTheClampStripFirst() + { + // The area past the clamps usually wins, so its layouts are previewed before the + // whole area's. + var plate = MakePlate(new ClampZone("front-1", ZoneA), new ClampZone("front-2", ZoneB)); + var item = new NestItem { Drawing = RectDrawing(4, 4) }; + var strip = PlateFillService.ClampFreeArea(plate, plate.WorkArea()); + var areas = new List(); + + PlateFillService.FillItem("Fill", plate, item, plate.WorkArea(), + new InlineProgress(update => areas.Add(update.ActiveWorkArea)), + CancellationToken.None); + + Assert.Equal(strip.Bottom, areas[0].Bottom, 9); + Assert.Contains(areas, area => System.Math.Abs(area.Bottom - plate.WorkArea().Bottom) < 1e-9); + var firstWhole = areas.FindIndex(area => area.Bottom < strip.Bottom - 1e-9); + Assert.All(areas.Take(firstWhole), area => Assert.Equal(strip.Bottom, area.Bottom, 9)); + } + [Fact] public void ClampFreeAreaMovesTheClampedEdgePastTheKeepOuts() { diff --git a/OpenNest.Engine/Fill/FillLinear.cs b/OpenNest.Engine/Fill/FillLinear.cs index 49364f74..8535669f 100644 --- a/OpenNest.Engine/Fill/FillLinear.cs +++ b/OpenNest.Engine/Fill/FillLinear.cs @@ -648,6 +648,19 @@ namespace OpenNest.Engine.Fill public int FallbackCount => fallbackCount ??= (1 + owner.BboxCopies(basePattern, axis)) * basePattern.Parts.Count; + /// + /// The two part lists can return while : + /// the tiling, and the bounding-box fallback built as Resolve builds it. A caller + /// that would discard either outcome can skip the check. Neither list is the + /// resolved one; the grid is unchanged. + /// + internal (List Tiling, List Fallback) PendingOutcomes() + { + var fallback = new List(basePattern.Parts); + fallback.AddRange(owner.TilePatternBbox(basePattern, axis)); + return (parts, fallback); + } + /// Runs the overlap check if it is pending and returns the grid's parts. public List Resolve() { diff --git a/OpenNest.Engine/Fill/PairFiller.cs b/OpenNest.Engine/Fill/PairFiller.cs index 2c88f3f4..1bbd3ef4 100644 --- a/OpenNest.Engine/Fill/PairFiller.cs +++ b/OpenNest.Engine/Fill/PairFiller.cs @@ -582,7 +582,7 @@ namespace OpenNest.Engine.Fill // 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 wholeGrids = new List(); var wholeEngine = new FillLinear(workArea, partSpacing) { Label = "Pairs", PartialCopies = false }; foreach (var (pattern, dir) in claimed) @@ -600,19 +600,21 @@ namespace OpenNest.Engine.Fill 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); + // partial copies, so it is that grid, already tried. Its overlap check + // runs here only when the answer depends on it. + var gridCount = grid.Count; + bool Smaller(int count) => count > 0 && count < gridCount; + var whole = wholeEngine.FillDeferred(pattern, dir); + if (whole.IsPending && Smaller(whole.Count) != Smaller(whole.FallbackCount)) + whole.Resolve(); + if (Smaller(whole.Count)) + wholeGrids.Add(whole); } } if (grids.Count == 0) return null; - // Sort by count descending so we try the best grids first - SortByCount(grids); - int Bound(List gridParts) => gridParts.Count + remnantFiller.EstimateUpperBound(gridParts, workArea, maxUtilization, partArea); @@ -628,10 +630,28 @@ namespace OpenNest.Engine.Fill return total; } + // Whether the grid, however its overlap check turns out, with an optimistic remnant + // still cannot place more than toBeat parts. + bool CannotBeat(FillLinear.DeferredGrid grid, int toBeat) + { + if (!grid.IsPending) + return Bound(grid.Resolve()) <= toBeat; + + var (tiling, fallback) = grid.PendingOutcomes(); + return Bound(tiling) <= toBeat && Bound(fallback) <= toBeat; + } + 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; + // Early abort: if the best grid + optimistic remnant can't beat the global best, skip + // Phase 2. When no grid can, whichever is the best cannot, and no check need run. + // Otherwise sort by count descending, so the best grids are tried first. + var noneCanWin = minCountToBeat > 0 && grids.All(grid => CannotBeat(grid, minCountToBeat)); + if (!noneCanWin) + SortByCount(grids); + + var topBound = noneCanWin ? minCountToBeat + : minCountToBeat > 0 ? Bound(grids[0].Resolve()) : int.MaxValue; if (topBound <= minCountToBeat) { Debug.WriteLine( @@ -659,11 +679,15 @@ namespace OpenNest.Engine.Fill // 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) + foreach (var whole in wholeGrids) { token.ThrowIfCancellationRequested(); var toBeat = System.Math.Max(best?.Count ?? 0, minCountToBeat); + if (CannotBeat(whole, toBeat)) + continue; + + var wholeParts = whole.Resolve(); if (Bound(wholeParts) <= toBeat) continue; diff --git a/OpenNest.Engine/Jobs/InteractiveClamps.cs b/OpenNest.Engine/Jobs/InteractiveClamps.cs index ceef138d..a4996b8c 100644 --- a/OpenNest.Engine/Jobs/InteractiveClamps.cs +++ b/OpenNest.Engine/Jobs/InteractiveClamps.cs @@ -107,43 +107,67 @@ internal static class InteractiveClamps /// holes subtracted against the keep-out rectangle, matching the C1 checker's verdict /// (positive-area overlap only - flush contact is clear). /// - public static bool MaterialInKeepOut(Part part, Box keepOut) - { - var partProfile = new ShapeProfile(PartGeometry.GetPartEntities(part)); - if (partProfile.Perimeter == null) - return true; - // A keep-out below the polygon tolerance collapses in the tolerant test and would - // read as clear (PM b0062c73); judge it tolerance-free instead. - if (KeepOutOverlap.NeedsToleranceFreeTest(keepOut)) - return KeepOutOverlap.ProfileEnters(partProfile, new Vector(0, 0), keepOut); - var zoneProfile = new ShapeProfile(RectangleEntities(keepOut)); - if (zoneProfile.Perimeter == null) - return true; - return Collision.HasOverlap( - partProfile.Perimeter.ToPolygonWithTolerance(0.001), - zoneProfile.Perimeter.ToPolygonWithTolerance(0.001), - HolePolygons(partProfile), - HolePolygons(zoneProfile)); - } + public static bool MaterialInKeepOut(Part part, Box keepOut) => + new PartMaterial(part).InKeepOut(keepOut); - public static bool MaterialsTooClose(Part first, Part second, double spacing) + public static bool MaterialsTooClose(Part first, Part second, double spacing) => + new PartMaterial(first).TooClose(new PartMaterial(second), spacing); + + /// + /// A part's material as the checks above read it, built once on first use. A certification + /// that tests one part against many neighbors holds one of these per part, so the part's + /// profile and polygons are not rebuilt for every pair. The part must not move or change + /// while this is in use. + /// + internal sealed class PartMaterial(Part part) { - var a = new ShapeProfile(PartGeometry.GetPartEntities(first)); - var b = new ShapeProfile(PartGeometry.GetPartEntities(second)); - if (a.Perimeter == null || b.Perimeter == null) - return true; - var outerA = a.Perimeter.ToPolygonWithTolerance(0.001); - var outerB = b.Perimeter.ToPolygonWithTolerance(0.001); - var holesA = HolePolygons(a); - var holesB = HolePolygons(b); - if (Collision.HasOverlap(outerA, outerB, holesA, holesB)) - return true; - if (spacing <= NestTolerances.SpacingSlack) - return false; - // The profiles are already in world space. Facets at the polygons' tolerance understate - // an arc gap by more than the slack, which would reject a pair placed at the spacing. - return NativeContours.Of(a, new Vector(0, 0)) - .TooClose(NativeContours.Of(b, new Vector(0, 0)), spacing); + private ShapeProfile profile; + private Polygon outer; + private List holes; + private NativeContours contours; + + private ShapeProfile Profile => profile ??= new ShapeProfile(PartGeometry.GetPartEntities(part)); + + private Polygon Outer => outer ??= Profile.Perimeter.ToPolygonWithTolerance(0.001); + + private List Holes => holes ??= HolePolygons(Profile) ?? NoHoles; + + private static readonly List NoHoles = new(); + + private static List HolesOrNull(List holes) => holes.Count == 0 ? null : holes; + + public bool InKeepOut(Box keepOut) + { + if (Profile.Perimeter == null) + return true; + // A keep-out below the polygon tolerance collapses in the tolerant test and would + // read as clear (PM b0062c73); judge it tolerance-free instead. + if (KeepOutOverlap.NeedsToleranceFreeTest(keepOut)) + return KeepOutOverlap.ProfileEnters(Profile, new Vector(0, 0), keepOut); + var zoneProfile = new ShapeProfile(RectangleEntities(keepOut)); + if (zoneProfile.Perimeter == null) + return true; + return Collision.HasOverlap( + Outer, + zoneProfile.Perimeter.ToPolygonWithTolerance(0.001), + HolesOrNull(Holes), + HolePolygons(zoneProfile)); + } + + public bool TooClose(PartMaterial other, double spacing) + { + if (Profile.Perimeter == null || other.Profile.Perimeter == null) + return true; + if (Collision.HasOverlap(Outer, other.Outer, HolesOrNull(Holes), HolesOrNull(other.Holes))) + return true; + if (spacing <= NestTolerances.SpacingSlack) + return false; + // The profiles are already in world space. Facets at the polygons' tolerance understate + // an arc gap by more than the slack, which would reject a pair placed at the spacing. + return Contours.TooClose(other.Contours, spacing); + } + + private NativeContours Contours => contours ??= NativeContours.Of(Profile, new Vector(0, 0)); } private static List HolePolygons(ShapeProfile profile) diff --git a/OpenNest.Engine/Jobs/Placement/PlateFillService.cs b/OpenNest.Engine/Jobs/Placement/PlateFillService.cs index ab27fdb6..3aabeeab 100644 --- a/OpenNest.Engine/Jobs/Placement/PlateFillService.cs +++ b/OpenNest.Engine/Jobs/Placement/PlateFillService.cs @@ -53,8 +53,8 @@ public static partial class PlateFillService if (!InteractiveClamps.HasZones(plate)) return filler.Fill(item, workArea, progress, token); - // Two clamp-clear layouts compete: the area filled as if the clamps were absent less - // the parts that hit one, and the area trimmed past the clamps' edge strip. + // Two clamp-clear layouts compete: the area trimmed past the clamps' edge strip, and + // the area filled as if the clamps were absent less the parts that hit one. var demand = new List { item }; return FillBesideClamps(filler, plate, workArea, progress, token, (area, sink) => FillDroppingClampHits( @@ -262,24 +262,28 @@ public static partial class PlateFillService } /// - /// Fills ignoring the clamps and drops the parts that hit one - /// (a layout packed around the clamps is usually worse). When every clamp in the area lies - /// on one edge, also fills the area with that edge moved past them, as a larger edge - /// spacing would, and keeps the better layout by the filler's own ranking; a tie keeps the - /// first. Previews never fall below the layout already found. + /// When every clamp in lies on one edge, fills the area with that + /// edge moved past them first, as a larger edge spacing would: that layout usually wins, so + /// its previews are the ones worth accepting early. Then fills the whole area ignoring the + /// clamps and drops the parts that hit one (a layout packed around the clamps is usually + /// worse), and keeps the better layout by the filler's own ranking; a tie keeps the first. + /// Previews never fall below the layout already found. /// private static List FillBesideClamps(PlateFiller filler, Plate plate, Box workArea, IProgress progress, CancellationToken token, Func, List> fill, List demand, int groupSize) { - var dropped = fill(workArea, ClearProgress(progress, plate, workArea, demand, groupSize, null, null)); var strip = ClampFreeArea(plate, workArea); - if (strip == null || token.IsCancellationRequested) - return dropped; + if (strip == null) + return fill(workArea, ClearProgress(progress, plate, workArea, demand, groupSize, null, null)); - var beside = fill(strip, ClearProgress(progress, plate, strip, demand, groupSize, - dropped, (candidate, current) => filler.IsBetterFill(candidate, current, workArea))); - return filler.IsBetterFill(beside, dropped, workArea) ? beside : dropped; + var beside = fill(strip, ClearProgress(progress, plate, strip, demand, groupSize, null, null)); + if (token.IsCancellationRequested) + return beside; + + var dropped = fill(workArea, ClearProgress(progress, plate, workArea, demand, groupSize, + beside, (candidate, current) => filler.IsBetterFill(candidate, current, workArea))); + return filler.IsBetterFill(dropped, beside, workArea) ? dropped : beside; } /// @@ -441,10 +445,35 @@ public static partial class PlateFillService List demand, int groupSize, List floor, Func, List, bool> isBetter) : IProgress { + // A fill reports its best layout again with every step it finishes, mostly unchanged; + // certifying a full sheet takes far longer than the step, so the last answer is kept. + private (Drawing Drawing, Vector Location, double Rotation)[] lastPoses; + private List lastClear; + + private List Certify(List parts) + { + var count = parts?.Count ?? 0; + var same = lastPoses != null && lastPoses.Length == count; + for (var i = 0; same && i < count; i++) + same = ReferenceEquals(lastPoses[i].Drawing, parts[i].BaseDrawing) + && lastPoses[i].Location.X == parts[i].Location.X + && lastPoses[i].Location.Y == parts[i].Location.Y + && lastPoses[i].Rotation == parts[i].Rotation; + if (same) + return lastClear; + + var clear = new List(); + AddClear(clear, parts, plate, area, demand, groupSize: groupSize); + lastPoses = new (Drawing, Vector, double)[count]; + for (var i = 0; i < count; i++) + lastPoses[i] = (parts[i].BaseDrawing, parts[i].Location, parts[i].Rotation); + lastClear = clear; + return clear; + } + public void Report(NestProgress value) { - var clear = new List(); - AddClear(clear, value.BestParts, plate, area, demand, groupSize: groupSize); + var clear = Certify(value.BestParts); if (clear.Count == 0) return; inner.Report(new NestProgress @@ -522,6 +551,7 @@ public static partial class PlateFillService { if (proposed == null || groupSize < 1) return; + var materials = new MaterialCache(); // FillLinear may append an incomplete trailing tile. Keep complete copies // ahead of it, but never expose the incomplete tail as a group. for (var start = 0; start + groupSize <= proposed.Count; start += groupSize) @@ -532,7 +562,7 @@ public static partial class PlateFillService for (var index = start; index < start + groupSize; index++) { if (!TryAddClear(batch, proposed[index], accepted, plate, area, - demand, previouslyPlaced)) + demand, previouslyPlaced, materials)) break; } if (batch.Count == groupSize) @@ -541,7 +571,8 @@ public static partial class PlateFillService } private static bool TryAddClear(List batch, Part part, List accepted, - Plate plate, Box area, List demand, List previouslyPlaced) + Plate plate, Box area, List demand, List previouslyPlaced, + MaterialCache materials) { var bounds = part.BoundingBox; var full = plate.WorkArea(); @@ -565,26 +596,39 @@ public static partial class PlateFillService ReferenceEquals(p.BaseDrawing, item.Drawing)) + batch.Count(p => ReferenceEquals(p.BaseDrawing, item.Drawing)) < item.Quantity))) return false; + var material = materials.Of(part); if (InteractiveClamps.ValidationKeepOuts(plate).Any(zone => - Overlaps(bounds, zone) && InteractiveClamps.MaterialInKeepOut(part, zone))) + Overlaps(bounds, zone) && material.InKeepOut(zone))) return false; - if (plate.Parts.Any(existing => !existing.BaseDrawing.IsCutOff && - Overlaps(bounds, existing.BoundingBox.Offset(plate.PartSpacing)) - && InteractiveClamps.MaterialsTooClose(part, existing, plate.PartSpacing)) - || accepted.Any(existing => Overlaps(bounds, - existing.BoundingBox.Offset(plate.PartSpacing)) - && InteractiveClamps.MaterialsTooClose(part, existing, plate.PartSpacing)) - || batch.Any(existing => Overlaps(bounds, - existing.BoundingBox.Offset(plate.PartSpacing)) - && InteractiveClamps.MaterialsTooClose(part, existing, plate.PartSpacing)) - || (previouslyPlaced?.Any(existing => Overlaps(bounds, - existing.BoundingBox.Offset(plate.PartSpacing)) - && InteractiveClamps.MaterialsTooClose(part, existing, plate.PartSpacing)) ?? false)) + var reach = bounds.Offset(plate.PartSpacing); + bool TooClose(Part existing) => Overlaps(reach, existing.BoundingBox) + && material.TooClose(materials.Of(existing), plate.PartSpacing); + if (plate.Parts.Any(existing => !existing.BaseDrawing.IsCutOff && TooClose(existing)) + || accepted.Any(TooClose) + || batch.Any(TooClose) + || (previouslyPlaced?.Any(TooClose) ?? false)) return false; batch.Add(part); return true; } + /// + /// The material of each part one certification reads (), + /// by part identity. It lives for that certification only: the parts must not move meanwhile. + /// + private sealed class MaterialCache + { + private readonly Dictionary materials = + new(ReferenceEqualityComparer.Instance); + + public InteractiveClamps.PartMaterial Of(Part part) + { + if (!materials.TryGetValue(part, out var material)) + materials.Add(part, material = new InteractiveClamps.PartMaterial(part)); + return material; + } + } + private static bool Overlaps(Box a, Box b) => a.Left < b.Right && a.Right > b.Left && a.Bottom < b.Top && a.Top > b.Bottom; diff --git a/docs/nesting-engines.md b/docs/nesting-engines.md index eaf179a5..40d2768c 100644 --- a/docs/nesting-engines.md +++ b/docs/nesting-engines.md @@ -244,15 +244,16 @@ spacing fills 180 in ten staggered rows of 18 with 2.7 inches above the top row. row straight over the one below opens a notch at its end where one more hexagon nests, so the plate holds 181. -On a plate with clamps, interactive Fill (Fill Area and filling from a part) fills as if the -clamps were absent, then drops every part that enters a clamp keep-out or sits too close to an -existing part, and a whole copy of a multi-part group when any member does. Packing around -the clamps usually gives a worse layout than losing the few parts on them. When every clamp -in the fill area lies on one edge, Fill also fills the area with that edge moved just past the -clamp keep-outs, as a larger edge spacing would, and keeps whichever layout the strategy ranks -better (a tie keeps the dropped-parts layout). Small parts usually win by dropping, large -parts by moving past the strip. The second fill reuses the cached best-fit pairs. Progress -previews are filtered by the same check and never fall below the first layout, so a preview +On a plate with clamps, interactive Fill (Fill Area and filling from a part) runs up to two +fills and keeps whichever layout the strategy ranks better (a tie keeps the first). When every +clamp in the fill area lies on one edge, the first fills the area with that edge moved just +past the clamp keep-outs, as a larger edge spacing would; it usually wins, so its previews are +the ones worth accepting early. The second fills as if the clamps were absent, then drops every +part that enters a clamp keep-out or sits too close to an existing part, and a whole copy of a +multi-part group when any member does: packing around the clamps usually gives a worse layout +than losing the few parts on them. With clamps on more than one edge only that fill runs. The +second fill reuses the cached best-fit pairs. Progress previews are filtered by the same check +(an unchanged preview is not checked again) and never fall below the first layout, so a preview accepted early is clamp-clear. When a quantity is requested and copies were dropped, the fill asks for that many more, up to two more times. Pack and interactive whole-plate Nest still pack only into the clamp-free areas.