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 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-23 17:41:23 -05:00
1 parent a937027174
commit db4b573e3b
9 files changed
+222 -9

No files matched your search

@@ -48,6 +48,14 @@ public sealed class LeadMaterialSnapshot
/// </summary> /// </summary>
internal bool HasDisplayPerimeter { get; } internal bool HasDisplayPerimeter { get; }
/// <summary>
/// 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 (<see cref="LeadPathValidator"/>): a pierce or lead off the sheet cuts air,
/// or the table. Set once by the planner's capture, before any check reads it.
/// </summary>
internal Box Sheet { get; set; }
/// <summary>Capture a stable, clean, rotation-baked program, applying location once. /// <summary>Capture a stable, clean, rotation-baked program, applying location once.
/// Unsupported or malformed geometry produces an incomplete snapshot; cancellation throws.</summary> /// Unsupported or malformed geometry produces an incomplete snapshot; cancellation throws.</summary>
public static LeadMaterialSnapshot Capture(Program cleanProgram, Vector location, public static LeadMaterialSnapshot Capture(Program cleanProgram, Vector location,
@@ -12,10 +12,11 @@ public sealed record LeadPathValidationResult(bool IsComplete, bool IsClear, str
/// <summary> /// <summary>
/// One lead motion of a fixed emission that failed validation. <see cref="Obstacle"/> indexes the /// One lead motion of a fixed emission that failed validation. <see cref="Obstacle"/> indexes the
/// other materials passed to the check, or is null when the lead meets its own part's material /// other materials passed to the check, or is null when the lead meets its own part's material,
/// or could not be checked. /// runs off the sheet (<see cref="OffSheet"/>) or could not be checked.
/// </summary> /// </summary>
internal sealed record FixedLeadFailure(int Motion, LeadPathValidationResult Result, int? Obstacle); internal sealed record FixedLeadFailure(int Motion, LeadPathValidationResult Result, int? Obstacle,
bool OffSheet = false);
/// <summary>Certifies actual emitted native lead paths against owned nominal material.</summary> /// <summary>Certifies actual emitted native lead paths against owned nominal material.</summary>
public static class LeadPathValidator public static class LeadPathValidator
@@ -79,6 +80,13 @@ public static class LeadPathValidator
if (move.Layer is not (LayerType.Leadin or LayerType.Leadout)) if (move.Layer is not (LayerType.Leadin or LayerType.Leadout))
continue; continue;
var (failure, obstacle) = CheckMotion(i); 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) if (failure == null)
continue; continue;
if (isFixed?.Invoke(i) != true || fixedFailures == null) if (isFixed?.Invoke(i) != true || fixedFailures == null)
@@ -302,6 +310,39 @@ public static class LeadPathValidator
} }
} }
private const string OffSheetPhrase = " past the plate's ";
/// <summary>Whether <paramref name="reason"/> is an <see cref="OffSheet"/> refusal.</summary>
internal static bool IsOffSheet(string reason) =>
reason?.StartsWith("Lead-", StringComparison.Ordinal) == true
&& reason.Contains(OffSheetPhrase, StringComparison.Ordinal);
/// <summary>
/// A complete refusal when the lead's native curve runs past <paramref name="sheet"/> by more
/// than the slack the pre-post plate edge check allows (docs/post-verification.md), else null.
/// </summary>
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);
}
}
/// <summary> /// <summary>
/// The exact native distance from <paramref name="point"/> to the nearest boundary of complete /// The exact native distance from <paramref name="point"/> to the nearest boundary of complete
/// material. Exceeding the budget throws. /// material. Exceeding the budget throws.
@@ -97,6 +97,8 @@ internal static class ContourEntrySelection
var uncertain = new List<ContourEntryCandidate>(); var uncertain = new List<ContourEntryCandidate>();
var sawIncomplete = false; var sawIncomplete = false;
string? incompleteReason = null; string? incompleteReason = null;
// The first entry refused for a lead off the sheet: named when nothing fits.
string? offSheetReason = null;
var index = 0; var index = 0;
ContourFeasibilityVerdict Verdict(ContourEntryCandidate candidate) ContourFeasibilityVerdict Verdict(ContourEntryCandidate candidate)
@@ -106,6 +108,8 @@ internal static class ContourEntrySelection
{ {
known = evaluate(candidate); known = evaluate(candidate);
verdicts[candidate.GeometryKey] = known; verdicts[candidate.GeometryKey] = known;
if (known.Status == ContourFeasibilityStatus.Blocked && LeadPathValidator.IsOffSheet(known.Reason))
offSheetReason ??= known.Reason;
evaluated.Add(candidate); evaluated.Add(candidate);
} }
return known; return known;
@@ -177,7 +181,7 @@ internal static class ContourEntrySelection
{ {
shortfall = ContourSelectionShortfall.Exhausted; shortfall = ContourSelectionShortfall.Exhausted;
reason = selected.Count == 0 reason = selected.Count == 0
? "No tested lead-in fits on this contour." ? "No tested lead-in fits on this contour." + (offSheetReason == null ? "" : " " + offSheetReason)
: null; : null;
} }
else else
@@ -71,6 +71,12 @@ public static class CuttingPlanService
var identities = new HashSet<Part>(ReferenceEqualityComparer.Instance); var identities = new HashSet<Part>(ReferenceEqualityComparer.Instance);
// Every part's box, read once, for slug slices to keep clear of parts nested in a cutout. // Every part's box, read once, for slug slices to keep clear of parts nested in a cutout.
Box[] partBoxes = null; 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++) for (var index = 0; index < request.Parts.Count; index++)
{ {
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
@@ -168,6 +174,10 @@ public static class CuttingPlanService
if (request.ConfirmedParameters != null) if (request.ConfirmedParameters != null)
{ {
material = LeadMaterialSnapshot.Capture(ownedClean, location, token, sharedSpans: member); 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 (!material.IsComplete)
{ {
if (!bestEffort) 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 // 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 // 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. // 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, private static FixedProgramPlacement CaptureMember(FixedProgramPlacement placed, Program clean,
CommonLineCapture commonLines, CuttingPlanRequest request, IReadOnlyList<LeadMaterialSnapshot> materials, CommonLineCapture commonLines, CuttingPlanRequest request, IReadOnlyList<LeadMaterialSnapshot> materials,
List<CuttingPlanFinding> warnings, bool bestEffort, CancellationToken token) List<CuttingPlanFinding> warnings, bool bestEffort, CancellationToken token)
@@ -44,6 +44,7 @@ internal static class FixedLeadWarnings
var obstacle = failure.Obstacle is int index ? materialOwners[index] : null; var obstacle = failure.Obstacle is int index ? materialOwners[index] : null;
var what = !failure.Result.IsComplete var what = !failure.Result.IsComplete
? $"could not be checked ({failure.Result.Reason})" ? $"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" : obstacle != null ? "contacts or enters another part's material"
: $"contacts or enters its own part's material ({failure.Result.Reason})"; : $"contacts or enters its own part's material ({failure.Result.Reason})";
var motion = execution.Motions[failure.Motion]; var motion = execution.Motions[failure.Motion];
@@ -360,7 +360,8 @@ public class CommonLinePlanningTests
[Fact] [Fact]
public void LeadInLongerThanASharedSpan_Refuses() 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.Equal(CuttingPlanStatus.UnsupportedGeometry, result.Status);
Assert.Contains(result.Findings, f => f.Message.Contains("shorter than the 12 external lead-in")); Assert.Contains(result.Findings, f => f.Message.Contains("shorter than the 12 external lead-in"));
@@ -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;
/// <summary>
/// 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.
/// </summary>
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<FixedLeadFailure>();
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);
}
}
@@ -93,7 +93,8 @@ public class PlanningCharacterizationTests
var clean = new Program(); 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(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); 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(); var locked = new Program();
locked.MoveTo(9, 10); locked.MoveTo(9, 10);
locked.Codes.Add(new LinearMove(5, 10) { Layer = LayerType.Leadin }); 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.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); 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)); 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(); var nest = new Nest();
return (Plate(nest, nested, host), host, nested, nest); return (Plate(nest, nested, host), host, nested, nest);
} }
+9 -2
View File
@@ -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 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 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 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. outside the genuine target contour joint and numerically uncertain queries refuse.
Material capture supports a simple closed perimeter minus disjoint, non-nested Material capture supports a simple closed perimeter minus disjoint, non-nested
holes; unsupported topology is not a bounding-box approximation. A line meeting a 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 accepted as given. So is each drawing-pinned contour of a
regenerated part (see [drawing pins](#drawing-pins)). Their violations are not refusals: 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 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 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 `PostVerificationKind.FixedLead` finding naming the part, the cutting contour where