diff --git a/OpenNest.Engine.Tests/Jobs/Cutouts/CutoutBoxProposalTests.cs b/OpenNest.Engine.Tests/Jobs/Cutouts/CutoutBoxProposalTests.cs
new file mode 100644
index 00000000..044a106e
--- /dev/null
+++ b/OpenNest.Engine.Tests/Jobs/Cutouts/CutoutBoxProposalTests.cs
@@ -0,0 +1,173 @@
+using Clipper2Lib;
+using OpenNest.CNC;
+using OpenNest.Engine.Jobs;
+using OpenNest.Engine.Jobs.Cutouts;
+using OpenNest.Engine.Tests.NestingEngines;
+using Xunit.Abstractions;
+using TestShapes = OpenNest.Engine.Tests.NestingEngines.Shapes;
+
+namespace OpenNest.Engine.Tests.Jobs.Cutouts;
+
+/// A rectangular hole solved as a knapsack of boxes, then gap-filled.
+public class CutoutBoxProposalTests
+{
+ private const double Spacing = 0.25;
+ private const double HoleWidth = 22.25;
+ private const double HoleHeight = 14.85;
+
+ private readonly ITestOutputHelper output;
+
+ public CutoutBoxProposalTests(ITestOutputHelper output) => this.output = output;
+
+ private static NestJobPart HoleFrame(double width = HoleWidth, double height = HoleHeight)
+ {
+ var program = TestShapes.Rectangle(width + 4, height + 4);
+ program.MoveTo(2, 2);
+ program.LineTo(2, 2 + height);
+ program.LineTo(2 + width, 2 + height);
+ program.LineTo(2 + width, 2);
+ program.LineTo(2, 2);
+ return JobBuilder.Part("frame", program, 1);
+ }
+
+ private static NestJobPart Box(string id, double w, double h, int count) =>
+ JobBuilder.Part(id, TestShapes.Rectangle(w, h), count, RotationPolicy.Automatic);
+
+ private static NestJobPart Wedge(string id, double w, double h, int count) =>
+ JobBuilder.Part(id, TestShapes.Polyline((0, 0), (w, 0), (0, h)), count, RotationPolicy.Automatic);
+
+ private static NestJobPart[] Rectangles() => new[]
+ {
+ Box("a", 19.12, 12, 1), Box("b", 16.81, 12.38, 1), Box("c", 15.86, 12.38, 1),
+ Box("d", 18.5, 9.3, 4), Box("e", 14.62, 7.62, 1), Box("f", 17.88, 6.05, 2),
+ Box("g", 13.75, 7.62, 1), Box("h", 16.81, 5.26, 1), Box("i", 21.5, 4.06, 8),
+ Box("j", 21, 4.06, 1), Box("k", 12.62, 6.56, 2), Box("l", 15.62, 4.06, 2),
+ Box("m", 13.5, 4.06, 2), Box("n", 11.75, 3, 1),
+ };
+
+ private static NestJobPart[] Triangles() => new[]
+ {
+ Wedge("t", 12.25, 6, 1), Wedge("u", 7.88, 7.88, 2), Wedge("v", 12.5, 3.9, 2),
+ Wedge("w", 5, 5, 1), Wedge("x", 4.5, 4.5, 4), Wedge("y", 5.75, 2.75, 4),
+ };
+
+ private static double Area(IEnumerable poses, IEnumerable parts)
+ {
+ var geometry = parts.ToDictionary(p => p.Id, p => JobPartGeometry.Read(p.Geometry));
+ return CutoutBoxProposal.OutlineArea(poses, id => geometry[id]);
+ }
+
+ private static void AssertClear(NestJobPart frame, IReadOnlyList parts,
+ IReadOnlyList poses)
+ {
+ var geometry = parts.ToDictionary(p => p.Id, p => JobPartGeometry.Read(p.Geometry));
+ var frameGeometry = JobPartGeometry.Read(frame.Geometry);
+ var framePose = new NestJobPlacement(frame.Id, 0, 0, 0, 0);
+ foreach (var pose in poses)
+ Assert.True(NestLayoutCheck.Clears(frameGeometry, framePose, geometry[pose.PartId], pose, Spacing),
+ $"{pose} meets the frame");
+ for (var i = 0; i < poses.Count; i++)
+ for (var j = i + 1; j < poses.Count; j++)
+ Assert.True(NestLayoutCheck.Clears(geometry[poses[i].PartId], poses[i],
+ geometry[poses[j].PartId], poses[j], Spacing), $"{poses[i]} meets {poses[j]}");
+ foreach (var part in parts)
+ {
+ var mine = poses.Where(p => p.PartId == part.Id).Select(p => p.InstanceIndex).ToArray();
+ Assert.True(mine.Length <= part.Quantity, $"{part.Id} over demand");
+ Assert.Equal(Enumerable.Range(0, mine.Length), mine);
+ }
+ }
+
+ [Fact]
+ public void RectanglesFillTheHoleLikeAKnapsack()
+ {
+ var frame = HoleFrame();
+ var parts = Rectangles();
+ var poses = CutoutBoxProposal.Fill(frame, 0, parts, Spacing);
+ var area = Area(poses, parts);
+ output.WriteLine($"rectangles: {area:F1} of {HoleWidth * HoleHeight:F1}, {string.Join(" ", poses.Select(p => p.PartId))}");
+ AssertClear(frame, parts, poses);
+ Assert.True(area >= 0.84 * HoleWidth * HoleHeight, $"seated {area:F1}");
+ }
+
+ [Fact]
+ public void MixedInsertsFillTheHole()
+ {
+ var frame = HoleFrame();
+ var parts = Rectangles().Concat(Triangles()).ToArray();
+ var poses = CutoutBoxProposal.Fill(frame, 0, parts, Spacing);
+ var area = Area(poses, parts);
+ output.WriteLine($"mixed: {area:F1} of {HoleWidth * HoleHeight:F1}, {string.Join(" ", poses.Select(p => p.PartId))}");
+ AssertClear(frame, parts, poses);
+ Assert.True(area >= 0.84 * HoleWidth * HoleHeight, $"seated {area:F1}");
+ }
+
+ [Fact]
+ public void TrianglesPairIntoBoxes()
+ {
+ var frame = HoleFrame(8.5, 8.5);
+ var wedge = Wedge("t", 7.5, 7.5, 2);
+ var poses = CutoutBoxProposal.Fill(frame, 0, new[] { wedge }, Spacing);
+ Assert.Equal(2, poses.Count);
+ AssertClear(frame, new[] { wedge }, poses);
+ }
+
+ [Fact]
+ public void RouterTakesTheBoxProposalWhenItSeatsMoreArea()
+ {
+ var frame = HoleFrame();
+ var parts = Rectangles();
+ var routed = CutoutRouter.Fill(frame, 0, parts, Spacing);
+ var boxed = CutoutBoxProposal.Fill(frame, 0, parts, Spacing);
+ output.WriteLine($"router {Area(routed, parts):F1}, boxes {Area(boxed, parts):F1}");
+ AssertClear(frame, parts, routed);
+ Assert.True(Area(routed, parts) >= Area(boxed, parts) - 1e-6);
+ }
+
+ [Fact]
+ public void SameInputGivesTheSameLayout()
+ {
+ var frame = HoleFrame();
+ var parts = Rectangles();
+ Assert.Equal(CutoutBoxProposal.Fill(frame, 0, parts, Spacing), CutoutBoxProposal.Fill(frame, 0, parts, Spacing));
+ }
+
+ [Fact]
+ public void QuantityAndRotationPolicyAreRespected()
+ {
+ var frame = HoleFrame();
+ var fixedBar = JobBuilder.Rectangle("bar", 4, 13, 3, RotationPolicy.Fixed(0));
+ var poses = CutoutBoxProposal.Fill(frame, 0, new[] { fixedBar }, Spacing);
+ Assert.Equal(3, poses.Count);
+ Assert.All(poses, p => Assert.Equal(0, p.Rotation));
+ AssertClear(frame, new[] { fixedBar }, poses);
+ }
+
+ [Fact]
+ public void RoundHoleIsNotARectangle()
+ {
+ var frame = JobBuilder.Part("frame", TestShapes.Ring(30, 20), 1);
+ Assert.Empty(CutoutBoxProposal.Fill(frame, 0, new[] { Box("a", 5, 5, 2) }, Spacing));
+ }
+
+ [Fact]
+ public void RoundedCornersCostAFractionOfTheirRadius()
+ {
+ const double radius = 0.25;
+ var hole = new PathD();
+ for (var corner = 0; corner < 4; corner++)
+ {
+ var cx = corner is 0 or 3 ? 20 - radius : radius;
+ var cy = corner < 2 ? 10 - radius : radius;
+ for (var step = 0; step <= 12; step++)
+ {
+ var angle = (corner + step / 12.0) * System.Math.PI / 2;
+ hole.Add(new PointD(cx + radius * System.Math.Cos(angle), cy + radius * System.Math.Sin(angle)));
+ }
+ }
+ var rectangle = CutoutBoxProposal.InscribedRectangle(hole);
+ Assert.NotNull(rectangle);
+ Assert.InRange(rectangle.Value.W, 20 - 2 * 0.45 * radius, 20);
+ Assert.InRange(rectangle.Value.H, 10 - 2 * 0.45 * radius, 10);
+ }
+}
diff --git a/OpenNest.Engine/Jobs/Cutouts/CutoutBoxProposal.cs b/OpenNest.Engine/Jobs/Cutouts/CutoutBoxProposal.cs
new file mode 100644
index 00000000..f1f4e2a8
--- /dev/null
+++ b/OpenNest.Engine/Jobs/Cutouts/CutoutBoxProposal.cs
@@ -0,0 +1,456 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using Clipper2Lib;
+using OpenNest.Engine.NestingEngines.Rectangles;
+using OpenNest.Engine.RectanglePacking;
+using OpenNest.Geometry;
+using OpenNest.Math;
+
+namespace OpenNest.Engine.Jobs.Cutouts;
+
+///
+/// Frame-local proposal for a rectangular cutout, solved the way a person would: a small knapsack
+/// over which inserts to take, packed as boxes. A counted beam search over maximal free rectangles
+/// picks insert copies at their minimum-area rotation and its quarter turn, plus a part and its half
+/// turn slid together when that box is clearly denser, to maximize seated outline area.
+/// then drops the remaining demand into what is left. Every pose
+/// is certified with . Deterministic; never changes a job.
+///
+internal static class CutoutBoxProposal
+{
+ private const double MaxSpacing = 100;
+
+ /// Hole area over bounding-box area below which a hole is not a rectangle.
+ private const double MinRectangularity = 0.97;
+
+ /// Inscribed rectangle area over hole area below which a notch has ruined it.
+ private const double MinInscribed = 0.8;
+
+ /// Points per edge when finding what intrudes on the rectangle; catches a chamfer.
+ private const int EdgeSamples = 16;
+
+ private const double InsideTolerance = 1e-9;
+
+ private const int BeamWidth = 150;
+
+ /// Search states expanded per pass: the bound on the search, independent of time.
+ private const int NodesPerPass = 6000;
+
+ /// Best distinct insert selections certified and gap-filled.
+ private const int PlansTried = 3;
+
+ /// A part denser than this in its box is not worth pairing.
+ private const double MaxPairedDensity = 0.8;
+
+ private const double MinPairGain = 0.05;
+ private const int SlideSteps = 12;
+
+ /// One way of searching: anchor order, and how much of the free space the ranking
+ /// expects to fill. A lean guess favors dense early choices, a full one keeps options open.
+ private static readonly (bool Columns, double Density)[] Passes =
+ {
+ (false, 0.85), (true, 0.85), (false, 0.6), (true, 0.6),
+ };
+
+ /// A box the search can place: one copy or a pair. Width and Height carry the part
+ /// spacing; each member's pose is relative to the box's lower-left corner.
+ private sealed record Item(int Type, int Copies, double Width, double Height, double Area,
+ (double X, double Y, double Rotation)[] Members);
+
+ private sealed record State(IReadOnlyList Free, int[] Used, double Seated, double Rank,
+ State? Parent, Item? Item, double X, double Y);
+
+ /// Poses in the frame's own coordinates clearing the frame and each other; empty when
+ /// the hole is not a rectangle. Instance indices count per requirement.
+ internal static IReadOnlyList Fill(NestJobPart frame, int cutoutIndex,
+ IReadOnlyList inserts, double spacing, CutoutMemo? memo = null, CancellationToken token = default)
+ {
+ ArgumentNullException.ThrowIfNull(frame);
+ ArgumentNullException.ThrowIfNull(inserts);
+ token.ThrowIfCancellationRequested();
+ if (inserts.Count == 0 || !double.IsFinite(spacing) || spacing < 0 || spacing > MaxSpacing)
+ return Array.Empty();
+ var frameGeometry = memo?.Read(frame.Geometry) ?? JobPartGeometry.TryRead(frame.Geometry);
+ if (frameGeometry == null || !CutoutCoordinates.WithinRange(frameGeometry.Bounds))
+ return Array.Empty();
+ ArgumentOutOfRangeException.ThrowIfNegative(cutoutIndex);
+ ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(cutoutIndex, frameGeometry.Cutouts.Count);
+ var cutout = frameGeometry.Cutouts[cutoutIndex];
+ if (!cutout.IsClosed() || !CutoutCoordinates.WithinRange(cutout.BoundingBox))
+ return Array.Empty();
+ var hole = ClipperBridge.ToPath(
+ ClipperBridge.Flatten(cutout, CutoutLatticeFill.FlattenTolerance, circumscribe: false), new Vector());
+ if (InscribedRectangle(hole) is not { } rectangle || spacing * 2 >= System.Math.Min(rectangle.W, rectangle.H))
+ return Array.Empty();
+ var geometries = new Dictionary(StringComparer.Ordinal);
+ foreach (var insert in inserts)
+ {
+ var geometry = memo?.Read(insert.Geometry) ?? JobPartGeometry.TryRead(insert.Geometry);
+ if (geometry == null || !CutoutCoordinates.WithinRange(geometry.Bounds))
+ return Array.Empty();
+ geometries[insert.Id] = geometry;
+ }
+
+ // Boxes grow by the spacing on their right and top, and the bin by one spacing: touching
+ // boxes are one spacing apart and the last may reach the wall's inset, as on a sheet.
+ var binWidth = rectangle.W - spacing;
+ var binHeight = rectangle.H - spacing;
+ var stock = new NestPlateStock("cutout", new Size(rectangle.H, rectangle.W), 1, spacing);
+ var types = BoxCatalog.Build(new NestJob(inserts, new[] { stock }));
+ var items = Items(types, geometries, spacing, binWidth, binHeight, memo, token);
+ if (items.Count == 0)
+ return Array.Empty();
+ var demand = inserts.Select(p => p.Quantity).ToArray();
+ var plans = new Dictionary();
+ foreach (var (columns, density) in Passes)
+ Search(items, demand, binWidth, binHeight, columns, density, plans, token);
+
+ var framePose = new NestJobPlacement(frame.Id, 0, 0, 0, 0);
+ var preparedFrame = NestLayoutCheck.Prepare(frameGeometry, framePose, spacing);
+ List? best = null;
+ var bestArea = 0.0;
+ foreach (var plan in plans.Values.OrderByDescending(p => p.Seated).Take(PlansTried))
+ {
+ token.ThrowIfCancellationRequested();
+ var poses = new List();
+ foreach (var (item, x, y) in Placements(plan))
+ {
+ var kept = new List();
+ foreach (var (dx, dy, rotation) in item.Members)
+ {
+ var part = inserts[item.Type];
+ var pose = new NestJobPlacement(part.Id, 0,
+ System.Math.Round(rectangle.X + spacing + x + dx, 8),
+ System.Math.Round(rectangle.Y + spacing + y + dy, 8), rotation);
+ if (Clears(pose, geometries, preparedFrame, poses.Concat(kept), spacing, memo, token))
+ kept.Add(pose);
+ }
+ poses.AddRange(kept);
+ }
+ if (poses.Count == 0)
+ continue;
+ poses.AddRange(GapFill(frame, cutoutIndex, inserts, poses, geometries, rectangle, spacing, memo, token));
+ var area = OutlineArea(poses, id => geometries[id]);
+ if (area > bestArea)
+ {
+ best = poses;
+ bestArea = area;
+ }
+ }
+ if (best == null)
+ return Array.Empty();
+ var counts = new Dictionary(StringComparer.Ordinal);
+ return best.Select(p =>
+ {
+ var index = counts.GetValueOrDefault(p.PartId);
+ counts[p.PartId] = index + 1;
+ return p with { InstanceIndex = index };
+ }).ToArray();
+ }
+
+ /// Outline area of the placed parts, the measure this proposal maximizes.
+ internal static double OutlineArea(IEnumerable poses, Func geometry) =>
+ poses.Sum(p => System.Math.Abs(geometry(p.PartId).Perimeter.Area()));
+
+ /// The axis-aligned rectangle a nearly rectangular hole holds, or null: starts from
+ /// the bounds and moves a side past whatever intrudes deepest, so rounded corners cost a side
+ /// about 0.3 of their radius. It may still clip a corner by a chord; certification decides.
+ internal static Rect? InscribedRectangle(PathD hole)
+ {
+ if (hole.Count < 3)
+ return null;
+ var left = hole.Min(p => p.x);
+ var right = hole.Max(p => p.x);
+ var bottom = hole.Min(p => p.y);
+ var top = hole.Max(p => p.y);
+ var bounds = (right - left) * (top - bottom);
+ var area = System.Math.Abs(Clipper.Area(hole));
+ if (!(bounds > 0) || area < MinRectangularity * bounds)
+ return null;
+
+ var points = new List(hole.Count * EdgeSamples);
+ for (var i = 0; i < hole.Count; i++)
+ {
+ var a = hole[i];
+ var b = hole[(i + 1) % hole.Count];
+ for (var s = 0; s < EdgeSamples; s++)
+ {
+ var t = s / (double)EdgeSamples;
+ points.Add(new PointD(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t));
+ }
+ }
+ for (var moves = 0; moves < points.Count; moves++)
+ {
+ var depth = InsideTolerance;
+ PointD? deepest = null;
+ foreach (var p in points)
+ {
+ var d = System.Math.Min(System.Math.Min(p.x - left, right - p.x),
+ System.Math.Min(p.y - bottom, top - p.y));
+ if (d > depth)
+ {
+ depth = d;
+ deepest = p;
+ }
+ }
+ if (deepest is not { } q)
+ break;
+ if (q.x - left == depth)
+ left = q.x;
+ else if (right - q.x == depth)
+ right = q.x;
+ else if (q.y - bottom == depth)
+ bottom = q.y;
+ else
+ top = q.y;
+ }
+ var width = right - left;
+ var height = top - bottom;
+ return width > 0 && height > 0 && width * height >= MinInscribed * area
+ ? new Rect(left, bottom, width, height)
+ : null;
+ }
+
+ private static List- Items(IReadOnlyList types, Dictionary geometries,
+ double spacing, double binWidth, double binHeight, CutoutMemo? memo, CancellationToken token)
+ {
+ var items = new List
- ();
+ foreach (var type in types)
+ {
+ var geometry = geometries[type.Id];
+ var area = System.Math.Abs(geometry.Perimeter.Area());
+ foreach (var orientation in type.Orientations)
+ {
+ token.ThrowIfCancellationRequested();
+ Add(new Item(type.Index, 1, orientation.Width + spacing, orientation.Height + spacing, area,
+ new[] { (-orientation.OffsetX, -orientation.OffsetY, orientation.Angle) }));
+ var density = area / (orientation.Width * orientation.Height);
+ if (type.Part.Quantity < 2 || density >= MaxPairedDensity)
+ continue;
+ foreach (var pair in Pairs(type, orientation, geometry, area, density, spacing, memo, token))
+ Add(pair);
+ }
+ }
+ return items;
+
+ void Add(Item item)
+ {
+ if (item.Width <= binWidth + MaxRectsSheet.Eps && item.Height <= binHeight + MaxRectsSheet.Eps)
+ items.Add(item);
+ }
+ }
+
+ /// A copy and its half turn slid together along each axis: two triangles close into
+ /// a rectangle. No best-fit search, so this adds a dozen clearance checks per slide.
+ private static IEnumerable
- Pairs(BoxType type, BoxOrientation orientation, JobPartGeometry geometry,
+ double area, double density, double spacing, CutoutMemo? memo, CancellationToken token)
+ {
+ var turned = Angle.NormalizeRad(orientation.Angle + System.Math.PI);
+ if (!type.Part.Rotation.Allows(turned)
+ || BoxCatalog.RotatedMaterialBounds(type.Part.Geometry, turned) is not { } bounds)
+ yield break;
+ var first = new NestJobPlacement(type.Id, 0, -orientation.OffsetX, -orientation.OffsetY, orientation.Angle);
+ foreach (var along in new[] { true, false })
+ {
+ var clear = (along ? orientation.Width : orientation.Height) + spacing;
+ NestJobPlacement Second(double slide) => new(type.Id, 1,
+ (along ? slide : 0) - bounds.Left, (along ? 0 : slide) - bounds.Bottom, turned);
+ bool Free(double slide) => memo?.Clears(geometry, first, geometry, Second(slide), spacing)
+ ?? NestLayoutCheck.Clears(geometry, first, geometry, Second(slide), spacing);
+ token.ThrowIfCancellationRequested();
+ if (!Free(clear))
+ continue;
+ var low = 0.0;
+ for (var step = 0; step < SlideSteps; step++)
+ {
+ token.ThrowIfCancellationRequested();
+ var middle = (low + clear) / 2;
+ if (Free(middle))
+ clear = middle;
+ else
+ low = middle;
+ }
+ var width = System.Math.Max(orientation.Width, (along ? clear : 0) + bounds.Width);
+ var height = System.Math.Max(orientation.Height, (along ? 0 : clear) + bounds.Height);
+ if (2 * area / (width * height) < density + MinPairGain)
+ continue;
+ yield return new Item(type.Index, 2, width + spacing, height + spacing, 2 * area, new[]
+ {
+ (first.X, first.Y, first.Rotation),
+ ((along ? clear : 0) - bounds.Left, (along ? 0 : clear) - bounds.Bottom, turned),
+ });
+ }
+ }
+
+ /// Beam search over the lowest-leftmost (or leftmost-lowest) free corner: each level
+ /// puts a box there or gives the corner up. Adds its best distinct selections to
+ /// , which keeps one layout per selection.
+ private static void Search(IReadOnlyList
- items, int[] demand, double binWidth, double binHeight,
+ bool columns, double density, Dictionary plans, CancellationToken token)
+ {
+ var used = new int[demand.Length];
+ var free = Usable(new[] { new Rect(0, 0, binWidth, binHeight) }, items, used, demand);
+ var beam = new List { new(free, used, 0, 0, null, null, 0, 0) };
+ var nodes = 0;
+ while (beam.Count > 0 && nodes < NodesPerPass)
+ {
+ token.ThrowIfCancellationRequested();
+ var next = new List();
+ foreach (var state in beam)
+ {
+ Keep(plans, state);
+ if (state.Free.Count == 0 || nodes++ >= NodesPerPass)
+ continue;
+ var anchor = state.Free[0];
+ foreach (var candidate in state.Free)
+ if (columns
+ ? (candidate.X, candidate.Y).CompareTo((anchor.X, anchor.Y)) < 0
+ : (candidate.Y, candidate.X).CompareTo((anchor.Y, anchor.X)) < 0)
+ anchor = candidate;
+ foreach (var item in items)
+ {
+ if (state.Used[item.Type] + item.Copies > demand[item.Type]
+ || item.Width > anchor.W + MaxRectsSheet.Eps || item.Height > anchor.H + MaxRectsSheet.Eps)
+ continue;
+ var taken = (int[])state.Used.Clone();
+ taken[item.Type] += item.Copies;
+ var box = new Rect(anchor.X, anchor.Y, item.Width, item.Height);
+ next.Add(Child(Usable(MaxRectsSheet.Carve(state.Free, box), items, taken, demand),
+ taken, state.Seated + item.Area, state, item, anchor.X, anchor.Y));
+ }
+ // Giving the corner up drops only this rectangle; overlapping ones stay.
+ var rest = new List(state.Free.Count);
+ foreach (var candidate in state.Free)
+ if (candidate != anchor)
+ rest.Add(candidate);
+ next.Add(Child(rest, state.Used, state.Seated, state.Parent, state.Item, state.X, state.Y));
+ }
+ var seen = new HashSet<(long, long)>();
+ beam = next.OrderByDescending(s => s.Rank)
+ .Where(s => seen.Add((Selection(s.Used), (long)System.Math.Round(s.Rank * 1e6))))
+ .Take(BeamWidth)
+ .ToList();
+ }
+ foreach (var state in beam)
+ Keep(plans, state);
+
+ State Child(IReadOnlyList rest, int[] taken, double seated, State? parent, Item? item, double x, double y) =>
+ new(rest, taken, seated, seated + density * UnionArea(rest), parent, item, x, y);
+ }
+
+ private static void Keep(Dictionary plans, State state)
+ {
+ if (state.Seated > 0)
+ plans.TryAdd(Selection(state.Used), state);
+ }
+
+ /// FNV-1a over the copy counts: stable across processes, unlike HashCode.
+ private static long Selection(int[] used)
+ {
+ var hash = unchecked((long)0xcbf29ce484222325);
+ foreach (var count in used)
+ hash = unchecked((hash ^ count) * 0x100000001b3);
+ return hash;
+ }
+
+ /// Free rectangles some remaining box still fits; the rest is dead space.
+ private static List Usable(IReadOnlyList free, IReadOnlyList
- items, int[] used, int[] demand)
+ {
+ var usable = new List(free.Count);
+ foreach (var rect in free)
+ foreach (var item in items)
+ if (used[item.Type] + item.Copies <= demand[item.Type]
+ && item.Width <= rect.W + MaxRectsSheet.Eps && item.Height <= rect.H + MaxRectsSheet.Eps)
+ {
+ usable.Add(rect);
+ break;
+ }
+ return usable;
+ }
+
+ private static double UnionArea(IReadOnlyList rects)
+ {
+ if (rects.Count == 0)
+ return 0;
+ var edges = new double[rects.Count * 2];
+ for (var i = 0; i < rects.Count; i++)
+ {
+ edges[2 * i] = rects[i].X;
+ edges[2 * i + 1] = rects[i].Right;
+ }
+ Array.Sort(edges);
+ var spans = new List<(double Low, double High)>(rects.Count);
+ var area = 0.0;
+ for (var i = 1; i < edges.Length; i++)
+ {
+ var width = edges[i] - edges[i - 1];
+ if (width <= 0)
+ continue;
+ spans.Clear();
+ foreach (var rect in rects)
+ if (rect.X <= edges[i - 1] && rect.Right >= edges[i])
+ spans.Add((rect.Y, rect.Top));
+ spans.Sort();
+ var reach = double.NegativeInfinity;
+ var height = 0.0;
+ foreach (var (low, high) in spans)
+ {
+ height += System.Math.Max(0, high - System.Math.Max(low, reach));
+ reach = System.Math.Max(reach, high);
+ }
+ area += width * height;
+ }
+ return area;
+ }
+
+ private static List<(Item Item, double X, double Y)> Placements(State plan)
+ {
+ var placed = new List<(Item, double, double)>();
+ for (var state = plan; state?.Item != null; state = state.Parent)
+ placed.Add((state.Item, state.X, state.Y));
+ placed.Reverse();
+ return placed;
+ }
+
+ /// The remaining demand dropped into what the boxes left, by the frontier packer,
+ /// which certifies its own poses against the frame and the boxes.
+ private static IReadOnlyList GapFill(NestJobPart frame, int cutoutIndex,
+ IReadOnlyList inserts, List poses,
+ Dictionary geometries, Rect rectangle, double spacing, CutoutMemo? memo,
+ CancellationToken token)
+ {
+ var left = rectangle.W * rectangle.H - OutlineArea(poses, id => geometries[id]);
+ var rest = new List();
+ foreach (var part in inserts)
+ {
+ var quantity = part.Quantity - poses.Count(p => p.PartId == part.Id);
+ if (quantity > 0 && System.Math.Abs(geometries[part.Id].Perimeter.Area()) <= left)
+ rest.Add(new NestJobPart(part.Id, part.Geometry, quantity, part.Priority, part.Rotation));
+ }
+ if (rest.Count == 0)
+ return Array.Empty();
+ var occupied = poses.Select(p => (geometries[p.PartId], p)).ToArray();
+ return CutoutPackerProposal.Fill(frame, cutoutIndex, rest, spacing, occupied, memo, token);
+ }
+
+ private static bool Clears(NestJobPlacement pose, Dictionary geometries,
+ NestLayoutCheck.PreparedPlacement frame, IEnumerable accepted, double spacing,
+ CutoutMemo? memo, CancellationToken token)
+ {
+ var geometry = geometries[pose.PartId];
+ foreach (var other in accepted)
+ {
+ token.ThrowIfCancellationRequested();
+ var otherGeometry = geometries[other.PartId];
+ var clears = memo?.Clears(otherGeometry, other, geometry, pose, spacing)
+ ?? NestLayoutCheck.Clears(otherGeometry, other, geometry, pose, spacing);
+ if (!clears)
+ return false;
+ }
+ token.ThrowIfCancellationRequested();
+ return NestLayoutCheck.Clears(frame, geometry, pose);
+ }
+}
diff --git a/OpenNest.Engine/Jobs/Cutouts/CutoutRouter.cs b/OpenNest.Engine/Jobs/Cutouts/CutoutRouter.cs
index 00cf5850..eb67c160 100644
--- a/OpenNest.Engine/Jobs/Cutouts/CutoutRouter.cs
+++ b/OpenNest.Engine/Jobs/Cutouts/CutoutRouter.cs
@@ -157,7 +157,12 @@ internal static class CutoutRouter
// the same area more compactly.
var packed = CutoutPackerProposal.Fill(frame, cutoutIndex, inserts, spacing,
Array.Empty<(JobPartGeometry Geometry, NestJobPlacement Pose)>(), memo, token);
- if (CutoutSeatedArea.Better(packed, accepted, id => geometries[id]))
+ // A rectangular hole is also solved as a knapsack of boxes; it wins on seated outline area.
+ var boxed = CutoutBoxProposal.Fill(frame, cutoutIndex, inserts, spacing, memo, token);
+ var packedWins = CutoutSeatedArea.Better(packed, accepted, id => geometries[id]);
+ if (CutoutSeatedArea.Better(boxed, packedWins ? packed : accepted, id => geometries[id]))
+ return Observe(boxed);
+ if (packedWins)
return Observe(packed);
foreach (var (pose, lattice) in observed)
observeAccepted?.Invoke(pose, lattice);
diff --git a/OpenNest.Engine/RectanglePacking/MaxRectsSheet.cs b/OpenNest.Engine/RectanglePacking/MaxRectsSheet.cs
index 29b7ceb8..8030eee2 100644
--- a/OpenNest.Engine/RectanglePacking/MaxRectsSheet.cs
+++ b/OpenNest.Engine/RectanglePacking/MaxRectsSheet.cs
@@ -105,6 +105,15 @@ internal sealed class MaxRectsSheet
public void Block(Rect keepOut) => Split(keepOut);
private void Split(Rect item)
+ {
+ var next = Carve(free, item);
+ free.Clear();
+ free.AddRange(next);
+ }
+
+ /// The maximal free rectangles left once is taken out of
+ /// ; a search that branches keeps its own lists with this.
+ internal static List Carve(IReadOnlyList free, Rect item)
{
var next = new List(free.Count + 8);
foreach (var f in free)
@@ -123,8 +132,7 @@ internal sealed class MaxRectsSheet
if (item.Top < f.Top - Eps)
next.Add(new Rect(f.X, item.Top, f.W, f.Top - item.Top));
}
- free.Clear();
- free.AddRange(Prune(next));
+ return Prune(next);
}
private static List Prune(List rects)
diff --git a/docs/nesting-engines.md b/docs/nesting-engines.md
index 699354af..9aac0089 100644
--- a/docs/nesting-engines.md
+++ b/docs/nesting-engines.md
@@ -395,6 +395,19 @@ across a tall window, now stand together against one wall. Without a boundary th
unchanged: rectangular stock still starts from the work-area inner-fit rectangle, so engine
layouts are identical.
+A nearly rectangular cutout (at least 0.97 of its bounding box) is also solved as a small knapsack
+by `CutoutBoxProposal`. Inside the rectangle the flattened cutout holds, a deterministic beam search
+over maximal free rectangles (`MaxRectsSheet.Carve`), bounded by a count of expanded states, places
+or gives up the lowest-left free corner, and in other passes the leftmost-low one, to maximize
+seated outline area. Boxes come from `BoxCatalog`, so they follow the rotation policy and the layout
+check's arc flattening. A part filling under 0.8 of its box with two or more copies is also offered
+with its half turn slid against it along each axis, which closes two triangles into one box; the
+slide takes a few clearance checks where a best-fit search can take a minute for a new drawing, and
+only pairs at least 0.05 denser than a single copy are offered. The three best selections are
+certified with `NestLayoutCheck.Clears`, then `CutoutPackerProposal` drops the remaining demand into
+what is left, with the boxes as its occupants. The router keeps this proposal only when it seats
+more outline area than the others.
+
When the cutout is one circle and every insert fills at least 0.8 of its enclosing circle
(discs, washers, gears by their tip circle), `CutoutCirclePacker` first packs the whole insert
list as discs: largest first, at centers tangent to two of the hole wall and the placed discs,