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 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-21 14:21:34 -05:00
1 parent 7964785af5
commit 4b3d7d57aa
11 files changed
+587 -64

No files matched your search

@@ -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;
/// <summary>
/// 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.
/// </summary>
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),
};
/// <summary>The reported drawing's outline, in absolute coordinates.</summary>
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, (string, int)> { [drawing] = ("J-Bar", 33) }));
}
}
+12 -3
View File
@@ -67,6 +67,13 @@ namespace OpenNest.Engine.Fill
/// </summary>
internal bool LeadingParts { get; init; } = true;
/// <summary>
/// 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.
/// </summary>
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<Part>(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
+319
View File
@@ -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
{
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// Every insert is a <see cref="Compactor"/> 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.
/// </remarks>
internal static class GridEndInserter
{
/// <summary>Positions across the row a copy is first slid in from, per template.</summary>
private const int CoarseSamples = 24;
/// <summary>Most positions tried around the best coarse landing.</summary>
private const int FineSamples = 24;
/// <summary>Most copies slid in from one side.</summary>
private const int MaxInserts = 4;
/// <summary>
/// The most parts found among the grid moved to each corner of <paramref name="area"/>,
/// with and without copies slid in from its open sides, each with the strip left beyond
/// them filled by <paramref name="fillStrip"/>; null when none places more than
/// <paramref name="toBeat"/> parts or the grid alone. A strip is filled only when the
/// parts it could hold by <paramref name="partArea"/> (the part's true area) could beat
/// the best so far, since each fill lays out the strip with pairs.
/// </summary>
public static List<Part> Complete(
List<Part> grid,
Box area,
double spacing,
double partArea,
int toBeat,
Func<Box, List<Part>> 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<Part> 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<Part>(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<Part> candidate)
{
if (candidate != null && candidate.Count > Floor())
best = candidate;
}
}
/// <summary>
/// <paramref name="parts"/> and the most parts <paramref name="fillStrip"/> places in one
/// of the strips between their bounds and the area's edges, or <paramref name="parts"/>
/// alone when no strip could lift the total above <paramref name="toBeat"/> by area.
/// </summary>
private static List<Part> WithStrip(
List<Part> parts,
Box area,
double spacing,
double partArea,
int toBeat,
Func<Box, List<Part>> 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<Part> 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<Part>(parts.Count + bestStrip.Count);
result.AddRange(parts);
result.AddRange(bestStrip);
return result;
}
/// <summary>Slides copies in along <paramref name="slide"/> until none fits.</summary>
private static void InsertMany(
List<Part> parts,
List<Part> 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);
}
}
/// <summary>
/// A copy slid in along <paramref name="slide"/> 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.
/// </summary>
private static Part InsertOne(
List<Part> parts,
List<Part> 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<Part>(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;
}
/// <summary>
/// A copy of <paramref name="template"/> just beyond the area edge the slide starts from,
/// its lower bound across the slide at <paramref name="across"/>.
/// </summary>
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;
}
/// <summary>How far the copy got: smaller is deeper along the slide.</summary>
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;
}
}
+85 -48
View File
@@ -112,6 +112,12 @@ namespace OpenNest.Engine.Fill
init => remnantFiller.StripeConvergence = value;
}
/// <summary>
/// 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.
/// </summary>
public bool WholePairGrids { get; init; } = true;
/// <summary>
/// The Fill
/// </summary>
@@ -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<Part> EvaluateHerringbones(
Drawing drawing,
Box workArea,
int targetCount,
List<Part> best,
List<BestFitResult> candidates,
List<BestFitResult> 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<BestFitResult> bestFits,
@@ -397,6 +408,7 @@ namespace OpenNest.Engine.Fill
drawing,
workArea,
minCountToBeat,
targetCount,
maxUtilization,
partArea,
bestFits,
@@ -539,6 +551,7 @@ namespace OpenNest.Engine.Fill
/// <param name="drawing">The drawing<see cref="Drawing"/></param>
/// <param name="workArea">The workArea<see cref="Box"/></param>
/// <param name="minCountToBeat">The minCountToBeat<see cref="int"/></param>
/// <param name="targetCount">The quantity the fill needs, or zero for as many as fit</param>
/// <param name="maxUtilization">The maxUtilization<see cref="double"/></param>
/// <param name="partArea">The partArea<see cref="double"/></param>
/// <param name="bestFits">The pairs the remnant strips are also filled with</param>
@@ -549,6 +562,7 @@ namespace OpenNest.Engine.Fill
Drawing drawing,
Box workArea,
int minCountToBeat,
int targetCount,
double maxUtilization,
double partArea,
List<BestFitResult> 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<FillLinear.DeferredGrid>();
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<List<Part>>();
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<Part> gridParts) =>
gridParts.Count + remnantFiller.EstimateUpperBound(gridParts, workArea, maxUtilization, partArea);
List<Part> WithRemnant(List<Part> 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<Part>(gridParts.Count + remnantParts.Count);
total.AddRange(gridParts);
total.AddRange(remnantParts);
return total;
}
List<Part> 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<Part> 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<Part> total;
if (remnantParts != null && remnantParts.Count > 0)
{
total = new List<Part>(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;
}
+52 -10
View File
@@ -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.
/// </summary>
private readonly ConcurrentDictionary<(double Width, double Length), List<Part>> pairStrips =
private readonly ConcurrentDictionary<(double Width, double Length, bool Complete), List<Part>> pairStrips =
new();
/// <summary>Pairs tried when tiling a strip with one pair as a grid.</summary>
@@ -35,6 +35,13 @@ namespace OpenNest.Engine.Fill
/// <summary>Grid candidates tried in a row without improvement before giving up.</summary>
private const int GridStaleLimit = 10;
/// <summary>
/// How many of a strip's densest grids <see cref="GridEndInserter"/> 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.
/// </summary>
private const int MaxCompletedGrids = 1;
private readonly ConcurrentDictionary<Drawing, double> minimumWidths =
new(ReferenceEqualityComparer.Instance);
@@ -125,7 +132,8 @@ namespace OpenNest.Engine.Fill
Drawing drawing,
Box remnantBox,
List<BestFitResult> 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
/// <summary>
/// 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 <paramref name="complete"/>, the densest pair grid is also completed with
/// <see cref="GridEndInserter"/>, whose own strips are filled without it.
/// </summary>
private List<Part> FillPairs(
Drawing drawing,
Box remnantBox,
List<BestFitResult> 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<Part>();
normalized = ComputePairs(drawing, origin, bestFits, token, complete) ?? new List<Part>();
pairStrips.TryAdd(key, normalized);
}
@@ -219,7 +231,8 @@ namespace OpenNest.Engine.Fill
Drawing drawing,
Box area,
List<BestFitResult> 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<BestFitResult> bestFits,
CancellationToken token
CancellationToken token,
out List<List<Part>> 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<Part> best = null;
var sinceImproved = 0;
var tiled = new List<(List<Part> 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;
}
@@ -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;
@@ -83,6 +83,14 @@ internal class PlateFiller
/// </summary>
internal bool StopAtQuantity { get; init; }
/// <summary>
/// When true (the default), the pairs phase also tiles each pair grid with whole pairs only
/// and refills the strip it leaves (<see cref="PairFiller.WholePairGrids"/>). 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.
/// </summary>
internal bool WholePairGrids { get; init; } = true;
public virtual List<double> 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);
@@ -19,8 +19,9 @@ internal static class PrivatePlateFill
/// <param name="length">X extent of the plate and work area.</param>
/// <param name="width">Y extent of the plate and work area.</param>
/// <param name="quantity">Copies wanted; zero fills the whole area.</param>
/// <param name="wholePairGrids">See <see cref="PlateFiller.WholePairGrids"/>.</param>
internal static List<Part> 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,
@@ -22,6 +22,12 @@ namespace OpenNest.Engine.Strategies
/// many (see <see cref="FillLinear.MaxParts"/>). Zero fills the whole work area.
/// </summary>
public int MaxQuantity { get; init; }
/// <summary>
/// Whether the pairs phase also tries its grids with whole pairs only
/// (<see cref="Fill.PairFiller.WholePairGrids"/>).
/// </summary>
public bool WholePairGrids { get; init; } = true;
public PartType PartType { get; set; }
/// <summary>
@@ -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,
+25
View File
@@ -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