diff --git a/OpenNest.Engine/NestingEngines/Irregular/FrontierPacker.cs b/OpenNest.Engine/NestingEngines/Irregular/FrontierPacker.cs index e26d36b3..f9123207 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/FrontierPacker.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/FrontierPacker.cs @@ -10,26 +10,6 @@ using OpenNest.Geometry; namespace OpenNest.Engine.NestingEngines.Irregular; -/// Direction the packing front sweeps across the sheet (the free strip is left behind it). -internal enum PackAxis -{ - /// Front moves in +X; parts settle toward low X, then low Y. - X, - - /// Front moves in +Y; parts settle toward low Y, then low X. - Y, -} - -internal sealed record Placed(Orientation Orientation, double X, double Y) -{ - public double Left => X + Orientation.MinX; - public double Right => X + Orientation.MaxX; - public double Bottom => Y + Orientation.MinY; - public double Top => Y + Orientation.MaxY; -} - -internal sealed record SheetFill(NestPlateStock Stock, IReadOnlyList Parts, double PartArea); - /// /// Fills one sheet with a frontier-advance rule over incrementally maintained free regions. /// @@ -48,6 +28,10 @@ internal sealed record SheetFill(NestPlateStock Stock, IReadOnlyList Par /// Given a , 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. +/// +/// reads as its steps: regions and pairs are tracked for the demand, seated +/// parts are taken, and then and alternate until +/// nothing more fits, with Lattice blocks offered before the first two placements. /// internal sealed class FrontierPacker { @@ -55,8 +39,27 @@ internal sealed class FrontierPacker /// chosen points are clamped back, which moves them far less than the clearance margin. private const double FitSlack = 2e-4; + /// Front advances, cross-axis positions and leading edges closer than this are the + /// same, and so are placement values closer than this times the larger of one and the value. + /// An advance within it is a gap fill. private const double Tie = 1e-6; + /// Slack when testing that a piece fits a work area cut short. + private const double SizeSlack = 1e-9; + + /// Least area an advance is divided by. + private const double MinArea = 1e-12; + + /// Times one fill asks the block catalog for blocks: on the sheet as the fill finds + /// it, and again after its first placement. + private const int MaxBlockPreparations = 2; + + /// Types offered blocks per preparation: those with the most part area left. + private const int MaxBlockTypes = 4; + + /// Fewest copies in a block, and so fewest left of a type offered one. + private const int MinBlockCopies = 3; + private readonly IReadOnlyList types; private readonly NoFitCache nfps; private readonly IReadOnlyDictionary> pairs; @@ -65,22 +68,19 @@ internal sealed class FrontierPacker private readonly double beta; private readonly IReadOnlyList? typeWeights; private readonly IReadOnlyList? groupRanks; - - /// - /// The placement rule's value of a candidate; lower wins. Gap fill prefers bigger parts - /// (negated area); advance prefers least advance per area. A type weight above one favors - /// the type: a more negative gap-fill value, a smaller advance score. Weight one is exact. - /// - internal static double PlacementValue(bool fills, double advance, double area, double beta, double weight) => - fills - ? -area * weight - : advance / System.Math.Pow(System.Math.Max(area, 1e-12), beta) / weight; - private readonly Box work; private readonly WorkCounter counter; private readonly BlockCatalog? blocks; private readonly ClampObstacles? clamps; private readonly PackBoundary? boundary; + /// The area filled: the boundary's bounds or the stock's work area, cut short by a + /// reach, or the box the fill is held within. + private readonly Box work; + + /// Whether is less than the whole area, so a piece that fits the + /// stock may still not fit it. + private readonly bool limited; + /// Outline to fill instead of the stock's work area; it must be /// fitted to . /// Per type, a rank served after priority: a type is placed only when @@ -119,21 +119,41 @@ internal sealed class FrontierPacker this.typeWeights = typeWeights; this.groupRanks = groupRanks; this.boundary = boundary; - work = boundary?.Bounds ?? stock.WorkArea; - if (reach is double end) - work = axis == PackAxis.X - ? new Box(work.Left, work.Bottom, System.Math.Clamp(end - work.Left, 0, work.Length), work.Width) - : new Box(work.Left, work.Bottom, work.Length, System.Math.Clamp(end - work.Bottom, 0, work.Width)); - if (within != null) - work = within; + work = WorkArea(boundary?.Bounds ?? stock.WorkArea, axis, reach, within); limited = reach != null || within != null; } - private readonly bool limited; + /// when given, else ended at + /// along the front axis. + private static Box WorkArea(Box whole, PackAxis axis, double? reach, Box? within) + { + var area = whole; + if (reach is double end) + area = axis == PackAxis.X + ? new Box(whole.Left, whole.Bottom, System.Math.Clamp(end - whole.Left, 0, whole.Length), whole.Width) + : new Box(whole.Left, whole.Bottom, whole.Length, System.Math.Clamp(end - whole.Bottom, 0, whole.Width)); + return within ?? area; + } + + /// + /// The placement rule's value of a candidate; lower wins. Gap fill prefers bigger parts + /// (negated area); advance prefers least advance per area. A type weight above one favors + /// the type: a more negative gap-fill value, a smaller advance score. Weight one is exact. + /// + internal static double PlacementValue(bool fills, double advance, double area, double beta, double weight) => + fills + ? -area * weight + : advance / System.Math.Pow(System.Math.Max(area, MinArea), beta) / weight; + + /// The edge of the work area the packing front leaves from. + private double FrontOrigin => axis == PackAxis.X ? work.Left : work.Bottom; + + /// How far along the front axis a part reaches. + private double Reach(Placed part) => axis == PackAxis.X ? part.Right : part.Top; private bool Fits(double width, double height) => (boundary?.Fits(width, height) ?? stock.Fits(width, height)) - && (!limited || (width <= work.Length + 1e-9 && height <= work.Width + 1e-9)); + && (!limited || (width <= work.Length + SizeSlack && height <= work.Width + SizeSlack)); /// Parts already on the sheet: they block space and hold the packing /// front where they reached, so the fill starts as gap fill. They are not returned. @@ -142,286 +162,405 @@ internal sealed class FrontierPacker public SheetFill Fill(IReadOnlyList remaining, CancellationToken token, IReadOnlyList? seated = null, double? front = null) { - var left = remaining.ToArray(); - var states = new List(); - var byOrientation = new Dictionary(ReferenceEqualityComparer.Instance); - bool Track(Orientation o, bool single) + var sheet = new Sheet(remaining.ToArray(), token) { - if (byOrientation.ContainsKey(o)) - return true; - 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; - if (clamps != null) - for (var i = 0; i < clamps.Count; i++) - { - token.ThrowIfCancellationRequested(); - var nfp = clamps.Get(i, o); - token.ThrowIfCancellationRequested(); - region.Subtract(nfp, 0, 0); - 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; + Front = System.Math.Max(FrontOrigin, front ?? double.NegativeInfinity), + }; + TrackDemand(sheet); + if (seated is { Count: > 0 }) + Seat(sheet, seated); + var firstNew = sheet.Placed.Count; + DropEmpty(sheet); + PrepareBlocks(sheet); + + while (sheet.Regions.Count > 0) + { + token.ThrowIfCancellationRequested(); + var choice = Choose(sheet); + if (choice == null) + break; + Place(sheet, choice); + PrepareBlocks(sheet); } - var offered = new List(); + + var placed = sheet.Placed; + return new SheetFill(stock, firstNew == 0 ? placed : placed.GetRange(firstNew, placed.Count - firstNew), + sheet.PartArea); + } + + /// One call: the copies left per type, what is still in play, the + /// parts on the sheet and how far the packing front has come. + private sealed class Sheet(int[] left, CancellationToken token) + { + public int[] Left { get; } = left; + public CancellationToken Token { get; } = token; + + /// Regions with room left for a type with copies left, in the order tracked. + public List Regions { get; } = new(); + + /// The region of every orientation tracked so far, retired or not. + public Dictionary ByOrientation { get; } = new(ReferenceEqualityComparer.Instance); + + public List Pairs { get; } = new(); + public List Blocks { get; } = new(); + + /// Times the block catalog was to be asked; see . + public int BlockPreparations { get; set; } + + /// Every part on the sheet in placement order, the seated ones first. + public List Placed { get; } = new(); + + /// Part area this fill placed; seated parts are not counted. + public double PartArea { get; set; } + + public double Front { get; set; } + } + + /// + /// Starts a region for every orientation of each type with copies left, and offers each of its + /// pairs whose members both have room when two or more copies are left. + /// + private void TrackDemand(Sheet sheet) + { foreach (var type in types) { - if (left[type.Index] <= 0) + if (sheet.Left[type.Index] <= 0) continue; foreach (var o in type.Orientations) - Track(o, single: true); - if (left[type.Index] < 2 || !pairs.TryGetValue(type.Index, out var typePairs)) + Track(sheet, o, single: true); + if (sheet.Left[type.Index] < 2 || !pairs.TryGetValue(type.Index, out var typePairs)) continue; foreach (var pair in typePairs) { // Members missing from the catalog get regions too, but only for pair placement. - 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])); + if (Fits(pair.Width, pair.Height) && Track(sheet, pair.A, single: false) + && Track(sheet, pair.B, single: false)) + sheet.Pairs.Add(new PairState(pair, sheet.ByOrientation[pair.A], sheet.ByOrientation[pair.B])); } } - - var placed = new List(); - void Block(Placed part) - { - // Regions are independent, so they update in parallel without affecting determinism. - var snapshot = states.ToArray(); - counter.Add(snapshot.Length); - Parallel.For( - 0, - snapshot.Length, - new ParallelOptions { CancellationToken = token }, - i => snapshot[i].Subtract(nfps.Get(part.Orientation, snapshot[i].Orientation), part.X, part.Y) - ); - } - var frontAt = System.Math.Max(axis == PackAxis.X ? work.Left : work.Bottom, front ?? double.NegativeInfinity); - if (seated is { Count: > 0 }) - { - foreach (var part in seated) - { - placed.Add(part); - frontAt = System.Math.Max(frontAt, axis == PackAxis.X ? part.Right : part.Top); - } - // As Block for each seated part in turn, in one parallel pass: each region loses the - // same positions in the same order. - var snapshot = states.ToArray(); - counter.Add((long)snapshot.Length * seated.Count); - Parallel.For( - 0, - snapshot.Length, - new ParallelOptions { CancellationToken = token }, - i => - { - foreach (var part in seated) - snapshot[i].Subtract(nfps.Get(part.Orientation, snapshot[i].Orientation), part.X, part.Y); - } - ); - } - var firstNew = placed.Count; - states.RemoveAll(s => s.IsEmpty); - offered.RemoveAll(p => p.A.IsEmpty || p.B.IsEmpty); - var blockStates = new List(); - var preparations = 0; - void PrepareBlocks() - { - if (blocks == null || preparations++ >= 2) - return; - var rectangles = BlockCatalog.Rectangles(work, placed, stock.PartSpacing); - foreach (var type in types.Where(t => left[t.Index] > 2) - .OrderByDescending(t => t.Area * left[t.Index]).ThenBy(t => t.Index).Take(4)) - foreach (var rectangle in rectangles) - { - var members = blocks.Get(type, left[type.Index], rectangle, token); - if (members.Count <= 2) - 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 (!Fits(width, height)) - continue; - foreach (var member in members) - { - if (byOrientation.ContainsKey(member.Orientation)) - continue; - if (!Track(member.Orientation, single: false)) - break; - var region = byOrientation[member.Orientation]; - foreach (var existing in placed) - region.Subtract(nfps.Get(existing.Orientation, member.Orientation), existing.X, existing.Y); - } - if (members.All(p => byOrientation.ContainsKey(p.Orientation))) - blockStates.Add(new BlockState(members, members.Select(p => byOrientation[p.Orientation]).ToArray())); - } - } - PrepareBlocks(); - var partArea = 0.0; - - while (states.Count > 0) - { - token.ThrowIfCancellationRequested(); - var choice = Choose(states, offered, blockStates, frontAt); - if (choice == null) - break; - - var typeIndex = choice[0].Orientation.TypeIndex; - foreach (var part in choice) - { - placed.Add(part); - partArea += types[typeIndex].Area; - frontAt = System.Math.Max(frontAt, axis == PackAxis.X ? part.Right : part.Top); - } - - left[typeIndex] -= choice.Count; - blockStates.RemoveAll(b => b.Members.Count > left[b.Members[0].Orientation.TypeIndex]); - if (left[typeIndex] == 0) - states.RemoveAll(s => s.Orientation.TypeIndex == typeIndex); - if (left[typeIndex] < 2) - { - offered.RemoveAll(p => p.Pose.TypeIndex == typeIndex); - states.RemoveAll(s => s.Orientation.TypeIndex == typeIndex && !s.Single); - } - - // Each surviving region loses the positions the new parts now block. - foreach (var part in choice) - Block(part); - states.RemoveAll(s => s.IsEmpty); - offered.RemoveAll(p => p.A.IsEmpty || p.B.IsEmpty); - if (offered.Count == 0 && blocks == null) - states.RemoveAll(s => !s.Single); - blockStates.RemoveAll(b => b.Regions.Any(r => r.IsEmpty)); - PrepareBlocks(); - } - - return new SheetFill(stock, firstNew == 0 ? placed : placed.GetRange(firstNew, placed.Count - firstNew), partArea); } /// - /// The next placement: one part, or both members of a pair. Singles and pairs compete - /// under the same rule; a pair counts as one piece of twice the part area, and on a tie - /// the single (considered first) is kept. + /// Whether the orientation has a region on this sheet, starting one when it is new to it. A + /// region keeps the it was started with. /// - private IReadOnlyList? Choose(List states, List offered, List blocks, double front) + private bool Track(Sheet sheet, Orientation o, bool single) { - IReadOnlyList? bestParts = null; - var bestFills = false; - var bestValue = double.PositiveInfinity; - var bestSide = double.PositiveInfinity; - var bestLead = double.PositiveInfinity; - var bestPriority = int.MinValue; - var bestRank = int.MaxValue; + if (sheet.ByOrientation.ContainsKey(o)) + return true; + if (StartRegion(o, single, sheet.Token) is not { } region) + return false; + sheet.Regions.Add(region); + sheet.ByOrientation[o] = region; + return true; + } - void Consider(Func> build, int typeIndex, double area, double advance, double side, double lead) + /// + /// The orientation's region on an empty sheet: its inner fit less what the clamps and the + /// boundary's obstacles block. Null when the orientation does not fit or has no room. + /// + private Region? StartRegion(Orientation o, bool single, CancellationToken token) + { + if (!Fits(o.Width, o.Height)) + return null; + var region = boundary == null ? new Region(o, work, single) : new Region(o, boundary, single); + if (region.IsEmpty) + return null; + if (clamps != null) + for (var i = 0; i < clamps.Count; i++) + { + token.ThrowIfCancellationRequested(); + var nfp = clamps.Get(i, o); + token.ThrowIfCancellationRequested(); + region.Subtract(nfp, 0, 0); + 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); + } + return region; + } + + /// Takes the parts already on the sheet: they hold the packing front where they + /// reached, and every region loses the positions they block. + private void Seat(Sheet sheet, IReadOnlyList seated) + { + foreach (var part in seated) { - var priority = types[typeIndex].Part.Priority; - var rank = groupRanks?[typeIndex] ?? 0; - if (priority < bestPriority || (priority == bestPriority && rank > bestRank)) - return; - var fills = advance <= Tie; - var value = PlacementValue(fills, advance, area, beta, typeWeights?[typeIndex] ?? 1.0); + sheet.Placed.Add(part); + sheet.Front = System.Math.Max(sheet.Front, Reach(part)); + } + Block(sheet, seated); + } - var better = bestParts == null - || priority > bestPriority - || rank < bestRank - || (fills && !bestFills) - || ( - fills == bestFills - && ( - value < bestValue - Tie * System.Math.Max(1, System.Math.Abs(bestValue)) - || ( - value <= bestValue + Tie * System.Math.Max(1, System.Math.Abs(bestValue)) - && (side < bestSide - Tie || (side <= bestSide + Tie && lead < bestLead - Tie)) - ) - ) - ); - if (!better) - return; - bestParts = build(); - bestPriority = priority; - bestRank = rank; - bestFills = fills; - bestValue = value; - bestSide = side; - bestLead = lead; + /// + /// Takes the positions block out of every region in play, in one + /// pass: regions are independent, so they update in parallel without affecting determinism, + /// and each loses the parts in order. + /// + private void Block(Sheet sheet, IReadOnlyList parts) + { + var snapshot = sheet.Regions.ToArray(); + counter.Add((long)snapshot.Length * parts.Count); + Parallel.For( + 0, + snapshot.Length, + new ParallelOptions { CancellationToken = sheet.Token }, + i => + { + foreach (var part in parts) + snapshot[i].Block(part, nfps); + } + ); + } + + /// Retires the regions with no room left, and the pairs with a member that has none. + private static void DropEmpty(Sheet sheet) + { + sheet.Regions.RemoveAll(s => s.IsEmpty); + sheet.Pairs.RemoveAll(p => p.A.IsEmpty || p.B.IsEmpty); + } + + /// + /// Offers Lattice blocks: for each of the types with the most part area left, the block the + /// catalog fills each free rectangle of the sheet with, when it holds copies enough and fits. + /// Only the first calls of a fill ask the catalog. + /// + private void PrepareBlocks(Sheet sheet) + { + if (blocks == null || sheet.BlockPreparations++ >= MaxBlockPreparations) + return; + var left = sheet.Left; + var rectangles = BlockCatalog.Rectangles(work, sheet.Placed, stock.PartSpacing); + foreach (var type in types.Where(t => left[t.Index] >= MinBlockCopies) + .OrderByDescending(t => t.Area * left[t.Index]).ThenBy(t => t.Index).Take(MaxBlockTypes)) + foreach (var rectangle in rectangles) + { + var members = blocks.Get(type, left[type.Index], rectangle, sheet.Token); + if (members.Count < MinBlockCopies) + 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 (!Fits(width, height)) + continue; + if (TrackMembers(sheet, members)) + sheet.Blocks.Add(new BlockState(members, + members.Select(p => sheet.ByOrientation[p.Orientation]).ToArray())); + } + } + + /// + /// Whether every member's orientation has a region. One new to the sheet gets a region for + /// block placement only, less what the parts already on the sheet block. + /// + private bool TrackMembers(Sheet sheet, IReadOnlyList members) + { + foreach (var member in members) + { + if (sheet.ByOrientation.ContainsKey(member.Orientation)) + continue; + if (!Track(sheet, member.Orientation, single: false)) + return false; + var region = sheet.ByOrientation[member.Orientation]; + foreach (var existing in sheet.Placed) + region.Block(existing, nfps); + } + return true; + } + + /// + /// Puts the chosen parts on the sheet, then retires what they end: blocks and pairs the type + /// has too few copies left for, its regions when none is left, and whatever lost its last room + /// to the new parts. + /// + private void Place(Sheet sheet, IReadOnlyList choice) + { + var left = sheet.Left; + var typeIndex = choice[0].Orientation.TypeIndex; + foreach (var part in choice) + { + sheet.Placed.Add(part); + sheet.PartArea += types[typeIndex].Area; + sheet.Front = System.Math.Max(sheet.Front, Reach(part)); } - foreach (var region in states) + left[typeIndex] -= choice.Count; + sheet.Blocks.RemoveAll(b => b.Members.Count > left[b.Members[0].Orientation.TypeIndex]); + if (left[typeIndex] == 0) + sheet.Regions.RemoveAll(s => s.Orientation.TypeIndex == typeIndex); + if (left[typeIndex] < 2) + { + sheet.Pairs.RemoveAll(p => p.Pose.TypeIndex == typeIndex); + sheet.Regions.RemoveAll(s => s.Orientation.TypeIndex == typeIndex && !s.Single); + } + + // Each surviving region loses the positions the new parts now block, a pass per part. + foreach (var part in choice) + Block(sheet, new[] { part }); + DropEmpty(sheet); + if (sheet.Pairs.Count == 0 && blocks == null) + sheet.Regions.RemoveAll(s => !s.Single); + sheet.Blocks.RemoveAll(b => b.Regions.Any(r => r.IsEmpty)); + } + + /// + /// The next placement: one part, both members of a pair, or a block. All compete under the + /// same rule; a pair or block counts as one piece of its members' area, and on a tie the one + /// considered first is kept: singles, then pairs, then blocks. + /// + private IReadOnlyList? Choose(Sheet sheet) + { + var leader = new Leader(); + var front = sheet.Front; + + foreach (var region in sheet.Regions) { if (!region.Single) continue; - if (!region.TryLowest(axis, front, out var point, out var advance, out var side, out var lead)) + if (!region.TryLowest(axis, front, out var spot)) continue; var o = region.Orientation; - Consider(() => new[] { new Placed(o, point.x, point.y) }, o.TypeIndex, types[o.TypeIndex].Area, advance, side, lead); + Consider(leader, spot, o.TypeIndex, types[o.TypeIndex].Area, + () => new[] { new Placed(o, spot.Point.x, spot.Point.y) }); } - foreach (var state in offered) + foreach (var state in sheet.Pairs) { var pair = state.Pose; - if (!state.TryLowest(axis, front, counter, out var point, out var advance, out var side, out var lead)) + if (!state.TryLowest(axis, front, counter, out var spot)) continue; - Consider( - () => new[] { new Placed(pair.A, point.x, point.y), new Placed(pair.B, point.x + pair.Dx, point.y + pair.Dy) }, - pair.TypeIndex, - 2 * types[pair.TypeIndex].Area, - advance, - side, - lead - ); + Consider(leader, spot, pair.TypeIndex, 2 * types[pair.TypeIndex].Area, + () => new[] + { + new Placed(pair.A, spot.Point.x, spot.Point.y), + new Placed(pair.B, spot.Point.x + pair.Dx, spot.Point.y + pair.Dy), + }); } - foreach (var block in blocks) + foreach (var block in sheet.Blocks) { - if (!block.TryLowest(axis, front, counter, out var point, out var advance, out var side, out var lead)) + if (!block.TryLowest(axis, front, counter, out var spot)) continue; var typeIndex = block.Members[0].Orientation.TypeIndex; - Consider(() => block.Members.Select(p => new Placed(p.Orientation, p.X + point.x, p.Y + point.y)).ToArray(), - typeIndex, block.Members.Count * types[typeIndex].Area, advance, side, lead); + Consider(leader, spot, typeIndex, block.Members.Count * types[typeIndex].Area, + () => block.Members.Select(p => new Placed(p.Orientation, p.X + spot.Point.x, p.Y + spot.Point.y)) + .ToArray()); } - return bestParts; + return leader.Parts; } - private sealed class BlockState(IReadOnlyList members, Region[] regions) + /// The candidate leading a so far, and what it scored. + private sealed class Leader { - public IReadOnlyList Members { get; } = members; - public Region[] Regions { get; } = regions; + public IReadOnlyList? Parts { get; set; } + public int Priority { get; set; } = int.MinValue; + public int Rank { get; set; } = int.MaxValue; + public bool Fills { get; set; } + public double Value { get; set; } = double.PositiveInfinity; + public double Side { get; set; } = double.PositiveInfinity; + public double Lead { get; set; } = double.PositiveInfinity; + } - public bool TryLowest(PackAxis axis, double front, WorkCounter counter, - out PointD point, out double advance, out double side, out double lead) - { - var free = Clipper.TranslatePaths(Regions[0].Free, -Members[0].X, -Members[0].Y); - var minX = double.NegativeInfinity; - var minY = double.NegativeInfinity; - var maxX = double.PositiveInfinity; - var maxY = double.PositiveInfinity; - for (var i = 0; i < Members.Count; i++) + /// + /// Makes a candidate the leader when the rule prefers it: the higher priority, then the lower + /// group rank, then a gap fill over an advance, then the lower , + /// then the spot that . Its parts are built only when it leads. + /// + private void Consider(Leader leader, Spot spot, int typeIndex, double area, Func> build) + { + var priority = types[typeIndex].Part.Priority; + var rank = groupRanks?[typeIndex] ?? 0; + if (priority < leader.Priority || (priority == leader.Priority && rank > leader.Rank)) + return; + var fills = spot.Advance <= Tie; + var value = PlacementValue(fills, spot.Advance, area, beta, typeWeights?[typeIndex] ?? 1.0); + + var valueTie = Tie * System.Math.Max(1, System.Math.Abs(leader.Value)); + var better = leader.Parts == null + || priority > leader.Priority + || rank < leader.Rank + || (fills && !leader.Fills) + || ( + fills == leader.Fills + && ( + value < leader.Value - valueTie + || (value <= leader.Value + valueTie && SettlesLower(spot.Side, spot.Lead, leader.Side, leader.Lead)) + ) + ); + if (!better) + return; + leader.Parts = build(); + leader.Priority = priority; + leader.Rank = rank; + leader.Fills = fills; + leader.Value = value; + leader.Side = spot.Side; + leader.Lead = spot.Lead; + } + + /// Whether a spot lies lower across the front axis than the best, or level with it + /// and with a lower leading edge. + private static bool SettlesLower(double side, double lead, double bestSide, double bestLead) => + side < bestSide - Tie || (side <= bestSide + Tie && lead < bestLead - Tie); + + /// A reference point for a piece and what it scores there: how far it pushes the + /// packing front, its low edge across the front axis and its leading edge along it. + private readonly record struct Spot(PointD Point, double Advance, double Side, double Lead); + + /// A box by its edges: the reference points a piece may take, or the piece's own + /// extent around its reference point. + private readonly record struct Extents(double MinX, double MinY, double MaxX, double MaxY); + + /// + /// The best vertex of for a piece occupying + /// around its reference point, each vertex clamped to the inner-fit box : + /// least front advance, then the spot that . Vertices suffice + /// because every score is linear in position. + /// + private static bool BestVertex(PathsD free, Extents fit, Extents piece, PackAxis axis, double front, out Spot best) + { + var point = default(PointD); + var advance = double.PositiveInfinity; + var side = double.PositiveInfinity; + var lead = double.PositiveInfinity; + var found = false; + foreach (var path in free) + foreach (var raw in path) { - var member = Members[i]; - var region = Regions[i]; - minX = System.Math.Max(minX, region.MinX - member.X); - minY = System.Math.Max(minY, region.MinY - member.Y); - maxX = System.Math.Min(maxX, region.MaxX - member.X); - maxY = System.Math.Min(maxY, region.MaxY - member.Y); - if (i > 0) + var x = System.Math.Clamp(raw.x, fit.MinX, fit.MaxX); + var y = System.Math.Clamp(raw.y, fit.MinY, fit.MaxY); + double reach, across, start; + if (axis == PackAxis.X) { - counter.Add(1); - free = Clipper.Intersect(free, Clipper.TranslatePaths(region.Free, -member.X, -member.Y), - FillRule.NonZero, NoFitCache.Precision); + reach = x + piece.MaxX; + across = y + piece.MinY; + start = x + piece.MinX; } + else + { + reach = y + piece.MaxY; + across = x + piece.MinX; + start = y + piece.MinY; + } + var adv = System.Math.Max(0, reach - front); + var better = !found + || adv < advance - Tie + || (adv <= advance + Tie && SettlesLower(across, start, side, lead)); + if (!better) + continue; + found = true; + point = new PointD(x, y); + advance = adv; + side = across; + lead = start; } - return BestVertex(free, minX, minY, System.Math.Max(minX, maxX), System.Math.Max(minY, maxY), - (Members.Min(p => p.Left), Members.Min(p => p.Bottom), Members.Max(p => p.Right), Members.Max(p => p.Top)), - axis, front, out point, out advance, out side, out lead); - } + best = new Spot(point, advance, side, lead); + return found; } /// Legal reference points for one orientation on this sheet. @@ -474,6 +613,10 @@ internal sealed class FrontierPacker public bool IsEmpty => free.Count == 0; + /// Takes out the positions at which this orientation would meet . + public void Block(Placed part, NoFitCache nfps) => + Subtract(nfps.Get(part.Orientation, Orientation), part.X, part.Y); + public void Subtract(Nfp nfp, double dx, double dy) { if ( @@ -501,74 +644,15 @@ internal sealed class FrontierPacker public double MaxX => maxX; public double MaxY => maxY; - /// - /// Best vertex of the free region: least front advance, then lowest cross-axis position, - /// then lowest leading edge. Vertices suffice because every score is linear in position. - /// - public bool TryLowest(PackAxis axis, double front, out PointD point, out double advance, out double side, out double lead) + /// The of the free region. + public bool TryLowest(PackAxis axis, double front, out Spot spot) { var o = Orientation; - return BestVertex(free, minX, minY, maxX, maxY, (o.MinX, o.MinY, o.MaxX, o.MaxY), - axis, front, out point, out advance, out side, out lead); + return BestVertex(free, new Extents(minX, minY, maxX, maxY), new Extents(o.MinX, o.MinY, o.MaxX, o.MaxY), + axis, front, out spot); } } - /// - /// Scores the vertices of , each clamped to the inner-fit box - /// [minX, maxX] x [minY, maxY], for a piece occupying around its - /// reference point. - /// - private static bool BestVertex( - PathsD free, - double minX, - double minY, - double maxX, - double maxY, - (double MinX, double MinY, double MaxX, double MaxY) box, - PackAxis axis, - double front, - out PointD point, - out double advance, - out double side, - out double lead - ) - { - point = default; - advance = side = lead = double.PositiveInfinity; - var found = false; - foreach (var path in free) - foreach (var raw in path) - { - var x = System.Math.Clamp(raw.x, minX, maxX); - var y = System.Math.Clamp(raw.y, minY, maxY); - double reach, across, start; - if (axis == PackAxis.X) - { - reach = x + box.MaxX; - across = y + box.MinY; - start = x + box.MinX; - } - else - { - reach = y + box.MaxY; - across = x + box.MinX; - start = y + box.MinY; - } - var adv = System.Math.Max(0, reach - front); - var better = !found - || adv < advance - Tie - || (adv <= advance + Tie && (across < side - Tie || (across <= side + Tie && start < lead - Tie))); - if (!better) - continue; - found = true; - point = new PointD(x, y); - advance = adv; - side = across; - lead = start; - } - return found; - } - /// /// Legal reference points for a pair: member A's free region intersected with member B's /// moved back by the pair offset. Recomputed only after either member's region changes. @@ -582,8 +666,7 @@ internal sealed class FrontierPacker public Region A { get; } = a; public Region B { get; } = b; - public bool TryLowest(PackAxis axis, double front, WorkCounter counter, - out PointD point, out double advance, out double side, out double lead) + public bool TryLowest(PackAxis axis, double front, WorkCounter counter, out Spot spot) { if (versionA != A.Version || versionB != B.Version) { @@ -597,8 +680,8 @@ internal sealed class FrontierPacker var maxX = System.Math.Max(minX, System.Math.Min(A.MaxX, B.MaxX - Pose.Dx)); var minY = System.Math.Max(A.MinY, B.MinY - Pose.Dy); var maxY = System.Math.Max(minY, System.Math.Min(A.MaxY, B.MaxY - Pose.Dy)); - return BestVertex(free, minX, minY, maxX, maxY, (Pose.MinX, Pose.MinY, Pose.MaxX, Pose.MaxY), - axis, front, out point, out advance, out side, out lead); + return BestVertex(free, new Extents(minX, minY, maxX, maxY), + new Extents(Pose.MinX, Pose.MinY, Pose.MaxX, Pose.MaxY), axis, front, out spot); } private PathsD Intersect() @@ -616,4 +699,44 @@ internal sealed class FrontierPacker return result; } } + + /// + /// Legal reference points for a block: every member's free region moved back by the member's + /// place in the block, intersected. Recomputed for every choice. + /// + private sealed class BlockState(IReadOnlyList members, Region[] regions) + { + public IReadOnlyList Members { get; } = members; + + /// Each member's region, in member order. + public Region[] Regions { get; } = regions; + + public bool TryLowest(PackAxis axis, double front, WorkCounter counter, out Spot spot) + { + var free = Clipper.TranslatePaths(Regions[0].Free, -Members[0].X, -Members[0].Y); + var minX = double.NegativeInfinity; + var minY = double.NegativeInfinity; + var maxX = double.PositiveInfinity; + var maxY = double.PositiveInfinity; + for (var i = 0; i < Members.Count; i++) + { + var member = Members[i]; + var region = Regions[i]; + minX = System.Math.Max(minX, region.MinX - member.X); + minY = System.Math.Max(minY, region.MinY - member.Y); + maxX = System.Math.Min(maxX, region.MaxX - member.X); + maxY = System.Math.Min(maxY, region.MaxY - member.Y); + if (i > 0) + { + counter.Add(1); + free = Clipper.Intersect(free, Clipper.TranslatePaths(region.Free, -member.X, -member.Y), + FillRule.NonZero, NoFitCache.Precision); + } + } + return BestVertex(free, new Extents(minX, minY, System.Math.Max(minX, maxX), System.Math.Max(minY, maxY)), + new Extents(Members.Min(p => p.Left), Members.Min(p => p.Bottom), Members.Max(p => p.Right), + Members.Max(p => p.Top)), + axis, front, out spot); + } + } } diff --git a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Improvements.cs b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Improvements.cs index b7b03209..20cae65f 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Improvements.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Improvements.cs @@ -133,7 +133,7 @@ public sealed partial class IrregularNestingEngine { var fill = new EdgeFirstFill(types, CacheFor(stock), stock, ClampsFor(stock), Work, () => new FrontierPacker(types, CacheFor(stock), PairsFor(stock), stock, PackAxis.X, 1.0, Work, - null, ClampsFor(stock)), + clamps: ClampsFor(stock)), Orient).Fill(bin, token); if (fill == null) return null; diff --git a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Solver.cs b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Solver.cs index be4e395f..5316dd51 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Solver.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Solver.cs @@ -271,7 +271,7 @@ public sealed partial class IrregularNestingEngine { FrontierPacker Ordinary() => packer(null, null); FrontierPacker Within(OpenNest.Geometry.Box box) => new(types, CacheFor(stock), PairsFor(stock), stock, - PackAxis.Y, 1.0, Work, null, ClampsFor(stock), null, weights, null, null, box); + PackAxis.Y, 1.0, Work, clamps: ClampsFor(stock), typeWeights: weights, within: box); BandedFill Bands(long budget) => new(types, BlocksFor(stock), stock, ClampsFor(stock), Ordinary, CompareSheets, Work, budget); diff --git a/OpenNest.Engine/NestingEngines/Irregular/PackAxis.cs b/OpenNest.Engine/NestingEngines/Irregular/PackAxis.cs new file mode 100644 index 00000000..1965d86b --- /dev/null +++ b/OpenNest.Engine/NestingEngines/Irregular/PackAxis.cs @@ -0,0 +1,11 @@ +namespace OpenNest.Engine.NestingEngines.Irregular; + +/// Direction the packing front sweeps across the sheet (the free strip is left behind it). +internal enum PackAxis +{ + /// Front moves in +X; parts settle toward low X, then low Y. + X, + + /// Front moves in +Y; parts settle toward low Y, then low X. + Y, +} diff --git a/OpenNest.Engine/NestingEngines/Irregular/SheetFill.cs b/OpenNest.Engine/NestingEngines/Irregular/SheetFill.cs new file mode 100644 index 00000000..952b3a92 --- /dev/null +++ b/OpenNest.Engine/NestingEngines/Irregular/SheetFill.cs @@ -0,0 +1,17 @@ +#nullable enable +using System.Collections.Generic; +using OpenNest.Engine.Jobs; + +namespace OpenNest.Engine.NestingEngines.Irregular; + +/// A part on a sheet: its orientation with the reference point at (X, Y). +internal sealed record Placed(Orientation Orientation, double X, double Y) +{ + public double Left => X + Orientation.MinX; + public double Right => X + Orientation.MaxX; + public double Bottom => Y + Orientation.MinY; + public double Top => Y + Orientation.MaxY; +} + +/// One sheet of a stock with the parts packed on it, in placement order, and their area. +internal sealed record SheetFill(NestPlateStock Stock, IReadOnlyList Parts, double PartArea);