perf(geometry): skip far entities when classifying a slide contact

GetMaterialSector measured the contact point against every entity of a
boundary, twice per contact, with trigonometry for each arc. Each entity
now has a box no point within the incidence tolerance of it lies outside,
built once when the boundary is prepared; entities whose box misses the
point are skipped unmeasured. They are farther than the tolerance, so the
nearest entity, the off-boundary verdict and the ambiguity check are
unchanged, and every slide distance is the same.

N26-2J9 Auto Nest: 724 s to 621 s, the same plans and result.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Fable 5.2 committed 2026-11-22 14:52:50 -05:00
1 parent 81858a1369
commit 6eec5bb63e
2 files changed
+258 -11

No files matched your search

+113 -11
View File
@@ -52,6 +52,14 @@ namespace OpenNest.Geometry
private readonly int[] following;
private readonly bool[] materialLeft;
// Per entity, a box holding every point GetMaterialSector could find within the
// incidence tolerance of it, and per loop its entity count. Null when unresolved.
private readonly double[] nearMinX;
private readonly double[] nearMinY;
private readonly double[] nearMaxX;
private readonly double[] nearMaxY;
private readonly int[] loopLength;
private SlideContactGeometry(
List<Entity> entities,
int[] loopOf,
@@ -65,8 +73,103 @@ namespace OpenNest.Geometry
this.previous = previous;
this.following = following;
this.materialLeft = materialLeft;
if (materialLeft == null)
return;
var count = entities.Count;
nearMinX = new double[count];
nearMinY = new double[count];
nearMaxX = new double[count];
nearMaxY = new double[count];
loopLength = new int[materialLeft.Length];
for (var i = 0; i < count; i++)
{
NearBox(entities[i], out nearMinX[i], out nearMinY[i], out nearMaxX[i], out nearMaxY[i]);
loopLength[loopOf[i]]++;
}
}
// Slack of the near boxes beyond the incidence tolerance: Box.Contains and
// Angle.IsBetweenRad accept points Tolerance.Epsilon outside a line's box or past an
// arc's ends, and DistanceTo measures from what they accept.
private const double NearPad = 10 * Tolerance.Epsilon;
/// <summary>
/// A box no point within <see cref="IncidenceTolerance"/> of the entity, as
/// <see cref="DistanceTo"/> measures it, lies outside. An entity whose box misses a
/// point is therefore farther from it than the tolerance without measuring.
/// </summary>
internal static void NearBox(Entity entity, out double minX, out double minY, out double maxX, out double maxY)
{
switch (entity)
{
case Line line:
{
// The closest point is the foot of the perpendicular when the line's
// own box holds it (to Tolerance.Epsilon), else an end point.
var box = line.BoundingBox;
minX = System.Math.Min(box.Left, System.Math.Min(line.pt1.X, line.pt2.X)) - NearPad;
minY = System.Math.Min(box.Bottom, System.Math.Min(line.pt1.Y, line.pt2.Y)) - NearPad;
maxX = System.Math.Max(box.Right, System.Math.Max(line.pt1.X, line.pt2.X)) + NearPad;
maxY = System.Math.Max(box.Top, System.Math.Max(line.pt1.Y, line.pt2.Y)) + NearPad;
break;
}
case Arc arc:
{
// On the circle at an angle the arc takes (to Tolerance.Epsilon past
// either end, a chord of at most radius x Epsilon), else at an end.
var r = System.Math.Abs(arc.Radius);
var pad = NearPad + r * NearPad;
var start = arc.StartPoint();
var end = arc.EndPoint();
minX = System.Math.Min(start.X, end.X);
minY = System.Math.Min(start.Y, end.Y);
maxX = System.Math.Max(start.X, end.X);
maxY = System.Math.Max(start.Y, end.Y);
if (Angle.IsBetweenRad(0, arc.StartAngle, arc.EndAngle, arc.IsReversed))
maxX = System.Math.Max(maxX, arc.Center.X + r);
if (Angle.IsBetweenRad(Angle.HalfPI, arc.StartAngle, arc.EndAngle, arc.IsReversed))
maxY = System.Math.Max(maxY, arc.Center.Y + r);
if (Angle.IsBetweenRad(System.Math.PI, arc.StartAngle, arc.EndAngle, arc.IsReversed))
minX = System.Math.Min(minX, arc.Center.X - r);
if (Angle.IsBetweenRad(3 * Angle.HalfPI, arc.StartAngle, arc.EndAngle, arc.IsReversed))
minY = System.Math.Min(minY, arc.Center.Y - r);
minX -= pad;
minY -= pad;
maxX += pad;
maxY += pad;
break;
}
case Circle circle:
{
var reach = System.Math.Abs(circle.Radius) * (1 + NearPad) + NearPad;
minX = circle.Center.X - reach;
minY = circle.Center.Y - reach;
maxX = circle.Center.X + reach;
maxY = circle.Center.Y + reach;
break;
}
default:
// DistanceTo never finds such an entity near; its box rejects nothing.
minX = minY = double.NegativeInfinity;
maxX = maxY = double.PositiveInfinity;
break;
}
// A box that is not a number rejects nothing either.
if (double.IsNaN(minX) || double.IsNaN(minY) || double.IsNaN(maxX) || double.IsNaN(maxY))
{
minX = minY = double.NegativeInfinity;
maxX = maxY = double.PositiveInfinity;
}
}
/// <summary>
/// True when the point is outside the entity's near box, so farther from the entity
/// than the incidence tolerance. False for a point that is not a number.
/// </summary>
private bool FarFrom(int index, double x, double y) =>
x < nearMinX[index] || x > nearMaxX[index] || y < nearMinY[index] || y > nearMaxY[index];
/// <summary>True when every entity belongs to a closed loop with a known material side.</summary>
public bool IsResolved => materialLeft != null;
@@ -177,10 +280,17 @@ namespace OpenNest.Geometry
if (materialLeft == null)
return ContactSide.Unresolved;
// Entities whose near box misses the point are farther than the tolerance: they
// cannot be the nearest of a point on the boundary, nor make it ambiguous. When
// every entity is that far the point is off the boundary, as when measured.
var x = point.X;
var y = point.Y;
var best = -1;
var bestDistance = double.MaxValue;
for (var i = 0; i < entities.Count; i++)
{
if (FarFrom(i, x, y))
continue;
var distance = DistanceTo(entities[i], point);
if (distance < bestDistance)
{
@@ -193,7 +303,7 @@ namespace OpenNest.Geometry
return ContactSide.Off;
// Walk to the entities that enter and leave the tolerance disc.
var loopLength = LoopLength(best);
var loopLength = this.loopLength[loopOf[best]];
var incoming = best;
var steps = 0;
var smoothLoop = loopLength == 1 && (entities[best] is Circle
@@ -218,7 +328,7 @@ namespace OpenNest.Geometry
// makes the local material side ambiguous.
for (var i = 0; i < entities.Count; i++)
{
if (InRun(i, incoming, outgoing))
if (FarFrom(i, x, y) || InRun(i, incoming, outgoing))
continue;
if (DistanceTo(entities[i], point) <= IncidenceTolerance)
return ContactSide.Ambiguous;
@@ -254,14 +364,6 @@ namespace OpenNest.Geometry
: ContactSide.Ambiguous;
}
private int LoopLength(int index)
{
var length = 1;
for (var i = following[index]; i != index; i = following[i])
length++;
return length;
}
private bool StartsNear(int index, Vector point) =>
EntityEndpoints.TryGet(entities[index], out var start, out _)
&& start.DistanceTo(point) <= JointTolerance;
@@ -337,7 +439,7 @@ namespace OpenNest.Geometry
return length > 0 ? new Vector(dx / length, dy / length) : new Vector();
}
private static double DistanceTo(Entity entity, Vector point)
internal static double DistanceTo(Entity entity, Vector point)
{
switch (entity)
{
@@ -0,0 +1,145 @@
using OpenNest.Geometry;
using OpenNest.Math;
namespace OpenNest.Tests.Geometry;
/// <summary>
/// <see cref="SlideContactGeometry.GetMaterialSector"/> skips the entities whose near box misses
/// the contact point. That leaves every answer as it was only while no point within the
/// incidence tolerance of an entity lies outside the entity's box.
/// </summary>
public class SlideContactNearBoxTests
{
private const double Tolerance = SlideContactGeometry.IncidenceTolerance;
[Fact]
public void Lines_HoldEveryPointWithinTolerance()
{
var random = new Random(1);
for (var i = 0; i < 2000; i++)
{
var line = new Line(Coordinate(random), Coordinate(random), Coordinate(random), Coordinate(random));
if (i % 5 == 0)
line = new Line(line.pt1.X, line.pt1.Y, line.pt1.X, line.pt2.Y); // Vertical.
if (i % 7 == 0)
line = new Line(line.pt1.X, line.pt1.Y, line.pt2.X, line.pt1.Y); // Horizontal.
foreach (var point in Around(line, random))
AssertHeldWhenNear(line, point);
}
}
[Fact]
public void Arcs_HoldEveryPointWithinTolerance()
{
var random = new Random(2);
var radii = new[] { 1e-3, 0.05, 0.25, 1, 7.5, 120, 5000 };
for (var i = 0; i < 4000; i++)
{
var radius = radii[i % radii.Length];
var start = random.NextDouble() * Angle.TwoPI;
// Sweeps from a sliver to the whole circle, and ends on the axis extremes.
var sweep = (i % 6) switch
{
0 => 1e-6,
1 => Angle.TwoPI - 1e-6,
2 => Angle.HalfPI,
_ => random.NextDouble() * Angle.TwoPI,
};
if (i % 4 == 0)
start = (i / 4 % 4) * Angle.HalfPI;
var arc = new Arc(Coordinate(random), Coordinate(random), radius, start, start + sweep, i % 2 == 0);
foreach (var point in Around(arc, random))
AssertHeldWhenNear(arc, point);
}
}
[Fact]
public void Circles_HoldEveryPointWithinTolerance()
{
var random = new Random(3);
for (var i = 0; i < 500; i++)
{
var circle = new Circle(Coordinate(random), Coordinate(random), 0.01 + random.NextDouble() * 50);
for (var k = 0; k < 64; k++)
{
var angle = k * Angle.TwoPI / 64;
foreach (var radial in new[] { -Tolerance, 0, Tolerance })
AssertHeldWhenNear(circle, new Vector(
circle.Center.X + (circle.Radius + radial) * System.Math.Cos(angle),
circle.Center.Y + (circle.Radius + radial) * System.Math.Sin(angle)));
}
}
}
[Fact]
public void FarPointsAreRejected()
{
// The box is worth having only if it rejects: a point well away from each entity is out.
var entities = new Entity[]
{
new Line(0, 0, 10, 0),
new Arc(0, 0, 5, 0, Angle.HalfPI),
new Circle(0, 0, 5),
};
foreach (var entity in entities)
{
SlideContactGeometry.NearBox(entity, out var minX, out var minY, out var maxX, out var maxY);
Assert.False(Holds(minX, minY, maxX, maxY, new Vector(-20, -20)));
Assert.False(Holds(minX, minY, maxX, maxY, new Vector(3, 30)));
}
}
private static double Coordinate(Random random) => (random.NextDouble() - 0.5) * 400;
// Points on the line, at and just past its ends, and a tolerance off to either side.
private static IEnumerable<Vector> Around(Line line, Random random)
{
var dx = line.pt2.X - line.pt1.X;
var dy = line.pt2.Y - line.pt1.Y;
var length = System.Math.Sqrt(dx * dx + dy * dy);
if (length == 0)
yield break;
var ux = dx / length;
var uy = dy / length;
var along = new[]
{
-2e-5, -1e-5, -Tolerance, 0, Tolerance, length / 3, length - Tolerance, length, length + Tolerance,
length + 1e-5, length + 2e-5, random.NextDouble() * length,
};
foreach (var t in along)
foreach (var off in new[] { -Tolerance, -Tolerance / 2, 0, Tolerance / 2, Tolerance })
yield return new Vector(line.pt1.X + ux * t - uy * off, line.pt1.Y + uy * t + ux * off);
}
// Points on the arc, at and just past its ends, at the axis extremes, and a tolerance in or out.
private static IEnumerable<Vector> Around(Arc arc, Random random)
{
var sign = arc.IsReversed ? -1.0 : 1.0;
var sweep = arc.SweepAngle();
var angles = new List<double> { 0, Angle.HalfPI, System.Math.PI, 3 * Angle.HalfPI };
foreach (var t in new[] { -3e-5, -1e-5, -1e-6, -1e-9, 0, 1e-9, 1e-6 })
{
angles.Add(arc.StartAngle + sign * t);
angles.Add(arc.EndAngle + sign * -t);
}
for (var k = 0; k < 12; k++)
angles.Add(arc.StartAngle + sign * sweep * random.NextDouble());
foreach (var angle in angles)
foreach (var radial in new[] { -Tolerance, -Tolerance / 2, 0, Tolerance / 2, Tolerance })
yield return new Vector(
arc.Center.X + (arc.Radius + radial) * System.Math.Cos(angle),
arc.Center.Y + (arc.Radius + radial) * System.Math.Sin(angle));
}
private static void AssertHeldWhenNear(Entity entity, Vector point)
{
if (SlideContactGeometry.DistanceTo(entity, point) > Tolerance)
return;
SlideContactGeometry.NearBox(entity, out var minX, out var minY, out var maxX, out var maxY);
Assert.True(Holds(minX, minY, maxX, maxY, point),
$"{entity} is within tolerance of {point} but its near box [{minX}, {minY}] - [{maxX}, {maxY}] misses it.");
}
private static bool Holds(double minX, double minY, double maxX, double maxY, Vector point) =>
!(point.X < minX || point.X > maxX || point.Y < minY || point.Y > maxY);
}