perf(planner): skip far parts on large plates without changing the plan

The 5k-washers corpus plate planned in about 90 s alone and timed out at the
corpus's 120 s limit whenever anything else ran, making the corpus fragile.
Profiling showed nearly all of it was linear scans over every part, repeated
per candidate: each lead check walked all 5,742 materials (and first re-tested
that all were complete), each rapid walked every completed contour, each
expansion rebuilt a HashSet of every cut part, each checker copy regrew its
obstacle list, and the nested-part search tested all 33 million part pairs.

A uniform grid over extents (ExtentGrid) now leaves out only parts whose
extents lie beyond the margin the existing skip tests use, and the rest are
visited in their original order, so every check returns exactly what the full
scan returned (same findings, same first obstacle, same budget charges):
- LeadPathValidator visits only materials not clear of the lead's queries or
  its midpoint's row, through a shared LeadMaterialSet built once per walk and
  replay; ContourEntryFeasibility reuses that set instead of copying it per part.
- ReleasedContourState keeps a read-only obstacle prefix with a grid, shared by
  copies, so copies stay cheap and rapids test only nearby contours.
- The search keeps one ordinal flag array per order instead of a HashSet per call.
- CuttingDependencyGraph tests each part only against hosts whose bounds can hold it.

Plate 1 alone: 93.3 s -> 12.3 s (capture 2.7 -> 1.2 s, plan 90.6 -> 11.1 s),
with the identical plan digest and 86,245 expansions; plate 2 also plans
identically. The problem-nest corpus (part-order,entries) gives every plate the
same outcome and expansion count as master, and the Collision kernel and every
tolerance are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-12-02 12:58:28 -05:00
1 parent d45e5ff202
commit b97929a53d
9 files changed
+411 -26

No files matched your search

@@ -0,0 +1,44 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using OpenNest.Diagnostics;
namespace OpenNest.CNC.CuttingPlanning;
/// <summary>
/// An immutable list of placed materials with a grid over their extents, shared by every lead
/// check of one planning attempt. <see cref="LeadPathValidator"/> then visits only the materials
/// its full scan would query, in the same order, so a plate of thousands of parts does not walk
/// all of them for every lead. Its results are the full scan's.
/// </summary>
internal sealed class LeadMaterialSet : IReadOnlyList<LeadMaterialSnapshot>
{
private readonly LeadMaterialSnapshot[] materials;
private ExtentGrid grid;
internal LeadMaterialSet(IEnumerable<LeadMaterialSnapshot> materials)
{
this.materials = materials.ToArray();
HasNull = this.materials.Any(m => m == null);
AllComplete = !HasNull && this.materials.All(m => m.IsComplete);
}
/// <summary>Whether any material is missing.</summary>
internal bool HasNull { get; }
/// <summary>Whether every material is present and complete, as the validator requires.</summary>
internal bool AllComplete { get; }
public int Count => materials.Length;
public LeadMaterialSnapshot this[int index] => materials[index];
public IEnumerator<LeadMaterialSnapshot> GetEnumerator() => ((IEnumerable<LeadMaterialSnapshot>)materials).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <summary>The grid over the materials' extents, built on first use; null unless every material is complete.</summary>
internal ExtentGrid Grid => AllComplete
? System.Threading.LazyInitializer.EnsureInitialized(ref grid, () => new ExtentGrid(materials.Select(m => m.Extent).ToArray()))
: null;
}
@@ -57,7 +57,8 @@ public static class LeadPathValidator
return new(false, false, "Missing execution or material snapshots.");
if (!double.IsFinite(pierceRadius) || pierceRadius < 0)
return new(false, false, "Pierce zone radius must be finite and nonnegative.");
if (!target.IsComplete || otherMaterials.Any(m => m == null || !m.IsComplete))
if (!target.IsComplete || (otherMaterials is LeadMaterialSet set ? !set.AllComplete
: otherMaterials.Any(m => m == null || !m.IsComplete)))
return new(false, false, "Material snapshot is incomplete.");
try
{
@@ -217,9 +218,12 @@ public static class LeadPathValidator
? $"Common-line lead motion {i} contacts its part's material ({failure}). The lead runs along the shared line: shorten the lead-in or lead-out, or cut the common lines twice."
: $"Lead motion {i} contacts or enters target material outside its adjacent contour joint ({failure})."), null);
var reach = move.Curve.Extent;
for (var other = 0; other < otherMaterials.Count; other++)
var midpoint = move.Curve.Midpoint;
var visited = Visited(otherMaterials, reach, 0, midpoint.Y);
for (var k = 0; k < (visited?.Count ?? otherMaterials.Count); k++)
{
token.ThrowIfCancellationRequested();
var other = visited?[k] ?? k;
var material = otherMaterials[other];
if (ReferenceEquals(material, target))
continue;
@@ -239,15 +243,17 @@ public static class LeadPathValidator
return (null, null);
if (!breakLead && Clearance(target) is { } own)
return (Short(own, "its own part's material"), null);
for (var other = 0; other < otherMaterials.Count; other++)
var pierce = new PostVerificationGeometry.Extent(start.X, start.Y, start.X, start.Y);
var visitedNear = Visited(otherMaterials, pierce, pierceRadius, null);
for (var k = 0; k < (visitedNear?.Count ?? otherMaterials.Count); k++)
{
token.ThrowIfCancellationRequested();
var other = visitedNear?[k] ?? k;
var material = otherMaterials[other];
if (ReferenceEquals(material, target))
continue;
// Every boundary of material this far away is farther than the zone.
if (new PostVerificationGeometry.Extent(start.X, start.Y, start.X, start.Y)
.IsClearOfQueriesFrom(material.Extent, pierceRadius))
if (pierce.IsClearOfQueriesFrom(material.Extent, pierceRadius))
continue;
if (Clearance(material) is { } distance)
return (Short(distance, "another placed part"), other);
@@ -292,7 +298,6 @@ public static class LeadPathValidator
// still asked natively unless the lead lies beside the material's rows.
bool FarInside(LeadMaterialSnapshot material)
{
var midpoint = move.Curve.Midpoint;
return !material.Extent.IsClearOfRow(midpoint.Y) && material.ContainsMaterial(midpoint, token);
}
@@ -310,6 +315,34 @@ public static class LeadPathValidator
}
}
/// <summary>
/// The indices, ascending, of the other materials a lead scan must visit, or null for all of
/// them. With a <see cref="LeadMaterialSet"/>, its grid leaves out only materials the scan
/// would pass over unqueried: clear of every native query from <paramref name="query"/>
/// (<see cref="PostVerificationGeometry.Extent.IsClearOfQueriesFrom"/> with
/// <paramref name="reach"/>) and, when <paramref name="row"/> is given, clear of that row
/// (<see cref="PostVerificationGeometry.Extent.IsClearOfRow"/>). Visiting the rest in order
/// gives the full scan's result.
/// </summary>
private static List<int> Visited(IReadOnlyList<LeadMaterialSnapshot> materials,
PostVerificationGeometry.Extent query, double reach, double? row)
{
if (materials is not LeadMaterialSet { Grid: { } grid } || !query.IsWellConditioned
|| row is { } y && !(System.Math.Abs(y) <= PostVerificationGeometry.Extent.WellConditionedLimit))
return null;
// Each material's test widens its gap by its span with the query; the whole set's span
// bounds them all, and doubling the margin covers rounding.
var union = grid.Whole.Union(query);
var span = System.Math.Max(union.MaxX - union.MinX, union.MaxY - union.MinY);
var margin = 2 * (PostVerificationGeometry.Extent.ClearMargin + reach
+ PostVerificationGeometry.Extent.SpanRounding * span);
if (!double.IsFinite(margin))
return null;
return row is { } rowY
? grid.InRows(System.Math.Min(query.MinY, rowY), System.Math.Max(query.MaxY, rowY), margin)
: grid.Near(query, margin);
}
private const string OffSheetPhrase = " past the plate's ";
/// <summary>Whether <paramref name="reason"/> is an <see cref="OffSheet"/> refusal.</summary>
@@ -10,6 +10,12 @@ namespace OpenNest.CNC.CuttingPlanning;
/// <summary>Direct XY completed-contour checker. This is not physical machine safety.</summary>
public sealed class ReleasedContourState
{
// Completed contours in the order they closed: a read-only prefix with a grid over it, both
// shared with copies, then the ones added since. Obstacles are only ever appended, so copying
// a state copies only the recent ones, and a rapid tests the prefix obstacles the grid finds
// it may reach and every recent one.
private Obstacle[] shared = [];
private ExtentGrid sharedGrid;
private readonly List<Obstacle> obstacles = new();
private readonly bool reportMissingLeadIns;
// Parts (by caller part number) whose single tab may not hold them level: once cut, their
@@ -80,6 +86,8 @@ public sealed class ReleasedContourState
AvoidTabbedPart = AvoidTabbedPart,
partContours = partContours,
partClosed = partClosed,
shared = shared,
sharedGrid = sharedGrid,
};
copy.obstacles.AddRange(obstacles);
return copy;
@@ -395,9 +403,21 @@ public sealed class ReleasedContourState
var reach = new PostVerificationGeometry.Extent(System.Math.Min(start.X, move.End.X),
System.Math.Min(start.Y, move.End.Y), System.Math.Max(start.X, move.End.X),
System.Math.Max(start.Y, move.End.Y));
foreach (var obstacle in obstacles)
if (obstacles.Count > UnindexedObstacles)
{
shared = [.. shared, .. obstacles];
sharedGrid = new ExtentGrid(shared.Select(o => o.Extent).ToArray());
obstacles.Clear();
}
// The grid leaves out only obstacles well clear of the rapid, which the scan would skip
// below; the rest are tested in obstacle order, as without it.
var near = sharedGrid != null && reach.IsWellConditioned
? sharedGrid.Near(reach, 2 * PostVerificationGeometry.Extent.ClearMargin) : null;
var fromShared = near?.Count ?? shared.Length;
for (var k = 0; k < fromShared + obstacles.Count; k++)
{
token.ThrowIfCancellationRequested();
var obstacle = k < fromShared ? shared[near?[k] ?? k] : obstacles[k - fromShared];
// A rapid well clear of a contour's extent can neither cross nor touch it.
if (reach.IsClearOf(obstacle.Extent))
continue;
@@ -733,6 +753,9 @@ public sealed class ReleasedContourState
internal void Union(int a, int b) => parents[Find(a)] = Find(b);
}
// The most recent obstacles a rapid scans in full: past this, they join the shared prefix.
private const int UnindexedObstacles = 128;
private sealed record Obstacle(int Part, int Contour, IReadOnlyList<PostVerificationGeometry.Curve> Curves,
Vector? OvercutEnd)
{
+105
View File
@@ -0,0 +1,105 @@
using System.Collections.Generic;
namespace OpenNest.Diagnostics;
/// <summary>
/// A uniform grid over many extents, for scans that skip every extent clear of a query, so a
/// plate of thousands of parts does not test each one for every rapid or lead. It returns in
/// ascending order every extent whose cells a query widened by a margin reaches, and every extent
/// that is not well conditioned. An extent it leaves out is well conditioned and lies more than
/// the margin beyond the query along X or Y, so a scan that skips only such extents, and keeps
/// the order, gives the full scan's result. Read only once built, so scans may share it.
/// </summary>
internal sealed class ExtentGrid
{
private readonly int[] always;
private readonly List<int>[] cells;
private readonly int columns;
private readonly int rows;
private readonly double width;
private readonly double height;
internal ExtentGrid(IReadOnlyList<PostVerificationGeometry.Extent> extents)
{
Count = extents.Count;
var always = new List<int>();
var whole = PostVerificationGeometry.Extent.None;
for (var i = 0; i < extents.Count; i++)
{
if (extents[i].IsWellConditioned)
whole = whole.Union(extents[i]);
else
always.Add(i);
}
this.always = always.ToArray();
Whole = whole;
var indexed = extents.Count - always.Count;
if (indexed == 0)
{
cells = [];
return;
}
columns = rows = System.Math.Max(1, (int)System.Math.Ceiling(System.Math.Sqrt(indexed)));
width = Size(whole.MaxX - whole.MinX, columns);
height = Size(whole.MaxY - whole.MinY, rows);
cells = new List<int>[columns * rows];
for (var i = 0; i < extents.Count; i++)
{
var extent = extents[i];
if (!extent.IsWellConditioned)
continue;
for (var y = Row(extent.MinY); y <= Row(extent.MaxY); y++)
for (var x = Column(extent.MinX); x <= Column(extent.MaxX); x++)
(cells[y * columns + x] ??= new List<int>()).Add(i);
}
}
/// <summary>The number of extents indexed, including those not well conditioned.</summary>
internal int Count { get; }
/// <summary>The union of every well-conditioned extent; <see cref="PostVerificationGeometry.Extent.None"/> when there is none.</summary>
internal PostVerificationGeometry.Extent Whole { get; }
/// <summary>
/// The indices, ascending, of every extent not provably more than <paramref name="margin"/>
/// beyond <paramref name="query"/> along X or Y. The caller passes a well-conditioned query
/// and a finite, nonnegative margin.
/// </summary>
internal List<int> Near(PostVerificationGeometry.Extent query, double margin) => cells.Length == 0
? new List<int>(always)
: Collect(Row(query.MinY - margin), Row(query.MaxY + margin),
Column(query.MinX - margin), Column(query.MaxX + margin));
/// <summary>
/// The indices, ascending, of every extent not provably more than <paramref name="margin"/>
/// above <paramref name="maxY"/> or below <paramref name="minY"/>, whatever its X. The caller
/// passes finite values and a nonnegative margin.
/// </summary>
internal List<int> InRows(double minY, double maxY, double margin) => cells.Length == 0
? new List<int>(always)
: Collect(Row(minY - margin), Row(maxY + margin), 0, columns - 1);
private List<int> Collect(int y0, int y1, int x0, int x1)
{
var found = new List<int>(always);
for (var y = y0; y <= y1; y++)
for (var x = x0; x <= x1; x++)
if (cells[y * columns + x] is { } cell)
found.AddRange(cell);
found.Sort();
var unique = 0;
for (var i = 0; i < found.Count; i++)
if (i == 0 || found[i] != found[i - 1])
found[unique++] = found[i];
found.RemoveRange(unique, found.Count - unique);
return found;
}
// A degenerate span (every extent at one coordinate) takes any positive cell size.
private static double Size(double span, int count) => span / count is var size && size > 0 ? size : 1;
// Monotone in the coordinate, so a cell range left out lies wholly beyond the query's.
private int Column(double x) => (int)System.Math.Clamp(System.Math.Floor((x - Whole.MinX) / width), 0, columns - 1);
private int Row(double y) => (int)System.Math.Clamp(System.Math.Floor((y - Whole.MinY) / height), 0, rows - 1);
}
@@ -46,7 +46,7 @@ public sealed class ContourEntryFeasibility
private readonly PreparedContours prepared;
private readonly Vector location;
private readonly LeadMaterialSnapshot ownMaterial;
private readonly LeadMaterialSnapshot[] materials;
private readonly IReadOnlyList<LeadMaterialSnapshot> materials;
private readonly Dictionary<Key, ContourFeasibilityVerdict> cache = new();
private readonly LeadContactMemo? leadContacts;
@@ -67,6 +67,15 @@ public sealed class ContourEntryFeasibility
if (otherMaterials == null)
throw new ArgumentException("Placed-material snapshots are required.", nameof(otherMaterials));
this.location = location;
if (otherMaterials is LeadMaterialSet set)
{
if (set.HasNull)
throw new ArgumentException("Placed-material snapshots must not be null.", nameof(otherMaterials));
// Already immutable and shared by the search's adapters. The validator passes over the
// own material by reference and visits the others in their order, as in the copy below.
materials = set;
return;
}
// Immutable copy; the validator's own-material-first convention is preserved.
var all = new List<LeadMaterialSnapshot> { this.ownMaterial };
foreach (var material in otherMaterials)
@@ -4,6 +4,7 @@ using System.Linq;
using System.Threading;
using OpenNest.CNC.CuttingPlanning;
using OpenNest.CutOffs;
using OpenNest.Diagnostics;
using OpenNest.Geometry;
using OpenNest.Math;
@@ -46,6 +47,9 @@ internal sealed class CuttingDependencyGraph
return prerequisites[ordinal].All(finished.Contains);
}
/// <summary>As <see cref="IsReady(int, IEnumerable{int})"/>, asking <paramref name="done"/> of each prerequisite.</summary>
internal bool IsReady(int ordinal, Func<int, bool> done) => prerequisites[ordinal].All(done);
/// <summary>First (part, missing prerequisite) in a proposed complete order, or null.</summary>
internal (int Part, int Prerequisite)? FirstViolation(IReadOnlyList<int> order)
{
@@ -111,8 +115,12 @@ internal sealed class CuttingDependencyGraph
edges[part].Add(cut);
}
}
// Each part tests, in ordinal order, only the hosts whose bounds the grid cannot show to
// be too far from its own to hold it, so a plate of thousands of parts is not squared.
var hosts = Enumerable.Range(0, nodes.Count).Where(i => !nodes[i].IsCutOff).ToArray();
var hostGrid = new ExtentGrid(hosts.Select(i => ExtentOf(nodes[i].HostBounds)).ToArray());
for (var inner = 0; inner < nodes.Count; inner++)
for (var host = 0; host < nodes.Count; host++)
foreach (var host in Hosts(inner))
{
token.ThrowIfCancellationRequested();
// Bounds only select candidates; containment itself is proven on native material.
@@ -136,6 +144,18 @@ internal sealed class CuttingDependencyGraph
}
}
}
// A box within another, as IsWithin allows, lies within its extent widened by Epsilon; a
// part without usable bounds tests every host, as IsWithin then decides (or throws).
IEnumerable<int> Hosts(int inner)
{
if (nodes[inner].IsCutOff)
return [];
if (nodes[inner].CleanBounds is not { } bounds || ExtentOf(bounds) is not { IsWellConditioned: true } extent)
return Enumerable.Range(0, nodes.Count);
return hostGrid.Near(extent, 2 * Tolerance.Epsilon).Select(k => hosts[k]);
}
// Cut-first parts (test coupons) precede every other part, except one that must already
// precede the coupon (nested in its cutout): containment wins over the preference.
for (var first = 0; first < nodes.Count; first++)
@@ -154,6 +174,10 @@ internal sealed class CuttingDependencyGraph
return graph;
}
private static PostVerificationGeometry.Extent ExtentOf(Box box) => new(
System.Math.Min(box.Left, box.Right), System.Math.Min(box.Bottom, box.Top),
System.Math.Max(box.Left, box.Right), System.Math.Max(box.Bottom, box.Top));
// Every ordinal that must come before the given one, directly or transitively.
private static HashSet<int> Ancestors(IReadOnlyList<SortedSet<int>> edges, int ordinal)
{
@@ -578,7 +578,7 @@ public static class CuttingPlanService
var raises = new List<CuttingPlanFinding>();
var raisedRapids = 0;
var materialOwners = snapshot.Placements.Where(p => !p.IsCutOff).ToArray();
var materials = materialOwners.Select(p => p.Material).ToArray();
var materials = new LeadMaterialSet(materialOwners.Select(p => p.Material));
foreach (var proposal in order)
{
token.ThrowIfCancellationRequested();
@@ -507,8 +507,8 @@ internal static class JointCuttingPlanSearch
private readonly List<CuttingPlanFinding> rejected = [];
// Placements this walk never cuts and counts as cut from the start (attached cut-offs).
private readonly HashSet<int> excluded = [.. excluded];
private readonly LeadMaterialSnapshot[] materials =
snapshot.Placements.Where(p => !p.IsCutOff).Select(p => p.Material).ToArray();
private readonly LeadMaterialSet materials =
new(snapshot.Placements.Where(p => !p.IsCutOff).Select(p => p.Material));
// One feasibility adapter per source part per captured planning attempt: verdicts
// memoize per owned choice for the attempt, never statically or across attempts.
private readonly Dictionary<int, ContourEntryFeasibility> feasibility = [];
@@ -516,6 +516,9 @@ internal static class JointCuttingPlanSearch
// walk: each prefix repeats its earlier contours' leads. Replay never uses it.
private readonly LeadContactMemo leadContacts = new();
private readonly HashSet<int> reportedNoFit = [];
// Finished's last order and its flags.
private FixedProgramPlacement[] finishedOrder;
private bool[] finishedFlags;
private readonly HashSet<int> reportedNoScrap = [];
// The perimeter pierce-zone fallback's scrap geometry, built on first use.
private ScrapPierceSearch scrapPierces;
@@ -641,18 +644,18 @@ internal static class JointCuttingPlanSearch
private FixedProgramPlacement NextCut(Node node, int[] sequence, FixedProgramPlacement source)
{
var finished = Finished(node);
finished.Add(source.SourceOrdinal);
var cut = Finished(node);
bool Done(int ordinal) => ordinal == source.SourceOrdinal || Cut(node, cut, ordinal);
if (sequence != null)
for (var i = node.Order.Length + 1; i < sequence.Length; i++)
if (!finished.Contains(sequence[i]) && !IsSegment(snapshot.Placements[sequence[i]]))
if (!Done(sequence[i]) && !IsSegment(snapshot.Placements[sequence[i]]))
return snapshot.Placements[sequence[i]];
var from = Exit(source);
FixedProgramPlacement best = null;
var bestDistance = double.PositiveInfinity;
foreach (var candidate in snapshot.Placements
.Where(p => !finished.Contains(p.SourceOrdinal) && !IsSegment(p)
&& snapshot.Dependencies.IsReady(p.SourceOrdinal, finished))
.Where(p => !Done(p.SourceOrdinal) && !IsSegment(p)
&& snapshot.Dependencies.IsReady(p.SourceOrdinal, Done))
.OrderBy(p => p.SourceOrdinal))
{
var distance = Center(candidate).DistanceTo(from);
@@ -758,11 +761,12 @@ internal static class JointCuttingPlanSearch
sources = [active.Source];
else
{
var finished = Finished(node);
var cut = Finished(node);
bool Done(int ordinal) => Cut(node, cut, ordinal);
sources = sequence == null
? snapshot.Placements.Where(p => !finished.Contains(p.SourceOrdinal)
&& snapshot.Dependencies.IsReady(p.SourceOrdinal, finished))
: snapshot.Dependencies.IsReady(sequence[node.Order.Length], finished)
? snapshot.Placements.Where(p => !Done(p.SourceOrdinal)
&& snapshot.Dependencies.IsReady(p.SourceOrdinal, Done))
: snapshot.Dependencies.IsReady(sequence[node.Order.Length], Done)
? [snapshot.Placements[sequence[node.Order.Length]]] : [];
}
if (contourRecovery)
@@ -1723,14 +1727,31 @@ internal static class JointCuttingPlanSearch
? source.Propose(program, execution, choices, token) : null;
}
// The placements cut at a node, and the excluded ones, which count as cut throughout.
private HashSet<int> Finished(Node node)
// The placements cut at a node, and the excluded ones, which count as cut throughout, by
// ordinal (see Cut). Nodes share their order array while a part is cut, and each child of a
// node asks again, so the last order's flags are kept; no caller may change them.
private bool[] Finished(Node node)
{
var finished = node.Order.Select(o => o.SourceOrdinal).ToHashSet();
finished.UnionWith(excluded);
return finished;
if (!ReferenceEquals(finishedOrder, node.Order))
{
var cut = new bool[snapshot.Placements.Count];
foreach (var placement in node.Order)
if ((uint)placement.SourceOrdinal < (uint)cut.Length)
cut[placement.SourceOrdinal] = true;
foreach (var ordinal in excluded)
if ((uint)ordinal < (uint)cut.Length)
cut[ordinal] = true;
(finishedOrder, finishedFlags) = (node.Order, cut);
}
return finishedFlags;
}
// Whether a node's Finished flags hold an ordinal, as a set of them would; an ordinal past
// the placements (none is expected) is looked up directly.
private bool Cut(Node node, bool[] cut, int ordinal) =>
(uint)ordinal < (uint)cut.Length ? cut[ordinal]
: excluded.Contains(ordinal) || node.Order.Any(o => o.SourceOrdinal == ordinal);
internal void CountExpansion(FixedProgramPlacement source)
{
token.ThrowIfCancellationRequested();
@@ -0,0 +1,126 @@
using OpenNest.CNC;
using OpenNest.CNC.CuttingPlanning;
using OpenNest.Diagnostics;
using OpenNest.Geometry;
using Extent = OpenNest.Diagnostics.PostVerificationGeometry.Extent;
namespace OpenNest.Tests.CuttingPlanning;
/// <summary>
/// Large plates skip far parts through <see cref="ExtentGrid"/>: the lead check, the rapid check
/// and the nested-part search. Each must give exactly what testing every part gives.
/// </summary>
public class ExtentGridTests
{
[Fact]
public void Near_LeavesOutOnlyExtentsBeyondTheMargin()
{
var random = new Random(7);
var extents = Enumerable.Range(0, 500).Select(i => i % 97 == 0
? new Extent(double.NaN, 0, 1, 1) // Not well conditioned: always returned.
: Box(random, 100)).ToArray();
var grid = new ExtentGrid(extents);
for (var trial = 0; trial < 500; trial++)
{
var query = Box(random, 110);
var margin = random.NextDouble() * (trial % 3);
var near = grid.Near(query, margin);
Assert.Equal(near.Distinct().Order(), near);
for (var i = 0; i < extents.Length; i++)
if (!near.Contains(i))
Assert.True(extents[i].IsWellConditioned && Apart(extents[i], query, margin), $"Extent {i} left out.");
var rows = grid.InRows(query.MinY, query.MaxY, margin);
for (var i = 0; i < extents.Length; i++)
if (!rows.Contains(i))
Assert.True(extents[i].IsWellConditioned
&& (extents[i].MaxY + margin < query.MinY || query.MaxY + margin < extents[i].MinY), $"Row {i} left out.");
}
}
[Fact]
public void Near_EmptyOrDegenerateGrids()
{
Assert.Empty(new ExtentGrid([]).Near(new Extent(0, 0, 1, 1), 0));
var line = new ExtentGrid([new Extent(2, 0, 2, 5), new Extent(2, 7, 2, 9)]);
Assert.Equal([0, 1], line.Near(new Extent(2, 4, 2, 8), 0));
Assert.Empty(line.Near(new Extent(4, 0, 5, 9), 0.5));
}
[Theory]
[InlineData(0)]
[InlineData(0.3)]
public void LeadCheck_AgreesWithTheFullScan(double pierceRadius)
{
// 900 squares, so the set's grid has many cells; leads of random length and direction
// enter squares across the grid, some reaching their neighbors.
var squares = new List<(double X, double Y, LeadMaterialSnapshot Material)>();
for (var row = 0; row < 30; row++)
for (var column = 0; column < 30; column++)
{
var (x, y) = (column * 1.5, row * 1.5);
squares.Add((x, y, LeadMaterialSnapshot.Capture(LeadPathValidationTests.Rectangle(x, y, x + 1, y + 1), Vector.Zero)));
}
var all = squares.Select(s => s.Material).ToArray();
var set = new LeadMaterialSet(all);
var random = new Random(11);
var outcomes = new HashSet<bool>();
for (var trial = 0; trial < 400; trial++)
{
var (x, y, target) = squares[random.Next(squares.Count)];
var angle = System.Math.PI / 2 + random.NextDouble() * System.Math.PI;
var length = 0.1 + random.NextDouble() * 2;
var program = new Program();
program.MoveTo(x + length * System.Math.Cos(angle), y + 0.5 + length * System.Math.Sin(angle));
program.Codes.Add(new LinearMove(x, y + 0.5) { Layer = LayerType.Leadin });
program.LineTo(x, y + 1); program.LineTo(x + 1, y + 1); program.LineTo(x + 1, y);
program.LineTo(x, y); program.LineTo(x, y + 0.5);
var execution = ExecutionMotionReader.Read(program, Vector.Zero, null, default);
var full = LeadPathValidator.Check(execution, target, all, pierceRadius);
var indexed = LeadPathValidator.Check(execution, target, set, pierceRadius);
Assert.Equal(full, indexed);
outcomes.Add(full.IsClear);
}
Assert.Equal([false, true], outcomes.Order());
}
[Fact]
public void RapidCheck_FindsTheSameCrossingsInObstacleOrder_InCopiesToo()
{
// 400 cut squares put most obstacles in the shared grid; copies taken along the way
// must judge rapids just as a state that checked everything itself.
var state = new ReleasedContourState(reportMissingLeadIns: false);
ReleasedContourState copy = null;
var part = 0;
for (var row = 0; row < 20; row++)
for (var column = 0; column < 20; column++)
{
var (x, y) = (column * 2.0, row * 2.0);
var square = ExecutionMotionReader.Read(LeadPathValidationTests.Rectangle(x, y, x + 1, y + 1), Vector.Zero, null, default);
part++;
// A short rapid in from the gap below-left, so every square checks one.
var arrival = new Vector(x - 0.5, y - 0.5);
Assert.Empty(state.Check(square, arrival, part));
if (part == 250)
copy = state.Copy();
else if (part > 250)
Assert.Empty(copy.Check(square, arrival, part));
}
// Up column 0 from below the sheet to a square above it: it crosses parts 1, 21, ..., 381.
var probe = ExecutionMotionReader.Read(LeadPathValidationTests.Rectangle(0.5, 45, 1, 46), Vector.Zero, null, default);
var expected = Enumerable.Range(0, 20).Select(r => r * 20 + 1).ToArray();
Assert.Equal(expected, state.Check(probe, new Vector(0.5, -1), 401).Select(f => f.OtherPartNumber ?? 0));
Assert.Equal(expected, copy.Check(probe, new Vector(0.5, -1), 401).Select(f => f.OtherPartNumber ?? 0));
}
private static Extent Box(Random random, double size)
{
var (x, y) = (random.NextDouble() * size, random.NextDouble() * size);
return new Extent(x, y, x + random.NextDouble() * 5, y + random.NextDouble() * 5);
}
private static bool Apart(Extent a, Extent b, double margin) =>
a.MaxX + margin < b.MinX || b.MaxX + margin < a.MinX || a.MaxY + margin < b.MinY || b.MaxY + margin < a.MinY;
}