using System; using System.Collections.Generic; using System.Linq; using System.Threading; using OpenNest.Engine.Fill; using OpenNest.Geometry; namespace OpenNest.Engine.Jobs.Placement; /// New parts proposed for the leftover space of a plate that already holds parts. /// The nest's plate; never changed by the fill. /// The plate's parts when the fill ran, in order; the commit refuses a /// plate whose parts changed since. /// The proposed parts, clear of and the clamps. public sealed record LeftoverPlateFill(Plate Plate, IReadOnlyList Occupants, IReadOnlyList Parts); /// What proposed. /// One entry per plate that received parts, in the order given. /// Layout problems the independent check found in the proposals. /// Occupied plates the fill cannot use: an outlined sheet, or one with /// cut-offs. public sealed record LeftoverFillResult( IReadOnlyList Plates, IReadOnlyList Violations, IReadOnlyList Skipped) { public static LeftoverFillResult Empty { get; } = new(Array.Empty(), Array.Empty(), Array.Empty()); /// Copies of each drawing the proposals use, counting every physical copy of a plate /// (), by drawing reference. public IReadOnlyDictionary Placed() { var placed = new Dictionary(ReferenceEqualityComparer.Instance); foreach (var fill in Plates) foreach (var part in fill.Parts) placed[part.BaseDrawing] = placed.GetValueOrDefault(part.BaseDrawing) + System.Math.Max(1, fill.Plate.Quantity); return placed; } } /// /// Auto Nest's "current plates" leftover stage: fills the free space on plates that already hold /// parts with the fill strategies, around the parts already there, and checks each proposal with /// the same layout rules as a whole-job result, the existing parts held fixed. Whole-job engines /// never place on an occupied plate; only these certified fill proposals do. Nothing is /// committed: the plates and the caller's items are left unchanged. /// public static class PlateLeftoverFill { /// Fill rounds per item on one plate; a round that adds nothing ends it. private const int MaxRounds = 8; /// True when holds parts and the fill can use its leftover /// space: a rectangular sheet without cut-offs. public static bool CanFill(Plate plate) => plate != null && HasParts(plate) && PlateFillService.Refusal(plate) == null && plate.CutOffs.Count == 0 && !plate.Parts.Any(p => p.BaseDrawing.IsCutOff); /// True when holds at least one part that is not a cut-off. public static bool HasParts(Plate plate) => plate.Parts.Any(p => !p.BaseDrawing.IsCutOff); /// /// Fills each occupied plate of (the nest's plates, in order: messages /// name a plate by its position here) in turn with what remains of /// : items by priority, then larger parts first, each into the largest /// free rectangles left beside the parts already there. A plate repeated /// times uses that many copies of each part it receives. /// public static LeftoverFillResult Run( IReadOnlyList plates, IReadOnlyList items, string strategy, IProgress progress, CancellationToken token) { ArgumentNullException.ThrowIfNull(plates); ArgumentNullException.ThrowIfNull(items); var remaining = items.Where(i => i?.Drawing != null && i.Quantity > 0) .Select(i => (Item: i, Left: i.Quantity)) .ToList(); var fills = new List(); var violations = new List(); var skipped = new List(); for (var index = 0; index < plates.Count; index++) { token.ThrowIfCancellationRequested(); var plate = plates[index]; if (plate == null || !HasParts(plate)) continue; if (!CanFill(plate)) { skipped.Add(plate); continue; } if (remaining.All(r => r.Left <= 0)) break; var copies = System.Math.Max(1, plate.Quantity); var occupants = plate.Parts.ToList(); var accepted = new List(); var caps = new Dictionary(ReferenceEqualityComparer.Instance); foreach (var (item, left) in remaining .OrderByDescending(r => r.Item.Priority) .ThenByDescending(r => r.Item.Drawing.Area)) { var cap = left / copies; if (cap <= 0) continue; caps[item.Drawing] = caps.GetValueOrDefault(item.Drawing) + cap; FillItem(plate, item, cap, strategy, accepted, token); } if (accepted.Count == 0) continue; var check = Check(plate, occupants, accepted, caps); violations.AddRange(check.Select(v => $"Plate {index + 1}: {v}")); fills.Add(new LeftoverPlateFill(plate, occupants.AsReadOnly(), accepted.AsReadOnly())); // Two items of one drawing share its parts: each takes what it can, in order. var used = accepted .GroupBy(p => p.BaseDrawing, ReferenceEqualityComparer.Instance) .ToDictionary(g => g.Key, g => g.Count() * copies, ReferenceEqualityComparer.Instance); for (var i = 0; i < remaining.Count; i++) { var drawing = remaining[i].Item.Drawing; var take = System.Math.Min(remaining[i].Left, used.GetValueOrDefault(drawing)); used[drawing] = used.GetValueOrDefault(drawing) - take; remaining[i] = (remaining[i].Item, remaining[i].Left - take); } progress?.Report(new NestProgress { BestParts = occupants.Concat(accepted).ToList(), ActiveWorkArea = plate.WorkArea(), PlateNumber = index + 1, IsOverallBest = true, Description = $"Plate {index + 1}: {accepted.Count} parts added around existing parts", }); } return new LeftoverFillResult(fills.AsReadOnly(), violations.AsReadOnly(), skipped.AsReadOnly()); } /// /// Up to copies of into the free rectangles of /// , largest first, recomputing them after every accepted fill (free /// rectangles overlap). Every proposal is certified clear of the plate's parts, the parts /// already accepted and the clamps, and must keep the item's rotation limits. /// private static void FillItem(Plate plate, NestItem item, int cap, string strategy, List accepted, CancellationToken token) { var rotation = RotationPolicy.FromLegacy(item.StepAngle, item.RotationStart, item.RotationEnd, item.Drawing.Constraints?.Allow180Equivalent ?? false); var size = item.Drawing.Program.BoundingBox(); var placed = 0; for (var round = 0; round < MaxRounds && placed < cap; round++) { var before = placed; foreach (var region in FreeRegions(plate, accepted)) { token.ThrowIfCancellationRequested(); if (placed >= cap) break; if (!Fits(region, size)) continue; var demand = new NestItem { Drawing = item.Drawing, Quantity = cap - placed, Priority = item.Priority, RotationStart = item.RotationStart, RotationEnd = item.RotationEnd, StepAngle = item.StepAngle, }; var proposed = PlateFillService.FillItem(strategy, plate, demand, region, null, token) ?.Where(p => rotation.Allows(p.Rotation)) .ToList(); var clear = PlateFillService.CertifyClear(plate, region, proposed, accepted, new List { demand }); if (clear.Count == 0) continue; accepted.AddRange(clear); placed += clear.Count; // The free rectangles changed; start again from the largest. break; } if (placed == before) return; } } /// The plate's free rectangles beside its parts, the accepted parts and the clamps, /// largest first. private static List FreeRegions(Plate plate, List accepted) { var obstacles = InteractiveClamps.ClearanceRectangles(plate).ToList(); obstacles.AddRange(plate.Parts.Where(part => !part.BaseDrawing.IsCutOff) .Concat(accepted) .Select(part => part.BoundingBox.Offset(plate.PartSpacing))); return new RemnantFinder(plate.WorkArea(), obstacles).FindRemnants() .OrderByDescending(box => box.Length * box.Width) .ToList(); } private static bool Fits(Box region, Box size) { const double slack = 1e-6; return (region.Length + slack >= size.Length && region.Width + slack >= size.Width) || (region.Length + slack >= size.Width && region.Width + slack >= size.Length); } /// The whole-job layout rules on the plate's parts plus the proposal, the parts /// already there held fixed. private static List Check(Plate plate, List occupants, List proposed, IReadOnlyDictionary caps) { var requirements = caps.ToDictionary( c => c.Key, c => (c.Key.Name, c.Value), (IEqualityComparer)ReferenceEqualityComparer.Instance); var fixedParts = new HashSet(occupants, ReferenceEqualityComparer.Instance); return NestLayoutCheck.Validate( new List<(Plate, List)> { (plate, occupants.Concat(proposed).ToList()) }, requirements, fixedParts); } }