#nullable enable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Clipper2Lib; using OpenNest.Engine.Jobs; using OpenNest.Geometry; namespace OpenNest.Engine.NestingEngines.Irregular; /// /// Fills one sheet in full-height strips along its length, two ways. /// /// lays each like-part group out as a band: the group's Lattice pattern (the one /// interactive Fill gives that part alone, so a round part stacks, a hexagon tiles and an L /// interlocks with its pair) in the narrowest strip that holds all its copies, or a few rows lower /// to leave room along the sheet. Bands stand side by side, then the copies held back from them /// and the types too few to band fill the gaps. /// /// builds each strip as densely as it can from any parts: the strip holds /// the largest remaining part, as its band or as a column of it, and every other part fills the /// strip's gaps, so big parts go first and small ones fill around them. /// /// A person nesting many copies of a few parts lays them out in tidy columns; a frontier packer /// placing one part at a time instead leaves every group's last column ragged and scatters the /// smallest parts into the gaps between groups. /// internal sealed class BandedFill( IReadOnlyList types, BlockCatalog blocks, NestPlateStock stock, ClampObstacles? clamps, Func packer, Comparison compare, WorkCounter counter, long budget) { /// Fewest copies a band may hold back to be narrower; a third of them when more. private const int MaxHeldBack = 4; /// Narrower bands offered per type, those holding the most copies first. private const int MaxNarrower = 2; /// Lengths a full-height band's search steps through. private const int MaxSteps = 6; /// Halvings toward the area bound that follow a full-height band's steps. private const int Probes = 3; /// How far short of the last pattern's length or height the next one is asked for. private const double StepShort = 0.01; /// Lower band heights searched per type. private const int LowerHeights = 3; /// Lengths a lower band's search steps through; it makes no probes. private const int LowerSteps = 3; /// /// Work the trials of narrower and lower bands may spend whatever the budget: building the /// patterns is charged to the same meter and can spend the whole budget on its own, and a /// trial costs a few hundredths of a pattern. /// private const long TrialWork = 25_000; /// Partial sheets carried strip to strip. private const int Beam = 4; /// Most copies across in a strip packed as a column of its largest part. private const int MaxColumnCopies = 3; /// Column strips whose widths are closer than this are tried once. private const double SameWidth = 0.05; /// Lengths and areas closer than this are the same. private const double Same = 1e-6; /// Slack when testing that a pattern fits the room it is given. private const double FitSlack = 1e-9; /// A type's pattern. Height is the height of the box it was asked for, so a /// band cut short at the sheet's end is asked for in the same box. private sealed record Band(int Type, int Copies, double Length, double Height, IReadOnlyList Members); /// A partial sheet: the parts placed so far, the copies left per type, the part area /// placed and how far along the sheet the strips reach. private sealed record StripState(List Placed, int[] Rest, double Area, double Front); /// One call: the packer for a strip's gaps, how far behind a /// strip its gap fill looks and the band searches made so far. private sealed record StripRun(Func Within, double LookBack, CancellationToken Token) { public Dictionary<(int Type, int Copies), List> Bands { get; } = new(); } private readonly Box region = stock.WorkArea; private readonly double spacing = System.Math.Max(0, stock.PartSpacing); /// The work area's height with a side carrying clamps moved in past their keep-outs: /// a band seated there clears the clamps whole. private readonly (double Bottom, double Top) clear = ClearHeight(stock, clamps); private static (double Bottom, double Top) ClearHeight(NestPlateStock stock, ClampObstacles? clamps) { var (area, onEdges) = ClampObstacles.ClearOfEdges(stock.WorkArea, clamps); return onEdges ? (area.Bottom, area.Top) : (stock.WorkArea.Bottom, stock.WorkArea.Top); } /// The fill, or null when nothing bands on this sheet. public SheetFill? Fill(IReadOnlyList remaining, CancellationToken token) { if (stock.Outline != null) return null; var options = BandOptionsByType(remaining, token); if (options.Count == 0) return null; // Members a clamp takes off a band go to the gap fill; where a lower band of the type // could stand there whole instead, the search runs both ways and keeps the better sheet. replaceable = false; var best = Search(options, remaining, replace: false, token); if (replaceable) { var whole = Search(options, remaining, replace: true, token); if (compare(whole, best) < 0) best = whole; } return best; } /// Set when a band lost members to the clamps where a lower band of its type, of as /// many copies, seats whole. private bool replaceable; /// /// The best order of the types' first bands, then each type's other bands in turn. With /// , a band that loses members to the clamps gives way to the type's /// first lower band of as many copies that seats whole. /// private SheetFill Search(Dictionary> options, IReadOnlyList remaining, bool replace, CancellationToken token) { var (bands, best) = BestOrder(options, remaining, replace, token); return HoldBack(bands, best, options, remaining, replace, token); } /// /// of each type with copies enough to band, the types searched at /// once. Each type's search depends only on its own patterns (fixed step counts, no shared /// budget), so the result is the same in any order. Types with no band are left out. /// private Dictionary> BandOptionsByType(IReadOnlyList remaining, CancellationToken token) { var options = new Dictionary>(); var grouped = types.Where(t => remaining[t.Index] >= GroupedFill.MinGroup && t.Orientations.Count > 0) .Select(t => t.Index).ToArray(); if (grouped.Length == 0) return options; var found = new List[grouped.Length]; Parallel.For(0, grouped.Length, new ParallelOptions { CancellationToken = token }, i => found[i] = BandOptions(grouped[i], remaining[grouped[i]], token)); for (var i = 0; i < grouped.Length; i++) if (found[i].Count > 0) options[grouped[i]] = found[i]; return options; } /// Every type's narrowest full band in the order that packs best: longest first, /// shortest first or largest part first. private (Band[] Bands, SheetFill Fill) BestOrder(Dictionary> options, IReadOnlyList remaining, bool replace, CancellationToken token) { var full = options.Values.Select(o => o[0]).ToArray(); var orders = new[] { full.OrderByDescending(b => b.Length).ThenBy(b => b.Type).ToArray(), full.OrderBy(b => b.Length).ThenBy(b => b.Type).ToArray(), // Largest part first: small parts stay last, as filler for the gaps. full.OrderByDescending(b => types[b.Type].Area).ThenBy(b => b.Type).ToArray(), }; var bands = orders[0]; var best = Run(bands, options, remaining, replace, token); foreach (var order in orders.Skip(1)) { var fill = Run(order, options, remaining, replace, token); if (compare(fill, best) < 0) { best = fill; bands = order; } } return (bands, best); } /// /// Each of a type's other options (narrower bands holding fewer copies, lower bands) in its /// band's place, kept while that improves the sheet. The trials go round the bands, every /// type's first alternative before any type's second: the budget can end them early, and it /// must not end them before the last types in the order had a turn. They may spend /// whatever the budget. /// private SheetFill HoldBack(Band[] bands, SheetFill best, Dictionary> options, IReadOnlyList remaining, bool replace, CancellationToken token) { var limit = System.Math.Max(budget, counter.Value + TrialWork); var most = bands.Max(b => options[b.Type].Count); for (var k = 1; k < most; k++) for (var i = 0; i < bands.Length && counter.Value < limit; i++) { var choices = options[bands[i].Type]; if (k >= choices.Count) continue; var trial = bands.ToArray(); trial[i] = choices[k]; var candidate = Run(trial, options, remaining, replace, token); if (compare(candidate, best) < 0) { best = candidate; bands = trial; } } return best; } /// The bands seated left to right in the order given, then everything else filling /// around them. private SheetFill Run(IReadOnlyList bands, Dictionary> options, IReadOnlyList remaining, bool replace, CancellationToken token) { token.ThrowIfCancellationRequested(); var seated = new List(); var rest = remaining.ToArray(); var front = region.Left; foreach (var chosen in bands) { var band = chosen; var room = region.Right - front; if (room <= 0) break; if (band.Length > room + FitSlack) { // The sheet ends inside this band: as many copies as the room left holds. var partial = Pattern(band.Type, band.Copies, room, band.Height, token); if (partial == null) continue; band = partial; } var members = Seat(band, front); if (members.Count < band.Members.Count && Whole(band, options[band.Type], front, room) is { } whole) { replaceable = true; if (replace) members = whole; } seated.AddRange(members); rest[band.Type] -= members.Count; foreach (var member in members) front = System.Math.Max(front, member.Right); front += spacing; } return Finish(seated, seated.Sum(p => types[p.Orientation.TypeIndex].Area), rest, token); } /// /// The members of the type's first lower band of as many copies as /// that fits the room and seats whole at , for a band the clamps take /// members off; null when there is none. /// private List? Whole(Band band, List choices, double front, double room) { foreach (var lower in choices) { if (lower.Height >= band.Height || lower.Copies < band.Copies || lower.Length > room + FitSlack) continue; var members = Seat(lower, front); if (members.Count == lower.Members.Count) return members; } return null; } /// The sheet with the copies left over packed around the parts seated on it. private SheetFill Finish(IReadOnlyList seated, double seatedArea, int[] rest, CancellationToken token) { var parts = seated.ToList(); var partArea = seatedArea; if (rest.Any(r => r > 0)) { var leftovers = packer().Fill(rest, token, seated); parts.AddRange(leftovers.Parts); partArea += leftovers.PartArea; } return new SheetFill(stock, parts, partArea); } /// Takes each part's copy off the count left of its type. private static void Take(int[] rest, IEnumerable parts) { foreach (var part in parts) rest[part.Orientation.TypeIndex]--; } /// /// Strip by strip: each strip holds the largest remaining part, either as its Lattice band /// (full or holding fewer copies) or packed largest part first in a strip one to three copies /// wide, and every other part fills the strip's gaps, largest piece first. A beam of the /// partial sheets densest so far (part area per unit of length used) is /// carried strip to strip, so a strip is judged by what it leaves for the rest of the sheet, /// not by its own density alone; the best finished sheet wins. /// public SheetFill? FillStrips(IReadOnlyList remaining, Func within, CancellationToken token, int beamWidth = Beam) { if (stock.Outline != null) return null; var longestSide = types.Where(t => remaining[t.Index] > 0).SelectMany(t => t.Orientations) .Select(o => System.Math.Max(o.Width, o.Height)).DefaultIfEmpty(0).Max(); var run = new StripRun(within, longestSide, token); var beam = new List { new(new List(), remaining.ToArray(), 0, region.Left) }; var finished = new List(); while (beam.Count > 0) { token.ThrowIfCancellationRequested(); Prefetch(SearchesAhead(beam, run), token); var children = new List(); foreach (var state in beam) { var next = NextStrips(state, run); if (next.Count == 0) finished.Add(state); else children.AddRange(next); } beam = Densest(children, beamWidth); } SheetFill? best = null; foreach (var state in finished) { var sheet = Finish(state.Placed, state.Area, state.Rest, token); if (best == null || compare(sheet, best) < 0) best = sheet; } return best; } /// The largest part with copies left, which the next strip holds. private PartType? Largest(int[] rest) => types.Where(t => rest[t.Index] > 0 && t.Orientations.Count > 0) .OrderByDescending(t => t.Area).ThenBy(t => t.Index).FirstOrDefault(); /// The band searches the beam's next strips need and no strip has made yet, each /// once, for to run ahead in parallel. private List<(int Type, int Copies)> SearchesAhead(List beam, StripRun run) { var searches = new List<(int Type, int Copies)>(); foreach (var state in beam) { var largest = Largest(state.Rest); if (largest == null || state.Front >= region.Right || state.Rest[largest.Index] < GroupedFill.MinGroup) continue; var search = (largest.Index, state.Rest[largest.Index]); if (!run.Bands.ContainsKey(search) && !searches.Contains(search)) searches.Add(search); } return searches; } /// /// The partial sheets one strip past : its largest remaining part /// seated as each of its bands that fit, then packed as each column width. None when the /// sheet is finished: no part left, no room left, the work budget spent or no strip that /// takes a copy of the part. /// private List NextStrips(StripState state, StripRun run) { var strips = new List(); var largest = Largest(state.Rest); if (largest == null || state.Front >= region.Right || counter.Value >= budget) return strips; var t = largest.Index; var start = state.Placed.Count == 0 ? state.Front : state.Front + spacing; void Offer(IReadOnlyList seated, double end) { if (Strip(state, t, start, seated, end, run) is { } strip) strips.Add(strip); } if (state.Rest[t] >= GroupedFill.MinGroup) foreach (var band in StripBands(t, state.Rest[t], run)) { if (band.Length > region.Right - start + FitSlack) continue; var members = Seat(band, start); if (members.Count > 0) Offer(members, members.Max(p => p.Right)); } // The strip's own part fills its column first, then the others fill around it. foreach (var width in ColumnWidths(largest)) { var reach = Reach(start + width); if (reach <= state.Front) continue; var own = new int[types.Count]; own[t] = state.Rest[t]; var column = Behind(start, reach, run).Fill(own, run.Token, state.Placed, region.Top); if (column.Parts.Count > 0) Offer(column.Parts, start + width); } return strips; } /// /// with one more strip, from to /// : the parts seated in it, then every part with copies left filling its /// gaps. Null when the strip ends behind the front or takes no copy of the /// part. /// private StripState? Strip(StripState state, int largest, double start, IReadOnlyList seated, double end, StripRun run) { var reach = Reach(end); if (reach <= state.Front) return null; var rest = state.Rest.ToArray(); Take(rest, seated); var placed = state.Placed.Concat(seated).ToList(); IReadOnlyList gaps = rest.Any(r => r > 0) ? Behind(start, reach, run).Fill(rest, run.Token, placed, region.Top).Parts : Array.Empty(); var parts = seated.Concat(gaps).ToList(); if (!parts.Any(p => p.Orientation.TypeIndex == largest)) return null; Take(rest, gaps); placed.AddRange(gaps); return new StripState(placed, rest, state.Area + parts.Sum(p => types[p.Orientation.TypeIndex].Area), System.Math.Max(state.Front, parts.Max(p => p.Right))); } /// How far along the sheet a strip ending at is packed: just /// past its end, so a part ending there is inside. private double Reach(double end) => System.Math.Min(region.Right, end + Same); /// /// A packer for the strip from to . It looks /// back one part length behind the strip: gaps further back were filled with earlier strips, /// and parts there cost nothing to skip. /// private FrontierPacker Behind(double start, double reach, StripRun run) { var left = System.Math.Max(region.Left, start - run.LookBack); return run.Within(new Box(left, region.Bottom, reach - left, region.Width)); } /// The type's full-height bands for a strip, searched once per copy count. private List StripBands(int t, int copies, StripRun run) { if (!run.Bands.TryGetValue((t, copies), out var bands)) run.Bands[(t, copies)] = bands = FullBands(t, copies, run.Token); return bands; } /// Strip widths of one to copies of the part across, /// each distinct width once, narrowest first. private IEnumerable ColumnWidths(PartType type) { var widths = new List(); foreach (var o in type.Orientations) for (var k = 1; k <= MaxColumnCopies; k++) { var width = k * o.Width + (k - 1) * spacing; if (!widths.Any(w => System.Math.Abs(w - width) < SameWidth)) widths.Add(width); } return widths.OrderBy(w => w); } /// The densest partial sheets (part area per unit of /// length used), the shorter first among equals and those alike kept once. private List Densest(List children, int beamWidth) { double Density(StripState s) => s.Area / System.Math.Max(s.Front - region.Left, 1e-9); var beam = new List(); foreach (var child in children.OrderByDescending(Density).ThenBy(c => c.Front)) { if (beam.Count >= beamWidth) break; if (!beam.Any(b => Alike(b, child))) beam.Add(child); } return beam; } private static bool Alike(StripState a, StripState b) => System.Math.Abs(a.Front - b.Front) < Same && System.Math.Abs(a.Area - b.Area) < Same && a.Rest.SequenceEqual(b.Rest); /// A band's members starting at , flush to the bottom, or, /// when that leaves members on the clamps, flush to the top or just past the clamps along /// either side, whichever keeps the most off them; members on a clamp are left out. private List Seat(Band band, double front) { var minX = band.Members.Min(p => p.Left); var minY = band.Members.Min(p => p.Bottom); var maxY = band.Members.Max(p => p.Top); List Shifted(double dy) => band.Members .Select(m => new Placed(m.Orientation, m.X + front - minX, m.Y + dy)).Where(p => !OnClamp(p)).ToList(); var lowest = region.Bottom - minY; var highest = region.Top - maxY; var members = Shifted(lowest); var tried = new List { lowest }; foreach (var dy in new[] { highest, clear.Bottom - minY, clear.Top - maxY }) { if (members.Count == band.Members.Count) break; // Inside the work area, and a pose not tried yet. if (dy < lowest - FitSlack || dy > highest + FitSlack || tried.Any(d => System.Math.Abs(d - dy) < FitSlack)) continue; tried.Add(dy); var seated = Shifted(dy); if (seated.Count > members.Count) members = seated; } return members; } /// /// The type's bands of full work-area height (), then up to /// lower ones, each asked for just short of the last pattern's /// height, so each is a row or so lower: a lower band can sit past a clamp rail whole, and /// leaves a strip along the sheet that other parts fill. Lower bands search fewer lengths, /// except the first when the full band is taller than the height clear of the clamps: it is /// then asked for at that height and searched like the full band, since it is the type's full /// band wherever a clamp is in the way. A lower band no longer than the full one, of as many /// copies, takes the same length of sheet and leaves a strip beside it, so it stands first, /// in the full band's place. /// private List BandOptions(int t, int copies, CancellationToken token) { var options = FullBands(t, copies, token); var shortest = ShortestSide(types[t]); var last = options.FirstOrDefault(); for (var i = 0; i < LowerHeights && last != null; i++) { var height = Tall(last) - StepShort; // Nothing between the clear height and the full band's could sit past the clamps whole. var pastClamps = i == 0 && height > clear.Top - clear.Bottom - StepShort; if (pastClamps) height = clear.Top - clear.Bottom - StepShort; if (height < shortest) break; var lower = pastClamps ? Bands(t, copies, height, MaxSteps, Probes, token) : Bands(t, copies, height, LowerSteps, 0, token); options.AddRange(lower); last = lower.FirstOrDefault(); } if (options.Count > 1) { var full = options[0]; var lowest = options.Where(b => b.Copies >= full.Copies && b.Length <= full.Length + Same) .OrderBy(Tall).First(); if (!ReferenceEquals(lowest, full) && Tall(lowest) < Tall(full) - Same) { options.Remove(lowest); options.Insert(0, lowest); } } return options; } /// The height a band's members take, which is at most the height it was asked for. private static double Tall(Band band) => band.Members.Max(p => p.Top) - band.Members.Min(p => p.Bottom); /// The type's bands of full work-area height; see . private List FullBands(int t, int copies, CancellationToken token, Drawing? prefetch = null) => Bands(t, copies, region.Width, MaxSteps, Probes, token, prefetch); /// /// The type's bands of the given height, narrowest full one first, then each narrower one /// holding at most fewer copies. Lattice patterns grow in whole rows or /// columns, so each next band is asked for just short of the last one's length, and a few /// halvings toward the area bound catch patterns the steps skip. A pattern the certification /// rejects is stepped past the same way, so a type keeps its band when Fill's first pattern /// is under-spaced. /// private List Bands(int t, int copies, double height, int steps, int probes, CancellationToken token, Drawing? prefetch = null) { var fewest = copies - HeldBack(copies); var found = new List(); // A band stays unless another holds as many copies in no more length. void Keep(Band band) { if (band.Copies < fewest || found.Any(b => b.Copies >= band.Copies && b.Length <= band.Length + Same)) return; found.RemoveAll(b => b.Copies <= band.Copies && b.Length >= band.Length - Same); found.Add(band); } Band? NarrowestFull() => found.Where(b => b.Copies >= copies).OrderBy(b => b.Length).FirstOrDefault(); var length = region.Length; var rejections = 0; for (var step = 0; step < steps; step++) { var band = Pattern(t, copies, length, height, token, prefetch); if (band == null) { // Fill's pattern failed the spacing certification: just short of it Fill must // choose another, which often passes and holds as many copies. Such a retry is // not one of the steps, but there are no more of them than steps. var rejected = blocks.RejectedBandLength(types[t], copies, new Box(0, 0, length, height)); if (rejected <= StepShort || rejected - StepShort >= length || rejections++ >= steps) break; length = rejected - StepShort; step--; continue; } if (band.Copies < fewest) break; Keep(band); length = band.Length - StepShort; } var full = NarrowestFull(); if (full == null) return new List(); var lo = System.Math.Max(ShortestSide(types[t]), copies * types[t].Area / height); var hi = full.Length; for (var probe = 0; probe < probes && hi - lo > StepShort; probe++) { var mid = (lo + hi) / 2; var band = Pattern(t, copies, mid, height, token, prefetch); if (band != null) Keep(band); if (band != null && band.Copies >= copies) hi = band.Length; else lo = mid; } full = NarrowestFull()!; return found.Where(b => b.Copies < copies && b.Length < full.Length - Same).OrderByDescending(b => b.Copies) .Take(MaxNarrower).Prepend(full).ToList(); } /// Most copies a narrower band may leave to the gap fill. private static int HeldBack(int copies) => System.Math.Max(MaxHeldBack, copies / 3); private static double ShortestSide(PartType type) => type.Orientations.Min(o => System.Math.Min(o.Width, o.Height)); /// /// Builds the patterns of each (type, copies) band search ahead of need, the searches in /// parallel, so the ordinary searches that follow find them cached. Each search fills its /// own drawing and charges no work, so the work meter, the orientations and every result /// read as without it. /// private void Prefetch(IReadOnlyList<(int Type, int Copies)> searches, CancellationToken token) { if (searches.Count < 2) return; Parallel.For(0, searches.Count, new ParallelOptions { CancellationToken = token }, i => { var drawing = BlockCatalog.PrefetchDrawing(types[searches[i].Type]); try { FullBands(searches[i].Type, searches[i].Copies, token, drawing); } finally { BlockCatalog.ReleasePrefetch(drawing); } }); } /// The type's Lattice pattern in a length x width box, up to the copies wanted; with a /// drawing, built ahead of need (see ). private Band? Pattern(int t, int copies, double length, double width, CancellationToken token, Drawing? prefetch = null) { var members = blocks.Band(types[t], copies, new Box(0, 0, length, width), token, prefetch); // Bounds carry the arc flattening padding; a pattern they push past the box is no band. if (members.Count == 0 || members.Max(p => p.Top) - members.Min(p => p.Bottom) > width + FitSlack) return null; return new Band(t, members.Count, members.Max(p => p.Right) - members.Min(p => p.Left), width, members); } /// /// Whether a band member at its pose enters a clamp keep-out (its clearance included); such /// members are left to the gap fill, which packs around the clamps. /// private bool OnClamp(Placed member) { if (clamps == null) return false; var point = new PointD(member.X, member.Y); for (var i = 0; i < clamps.Count; i++) { var nfp = clamps.Get(i, member.Orientation); var b = nfp.Bounds; if (point.x < b.left || point.x > b.right || point.y < b.top || point.y > b.bottom) continue; foreach (var path in nfp.Region) if (Clipper.IsPositive(path) && Clipper.PointInPolygon(point, path) != PointInPolygonResult.IsOutside) return true; } return false; } }