From db4b573e3bd103c60007f092776790c3e29ba086 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Mon, 23 Nov 2026 17:41:16 -0500 Subject: [PATCH] fix(cutting): keep planned leads on the sheet Plan Cutting checked each lead only against part material, so it could pick an entry whose lead-in pierced past the plate's edge and still call the plan Ready; only the pre-post plate edge check noticed (N26-2D6 plate 2: PT97 0.25 from the left edge, a 0.3125 lead at 60 degrees ran 0.062 off it). The planner now stamps the plate's box on each part's lead material, and LeadPathValidator refuses a lead-in or lead-out past it by more than the plate edge check's slack, so the search enters from a side with room and a contour with none fails naming the edge. A locked or pinned lead off the sheet is a FixedLead warning. A part whose own material is already off the sheet keeps the old checks: no lead can fix it, and the edge check reports it. Co-Authored-By: Claude Opus 5.5 --- .../CuttingPlanning/LeadMaterialSnapshot.cs | 8 ++ .../CNC/CuttingPlanning/LeadPathValidator.cs | 47 ++++++- .../CuttingPlanning/ContourEntrySelection.cs | 6 +- .../CuttingPlanning/CuttingPlanService.cs | 18 +++ .../CuttingPlanning/FixedLeadWarnings.cs | 1 + .../CommonLines/CommonLinePlanningTests.cs | 3 +- .../CuttingPlanning/LeadOffSheetTests.cs | 132 ++++++++++++++++++ .../PlanningCharacterizationTests.cs | 5 +- docs/cutting-planner.md | 11 +- 9 files changed, 222 insertions(+), 9 deletions(-) create mode 100644 OpenNest.Tests/CuttingPlanning/LeadOffSheetTests.cs diff --git a/OpenNest.Core/CNC/CuttingPlanning/LeadMaterialSnapshot.cs b/OpenNest.Core/CNC/CuttingPlanning/LeadMaterialSnapshot.cs index 14b68c91..afc1f71c 100644 --- a/OpenNest.Core/CNC/CuttingPlanning/LeadMaterialSnapshot.cs +++ b/OpenNest.Core/CNC/CuttingPlanning/LeadMaterialSnapshot.cs @@ -48,6 +48,14 @@ public sealed class LeadMaterialSnapshot /// internal bool HasDisplayPerimeter { get; } + /// + /// The sheet this material is placed on (the plate's box, in the same frame), or null when + /// the check has no plate. Lead motions checked against this material as their own part's + /// must stay on it (): a pierce or lead off the sheet cuts air, + /// or the table. Set once by the planner's capture, before any check reads it. + /// + internal Box Sheet { get; set; } + /// Capture a stable, clean, rotation-baked program, applying location once. /// Unsupported or malformed geometry produces an incomplete snapshot; cancellation throws. public static LeadMaterialSnapshot Capture(Program cleanProgram, Vector location, diff --git a/OpenNest.Core/CNC/CuttingPlanning/LeadPathValidator.cs b/OpenNest.Core/CNC/CuttingPlanning/LeadPathValidator.cs index b17ddf1a..f70ad51b 100644 --- a/OpenNest.Core/CNC/CuttingPlanning/LeadPathValidator.cs +++ b/OpenNest.Core/CNC/CuttingPlanning/LeadPathValidator.cs @@ -12,10 +12,11 @@ public sealed record LeadPathValidationResult(bool IsComplete, bool IsClear, str /// /// One lead motion of a fixed emission that failed validation. indexes the -/// other materials passed to the check, or is null when the lead meets its own part's material -/// or could not be checked. +/// other materials passed to the check, or is null when the lead meets its own part's material, +/// runs off the sheet () or could not be checked. /// -internal sealed record FixedLeadFailure(int Motion, LeadPathValidationResult Result, int? Obstacle); +internal sealed record FixedLeadFailure(int Motion, LeadPathValidationResult Result, int? Obstacle, + bool OffSheet = false); /// Certifies actual emitted native lead paths against owned nominal material. public static class LeadPathValidator @@ -79,6 +80,13 @@ public static class LeadPathValidator if (move.Layer is not (LayerType.Leadin or LayerType.Leadout)) continue; var (failure, obstacle) = CheckMotion(i); + if (failure == null && target.Sheet is { } sheet && OffSheet(execution.Motions[i], sheet) is { } off) + { + if (isFixed?.Invoke(i) != true || fixedFailures == null) + return off; + fixedFailures.Add(new(i, off, null, OffSheet: true)); + continue; + } if (failure == null) continue; if (isFixed?.Invoke(i) != true || fixedFailures == null) @@ -302,6 +310,39 @@ public static class LeadPathValidator } } + private const string OffSheetPhrase = " past the plate's "; + + /// Whether is an refusal. + internal static bool IsOffSheet(string reason) => + reason?.StartsWith("Lead-", StringComparison.Ordinal) == true + && reason.Contains(OffSheetPhrase, StringComparison.Ordinal); + + /// + /// A complete refusal when the lead's native curve runs past by more + /// than the slack the pre-post plate edge check allows (docs/post-verification.md), else null. + /// + internal static LeadPathValidationResult OffSheet(ExecutionMotion move, Box sheet) + { + var bounds = move.Curve.ToEntity().BoundingBox; + var (edge, past) = ("left", sheet.Left - bounds.Left); + Furthest("bottom", sheet.Bottom - bounds.Bottom); + Furthest("right", bounds.Right - sheet.Right); + Furthest("top", bounds.Top - sheet.Top); + if (!double.IsFinite(past)) + return new(false, false, "Lead geometry or the sheet is not finite."); + return past > SpacingOutline.SpacingSlack + ? new(true, false, FormattableString.Invariant( + $"{(move.Layer == LayerType.Leadin ? "Lead-in" : "Lead-out")} runs {past:F3}{OffSheetPhrase}{edge} edge. ") + + "Move the part farther from the edge or shorten the lead, then replan.") + : null; + + void Furthest(string side, double distance) + { + if (!double.IsFinite(distance) || distance > past) + (edge, past) = (side, distance); + } + } + /// /// The exact native distance from to the nearest boundary of complete /// material. Exceeding the budget throws. diff --git a/OpenNest.Engine/CuttingPlanning/ContourEntrySelection.cs b/OpenNest.Engine/CuttingPlanning/ContourEntrySelection.cs index 637711d7..e3574099 100644 --- a/OpenNest.Engine/CuttingPlanning/ContourEntrySelection.cs +++ b/OpenNest.Engine/CuttingPlanning/ContourEntrySelection.cs @@ -97,6 +97,8 @@ internal static class ContourEntrySelection var uncertain = new List(); var sawIncomplete = false; string? incompleteReason = null; + // The first entry refused for a lead off the sheet: named when nothing fits. + string? offSheetReason = null; var index = 0; ContourFeasibilityVerdict Verdict(ContourEntryCandidate candidate) @@ -106,6 +108,8 @@ internal static class ContourEntrySelection { known = evaluate(candidate); verdicts[candidate.GeometryKey] = known; + if (known.Status == ContourFeasibilityStatus.Blocked && LeadPathValidator.IsOffSheet(known.Reason)) + offSheetReason ??= known.Reason; evaluated.Add(candidate); } return known; @@ -177,7 +181,7 @@ internal static class ContourEntrySelection { shortfall = ContourSelectionShortfall.Exhausted; reason = selected.Count == 0 - ? "No tested lead-in fits on this contour." + ? "No tested lead-in fits on this contour." + (offSheetReason == null ? "" : " " + offSheetReason) : null; } else diff --git a/OpenNest.Engine/CuttingPlanning/CuttingPlanService.cs b/OpenNest.Engine/CuttingPlanning/CuttingPlanService.cs index ec6d656a..47db9722 100644 --- a/OpenNest.Engine/CuttingPlanning/CuttingPlanService.cs +++ b/OpenNest.Engine/CuttingPlanning/CuttingPlanService.cs @@ -71,6 +71,12 @@ public static class CuttingPlanService var identities = new HashSet(ReferenceEqualityComparer.Instance); // Every part's box, read once, for slug slices to keep clear of parts nested in a cutout. Box[] partBoxes = null; + // The sheet every planned lead must stay on; none for a detached part list or a plate + // with no usable size, which the pre-post plate edge check reports instead. + var plateSize = request.Plate?.Size; + var sheetBox = plateSize is { } size && size.Length > 0 && size.Width > 0 + && double.IsFinite(size.Length) && double.IsFinite(size.Width) + ? request.Plate.BoundingBox(includeParts: false) : null; for (var index = 0; index < request.Parts.Count; index++) { token.ThrowIfCancellationRequested(); @@ -168,6 +174,10 @@ public static class CuttingPlanService if (request.ConfirmedParameters != null) { material = LeadMaterialSnapshot.Capture(ownedClean, location, token, sharedSpans: member); + // Leads must stay on the sheet, as the pre-post plate edge check requires. A part + // whose own material is already off it is past fixing by its leads: that check + // reports it, and the planner plans it as before. + material.Sheet = sheetBox != null && OnSheet(cleanBounds, sheetBox) ? sheetBox : null; if (!material.IsComplete) { if (!bestEffort) @@ -256,6 +266,14 @@ public static class CuttingPlanService // A common-line member regenerates from its marked clean program: holes as usual, then its // whole perimeter from its common line, or its remainder, from one fixed entry. Its leads are checked here, so a lead that // fits nowhere refuses with the span named rather than as a search that ran out. + // Whether clean material bounds lie on the sheet, with the plate edge check's slack. + private static bool OnSheet(Box material, Box sheet) + { + const double slack = SpacingOutline.SpacingSlack; + return material != null && material.Left >= sheet.Left - slack && material.Bottom >= sheet.Bottom - slack + && material.Right <= sheet.Right + slack && material.Top <= sheet.Top + slack; + } + private static FixedProgramPlacement CaptureMember(FixedProgramPlacement placed, Program clean, CommonLineCapture commonLines, CuttingPlanRequest request, IReadOnlyList materials, List warnings, bool bestEffort, CancellationToken token) diff --git a/OpenNest.Engine/CuttingPlanning/FixedLeadWarnings.cs b/OpenNest.Engine/CuttingPlanning/FixedLeadWarnings.cs index 0b2f9419..ad58ea06 100644 --- a/OpenNest.Engine/CuttingPlanning/FixedLeadWarnings.cs +++ b/OpenNest.Engine/CuttingPlanning/FixedLeadWarnings.cs @@ -44,6 +44,7 @@ internal static class FixedLeadWarnings var obstacle = failure.Obstacle is int index ? materialOwners[index] : null; var what = !failure.Result.IsComplete ? $"could not be checked ({failure.Result.Reason})" + : failure.OffSheet ? $"runs off the plate ({failure.Result.Reason})" : obstacle != null ? "contacts or enters another part's material" : $"contacts or enters its own part's material ({failure.Result.Reason})"; var motion = execution.Motions[failure.Motion]; diff --git a/OpenNest.Tests/CommonLines/CommonLinePlanningTests.cs b/OpenNest.Tests/CommonLines/CommonLinePlanningTests.cs index d1a4dbe9..50d75803 100644 --- a/OpenNest.Tests/CommonLines/CommonLinePlanningTests.cs +++ b/OpenNest.Tests/CommonLines/CommonLinePlanningTests.cs @@ -360,7 +360,8 @@ public class CommonLinePlanningTests [Fact] public void LeadInLongerThanASharedSpan_Refuses() { - var result = Plan(Row(2), Parameters(leadIn: 12)); + // Far enough from the edges that the long lead stays on the sheet. + var result = Plan(Row(2, x: 20, y: 20), Parameters(leadIn: 12)); Assert.Equal(CuttingPlanStatus.UnsupportedGeometry, result.Status); Assert.Contains(result.Findings, f => f.Message.Contains("shorter than the 12 external lead-in")); diff --git a/OpenNest.Tests/CuttingPlanning/LeadOffSheetTests.cs b/OpenNest.Tests/CuttingPlanning/LeadOffSheetTests.cs new file mode 100644 index 00000000..e0159943 --- /dev/null +++ b/OpenNest.Tests/CuttingPlanning/LeadOffSheetTests.cs @@ -0,0 +1,132 @@ +using OpenNest.CNC; +using OpenNest.CNC.CuttingPlanning; +using OpenNest.CNC.CuttingStrategy; +using OpenNest.Diagnostics; +using OpenNest.Engine.CuttingPlanning; +using OpenNest.Geometry; + +namespace OpenNest.Tests.CuttingPlanning; + +/// +/// Plan Cutting keeps every lead it chooses on the sheet, as the pre-post plate edge check +/// requires; a locked lead off the sheet is a fixed-lead warning, never a silent Ready plan. +/// +public class LeadOffSheetTests +{ + [Fact] + public void Validator_RefusesALeadPastItsMaterialsSheet() + { + var target = Snapshot(LeadPathValidationTests.Rectangle(0, 0, 10, 10)); + var lead = Read(ExternalLead()); // Pierces at (-3, 5). + + AssertClear(LeadPathValidator.Check(lead, target, [target])); + target.Sheet = new Box(-5, -5, 30, 30); + AssertClear(LeadPathValidator.Check(lead, target, [target])); + target.Sheet = new Box(-1, -1, 30, 30); + + var off = LeadPathValidator.Check(lead, target, [target]); + + Assert.True(off.IsComplete, off.Reason); + Assert.False(off.IsClear); + Assert.Contains("Lead-in runs 2.000 past the plate's left edge", off.Reason); + } + + [Fact] + public void Validator_CollectsAFixedLeadOffTheSheet() + { + var target = Snapshot(LeadPathValidationTests.Rectangle(0, 0, 10, 10)); + target.Sheet = new Box(-1, -1, 30, 30); + var failures = new List(); + + AssertClear(LeadPathValidator.Check(Read(ExternalLead()), target, [target], _ => true, failures, default)); + + var failure = Assert.Single(failures); + Assert.True(failure.OffSheet); + Assert.Null(failure.Obstacle); + } + + [Fact] + public void Plan_EntersFromASideWithRoomForTheLead() + { + // 0.2 from the left and bottom edges: a 1-long lead fits only from the top or right. + var part = new Part(new Drawing("near", LeadPathValidationTests.Rectangle(0, 0, 10, 10)), new Vector(0.2, 0.2)); + var plate = new Plate(20, 20); + plate.Parts.Add(part); + + var proposal = CuttingPlanBatch.Capture([plate], Parameters(), false).Plan(); + + Assert.True(proposal.CanApply, string.Join("\n", proposal.Describe("in"))); + Assert.Equal(CuttingCommitStatus.Applied, proposal.Apply().Status); + var report = PostVerificationAnalyzer.Analyze(new Nest { Plates = { plate } }); + Assert.DoesNotContain(report.Findings, f => f.Kind == PostVerificationKind.OffPlate); + } + + [Fact] + public void Plan_NoSideHasRoom_RefusesNamingTheEdge() + { + var part = new Part(new Drawing("tight", LeadPathValidationTests.Rectangle(0, 0, 10, 10)), new Vector(0.2, 0.2)); + var plate = new Plate(10.4, 10.4); + plate.Parts.Add(part); + + var planned = CuttingPlanBatch.Capture([plate], Parameters(), false).Plan(); + + Assert.False(planned.CanApply); + Assert.Contains(planned.Plates[0].Result.Findings, f => f.Message.Contains("past the plate's")); + } + + [Fact] + public void Plan_LockedLeadOffTheSheet_IsAFixedLeadWarning() + { + var part = new Part(new Drawing("locked", LeadPathValidationTests.Rectangle(0, 0, 10, 10)), new Vector(0.2, 0.2)); + var placed = new Program(); + placed.MoveTo(-3, 5); + placed.Codes.Add(new LinearMove(0, 5) { Layer = LayerType.Leadin }); + placed.LineTo(0, 10); placed.LineTo(10, 10); placed.LineTo(10, 0); placed.LineTo(0, 0); placed.LineTo(0, 5); + Assert.True(part.RestoreLeadInProgram(placed, false)); + part.LeadInsLocked = true; + var plate = new Plate(20, 20); + plate.Parts.Add(part); + + var planned = CuttingPlanBatch.Capture([plate], Parameters(), false).Plan().Plates[0]; + + Assert.False(planned.IsReady); + Assert.True(planned.HasOnlyFixedLeadWarnings); + var warning = Assert.Single(planned.Result.Findings); + Assert.Equal(PostVerificationKind.FixedLead, warning.Kind); + Assert.Contains("Locked lead on cutting contour 1 runs off the plate", warning.Message); + Assert.Contains("past the plate's left edge", warning.Message); + } + + private static CuttingParameters Parameters() => new() + { + ExternalLeadIn = new LineLeadIn { Length = 1, ApproachAngle = 90 }, + InternalLeadIn = new LineLeadIn { Length = 0.15, ApproachAngle = 90 }, + ExternalLeadOut = new NoLeadOut(), + InternalLeadOut = new NoLeadOut(), + PierceClearance = 0, + }; + + private static Program ExternalLead() + { + var p = new Program(); + p.MoveTo(-3, 5); + p.Codes.Add(new LinearMove(0, 5) { Layer = LayerType.Leadin }); + p.LineTo(0, 10); + return p; + } + + private static LeadMaterialSnapshot Snapshot(Program clean) + { + var snapshot = LeadMaterialSnapshot.Capture(clean, Vector.Zero); + Assert.True(snapshot.IsComplete, snapshot.Reason); + return snapshot; + } + + private static OwnedExecution Read(Program p) => ExecutionMotionReader.Read(p, Vector.Zero, null, default); + + private static void AssertClear(LeadPathValidationResult result) + { + Assert.True(result.IsComplete, result.Reason); + Assert.True(result.IsClear, result.Reason); + } +} diff --git a/OpenNest.Tests/CuttingPlanning/PlanningCharacterizationTests.cs b/OpenNest.Tests/CuttingPlanning/PlanningCharacterizationTests.cs index 51272381..e10c93de 100644 --- a/OpenNest.Tests/CuttingPlanning/PlanningCharacterizationTests.cs +++ b/OpenNest.Tests/CuttingPlanning/PlanningCharacterizationTests.cs @@ -93,7 +93,8 @@ public class PlanningCharacterizationTests var clean = new Program(); clean.MoveTo(5, 5); clean.LineTo(15, 5); clean.LineTo(15, 15); clean.LineTo(5, 15); clean.LineTo(5, 5); clean.MoveTo(0, 0); clean.LineTo(0, 20); clean.LineTo(20, 20); clean.LineTo(20, 0); clean.LineTo(0, 0); - var host = new Part(new Drawing("host", clean), new Vector(0, 0)); + // One in from the sheet corner, so the locked perimeter lead stays on the sheet. + var host = new Part(new Drawing("host", clean), new Vector(1, 1)); var locked = new Program(); locked.MoveTo(9, 10); locked.Codes.Add(new LinearMove(5, 10) { Layer = LayerType.Leadin }); @@ -102,7 +103,7 @@ public class PlanningCharacterizationTests locked.Codes.Add(new LinearMove(0, 10) { Layer = LayerType.Leadin }); locked.LineTo(0, 20); locked.LineTo(20, 20); locked.LineTo(20, 0); locked.LineTo(0, 0); locked.LineTo(0, 10); Assert.True(host.RestoreLeadInProgram(locked, true)); - var nested = new Part(new Drawing("nested", LeadPathValidationTests.Rectangle(0, 0, 2, 2)), new Vector(6, 9)); + var nested = new Part(new Drawing("nested", LeadPathValidationTests.Rectangle(0, 0, 2, 2)), new Vector(7, 10)); var nest = new Nest(); return (Plate(nest, nested, host), host, nested, nest); } diff --git a/docs/cutting-planner.md b/docs/cutting-planner.md index a9e08679..681e3c39 100644 --- a/docs/cutting-planner.md +++ b/docs/cutting-planner.md @@ -411,7 +411,13 @@ contact query still counts it as touched (for a very small arc up to 0.0001 beyo its radius). Nothing is skipped when either extent has a nonfinite bound or reaches beyond 1e6, where rounding of large supports can exceed any fixed margin. Actual lead-in and lead-out line/arc paths must stay in target scrap and avoid other -placed material; holes in other parts remain scrap. Tangent/coincident contacts +placed material; holes in other parts remain scrap. On a plate-scoped plan they +must also stay on the sheet: a lead whose native curve runs past the plate's box by +more than the pre-post plate edge check's slack is refused like a contact, so the +search enters from a side with room, and a contour with none fails naming the edge. +A part whose own material is already off the sheet keeps the old checks: no lead can +fix it, and the plate edge check reports it. +Tangent/coincident contacts outside the genuine target contour joint and numerically uncertain queries refuse. Material capture supports a simple closed perimeter minus disjoint, non-nested holes; unsupported topology is not a bounding-box approximation. A line meeting a @@ -604,7 +610,8 @@ parts) is a fixed emission: everything it does after the planner's rapid into it accepted as given. So is each drawing-pinned contour of a regenerated part (see [drawing pins](#drawing-pins)). Their violations are not refusals: -- Its lead-ins and lead-outs meeting another part's material or its own, a rapid inside +- Its lead-ins and lead-outs meeting another part's material or its own or running off + the plate, a rapid inside it crossing a completed contour, a lead-out after its own open contour, and coverage that cannot be certified (a tab gap, a partial, reversed or retraced cut) each become a `PostVerificationKind.FixedLead` finding naming the part, the cutting contour where