diff --git a/OpenNest.Engine/CuttingPlanning/CuttingNestedOrder.cs b/OpenNest.Engine/CuttingPlanning/CuttingNestedOrder.cs index a3ad0395..c11c8542 100644 --- a/OpenNest.Engine/CuttingPlanning/CuttingNestedOrder.cs +++ b/OpenNest.Engine/CuttingPlanning/CuttingNestedOrder.cs @@ -22,9 +22,12 @@ internal static class CuttingNestedOrder /// The point on a host's contours nearest a tool position. /// Optional point each part is left from (a cut-off's far end); null when /// every part is left from its center. + /// Optional points per part ordinal where a slender part may be reached and + /// left (see ); null when every part keeps its center. internal sealed record Context(IReadOnlyList Centers, IReadOnlyList> Prerequisites, IReadOnlyList> Inside, - Func HostEntry, CancellationToken Token, IReadOnlyList Exits = null); + Func HostEntry, CancellationToken Token, IReadOnlyList Exits = null, + IReadOnlyList> Visits = null); /// The part ordinals to order; prerequisites outside this set count as done. /// The modeled tool position before the first of these parts. @@ -65,14 +68,15 @@ internal static class CuttingNestedOrder int[] rootOrder; try { - rootOrder = CuttingPartOrder.Plan(roots, context.Centers, start, hostsLast, context.Token, endpoint, context.Exits); + rootOrder = CuttingPartOrder.Plan(roots, context.Centers, start, hostsLast, context.Token, endpoint, context.Exits, + context.Visits); } catch (InvalidOperationException) { try { rootOrder = CuttingPartOrder.Plan(roots, context.Centers, start, groupRules, context.Token, endpoint, - context.Exits); + context.Exits, context.Visits); } catch (InvalidOperationException) { @@ -99,6 +103,6 @@ internal static class CuttingNestedOrder return order.ToArray(); int[] Flat() => CuttingPartOrder.Plan(parts, context.Centers, start, context.Prerequisites, context.Token, endpoint, - context.Exits); + context.Exits, context.Visits); } } diff --git a/OpenNest.Engine/CuttingPlanning/CuttingPartOrder.cs b/OpenNest.Engine/CuttingPlanning/CuttingPartOrder.cs index 89e30817..73716836 100644 --- a/OpenNest.Engine/CuttingPlanning/CuttingPartOrder.cs +++ b/OpenNest.Engine/CuttingPlanning/CuttingPartOrder.cs @@ -13,6 +13,9 @@ namespace OpenNest.Engine.CuttingPlanning; /// rapid and lead along it. A part may be left from somewhere other than where it is reached (a /// cut-off is entered at its start and left at its far end): each leg then runs from one part's /// exit to the next part's center, and a reversed run is costed along its own directed legs. +/// A slender part may instead carry visit points: the tool reaches it at one of them and leaves +/// from the same one, whichever suits the parts on either side, so a long strip beside a row is +/// costed from its near end rather than from a center far from where it is cut. /// internal static class CuttingPartOrder { @@ -21,6 +24,9 @@ internal static class CuttingPartOrder /// Upper bound on improvement passes, so a large plate cannot loop for long. internal const int MaxPasses = 50; + /// Upper bound on rounds of placing slender parts at their visit points. + internal const int MaxVisitRounds = 8; + /// The part ordinals to order; prerequisites outside this set count as done. /// One representative point per part ordinal. /// The modeled tool position before the first of these parts. @@ -28,9 +34,10 @@ internal static class CuttingPartOrder /// Optional fixed final position after the last of these parts. /// Optional point each part is left from, per part ordinal; null when every /// part is left from its center. + /// Optional visit points per part ordinal; see the other overload. internal static int[] Plan(IReadOnlyList parts, IReadOnlyList centers, Vector start, IReadOnlyList> prerequisites, CancellationToken token, Vector? endpoint = null, - IReadOnlyList exits = null) + IReadOnlyList exits = null, IReadOnlyList> visits = null) { var local = new Dictionary(); for (var i = 0; i < parts.Count; i++) @@ -40,7 +47,9 @@ internal static class CuttingPartOrder .Select(p => (IReadOnlyCollection)prerequisites[p].Where(local.ContainsKey).Select(q => local[q]).ToArray()) .ToArray(); var localExits = exits == null ? null : parts.Select(p => exits[p]).ToArray(); - return Plan(localCenters, start, localPrerequisites, token, endpoint, localExits).Select(i => parts[i]).ToArray(); + var localVisits = visits == null ? null : parts.Select(p => visits[p]).ToArray(); + return Plan(localCenters, start, localPrerequisites, token, endpoint, localExits, localVisits) + .Select(i => parts[i]).ToArray(); } /// One representative point per part ordinal. @@ -55,13 +64,41 @@ internal static class CuttingPartOrder /// Optional point each part is left from; null (every part left from its center) keeps the /// symmetric route exactly. /// + /// + /// Optional points per part ordinal where a slender part may be reached and left; null or empty + /// for an ordinary part, which keeps its center and exit. Such a part is entered and left at the + /// same point. After the center tour, each is put at its best visit point for its neighbors and + /// moved to the gap where that detour is shortest, and the tour is improved again with those + /// points. Null keeps the center tour exactly. + /// internal static int[] Plan(IReadOnlyList centers, Vector start, IReadOnlyList> prerequisites, CancellationToken token, Vector? endpoint = null, - IReadOnlyList exits = null) + IReadOnlyList exits = null, IReadOnlyList> visits = null) { var count = centers.Count; var order = NearestNeighbor(centers, exits ?? centers, start, prerequisites, token); var position = new int[count]; + Improve(order, centers, exits, start, prerequisites, position, token, endpoint); + if (visits == null || !visits.Any(points => points is { Count: > 0 })) + return order; + + var arrive = centers.ToArray(); + var leave = (exits ?? centers).ToArray(); + for (var round = 0; round < MaxVisitRounds; round++) + { + token.ThrowIfCancellationRequested(); + var changed = Settle(order, arrive, leave, visits, start, endpoint); + changed |= Relocate(order, arrive, leave, visits, start, prerequisites, position, token, endpoint); + if (!changed) + break; + Improve(order, arrive, leave, start, prerequisites, position, token, endpoint); + } + return order; + } + + private static void Improve(int[] order, IReadOnlyList centers, IReadOnlyList exits, Vector start, + IReadOnlyList> prerequisites, int[] position, CancellationToken token, Vector? endpoint) + { for (var pass = 0; pass < MaxPasses; pass++) { token.ThrowIfCancellationRequested(); @@ -70,7 +107,90 @@ internal static class CuttingPartOrder if (!improved) break; } - return order; + } + + // The visit point cheapest between where the tool comes from and where it goes next (null at + // the open end), with the length of that detour. + private static (Vector Point, double Cost) BestVisit(IReadOnlyList points, Vector from, Vector? to) + { + var best = points[0]; + var bestCost = double.MaxValue; + foreach (var point in points) + { + var cost = from.DistanceTo(point) + (to is { } next ? point.DistanceTo(next) : 0); + if (cost < bestCost - Epsilon) + { + best = point; + bestCost = cost; + } + } + return (best, bestCost); + } + + // Puts each slender part at its best visit point for the parts now on either side of it. + private static bool Settle(int[] order, Vector[] arrive, Vector[] leave, + IReadOnlyList> visits, Vector start, Vector? endpoint) + { + var changed = false; + for (var k = 0; k < order.Length; k++) + { + var part = order[k]; + if (visits[part] is not { Count: > 0 } points) + continue; + var from = k == 0 ? start : leave[order[k - 1]]; + var to = k + 1 < order.Length ? arrive[order[k + 1]] : endpoint; + var current = from.DistanceTo(arrive[part]) + (to is { } next ? arrive[part].DistanceTo(next) : 0); + var (point, cost) = BestVisit(points, from, to); + if (cost >= current - Epsilon) + continue; + arrive[part] = leave[part] = point; + changed = true; + } + return changed; + } + + // Moves each slender part, at its best visit point, to the gap where its detour is shortest, + // when that beats its detour where it is and keeps every prerequisite earlier. + private static bool Relocate(int[] order, Vector[] arrive, Vector[] leave, + IReadOnlyList> visits, Vector start, IReadOnlyList> prerequisites, + int[] position, CancellationToken token, Vector? endpoint) + { + var changed = false; + var count = order.Length; + for (var part = 0; part < count; part++) + { + if (visits[part] is not { Count: > 0 } points) + continue; + token.ThrowIfCancellationRequested(); + var at = Array.IndexOf(order, part); + var rest = order.Where(p => p != part).ToArray(); + var current = Detour(points, rest, at).Cost; + var gaps = Enumerable.Range(0, count).Where(gap => gap != at) + .Select(gap => (Gap: gap, Detour: Detour(points, rest, gap))) + .Where(g => g.Detour.Cost < current - Epsilon) + .OrderBy(g => g.Detour.Cost).ThenBy(g => g.Gap); + foreach (var (gap, detour) in gaps) + { + var candidate = rest.Take(gap).Append(part).Concat(rest.Skip(gap)).ToArray(); + if (!Valid(candidate, prerequisites, position)) + continue; + Array.Copy(candidate, order, count); + arrive[part] = leave[part] = detour.Point; + changed = true; + break; + } + } + return changed; + + // The detour through the part inserted before rest[gap] (after the last at the end), net + // of the leg it replaces. + (Vector Point, double Cost) Detour(IReadOnlyList points, int[] rest, int gap) + { + var from = gap == 0 ? start : leave[rest[gap - 1]]; + Vector? to = gap < rest.Length ? arrive[rest[gap]] : endpoint; + var (point, cost) = BestVisit(points, from, to); + return (point, cost - (to is { } next ? from.DistanceTo(next) : 0)); + } } private static int[] NearestNeighbor(IReadOnlyList centers, IReadOnlyList exits, Vector start, diff --git a/OpenNest.Engine/CuttingPlanning/JointCuttingPlanSearch.cs b/OpenNest.Engine/CuttingPlanning/JointCuttingPlanSearch.cs index 9c5cc05e..6f8d9368 100644 --- a/OpenNest.Engine/CuttingPlanning/JointCuttingPlanSearch.cs +++ b/OpenNest.Engine/CuttingPlanning/JointCuttingPlanSearch.cs @@ -127,7 +127,7 @@ internal static class JointCuttingPlanSearch return kept.Order != null ? walk.Ready(kept.Order) : walk.Exhausted(); } - var centers = snapshot.Placements.Select(Center).ToArray(); + var centers = snapshot.Placements.Select(Arrival).ToArray(); var prerequisites = Enumerable.Range(0, count) .Select(i => new HashSet(snapshot.Dependencies.PrerequisitesOf(i).Except(excluded))).ToArray(); @@ -250,7 +250,8 @@ internal static class JointCuttingPlanSearch private static CuttingNestedOrder.Context NestedOrder(CuttingPlanSnapshot snapshot, Vector[] centers, HashSet[] prerequisites, CancellationToken token) { - var exits = snapshot.Placements.Any(p => p.IsCutOff) ? snapshot.Placements.Select(Exit).ToArray() : null; + var exits = snapshot.Placements.Any(IsFixed) ? snapshot.Placements.Select(Exit).ToArray() : null; + var visits = snapshot.Placements.Select(p => Visits(p, token)).ToArray(); var inside = snapshot.Placements.Select((placement, host) => placement.IsCutOff ? [] : snapshot.Dependencies.PrerequisitesOf(host).Where(p => !snapshot.Placements[p].IsCutOff).ToArray()).ToArray(); var contours = new Dictionary(); @@ -262,7 +263,7 @@ internal static class JointCuttingPlanSearch .Select(m => m.Curve.ToEntity()).ToArray(); return entities.Length == 0 ? centers[host] : entities.Select(e => e.ClosestPointTo(position)).MinBy(point => point.DistanceTo(position)); - }, token, exits); + }, token, exits, visits.Any(v => v != null) ? visits : null); } // Whether the pass stopped at a part whose approach crossed a tabbed part the capture still @@ -369,9 +370,47 @@ internal static class JointCuttingPlanSearch ? start : CutExtent(placement)?.Center ?? placement.Execution.DeparturePoint; - // Where the tool leaves a part, for ordering only: a cut-off's far end, otherwise its center. + // A program the planner keeps as given (a locked part or a cut-off): its pierce and departure + // are known, so the order is costed from them rather than from its center. + private static bool IsFixed(FixedProgramPlacement placement) => + placement.Prepared == null && placement.Execution.Motions.Any(m => !m.Rapid); + + // Where the tool reaches a part, for ordering only: a fixed program's first cut, otherwise its center. + private static Vector Arrival(FixedProgramPlacement placement) => + IsFixed(placement) && placement.Execution.Motions.First(m => !m.Rapid) is { Start: { } start } + ? start + : Center(placement); + + // Where the tool leaves a part, for ordering only: a fixed program's departure, otherwise its center. private static Vector Exit(FixedProgramPlacement placement) => - placement.IsCutOff ? placement.Execution.DeparturePoint : Center(placement); + IsFixed(placement) ? placement.Execution.DeparturePoint : Center(placement); + + /// Cut extents at least this many times longer than wide make a part slender. + internal const double SlenderAspect = 3; + + // Where the order may reach and leave a slender regenerated part with holes: its holes are cut + // first and its outside entry then leaves beside them toward the next part, so the tool is at a + // hole, possibly at one end of a long strip. Null for any other part, which keeps its center: a + // hole-less part's entry faces whatever comes next, so no point of it is likelier than another. + private static Vector[] Visits(FixedProgramPlacement placement, CancellationToken token) + { + if (placement.Prepared is not { HasCutPerimeter: true, PerimeterOrdinal: > 0 } prepared + || CutExtent(placement) is not { } box) + return null; + var across = box.Right - box.Left; + var up = box.Top - box.Bottom; + if (System.Math.Min(across, up) <= 0 || System.Math.Max(across, up) < SlenderAspect * System.Math.Min(across, up)) + return null; + var holes = prepared.HoleCenters(token).Take(prepared.PerimeterOrdinal) + .Where(c => c != null).Select(c => c!.Value + placement.Location).ToArray(); + if (holes.Length <= MaxVisitPoints) + return holes.Length == 0 ? null : holes; + // Evenly spread, the first and last included. + return Enumerable.Range(0, MaxVisitPoints) + .Select(i => holes[(int)System.Math.Round(i * (holes.Length - 1) / (double)(MaxVisitPoints - 1))]).ToArray(); + } + + private const int MaxVisitPoints = 12; // The extent of the part's placed cut material, or null when it has none. private static Box CutExtent(FixedProgramPlacement placement) diff --git a/OpenNest.Tests/CuttingPlanning/CuttingPartOrderTests.cs b/OpenNest.Tests/CuttingPlanning/CuttingPartOrderTests.cs index 3c284469..97efb6f6 100644 --- a/OpenNest.Tests/CuttingPlanning/CuttingPartOrderTests.cs +++ b/OpenNest.Tests/CuttingPlanning/CuttingPartOrderTests.cs @@ -122,6 +122,32 @@ public class CuttingPartOrderTests CancellationToken.None, exits: exits)); } + // Rows 0-9 stand at (0, 1) to (0, 10); part 10 is a strip whose center (3, 5) is beside the + // middle rows but which is only reached at its top end, (1, 9.5). + [Fact] + public void Plan_ReachesASlenderPartAtItsVisitPoint() + { + var centers = Enumerable.Range(1, 10).Select(y => new Vector(0, y)).Append(new Vector(3, 5)).ToArray(); + var visits = new IReadOnlyList[11]; + visits[10] = [new Vector(1, 9.5)]; + + var byCenter = Plan(centers, NoPrerequisites(11)); + var byVisit = CuttingPartOrder.Plan(centers, Vector.Zero, NoPrerequisites(11), CancellationToken.None, + visits: visits); + + Assert.InRange(Array.IndexOf(byCenter, 10), 1, 9); + Assert.Equal(Enumerable.Range(0, 11), byVisit); + } + + [Fact] + public void Plan_WithoutVisitPoints_KeepsTheCenterTour() + { + Vector[] centers = [new(-2, -1), new(0, -2), new(-4, 3), new(2, -4), new(0, -1)]; + + Assert.Equal(Plan(centers, NoPrerequisites(5)), CuttingPartOrder.Plan(centers, Vector.Zero, + NoPrerequisites(5), CancellationToken.None, visits: new IReadOnlyList[5])); + } + private static int[] Plan(Vector[] centers, IReadOnlyCollection[] prerequisites) => CuttingPartOrder.Plan(centers, Vector.Zero, prerequisites, CancellationToken.None); diff --git a/OpenNest.Tests/CuttingPlanning/PlanningCharacterizationTests.cs b/OpenNest.Tests/CuttingPlanning/PlanningCharacterizationTests.cs index 4a953432..51272381 100644 --- a/OpenNest.Tests/CuttingPlanning/PlanningCharacterizationTests.cs +++ b/OpenNest.Tests/CuttingPlanning/PlanningCharacterizationTests.cs @@ -45,7 +45,7 @@ public class PlanningCharacterizationTests [InlineData("holes-grid-kept-order", "93C5F4551BBB1246D0CD0BA569A0724E3900ADB07C25FC796E6B5A28E9F79FF1")] [InlineData("rounded-circle-leads", "E403D2486E2921A80A52C1C1787D63E52A308D54999A7D88E5B05EC99B65BEA7")] [InlineData("tabbed-perimeters", "BE84012043FDCA472AFC8E5508CEB49D7A18F1FC964717D8F6938D46E412065F")] - [InlineData("locked-among-regenerated", "CB8D8FB78148BED5D95B469B046548B3AD9A7457AE4AD4277BC8E32841EB8D74")] + [InlineData("locked-among-regenerated", "B8B46DE5244E4F18D359AF6CED3DEE2EE80E2B5C8806D66F382E39F5FFE297ED")] public void FocusedFixture_PlansExactlyAsBefore(string name, string expected) { var nest = new Nest(); diff --git a/OpenNest.Tests/CuttingPlanning/SlenderPartOrderTests.cs b/OpenNest.Tests/CuttingPlanning/SlenderPartOrderTests.cs new file mode 100644 index 00000000..46f62c0b --- /dev/null +++ b/OpenNest.Tests/CuttingPlanning/SlenderPartOrderTests.cs @@ -0,0 +1,89 @@ +using OpenNest.CNC; +using OpenNest.CNC.CuttingPlanning; +using OpenNest.CNC.CuttingStrategy; +using OpenNest.Engine.CuttingPlanning; +using OpenNest.Geometry; + +namespace OpenNest.Tests.CuttingPlanning; + +/// +/// A long strip standing beside a stack of rows (N26-2DJ: one terminal turned upright beside the +/// others) is cut where the tool reaches it, its top end, not where its center sits halfway up. +/// +public class SlenderPartOrderTests +{ + private const int Rows = 16; + + [Fact] + public void LockedStrip_IsCutBesideTheRowsNearItsPierce() + { + var parameters = ExplicitContourTests.Parameters(); + var parts = Stack(parameters); + var strip = Strip(parameters, LeadPathValidationTests.Rectangle(0, 0, 1, 14)); + strip.LeadInsLocked = true; + parts.Add(strip); + + var position = PositionOf(strip, parts, parameters); + + // Its pierce is at its top, beside rows 8 and 9. Ordered by its center, beside rows 4 + // and 5, it was cut sixth. + Assert.True(position is >= 8 and <= 10, $"strip cut at position {position}"); + } + + [Fact] + public void StripWithAHoleAtItsTop_IsCutBesideTheRowsNearTheHole() + { + var parameters = ExplicitContourTests.Parameters(); + var parts = Stack(parameters); + var drawing = LeadPathValidationTests.Rectangle(0, 0, 1, 14); + drawing.MoveTo(0.75, 13.5); drawing.ArcTo(0.75, 13.5, 0.5, 13.5, RotationType.CCW); + var strip = Strip(parameters, drawing); + parts.Add(strip); + + var position = PositionOf(strip, parts, parameters); + + // Its hole is cut first and its outside entry leaves beside it, at its top. Ordered by its + // center, it was cut last. + Assert.True(position is >= 8 and <= 10, $"strip cut at position {position}"); + } + + private static int PositionOf(Part strip, List parts, CuttingParameters parameters) + { + var result = CuttingPlanService.Plan(new CuttingPlanRequest(parts, confirmedParameters: parameters)); + Assert.True(result.ProposedOrder.Count != 0, $"{result.Status}: {string.Join("; ", result.Findings.Select(f => f.Message))}"); + return result.ProposedOrder.Select(p => p.SourcePart).ToList().IndexOf(strip); + } + + // Sixteen 16 x 1 rows, 1.5 apart, from y 0.5, each with a hole at its right end like the + // terminals: the stack runs on well past the strip's top. + private static List Stack(CuttingParameters parameters) => + Enumerable.Range(0, Rows).Select(row => + { + var clean = LeadPathValidationTests.Rectangle(0, 0, 16, 1); + clean.MoveTo(15.75, 0.5); clean.ArcTo(15.75, 0.5, 15.5, 0.5, RotationType.CCW); + var part = new Part(new Drawing($"row {row}", clean), new Vector(0, 0.5 + 1.5 * row)); + var prepared = PreparedContours.Capture(clean, parameters); + var choices = Enumerable.Range(0, prepared.Count) + .Select(contour => prepared.ClosestEntry(contour, contour == prepared.PerimeterOrdinal + ? new Vector(17, 0.5) : new Vector(15.75, 0.5))) + .ToArray(); + Assert.True(part.RestoreLeadInProgram(prepared.Emit(choices), false)); + part.CuttingParameters = parameters; + return part; + }).ToList(); + + // A 1 x 14 strip standing beside the rows, entered at its top edge. + private static Part Strip(CuttingParameters parameters, Program clean) + { + var part = new Part(new Drawing("strip", clean), new Vector(17, 0.5)); + var prepared = PreparedContours.Capture(clean, parameters); + var choices = Enumerable.Range(0, prepared.Count) + .Select(contour => contour == prepared.PerimeterOrdinal + ? prepared.ClosestEntry(contour, new Vector(0.5, 15)) + : prepared.ClosestEntry(contour, new Vector(0.75, 13.5))) + .ToArray(); + Assert.True(part.RestoreLeadInProgram(prepared.Emit(choices), false)); + part.CuttingParameters = parameters; + return part; + } +} diff --git a/docs/cutting-planner.md b/docs/cutting-planner.md index 7fb4973a..a9e08679 100644 --- a/docs/cutting-planner.md +++ b/docs/cutting-planner.md @@ -231,10 +231,17 @@ strip lines were added, and the segments are placed into that plan afterwards (s [cutoff segments](#cutoff-segments) below). The order is an open traveling-salesman path over part centers from the start point: nearest neighbor, then 2-opt reversals and Or-opt moves of one to three parts, never placing a part -before a cutoff or nested-part prerequisite. A cutoff is not a center: the path reaches -it where its cut starts and leaves from where it ends (read from its program as given; -the search may still reverse a head-locked far-edge segment), and a reversed run is -costed along its own legs from each part's exit. The parts +before a cutoff or nested-part prerequisite. A cutoff, or any program kept as given (a +locked part), is not a center: the path reaches it where its cut starts and leaves from +where it ends (read from its program as given; the search may still reverse a +head-locked far-edge segment), and a reversed run is costed along its own legs from each +part's exit. A slender regenerated part with holes (its cut extent at least three times +longer than wide) is not a center either: its holes are cut first and its outside entry +leaves beside them, so after the center tour the path reaches and leaves it at whichever +hole center suits the parts on either side, moves it to the gap where that detour is +shortest, and improves the tour again with those points. A long strip standing beside a +row of parts is then cut beside the rows at its holed end, not beside its middle, where +its center is. A hole-less part keeps its center: its entry faces whatever comes next. The parts before a line that splits the sheet therefore finish beside its start, and the part cut just before it faces that start. A part with other parts nested in its cutouts (a host) is cut after all of them, so the tool reaches it from whichever was