perf(core): clip collision triangles without a polygon per triangle

Collision.HasOverlap, Check and PartOverlapChecker now triangulate into
CollisionTriangle values (each ear's open vertices and box sides) and clip
them in two reused stack buffers, instead of building a Polygon entity per
triangle and three lists per clip. Same ears, vertices, bounds, pairs and
arithmetic, so verdicts and regions are bit-identical.

On the N26-2GT job a 30-copy Lattice fill of an 80-vertex arc-cornered
bracket fell from 15 s to about 4 s with identical poses, and Irregular's
first plan from 66 s to about 26 s, inside Default's 60 s limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-18 01:36:19 -05:00
1 parent fd15c13d88
commit 7ae01978f5
7 files changed
+508 -19

No files matched your search

+276 -1
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using OpenNest.Math;
namespace OpenNest.Geometry
@@ -82,6 +83,24 @@ namespace OpenNest.Geometry
return OverlapRegions(trianglesA(), trianglesB(), holesA, holesB, verdictOnly: true).Count > 0;
}
/// <summary>
/// <see cref="HasOverlap(Polygon, Polygon, List{Polygon}, List{Polygon})"/> with each
/// polygon's <see cref="TriangulateForClipping"/> supplied by the caller and resolved
/// lazily, only after the bounding boxes overlap; the verdict is then identical.
/// </summary>
internal static bool HasOverlapTriangulated(
Polygon a,
Func<List<CollisionTriangle>> trianglesA,
Polygon b,
Func<List<CollisionTriangle>> trianglesB
)
{
if (!BoundingBoxesOverlap(a.BoundingBox, b.BoundingBox))
return false;
return OverlapRegions(trianglesA(), trianglesB(), null, null, verdictOnly: true).Count > 0;
}
/// <summary>
/// The triangulation <see cref="Check"/> and <see cref="HasOverlap(Polygon, Polygon, List{Polygon}, List{Polygon})"/>
/// use for <paramref name="polygon"/>: ear-clipped triangles with bounds updated. Callers
@@ -89,6 +108,28 @@ namespace OpenNest.Geometry
/// </summary>
internal static List<Polygon> Triangulate(Polygon polygon) => TriangulateWithBounds(polygon);
/// <summary>
/// <see cref="Triangulate"/> as the clip loop reads it, without a polygon per triangle:
/// the same triangles, vertices and bounds. Callers may reuse it for the same polygon.
/// </summary>
internal static List<CollisionTriangle> TriangulateForClipping(Polygon polygon)
{
PerfCounters.CountPolygonTriangulation();
var sink = new TriangleSink(new List<CollisionTriangle>(polygon.Vertices.Count));
ConvexDecomposition.Triangulate(polygon, ref sink);
return sink.Triangles;
}
private readonly struct TriangleSink : ConvexDecomposition.IEarSink
{
public TriangleSink(List<CollisionTriangle> triangles) => Triangles = triangles;
public List<CollisionTriangle> Triangles { get; }
public void Add(Vector prev, Vector curr, Vector next) =>
Triangles.Add(new CollisionTriangle(prev, curr, next));
}
public static List<CollisionResult> CheckAll(
List<Polygon> polygons,
List<List<Polygon>> holes = null
@@ -140,7 +181,32 @@ namespace OpenNest.Geometry
List<Polygon> holesA,
List<Polygon> holesB,
bool verdictOnly = false
) => OverlapRegions(TriangulateWithBounds(a), TriangulateWithBounds(b), holesA, holesB, verdictOnly);
) => OverlapRegions(TriangulateForClipping(a), TriangulateForClipping(b), holesA, holesB, verdictOnly);
/// <summary>
/// <see cref="OverlapRegions(List{Polygon}, List{Polygon}, List{Polygon}, List{Polygon}, bool)"/>
/// over <see cref="TriangulateForClipping"/> triangles: the same pairs clipped in the same
/// order, so the same regions.
/// </summary>
private static List<Polygon> OverlapRegions(
List<CollisionTriangle> trisA,
List<CollisionTriangle> trisB,
List<Polygon> holesA,
List<Polygon> holesB,
bool verdictOnly = false
)
{
var regions = new List<Polygon>();
var stopAtFirst = verdictOnly
&& (holesA == null || holesA.Count == 0)
&& (holesB == null || holesB.Count == 0);
ClipTrianglePairs(trisA, trisB, regions, stopAtFirst);
if (regions.Count > 0)
regions = SubtractHoles(regions, holesA, holesB);
return regions;
}
private static List<Polygon> OverlapRegions(
List<Polygon> trisA,
@@ -219,6 +285,215 @@ namespace OpenNest.Geometry
}
}
/// <summary>
/// <see cref="ClipTrianglePairs(List{Polygon}, List{Polygon}, List{Polygon}, bool)"/> over
/// <see cref="CollisionTriangle"/>s, clipping in two reused buffers: the same pairs in the
/// same order with the same arithmetic, and a region polygon built only for a pair that
/// overlaps.
/// </summary>
private static void ClipTrianglePairs(
List<CollisionTriangle> trisA,
List<CollisionTriangle> trisB,
List<Polygon> regions,
bool stopAtFirst
)
{
if (trisA.Count == 0 || trisB.Count == 0)
return;
var candidatesA = TrianglesTouching(trisA, UnionBounds(trisB));
if (candidatesA.Count == 0)
return;
var candidatesB = TrianglesTouching(trisB, UnionBounds(trisA));
if (candidatesB.Count == 0)
return;
Span<Vector> first = stackalloc Vector[MaxClippedVertices];
Span<Vector> second = stackalloc Vector[MaxClippedVertices];
Span<double> distances = stackalloc double[MaxClippedVertices];
var spanA = CollectionsMarshal.AsSpan(trisA);
var spanB = CollectionsMarshal.AsSpan(trisB);
foreach (var a in candidatesA)
{
ref readonly var triA = ref spanA[a];
foreach (var b in candidatesB)
{
ref readonly var triB = ref spanB[b];
if (!BoundingBoxesOverlap(triA, triB))
continue;
var clipped = ClipConvex(triA, triB, first, second, distances);
if (clipped == null)
continue;
regions.Add(clipped);
if (stopAtFirst)
return;
}
}
}
/// <summary>
/// Most vertices clipping a triangle by a triangle's three half-spaces can leave: each
/// half-space keeps each vertex and adds at most one crossing after it.
/// </summary>
private const int MaxClippedVertices = 3 * 2 * 2 * 2;
private static (double Left, double Right, double Bottom, double Top) UnionBounds(
List<CollisionTriangle> triangles
)
{
var left = double.PositiveInfinity;
var right = double.NegativeInfinity;
var bottom = double.PositiveInfinity;
var top = double.NegativeInfinity;
foreach (var triangle in triangles)
{
left = System.Math.Min(left, triangle.Left);
right = System.Math.Max(right, triangle.Right);
bottom = System.Math.Min(bottom, triangle.Bottom);
top = System.Math.Max(top, triangle.Top);
}
return (left, right, bottom, top);
}
/// <summary>Indices of the triangles the polygon form of this test keeps, in order.</summary>
private static List<int> TrianglesTouching(
List<CollisionTriangle> triangles,
(double Left, double Right, double Bottom, double Top) union
)
{
var result = new List<int>(triangles.Count);
for (var i = 0; i < triangles.Count; i++)
{
var box = triangles[i];
var overlapX = System.Math.Min(box.Right, union.Right) - System.Math.Max(box.Left, union.Left);
var overlapY = System.Math.Min(box.Top, union.Top) - System.Math.Max(box.Bottom, union.Bottom);
if (overlapX > Tolerance.Epsilon && overlapY > Tolerance.Epsilon)
result.Add(i);
}
return result;
}
private static bool BoundingBoxesOverlap(in CollisionTriangle a, in CollisionTriangle b)
{
var overlapX = System.Math.Min(a.Right, b.Right) - System.Math.Max(a.Left, b.Left);
var overlapY = System.Math.Min(a.Top, b.Top) - System.Math.Max(a.Bottom, b.Bottom);
return overlapX > Tolerance.Epsilon && overlapY > Tolerance.Epsilon;
}
/// <summary>
/// <see cref="ClipConvex(List{Vector}, List{Vector})"/> of two triangles' open vertices,
/// alternating between two caller buffers of <see cref="MaxClippedVertices"/>.
/// </summary>
private static Polygon ClipConvex(
in CollisionTriangle subject,
in CollisionTriangle clip,
Span<Vector> first,
Span<Vector> second,
Span<double> distances
)
{
var count = subject.Count;
for (var i = 0; i < count; i++)
first[i] = subject[i];
var output = first;
var spare = second;
for (var i = 0; i < clip.Count && count >= 3; i++)
{
count = ClipHalfSpaceInside(output.Slice(0, count), clip[i], clip[(i + 1) % clip.Count], spare,
distances);
var swap = output;
output = spare;
spare = swap;
}
return PositiveAreaPolygon(output.Slice(0, count));
}
/// <summary>
/// <see cref="ClipHalfSpace"/> keeping the inside, written to <paramref name="kept"/>;
/// returns how many it kept. Each vertex's signed distance is computed once into
/// <paramref name="distances"/>, the same value ClipHalfSpace computes for it twice.
/// </summary>
private static int ClipHalfSpaceInside(
ReadOnlySpan<Vector> vertices,
Vector edgeStart,
Vector edgeEnd,
Span<Vector> kept,
Span<double> distances
)
{
var inside = false;
for (var i = 0; i < vertices.Length; i++)
{
distances[i] = Cross(edgeStart, edgeEnd, vertices[i]);
inside |= distances[i] >= 0;
}
// Every vertex strictly outside keeps nothing and crosses nowhere.
if (!inside)
return 0;
var count = 0;
for (var i = 0; i < vertices.Length; i++)
{
var current = vertices[i];
var nextIndex = i + 1 == vertices.Length ? 0 : i + 1;
var next = vertices[nextIndex];
var currentDistance = distances[i];
var nextDistance = distances[nextIndex];
if (currentDistance >= 0)
AddDistinct(kept, ref count, current);
if ((currentDistance < 0 && nextDistance > 0) || (currentDistance > 0 && nextDistance < 0))
{
var t = currentDistance / (currentDistance - nextDistance);
AddDistinct(kept, ref count, new Vector(
current.X + t * (next.X - current.X),
current.Y + t * (next.Y - current.Y)));
}
}
if (count > 1 && SamePoint(kept[0], kept[count - 1]))
count--;
return count;
}
private static void AddDistinct(Span<Vector> vertices, ref int count, Vector point)
{
if (count == 0 || !SamePoint(vertices[count - 1], point))
vertices[count++] = point;
}
private static Polygon PositiveAreaPolygon(ReadOnlySpan<Vector> vertices)
{
if (vertices.Length < 3)
return null;
var twiceArea = 0.0;
for (var i = 1; i + 1 < vertices.Length; i++)
twiceArea += Cross(vertices[0], vertices[i], vertices[i + 1]);
if (System.Math.Abs(twiceArea) <= 2 * Tolerance.Epsilon)
return null;
var polygon = new Polygon();
foreach (var vertex in vertices)
polygon.Vertices.Add(vertex);
polygon.Vertices.Add(vertices[0]);
polygon.UpdateBounds();
return polygon;
}
private static (double Left, double Right, double Bottom, double Top) UnionBounds(
List<Polygon> polygons
)
@@ -0,0 +1,67 @@
namespace OpenNest.Geometry
{
/// <summary>
/// One ear of <see cref="ConvexDecomposition.Triangulate(Polygon)"/> as the collision clip loop
/// reads its triangle polygon: the open vertices and the bounding-box sides, without building
/// the polygon. Every value is bit for bit what the loop reads from the polygon.
/// </summary>
internal readonly struct CollisionTriangle
{
public CollisionTriangle(Vector prev, Vector curr, Vector next)
{
// The polygon is [prev, curr, next], closed with prev by Polygon.Close only when prev
// and next differ by its fuzzy equality. Its open vertices drop a last vertex exactly
// equal to the first: the closing vertex, or next when it was not closed.
V0 = prev;
V1 = curr;
V2 = next;
Count = prev != next || !(prev.X == next.X && prev.Y == next.Y) ? 3 : 2;
// Polygon.UpdateBounds over the same vertices; the closing vertex repeats prev.
var minX = prev.X;
var maxX = prev.X;
var minY = prev.Y;
var maxY = prev.Y;
Include(curr, ref minX, ref maxX, ref minY, ref maxY);
Include(next, ref minX, ref maxX, ref minY, ref maxY);
// Box sides as Box computes them from its location and size.
Left = minX;
Bottom = minY;
Right = minX + (maxX - minX);
Top = minY + (maxY - minY);
}
public Vector V0 { get; }
public Vector V1 { get; }
public Vector V2 { get; }
/// <summary>Open vertices: 3, or 2 when next is exactly prev.</summary>
public int Count { get; }
public double Left { get; }
public double Right { get; }
public double Bottom { get; }
public double Top { get; }
public Vector this[int index] => index switch
{
0 => V0,
1 => V1,
_ => V2,
};
private static void Include(Vector vertex, ref double minX, ref double maxX, ref double minY, ref double maxY)
{
if (vertex.X < minX)
minX = vertex.X;
else if (vertex.X > maxX)
maxX = vertex.X;
if (vertex.Y < minY)
minY = vertex.Y;
else if (vertex.Y > maxY)
maxY = vertex.Y;
}
}
}
+41 -10
View File
@@ -15,7 +15,45 @@ namespace OpenNest.Geometry
/// </summary>
public static List<Polygon> Triangulate(Polygon polygon)
{
var triangles = new List<Polygon>();
var sink = new PolygonSink(new List<Polygon>());
Triangulate(polygon, ref sink);
return sink.Triangles;
}
/// <summary>
/// Receives each ear <see cref="Triangulate(Polygon)"/> cuts, in order, as the three
/// vertices it would build its triangle from (previous, ear, next).
/// </summary>
internal interface IEarSink
{
void Add(Vector prev, Vector curr, Vector next);
}
private struct PolygonSink : IEarSink
{
public PolygonSink(List<Polygon> triangles) => Triangles = triangles;
public List<Polygon> Triangles { get; }
public void Add(Vector prev, Vector curr, Vector next)
{
var tri = new Polygon();
tri.Vertices.Add(prev);
tri.Vertices.Add(curr);
tri.Vertices.Add(next);
tri.Close();
Triangles.Add(tri);
}
}
/// <summary>
/// The ear-clipping of <see cref="Triangulate(Polygon)"/>, handing each ear to
/// <paramref name="sink"/> instead of building a triangle polygon for it: the same ears,
/// from the same vertices, in the same order.
/// </summary>
internal static void Triangulate<TSink>(Polygon polygon, ref TSink sink)
where TSink : struct, IEarSink
{
var verts = new List<Vector>(polygon.Vertices);
// Remove closing vertex if polygon is closed.
@@ -27,7 +65,7 @@ namespace OpenNest.Geometry
verts.RemoveAt(verts.Count - 1);
if (verts.Count < 3)
return triangles;
return;
// Ensure counter-clockwise winding for ear detection.
if (SignedArea(verts) < 0)
@@ -85,12 +123,7 @@ namespace OpenNest.Geometry
var blocker = failedBlocker[currVertex];
if (!knownNotEar && IsEar(prev, curr, next, verts, nextOf, head, n, out blocker))
{
var tri = new Polygon();
tri.Vertices.Add(prev);
tri.Vertices.Add(curr);
tri.Vertices.Add(next);
tri.Close();
triangles.Add(tri);
sink.Add(prev, curr, next);
nextOf[prevVertex] = nextVertex;
prevOf[nextVertex] = prevVertex;
@@ -113,8 +146,6 @@ namespace OpenNest.Geometry
cursor = nextVertex;
}
}
return triangles;
}
/// <summary>
+5 -4
View File
@@ -49,7 +49,7 @@ namespace OpenNest
if (world1.Polygon == null || world2.Polygon == null)
return false;
return Collision.HasOverlap(
return Collision.HasOverlapTriangulated(
world1.Polygon,
world1.Triangles,
world2.Polygon,
@@ -144,7 +144,7 @@ namespace OpenNest
/// </summary>
private sealed class PreparedPart
{
private List<Polygon> triangles;
private List<CollisionTriangle> triangles;
public PreparedPart(Polygon polygon)
{
@@ -154,9 +154,10 @@ namespace OpenNest
public Polygon Polygon { get; }
public Func<List<Polygon>> Triangles { get; }
public Func<List<CollisionTriangle>> Triangles { get; }
private List<Polygon> GetTriangles() => triangles ??= Collision.Triangulate(Polygon);
private List<CollisionTriangle> GetTriangles() =>
triangles ??= Collision.TriangulateForClipping(Polygon);
}
private sealed class PreparedProgram
+21 -3
View File
@@ -168,11 +168,12 @@ public class PartOverlapCheckerTests
var actual = WorldPolygon(checker, p);
Assert.Equal(PolygonBits(expected), PolygonBits(actual));
// Cached triangles equal a fresh triangulation of the pre-change world polygon.
// The checker keeps them as clip triangles: each polygon's open vertices and box.
var expectedTriangles = Collision.Triangulate(expected);
var actualTriangles = WorldTriangles(checker, p);
Assert.Equal(expectedTriangles.Count, actualTriangles.Count);
for (var t = 0; t < expectedTriangles.Count; t++)
Assert.Equal(PolygonBits(expectedTriangles[t]), PolygonBits(actualTriangles[t]));
Assert.Equal(ClipBits(expectedTriangles[t]), ClipBits(actualTriangles[t]));
}
}
}
@@ -367,8 +368,25 @@ public class PartOverlapCheckerTests
private static Polygon WorldPolygon(PartOverlapChecker checker, Part part) =>
(Polygon)PreparedPartMember(checker, part, "Polygon");
private static List<Polygon> WorldTriangles(PartOverlapChecker checker, Part part) =>
((Func<List<Polygon>>)PreparedPartMember(checker, part, "Triangles"))();
private static List<CollisionTriangle> WorldTriangles(PartOverlapChecker checker, Part part) =>
((Func<List<CollisionTriangle>>)PreparedPartMember(checker, part, "Triangles"))();
/// <summary>A triangle polygon as the clip loop reads it: open vertices, then box sides.</summary>
private static long[] ClipBits(Polygon triangle)
{
var open = triangle.Vertices.ToList();
if (open.Count > 1 && open[0].X == open[^1].X && open[0].Y == open[^1].Y)
open.RemoveAt(open.Count - 1);
var box = triangle.BoundingBox;
return open.SelectMany(v => new[] { v.X, v.Y })
.Concat(new[] { box.Left, box.Right, box.Bottom, box.Top })
.Select(BitConverter.DoubleToInt64Bits).ToArray();
}
private static long[] ClipBits(CollisionTriangle triangle) =>
Enumerable.Range(0, triangle.Count).SelectMany(i => new[] { triangle[i].X, triangle[i].Y })
.Concat(new[] { triangle.Left, triangle.Right, triangle.Bottom, triangle.Top })
.Select(BitConverter.DoubleToInt64Bits).ToArray();
private static object PreparedPartMember(PartOverlapChecker checker, Part part, string property)
{
@@ -133,6 +133,103 @@ public class CollisionOverlapOnlyTests
Assert.Equal(new[] { "a", "c" }, resolved);
}
/// <summary>
/// The clip triangles PartOverlapChecker caches give the legacy verdicts, reused across many
/// pairs, and read every triangle exactly as the polygon triangulation does.
/// </summary>
[Fact]
public void SeededClippingTriangles_ReusedAcrossPairs_MatchLegacyVerdicts()
{
var random = new Random(17112026);
var decisions = 0;
var overlaps = 0;
var boxOverlapClear = 0;
for (var group = 0; group < 40; group++)
{
var polygons = new List<Polygon>();
var shapeA = Make(random, group % 6);
var shapeB = Make(random, (group / 6) % 6);
for (var sample = 0; sample < 25; sample++)
{
var (ax, ay, bx, by) = Offsets(random, shapeA, shapeB, sample);
var dx = random.NextDouble() * 4 - ax;
var dy = random.NextDouble() * 4 - ay;
polygons.Add(Move(shapeA, ax + dx, ay + dy));
polygons.Add(Move(shapeB, bx + dx, by + dy));
}
var triangles = polygons.Select(p => new Lazy<List<CollisionTriangle>>(() => Collision.TriangulateForClipping(p)))
.ToArray();
for (var i = 0; i < polygons.Count; i++)
for (var j = i + 1; j < polygons.Count; j++)
{
var expected = LegacyCollision.HasOverlap(polygons[i], polygons[j]);
var ti = triangles[i];
var tj = triangles[j];
var actual = Collision.HasOverlapTriangulated(polygons[i], () => ti.Value, polygons[j], () => tj.Value);
Assert.True(expected == actual, $"group={group} i={i} j={j} expected={expected}");
decisions++;
if (expected)
overlaps++;
else if (BoxesOverlap(polygons[i].BoundingBox, polygons[j].BoundingBox))
boxOverlapClear++;
}
for (var i = 0; i < polygons.Count; i++)
if (triangles[i].IsValueCreated)
Assert.Equal(ClipBits(Collision.Triangulate(polygons[i])), ClipBits(triangles[i].Value));
}
output.WriteLine($"clip-triangle decisions={decisions}; overlaps={overlaps}; bbox-overlap but clear={boxOverlapClear}");
Assert.Equal(40 * 50 * 49 / 2, decisions);
Assert.True(overlaps > 10000);
Assert.True(boxOverlapClear > 2000);
}
/// <summary>
/// Ears whose neighbors coincide exactly, or only within the fuzzy equality that closes a
/// triangle polygon, keep the polygon's open vertices and bounds.
/// </summary>
[Theory]
[InlineData(0.0)]
[InlineData(1e-12)]
[InlineData(1e-6)]
public void TriangulateForClipping_DegenerateEars_MatchTriangulateBitwise(double offset)
{
var polygons = new[]
{
// A spike back onto its own vertex, and collinear runs.
Ring((0, 0), (4, 0), (4, 2), (2, 2), (2 + offset, 3), (2, 2), (0, 2)),
Ring((0, 0), (1, 0), (2, 0), (3, offset), (3, 1), (2, 1), (1, 1 + offset), (0, 1)),
Ring((0, 0), (5, 0), (5, 5), (5 + offset, 5), (0, 5)),
Move(Make(new Random(3), 4), 123.456, -78.9),
};
foreach (var polygon in polygons)
{
var expected = ClipBits(Collision.Triangulate(polygon));
Assert.Equal(expected, ClipBits(Collision.TriangulateForClipping(polygon)));
}
}
/// <summary>Each triangle as the clip loop reads it: open vertices, then box sides.</summary>
private static long[] ClipBits(List<Polygon> triangles) => triangles
.SelectMany(t =>
{
var open = t.Vertices.ToList();
if (open.Count > 1 && open[0].X == open[^1].X && open[0].Y == open[^1].Y)
open.RemoveAt(open.Count - 1);
var box = t.BoundingBox;
return new[] { (long)open.Count }
.Concat(open.SelectMany(VectorBits))
.Concat(new[] { Bits(box.Left), Bits(box.Right), Bits(box.Bottom), Bits(box.Top) });
})
.Prepend(triangles.Count)
.ToArray();
private static long[] ClipBits(List<CollisionTriangle> triangles) => triangles
.SelectMany(t => new[] { (long)t.Count }
.Concat(Enumerable.Range(0, t.Count).SelectMany(i => VectorBits(t[i])))
.Concat(new[] { Bits(t.Left), Bits(t.Right), Bits(t.Bottom), Bits(t.Top) }))
.Prepend(triangles.Count)
.ToArray();
private static long[] TriangleBits(List<Polygon> triangles) => triangles
.SelectMany(t => new[] { t.BoundingBox.X, t.BoundingBox.Y, t.BoundingBox.Length, t.BoundingBox.Width }
.Concat(t.Vertices.SelectMany(v => new[] { v.X, v.Y })))
+1 -1
View File
@@ -66,7 +66,7 @@ dotnet test OpenNest.Tests/OpenNest.Tests.csproj -c Debug \
--filter 'FullyQualifiedName~DefaultFillComparerWorkTests|FullyQualifiedName~FillHelpersTests|FullyQualifiedName~FillExtentsTests|FullyQualifiedName~StrategyOverlapTests|FullyQualifiedName~FillLinearGeometryReuseTests|FullyQualifiedName~CollisionOverlapOnlyTests|FullyQualifiedName~PartOverlapCheckerTests'
```
`PerfCounters.FillScoreComputations`, `PartBoundaryPreparations`, `PartBoundsUpdates`, `OffsetPerimeterEntities`, `FeatureBitmaskCells`, `CrossingPointScans`, `OverlapPolygonPreparations`, and `PolygonTriangulations` increments compile away in Release: zero Release counters prove nothing. `OverlapPolygonPreparations` counts overlap-preparation starts (material extraction), not completed polygons: `Part.Intersects` counts both parts on every call, `PartOverlapChecker` counts once per distinct `Program`. `PolygonTriangulations` counts `Collision` triangulations; the checker triangulates a part at most once per check, and only after a bounding-box hit. Serialize counter assertions in `FillCacheCollection` and reset in `finally`. Keep `OpenNest.Tests/Fill/LegacyFillExtents.cs`, `OpenNest.Tests/Fill/LegacyFillLinear.cs`, `OpenNest.Tests/Geometry/LegacyCollision.cs`, and `OpenNest.Tests/Fill/LegacyPartOverlap.cs` frozen for differential tests (never route them through production helpers), not production or before timings; measure the actual baseline production code.
`PerfCounters.FillScoreComputations`, `PartBoundaryPreparations`, `PartBoundsUpdates`, `OffsetPerimeterEntities`, `FeatureBitmaskCells`, `CrossingPointScans`, `OverlapPolygonPreparations`, and `PolygonTriangulations` increments compile away in Release: zero Release counters prove nothing. `OverlapPolygonPreparations` counts overlap-preparation starts (material extraction), not completed polygons: `Part.Intersects` counts both parts on every call, `PartOverlapChecker` counts once per distinct `Program`. `PolygonTriangulations` counts `Collision` triangulations; the checker triangulates a part at most once per check, and only after a bounding-box hit. `HasOverlap`, `Check` and the checker clip `CollisionTriangle`s (each ear's open vertices and box sides, without a `Polygon` per triangle) in reused buffers with the polygon path's arithmetic; `CollisionOverlapOnlyTests` holds them bitwise to `Collision.Triangulate` and their verdicts to `LegacyCollision`. On a 30-copy fill of an 80-vertex arc-cornered bracket this cut a 15 s Lattice fill to about 4 s with identical poses: per-triangle `Polygon` entities (an interlocked ID each) and per-clip lists dominated. Serialize counter assertions in `FillCacheCollection` and reset in `finally`. Keep `OpenNest.Tests/Fill/LegacyFillExtents.cs`, `OpenNest.Tests/Fill/LegacyFillLinear.cs`, `OpenNest.Tests/Geometry/LegacyCollision.cs`, and `OpenNest.Tests/Fill/LegacyPartOverlap.cs` frozen for differential tests (never route them through production helpers), not production or before timings; measure the actual baseline production code.
Predictor regression checks: `dotnet test OpenNest.Tests/OpenNest.Tests.csproj -c Release --filter "FullyQualifiedName~AngleCandidateBuilderTests|FullyQualifiedName~AnglePredictorTests|FullyQualifiedName~FeatureExtractorTests"` (repeat in Debug for bitmap counters). `IrregularAngles_ReportsWarmNoModelPath` measures the public builder with a missing model and skips when a model is installed; never remove real model files to benchmark. `FeatureExtraction_ReportsFullAndScalarOnly` measures extraction separately.