feat(engine): let the Irregular packer fill an arbitrary boundary

Add PackBoundary: a closed outline with obstacles, bound to one
NoFitCache, whose per-orientation inner-fit polygon (the clearance
footprint inside the outline eroded by the other half clearance) is
computed once and shared. FrontierPacker takes an optional boundary and
seeds each region from that inner fit, drops orientations with no fit
and subtracts obstacle no-fit polygons like clamp ones; without a
boundary it is unchanged, so rectangular stock layouts are identical.

CutoutLatticeFill.InnerFit now calls the shared kernel with the same
Clipper operations, so lattice results are unchanged. The engine's
strategy variants are internal so a cutout proposal can reuse them.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Fable 5.1 committed 2026-10-28 17:44:08 -04:00
1 parent b8e8cc387d
commit f22e839850
5 files changed
+174 -17

No files matched your search

@@ -7,6 +7,7 @@ using Clipper2Lib;
using OpenNest.Engine.BestFit;
using OpenNest.Engine.Jobs.Adapters;
using OpenNest.Engine.Jobs.Placement;
using OpenNest.Engine.NestingEngines.Irregular;
using OpenNest.Geometry;
using OpenNest.Math;
@@ -189,13 +190,7 @@ internal static class CutoutLatticeFill
.OrderByDescending(p => System.Math.Abs(Clipper.Area(p))).FirstOrDefault();
if (grown == null || grown.Count < 3)
return new PathsD();
var reflected = new PathD(grown.Select(p => new PointD(-p.x, -p.y)));
// Clipper.MinkowskiSum rounds to two decimals; pass the job precision explicitly.
var forbidden = Clipper.Union(Minkowski.Sum(reflected, hole, true, Precision),
new PathsD { Clipper.TranslatePath(reflected, hole[0].x, hole[0].y) }, FillRule.NonZero, Precision);
var anchor = grown[0];
return Clipper.Difference(new PathsD { Clipper.TranslatePath(hole, -anchor.x, -anchor.y) }, forbidden,
FillRule.NonZero, Precision);
return PackBoundary.InnerFit(grown, new PathsD { hole });
}
/// <summary>Drops copies that fail the production clearance check against the frame; any
@@ -44,6 +44,10 @@ internal sealed record SheetFill(NestPlateStock Stock, IReadOnlyList<Placed> Par
/// 2. Otherwise advance - place the part whose front advance per unit area^beta is smallest,
/// i.e. the one that buys the most material coverage for the sheet length it consumes.
/// Parts are never placed in a sequence given up front; the sheet state decides what comes next.
///
/// Given a <see cref="PackBoundary"/>, the packer fills that outline instead of the stock's
/// rectangular work area: each region starts from the orientation's inner-fit polygon of the
/// boundary less the boundary's obstacles, and everything else is unchanged.
/// </summary>
internal sealed class FrontierPacker
{
@@ -63,7 +67,10 @@ internal sealed class FrontierPacker
private readonly WorkCounter counter;
private readonly BlockCatalog? blocks;
private readonly ClampObstacles? clamps;
private readonly PackBoundary? boundary;
/// <param name="boundary">Outline to fill instead of the stock's work area; it must be
/// fitted to <paramref name="nfps"/>.</param>
public FrontierPacker(
IReadOnlyList<PartType> types,
NoFitCache nfps,
@@ -73,9 +80,12 @@ internal sealed class FrontierPacker
double beta,
WorkCounter counter,
BlockCatalog? blocks = null,
ClampObstacles? clamps = null
ClampObstacles? clamps = null,
PackBoundary? boundary = null
)
{
if (boundary != null && !ReferenceEquals(boundary.Nfps, nfps))
throw new ArgumentException("The boundary is fitted to another no-fit cache.", nameof(boundary));
this.blocks = blocks;
this.clamps = stock.ClampZones.Count == 0 ? null : clamps ?? new ClampObstacles(stock);
this.counter = counter;
@@ -85,9 +95,13 @@ internal sealed class FrontierPacker
this.stock = stock;
this.axis = axis;
this.beta = beta;
work = stock.WorkArea;
this.boundary = boundary;
work = boundary?.Bounds ?? stock.WorkArea;
}
private bool Fits(double width, double height) =>
boundary?.Fits(width, height) ?? stock.Fits(width, height);
public SheetFill Fill(IReadOnlyList<int> remaining, CancellationToken token)
{
var left = remaining.ToArray();
@@ -97,9 +111,11 @@ internal sealed class FrontierPacker
{
if (byOrientation.ContainsKey(o))
return true;
if (!stock.Fits(o.Width, o.Height))
if (!Fits(o.Width, o.Height))
return false;
var region = boundary == null ? new Region(o, work, single) : new Region(o, boundary, single);
if (region.IsEmpty)
return false;
var region = new Region(o, work, single);
if (clamps != null)
for (var i = 0; i < clamps.Count; i++)
{
@@ -110,6 +126,13 @@ internal sealed class FrontierPacker
counter.Add(1);
token.ThrowIfCancellationRequested();
}
if (boundary != null)
for (var i = 0; i < boundary.ObstacleCount; i++)
{
token.ThrowIfCancellationRequested();
region.Subtract(nfps.Get(boundary.Obstacle(i), o), 0, 0);
counter.Add(1);
}
states.Add(region);
byOrientation[o] = region;
return true;
@@ -126,7 +149,7 @@ internal sealed class FrontierPacker
foreach (var pair in typePairs)
{
// Members missing from the catalog get regions too, but only for pair placement.
if (stock.Fits(pair.Width, pair.Height) && Track(pair.A, single: false) && Track(pair.B, single: false))
if (Fits(pair.Width, pair.Height) && Track(pair.A, single: false) && Track(pair.B, single: false))
offered.Add(new PairState(pair, byOrientation[pair.A], byOrientation[pair.B]));
}
}
@@ -148,7 +171,7 @@ internal sealed class FrontierPacker
continue;
var width = members.Max(p => p.Right) - members.Min(p => p.Left);
var height = members.Max(p => p.Top) - members.Min(p => p.Bottom);
if (!stock.Fits(width, height))
if (!Fits(width, height))
continue;
foreach (var member in members)
{
@@ -341,6 +364,15 @@ internal sealed class FrontierPacker
private RectD bounds;
public Region(Orientation orientation, Box work, bool single)
: this(orientation, work, single, null) { }
/// <summary>Starts from the orientation's inner fit of the boundary. No fit slack: the
/// inner fit already lies within the bounds box, and an exact fit against a cutout wall
/// would fail the clearance check anyway.</summary>
public Region(Orientation orientation, PackBoundary boundary, bool single)
: this(orientation, boundary.Bounds, single, boundary.InnerFit(orientation)) { }
private Region(Orientation orientation, Box work, bool single, PathsD? seed)
{
Orientation = orientation;
Single = single;
@@ -353,7 +385,7 @@ internal sealed class FrontierPacker
maxX = minX;
if (maxY < minY)
maxY = minY;
free = new PathsD
free = seed ?? new PathsD
{
new PathD
{
@@ -363,7 +395,8 @@ internal sealed class FrontierPacker
new(minX - FitSlack, maxY + FitSlack),
},
};
bounds = Clipper.GetBounds(free);
free.RemoveAll(p => p.Count < 3);
bounds = free.Count == 0 ? default : Clipper.GetBounds(free);
}
public Orientation Orientation { get; }
@@ -24,8 +24,9 @@ namespace OpenNest.Engine.NestingEngines.Irregular;
/// </summary>
public sealed class IrregularNestingEngine : INestingEngine
{
/// <summary>Strategy variants, tried in order: (front direction, area exponent beta).</summary>
private static readonly (PackAxis Axis, double Beta)[] Variants =
/// <summary>Strategy variants, tried in order: (front direction, area exponent beta).
/// The cutout packer proposal tries the same variants on a cutout.</summary>
internal static readonly (PackAxis Axis, double Beta)[] Variants =
{
(PackAxis.X, 1.0),
(PackAxis.Y, 1.0),
@@ -30,9 +30,13 @@ internal sealed class NoFitCache
public NoFitCache(double clearance)
{
Clearance = clearance;
halfClearance = clearance / 2;
}
/// <summary>The clearance two footprints together keep.</summary>
public double Clearance { get; }
public PathD Footprint(Orientation o) =>
footprints.GetOrAdd((o.TypeIndex, o.Index), _ => BuildFootprint(o));
@@ -0,0 +1,124 @@
#nullable enable
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Clipper2Lib;
using OpenNest.Geometry;
namespace OpenNest.Engine.NestingEngines.Irregular;
/// <summary>
/// A closed outline the packer fills in place of a rectangular work area: a frame's cutout in
/// frame coordinates, with the parts already seated in it as obstacles. Each orientation's
/// starting free region is its inner-fit polygon: the reference points at which its clearance
/// footprint lies inside the outline eroded by the other half of the clearance, so a part
/// keeps the full clearance from the frame exactly as it does from another part. The inner
/// fit is computed once per orientation and shared by every packing of this boundary.
/// </summary>
/// <remarks>Bound to one <see cref="NoFitCache"/>: its footprints define the inner fits and the
/// obstacle no-fit polygons, so a packer filling this boundary must use that cache.</remarks>
internal sealed class PackBoundary
{
/// <summary>Extra erosion beyond the half clearance, covering the outline's flattening and
/// the round-offset chords at its reflex corners.</summary>
private const double Margin = 0.002;
private const double ArcTolerance = 0.001;
private readonly PathsD eroded;
private readonly Orientation[] obstacles;
private readonly ConcurrentDictionary<(int, int), PathsD> innerFits = new();
/// <param name="outline">Closed polygon inscribed in the true outline, so flattening never
/// adds room.</param>
/// <param name="obstacles">Polygons circumscribing material already inside the outline, with
/// the chord deviation each was flattened with; every obstacle gets the full clearance.</param>
/// <param name="nfps">The cache whose footprints this boundary is fitted to.</param>
public PackBoundary(PathD outline, IReadOnlyList<(PathD Outline, double Tolerance)> obstacles, NoFitCache nfps)
{
Nfps = nfps;
var box = Clipper.GetBounds(outline);
Bounds = new Box(box.left, box.top, box.Width, box.Height); // Clipper RectD: top is the minimum Y.
eroded = Clipper.InflatePaths(new PathsD { Positive(outline) }, -(nfps.Clearance / 2 + Margin),
JoinType.Round, EndType.Polygon, 2.0, NoFitCache.Precision, ArcTolerance);
eroded.RemoveAll(p => p.Count < 3);
this.obstacles = new Orientation[obstacles.Count];
for (var i = 0; i < obstacles.Count; i++)
{
var path = Positive(obstacles[i].Outline);
var tolerance = obstacles[i].Tolerance;
var bounds = Clipper.GetBounds(path);
this.obstacles[i] = new Orientation
{
// Real part types are nonnegative, so obstacle footprints never alias them.
TypeIndex = -1,
Index = i,
Rotation = 0,
Outline = path,
Tolerance = tolerance,
MinX = bounds.left - tolerance,
MinY = bounds.top - tolerance,
MaxX = bounds.right + tolerance,
MaxY = bounds.bottom + tolerance,
};
}
}
public NoFitCache Nfps { get; }
/// <summary>Bounds of the outline: the packer's work area and front origin.</summary>
public Box Bounds { get; }
public int ObstacleCount => obstacles.Length;
public Orientation Obstacle(int index) => obstacles[index];
/// <summary>Coarse filter against the outline's bounds; the inner fit decides.</summary>
public bool Fits(double width, double height) =>
width <= Bounds.Length + 1e-9 && height <= Bounds.Width + 1e-9;
/// <summary>A fresh copy of the orientation's starting free region.</summary>
public PathsD InnerFit(Orientation orientation) =>
new(innerFits.GetOrAdd((orientation.TypeIndex, orientation.Index),
_ => InnerFit(Nfps.Footprint(orientation), eroded)));
/// <summary>
/// Reference points t at which <paramref name="grown"/> lies inside one component of
/// <paramref name="hole"/>: its anchor vertex is inside the component (t in component - anchor)
/// and its outline never meets the component's boundary (t outside boundary + reflected
/// outline, including the pose that contains the whole component).
/// </summary>
internal static PathsD InnerFit(PathD grown, PathsD hole)
{
if (grown.Count < 3)
return new PathsD();
var reflected = new PathD(grown.Select(p => new PointD(-p.x, -p.y)));
var anchor = grown[0];
var inside = new PathsD();
PathsD? forbidden = null;
foreach (var component in hole)
{
if (component.Count < 3)
continue;
inside.Add(Clipper.TranslatePath(component, -anchor.x, -anchor.y));
// Clipper.MinkowskiSum rounds to two decimals; pass the job precision explicitly.
var sweep = Clipper.Union(Minkowski.Sum(reflected, component, true, NoFitCache.Precision),
new PathsD { Clipper.TranslatePath(reflected, component[0].x, component[0].y) },
FillRule.NonZero, NoFitCache.Precision);
forbidden = forbidden == null ? sweep : Clipper.Union(forbidden, sweep, FillRule.NonZero, NoFitCache.Precision);
}
return forbidden == null
? new PathsD()
: Clipper.Difference(inside, forbidden, FillRule.NonZero, NoFitCache.Precision);
}
private static PathD Positive(PathD path)
{
if (path.Count >= 3 && !Clipper.IsPositive(path))
{
path = new PathD(path);
path.Reverse();
}
return path;
}
}