diff --git a/OpenNest.Engine/NestingEngines/Irregular/BandedFill.cs b/OpenNest.Engine/NestingEngines/Irregular/BandedFill.cs index 00c08f2f..af56b60b 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/BandedFill.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/BandedFill.cs @@ -3,6 +3,7 @@ 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; @@ -39,10 +40,58 @@ internal sealed class BandedFill( /// 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; + + /// 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); @@ -58,55 +107,137 @@ internal sealed class BandedFill( { if (stock.Outline != null) return null; - var region = stock.WorkArea; + var options = BandOptionsByType(remaining, token); + if (options.Count == 0) + return null; + var (bands, best) = BestOrder(options, remaining, token); + return HoldBack(bands, best, options, remaining, 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 null; - // Per type, its narrowest full band first, then narrower bands holding fewer copies. - var options = new Dictionary>(); - foreach (var (t, list) in grouped.Zip(BandsInParallel(grouped, remaining, region, token))) - if (list.Count > 0) - options[t] = list; - if (options.Count == 0) - return null; - var bands = options.ToDictionary(o => o.Key, o => o.Value[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; + } - // Both orders with every band full; then, on the better one, hold back copies band by - // band while that improves the sheet. + /// 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, CancellationToken token) + { + var full = options.Values.Select(o => o[0]).ToArray(); var orders = new[] { - bands.Values.OrderByDescending(b => b.Length).ThenBy(b => b.Type).Select(b => b.Type).ToArray(), - bands.Values.OrderBy(b => b.Length).ThenBy(b => b.Type).Select(b => b.Type).ToArray(), + 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. - bands.Values.OrderByDescending(b => types[b.Type].Area).ThenBy(b => b.Type).Select(b => b.Type).ToArray(), + full.OrderByDescending(b => types[b.Type].Area).ThenBy(b => b.Type).ToArray(), }; - int[]? bestOrder = null; - SheetFill? best = null; - foreach (var order in orders) + var bands = orders[0]; + var best = Run(bands, remaining, token); + foreach (var order in orders.Skip(1)) { - var fill = Run(order, order.ToDictionary(t => t, _ => 0), options, remaining, region, token); - if (best == null || compare(fill, best) < 0) + var fill = Run(order, remaining, token); + if (compare(fill, best) < 0) { best = fill; - bestOrder = order; + bands = order; } } - var choice = bestOrder!.ToDictionary(t => t, _ => 0); - foreach (var t in bestOrder!) - for (var k = 1; k < options[t].Count && counter.Value < budget; k++) + return (bands, best); + } + + /// Band by band, each of the type's other options (narrower bands holding fewer + /// copies, lower bands) in its place, kept while that improves the sheet. + private SheetFill HoldBack(Band[] bands, SheetFill best, Dictionary> options, + IReadOnlyList remaining, CancellationToken token) + { + for (var i = 0; i < bands.Length; i++) + { + var choices = options[bands[i].Type]; + for (var k = 1; k < choices.Count && counter.Value < budget; k++) { - var trial = new Dictionary(choice) { [t] = k }; - var candidate = Run(bestOrder, trial, options, remaining, region, token); - if (compare(candidate, best!) < 0) + var trial = bands.ToArray(); + trial[i] = choices[k]; + var candidate = Run(trial, remaining, token); + if (compare(candidate, best) < 0) { best = candidate; - choice = trial; + 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, IReadOnlyList remaining, 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); + 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 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 @@ -120,161 +251,205 @@ internal sealed class BandedFill( { if (stock.Outline != null) return null; - var region = stock.WorkArea; - var spacing = System.Math.Max(0, stock.PartSpacing); - var bandCache = new Dictionary<(int, int), List>(); - var lookBack = types.Where(t => remaining[t.Index] > 0).SelectMany(t => t.Orientations) + 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(); - // The band searches this level needs, run ahead in parallel. - var searches = new List<(int Type, int Copies)>(); foreach (var state in beam) { - var next = types.Where(t => state.Rest[t.Index] > 0 && t.Orientations.Count > 0) - .OrderByDescending(t => t.Area).ThenBy(t => t.Index).FirstOrDefault(); - if (next == null || state.Front >= region.Right || state.Rest[next.Index] < GroupedFill.MinGroup) - continue; - var search = (next.Index, state.Rest[next.Index]); - if (!bandCache.ContainsKey(search) && !searches.Contains(search)) - searches.Add(search); - } - Prefetch(searches, region, token); - foreach (var state in beam) - { - var largest = types.Where(t => state.Rest[t.Index] > 0 && t.Orientations.Count > 0) - .OrderByDescending(t => t.Area).ThenBy(t => t.Index).FirstOrDefault(); - if (largest == null || state.Front >= region.Right || counter.Value >= budget) - { - finished.Add(state); - continue; - } - var t = largest.Index; - var start = state.Placed.Count == 0 ? state.Front : state.Front + spacing; - var offered = 0; - void Offer(List seatedNow, double end) - { - var reach = System.Math.Min(region.Right, end + 1e-6); - if (reach <= state.Front) - return; - var counts = state.Rest.ToArray(); - foreach (var p in seatedNow) - counts[p.Orientation.TypeIndex]--; - var all = state.Placed.Concat(seatedNow).ToList(); - // The gap fill looks back one part length behind the strip: gaps further back - // were filled with earlier strips, and parts there cost nothing to skip. - var left = System.Math.Max(region.Left, start - lookBack); - var fill = counts.Any(c => c > 0) - ? within(new Box(left, region.Bottom, reach - left, region.Width)).Fill(counts, token, all, region.Top) - : new SheetFill(stock, Array.Empty(), 0); - var parts = seatedNow.Concat(fill.Parts).ToList(); - if (parts.Count == 0 || !parts.Any(p => p.Orientation.TypeIndex == t)) - return; - var rest = state.Rest.ToArray(); - foreach (var p in parts) - rest[p.Orientation.TypeIndex]--; - children.Add(new StripState(all.Concat(fill.Parts).ToList(), rest, - state.Area + parts.Sum(p => types[p.Orientation.TypeIndex].Area), - System.Math.Max(state.Front, parts.Max(p => p.Right)))); - offered++; - } - if (state.Rest[t] >= GroupedFill.MinGroup) - { - if (!bandCache.TryGetValue((t, state.Rest[t]), out var bands)) - bandCache[(t, state.Rest[t])] = bands = Bands(t, state.Rest[t], region, region.Width, MaxSteps, Probes, token); - foreach (var band in bands) - { - if (band.Length > region.Right - start + 1e-9) - continue; - var members = Seat(band, start, region); - if (members.Count > 0) - Offer(members, members.Max(p => p.Right)); - } - } - // Strip widths of one to three copies across, each distinct width once. - var widths = new List(); - foreach (var o in largest.Orientations) - for (var k = 1; k <= 3; k++) - { - var width = k * o.Width + (k - 1) * spacing; - if (!widths.Any(w => System.Math.Abs(w - width) < 0.05)) - widths.Add(width); - } - // The strip's own part fills its column first, then the others fill around it. - foreach (var width in widths.OrderBy(w => w)) - { - var reach = System.Math.Min(region.Right, start + width + 1e-6); - if (reach <= state.Front) - continue; - var own = new int[types.Count]; - own[t] = state.Rest[t]; - var left = System.Math.Max(region.Left, start - lookBack); - var column = within(new Box(left, region.Bottom, reach - left, region.Width)) - .Fill(own, token, state.Placed, region.Top); - if (column.Parts.Count > 0) - Offer(column.Parts.ToList(), start + width); - } - if (offered == 0) + var next = NextStrips(state, run); + if (next.Count == 0) finished.Add(state); + else + children.AddRange(next); } - double Rank(StripState c) => -c.Area / System.Math.Max(c.Front - region.Left, 1e-9); - beam = new List(); - foreach (var child in children.OrderBy(Rank).ThenBy(c => c.Front)) - { - if (beam.Count >= beamWidth) - break; - if (beam.Any(b => System.Math.Abs(b.Front - child.Front) < 1e-6 && System.Math.Abs(b.Area - child.Area) < 1e-6 - && b.Rest.SequenceEqual(child.Rest))) - continue; - beam.Add(child); - } + beam = Densest(children, beamWidth); } SheetFill? best = null; foreach (var state in finished) { - var placed = state.Placed.ToList(); - var partArea = state.Area; - if (state.Rest.Any(r => r > 0)) - { - var tail = packer().Fill(state.Rest, token, placed); - placed.AddRange(tail.Parts); - partArea += tail.PartArea; - } - var sheet = new SheetFill(stock, placed, partArea); + var sheet = Finish(state.Placed, state.Area, state.Rest, token); if (best == null || compare(sheet, best) < 0) best = sheet; } return best; } - /// Partial sheets carried strip to strip. - private const int Beam = 4; + /// 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(); - private sealed record StripState(List Placed, int[] Rest, double Area, double Front); + /// 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, Box region) + 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 members = Shifted(region.Bottom - minY); - var tried = new List { region.Bottom - minY }; - foreach (var dy in new[] { region.Top - maxY, clear.Bottom - minY, clear.Top - maxY }) + 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 < region.Bottom - minY - 1e-9 || dy > region.Top - maxY + 1e-9 - || tried.Any(d => System.Math.Abs(d - dy) < 1e-9)) + if (dy < lowest - FitSlack || dy > highest + FitSlack + || tried.Any(d => System.Math.Abs(d - dy) < FitSlack)) continue; tried.Add(dy); var seated = Shifted(dy); @@ -284,71 +459,54 @@ internal sealed class BandedFill( return members; } - /// The bands placed left to right in , then everything - /// else filling around them. - private SheetFill Run(int[] order, Dictionary choice, Dictionary> options, - IReadOnlyList remaining, Box region, CancellationToken token) + /// + /// 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. + /// + private List BandOptions(int t, int copies, CancellationToken token) { - token.ThrowIfCancellationRequested(); - var seated = new List(); - var rest = remaining.ToArray(); - var front = region.Left; - var spacing = System.Math.Max(0, stock.PartSpacing); - foreach (var t in order) + 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 band = options[t][choice[t]]; - var room = region.Right - front; - if (room <= 0) + var height = last.Members.Max(p => p.Top) - last.Members.Min(p => p.Bottom) - StepShort; + if (height < shortest) break; - if (band.Length > room + 1e-9) - { - // The sheet ends inside this band: as many copies as the room left holds. - var partial = Pattern(t, band.Copies, room, band.Height, token); - if (partial == null) - continue; - band = partial; - } - var members = Seat(band, front, region); - var maxX = front; - foreach (var placed in members) - { - seated.Add(placed); - rest[t]--; - maxX = System.Math.Max(maxX, placed.Right); - } - front = maxX + spacing; + var lower = Bands(t, copies, height, LowerSteps, 0, token); + options.AddRange(lower); + last = lower.FirstOrDefault(); } - var parts = seated.ToList(); - var partArea = seated.Sum(p => types[p.Orientation.TypeIndex].Area); - 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); + return options; } + /// 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 full region height, narrowest full one first, then each narrower one + /// 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. /// - private List Bands(int t, int copies, Box region, double height, int steps, int probes, - CancellationToken token, Drawing? prefetch = null) + private List Bands(int t, int copies, double height, int steps, int probes, CancellationToken token, + Drawing? prefetch = null) { - var type = types[t]; 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 + 1e-6)) - { - found.RemoveAll(b => b.Copies <= band.Copies && b.Length >= band.Length - 1e-6); - found.Add(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; for (var step = 0; step < steps; step++) { @@ -358,11 +516,10 @@ internal sealed class BandedFill( Keep(band); length = band.Length - StepShort; } - var full = found.Where(b => b.Copies >= copies).OrderBy(b => b.Length).FirstOrDefault(); + var full = NarrowestFull(); if (full == null) return new List(); - var lo = System.Math.Max(type.Orientations.Min(o => System.Math.Min(o.Width, o.Height)), - copies * type.Area / height); + 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++) { @@ -375,53 +532,16 @@ internal sealed class BandedFill( else lo = mid; } - full = found.Where(b => b.Copies >= copies).OrderBy(b => b.Length).First(); - return found.Where(b => b.Copies < copies && b.Length < full.Length - 1e-6).OrderBy(b => -b.Copies) + full = NarrowestFull()!; + return found.Where(b => b.Copies < copies && b.Length < full.Length - Same).OrderByDescending(b => b.Copies) .Take(MaxNarrower).Prepend(full).ToList(); } - /// - /// for each type 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. - /// - private List[] BandsInParallel(int[] typeIndexes, IReadOnlyList remaining, Box region, - CancellationToken token) - { - var result = new List[typeIndexes.Length]; - System.Threading.Tasks.Parallel.For(0, typeIndexes.Length, - new System.Threading.Tasks.ParallelOptions { CancellationToken = token }, - i => result[i] = BandOptions(typeIndexes[i], remaining[typeIndexes[i]], region, token)); - return result; - } + /// Most copies a narrower band may leave to the gap fill. + private static int HeldBack(int copies) => System.Math.Max(MaxHeldBack, copies / 3); - /// - /// 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. - /// - private List BandOptions(int t, int copies, Box region, CancellationToken token, Drawing? prefetch = null) - { - var options = Bands(t, copies, region, region.Width, MaxSteps, Probes, token, prefetch); - var shortest = types[t].Orientations.Min(o => System.Math.Min(o.Width, o.Height)); - var last = options.FirstOrDefault(); - for (var i = 0; i < LowerHeights && last != null; i++) - { - var height = last.Members.Max(p => p.Top) - last.Members.Min(p => p.Bottom) - StepShort; - if (height < shortest) - break; - var lower = Bands(t, copies, region, height, LowerSteps, 0, token, prefetch); - options.AddRange(lower); - last = lower.FirstOrDefault(); - } - return options; - } - - /// 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; + 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 @@ -429,36 +549,24 @@ internal sealed class BandedFill( /// 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, Box region, CancellationToken token) + private void Prefetch(IReadOnlyList<(int Type, int Copies)> searches, CancellationToken token) { if (searches.Count < 2) return; - System.Threading.Tasks.Parallel.For(0, searches.Count, - new System.Threading.Tasks.ParallelOptions { CancellationToken = token }, - i => + Parallel.For(0, searches.Count, new ParallelOptions { CancellationToken = token }, i => + { + var drawing = BlockCatalog.PrefetchDrawing(types[searches[i].Type]); + try { - var drawing = BlockCatalog.PrefetchDrawing(types[searches[i].Type]); - try - { - Bands(searches[i].Type, searches[i].Copies, region, region.Width, MaxSteps, Probes, token, drawing); - } - finally - { - BlockCatalog.ReleasePrefetch(drawing); - } - }); + FullBands(searches[i].Type, searches[i].Copies, token, drawing); + } + finally + { + BlockCatalog.ReleasePrefetch(drawing); + } + }); } - /// Most copies a narrower band may leave to the gap fill. - private static int HeldBack(int copies) => System.Math.Max(MaxHeldBack, copies / 3); - - private const int MaxSteps = 6; - - /// Narrower bands offered per type, those holding the most copies first. - private const int MaxNarrower = 2; - private const int Probes = 3; - private const double StepShort = 0.01; - /// 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, @@ -466,7 +574,7 @@ internal sealed class BandedFill( { 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 + 1e-9) + 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); }