refactor: remove unused OpenNest.Gpu project

OpenNest.Gpu never ran: the best-fit slide search passes native entities,
whose GpuDistanceComputer overload fell back to the CPU, and the GPU pair
evaluator was disabled earlier. Remove the project, its axis-only
ISlideComputer adapter (GpuDistanceComputer, BestFitCache.CreateSlideComputer,
BestFitFinder's slideComputer parameter), the Training tool's GPU wiring,
SpatialQuery.FlattenLines and the ILGPU tests. Best fit always uses
CpuDistanceComputer, as it already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-29 12:28:00 -05:00
1 parent 47497f4153
commit aeef9b58cd
22 files changed
+11 -1917

No files matched your search

+2 -2
View File
@@ -46,12 +46,12 @@ Releases: follow [the release procedure](docs/releasing.md) and `scripts/Publish
- `OpenNest`: WinForms UI (`Forms/`, `Controls/PlateView`, `Actions/`). `OpenNest.Data` holds cross-platform persistence; new-nest defaults live in `%APPDATA%\OpenNest\defaults.json` (in Database mode, the server's shared copy once it holds one). WinForms `Properties.Settings` persist to `%APPDATA%\OpenNest\user-settings.json` through `AppDataSettingsProvider`, never inside the Velopack install folder; `OpenNest.WinForms.Tests` redirects them to a temp file, so a test run never writes the user's settings. Posts live in `Posts/OpenNest.Posts.<Name>/` and deploy to each desktop app's output `Posts/` directory (WinForms and Avalonia). Desktop nest edits go through `BeginChange`/`RecordChange`; see [undo and redo](docs/undo-redo.md).
- `OpenNest.Desktop` (net8.0): toolkit-neutral desktop logic shared by the WinForms app and `OpenNest.Avalonia`, the cross-platform desktop in progress. It must not reference WinForms/WindowsDesktop, `System.Drawing.Common` or Avalonia (`OpenNest.Desktop.Tests` guards this, including transitive packages); put toolkit-specific rendering, dialogs and settings behind adapters in the front ends.
- `OpenNest.Server`: nest storage HTTP service, kept off Engine and IO. `OpenNest.Server.Worker`: the server nesting worker, shipped in the same image.
- `OpenNest.Console`, `OpenNest.Mcp`, `OpenNest.Api`: front ends; `OpenNest.Benchmark`: whole-job engine comparisons; `OpenNest.Gpu`: GPU evaluators; `OpenNest.Training`: ML data collection and the Python sketch-search prototype (`sketch-search/README.md`). Benchmark timing comparisons require `--parallel 1`; validate layouts and fulfillment, not just elapsed time.
- `OpenNest.Console`, `OpenNest.Mcp`, `OpenNest.Api`: front ends; `OpenNest.Benchmark`: whole-job engine comparisons; `OpenNest.Training`: ML data collection and the Python sketch-search prototype (`sketch-search/README.md`). Benchmark timing comparisons require `--parallel 1`; validate layouts and fulfillment, not just elapsed time.
## Geometry and ownership safeguards
- Marks are not material: use `SpecialLayers.IsMaterial` when deriving nesting/collision geometry; exclude rapid and scribe moves without removing them from display, cutting time or posts.
- Engine/validator collision paths retain the hand-written `Collision` kernel; its GPU port is on hold. Material-overlap diagnostics use Clipper2 per pair for connected shared-material islands and interior markers; see [material-overlap diagnostics](docs/geometry/visual-overlap-check.md). Polygon consumers use `ClipperBridge`; directional-distance consumers retain native-arc offsets. Validation uses `OffsetForValidation` and `NestTolerances.SpacingSlack`, not conservative display/preparation padding; Auto Nest's layout check, the runner's candidate validation and the pre-post part-spacing review all find spacing candidates with Core's `SpacingOutline` and confirm them on `NativeContours` (the outline circumscribes arcs by more than the slack), so they agree; an outlined sheet's edge test confirms the same way (`SheetOutline.Holds` with `NativeContours.Region`); `NestLayoutCheck.Clears` skips the confirmation and stays stricter for engine certification. Do not loosen tolerances to hide failures.
- Engine/validator collision paths retain the hand-written `Collision` kernel. Material-overlap diagnostics use Clipper2 per pair for connected shared-material islands and interior markers; see [material-overlap diagnostics](docs/geometry/visual-overlap-check.md). Polygon consumers use `ClipperBridge`; directional-distance consumers retain native-arc offsets. Validation uses `OffsetForValidation` and `NestTolerances.SpacingSlack`, not conservative display/preparation padding; Auto Nest's layout check, the runner's candidate validation and the pre-post part-spacing review all find spacing candidates with Core's `SpacingOutline` and confirm them on `NativeContours` (the outline circumscribes arcs by more than the slack), so they agree; an outlined sheet's edge test confirms the same way (`SheetOutline.Holds` with `NativeContours.Region`); `NestLayoutCheck.Clears` skips the confirmation and stays stricter for engine certification. Do not loosen tolerances to hide failures.
- `FillLinear` geometry caches are per public call, keyed by `Program` reference identity; never share them across calls/threads. `PartOverlapChecker` is per check; parts/programs must not mutate during its lifetime.
- `FillScore` ranks count, utilization, compactness; exact ties keep the current layout. Custom comparers remain authoritative. Preserve extents' negative/nonfinite-input fallback, pair preparation and adjusted-column overlap checks. Do not remove bounds recomputations without threshold/rounding characterization.
- `ObservableList` events own drawing/plate quantity tracking; avoid double accounting. Cutoff parts are excluded from quantity, utilization and overlap checks.
-17
View File
@@ -377,23 +377,6 @@ namespace OpenNest.Geometry
return SlideResolver.FirstBlocking(ref source, contacts, unit.X, unit.Y);
}
/// <summary>
/// Packs line segments into a flat double array [x1,y1,x2,y2, ...] for GPU transfer.
/// </summary>
public static double[] FlattenLines(List<Line> lines)
{
var result = new double[lines.Count * 4];
for (int i = 0; i < lines.Count; i++)
{
var line = lines[i];
result[i * 4] = line.pt1.X;
result[i * 4 + 1] = line.pt1.Y;
result[i * 4 + 2] = line.pt2.X;
result[i * 4 + 3] = line.pt2.Y;
}
return result;
}
/// <summary>
/// Computes the blocking directional distance using raw edge arrays and location
/// offsets. Sorts both edge arrays in place for pruning.
+1 -15
View File
@@ -46,7 +46,6 @@ namespace OpenNest.Engine.BestFit
> _derived = new();
public static Func<Drawing, double, IPairEvaluator> CreateEvaluator { get; set; }
public static Func<ISlideComputer> CreateSlideComputer { get; set; }
/// <summary>
/// Candidate sets (one per geometry and spacing) the process-wide pool keeps; the least
@@ -330,7 +329,6 @@ namespace OpenNest.Engine.BestFit
var canonical = CanonicalFrame.AsCanonicalCopy(drawing);
IPairEvaluator evaluator = null;
ISlideComputer slideComputer = null;
try
{
@@ -345,25 +343,13 @@ namespace OpenNest.Engine.BestFit
}
}
if (CreateSlideComputer != null)
{
try
{
slideComputer = CreateSlideComputer();
}
catch
{ /* fall back to CPU slide computation */
}
}
// The plate size only feeds the filter, which FindCandidates skips.
var finder = new BestFitFinder(0, 0, evaluator, slideComputer);
var finder = new BestFitFinder(0, 0, evaluator);
return finder.FindCandidates(canonical, spacing, StepSize);
}
finally
{
(evaluator as IDisposable)?.Dispose();
// Slide computer is managed by the factory as a singleton — don't dispose here
}
}
+2 -6
View File
@@ -18,15 +18,11 @@ namespace OpenNest.Engine.BestFit
public BestFitFinder(
double maxPlateWidth,
double maxPlateHeight,
IPairEvaluator evaluator = null,
ISlideComputer slideComputer = null
IPairEvaluator evaluator = null
)
{
_evaluator = evaluator ?? new PairEvaluator();
_distanceComputer =
slideComputer != null
? (IDistanceComputer)new GpuDistanceComputer(slideComputer)
: new CpuDistanceComputer();
_distanceComputer = new CpuDistanceComputer();
_filter = CreateFilter(maxPlateWidth, maxPlateHeight);
}
@@ -1,80 +0,0 @@
using System.Collections.Generic;
using OpenNest.Geometry;
namespace OpenNest.Engine.BestFit
{
public class GpuDistanceComputer : IDistanceComputer
{
private readonly ISlideComputer _slideComputer;
public GpuDistanceComputer(ISlideComputer slideComputer)
{
_slideComputer = slideComputer;
}
public double[] ComputeDistances(
List<Line> stationaryLines,
List<Line> movingTemplateLines,
SlideOffset[] offsets
)
{
// ISlideComputer is axis-only; do not quantize an arbitrary direction into
// an unrelated cardinal push. Native curves already use this same fallback.
foreach (var offset in offsets)
{
if (!((offset.DirX == 0 && System.Math.Abs(offset.DirY) == 1)
|| (offset.DirY == 0 && System.Math.Abs(offset.DirX) == 1)))
return new CpuDistanceComputer().ComputeDistances(stationaryLines, movingTemplateLines, offsets);
}
var stationarySegments = SpatialQuery.FlattenLines(stationaryLines);
var movingSegments = SpatialQuery.FlattenLines(movingTemplateLines);
var count = offsets.Length;
var flatOffsets = new double[count * 2];
var directions = new int[count];
for (var i = 0; i < count; i++)
{
flatOffsets[i * 2] = offsets[i].Dx;
flatOffsets[i * 2 + 1] = offsets[i].Dy;
directions[i] = DirectionVectorToInt(offsets[i].DirX, offsets[i].DirY);
}
return _slideComputer.ComputeBatchMultiDir(
stationarySegments,
stationaryLines.Count,
movingSegments,
movingTemplateLines.Count,
flatOffsets,
count,
directions
);
}
public double[] ComputeDistances(
List<Entity> stationaryEntities,
List<Entity> movingEntities,
SlideOffset[] offsets
)
{
// GPU path doesn't support native entities yet — fall back to CPU.
var cpu = new CpuDistanceComputer();
return cpu.ComputeDistances(stationaryEntities, movingEntities, offsets);
}
/// <summary>
/// Maps a unit direction vector to a PushDirection int for the GPU interface.
/// Up=0, Down=1, Left=2, Right=3.
/// </summary>
private static int DirectionVectorToInt(double dirX, double dirY)
{
if (dirX < -0.5)
return (int)PushDirection.Left;
if (dirX > 0.5)
return (int)PushDirection.Right;
if (dirY < -0.5)
return (int)PushDirection.Down;
return (int)PushDirection.Up;
}
}
}
-47
View File
@@ -1,47 +0,0 @@
using System;
namespace OpenNest.Engine.BestFit
{
/// <summary>
/// Batches directional-distance computations for multiple offset positions.
/// GPU implementations can process all offsets in a single kernel launch.
/// </summary>
public interface ISlideComputer : IDisposable
{
/// <summary>
/// Computes the first blocking contact distance for each offset position.
/// Separating/tangential contacts on closed boundaries do not block.
/// </summary>
/// <param name="stationarySegments">Flat array [x1,y1,x2,y2, ...] for stationary edges.</param>
/// <param name="stationaryCount">Number of line segments in stationarySegments.</param>
/// <param name="movingTemplateSegments">Flat array [x1,y1,x2,y2, ...] for moving edges at origin.</param>
/// <param name="movingCount">Number of line segments in movingTemplateSegments.</param>
/// <param name="offsets">Flat array [dx,dy, dx,dy, ...] of translation offsets.</param>
/// <param name="offsetCount">Number of offset positions.</param>
/// <param name="direction">Push direction.</param>
/// <returns>Array of minimum distances, one per offset position.</returns>
double[] ComputeBatch(
double[] stationarySegments,
int stationaryCount,
double[] movingTemplateSegments,
int movingCount,
double[] offsets,
int offsetCount,
PushDirection direction
);
/// <summary>
/// Computes first blocking contact distances with per-offset directions.
/// Uploads segment data once for all offsets, reducing GPU round-trips.
/// </summary>
double[] ComputeBatchMultiDir(
double[] stationarySegments,
int stationaryCount,
double[] movingTemplateSegments,
int movingCount,
double[] offsets,
int offsetCount,
int[] directions
);
}
}
-109
View File
@@ -1,109 +0,0 @@
using System;
using System.Diagnostics;
using ILGPU;
using ILGPU.Runtime;
using OpenNest.Engine.BestFit;
namespace OpenNest.Gpu
{
public static class GpuEvaluatorFactory
{
private static bool _probed;
private static bool _gpuAvailable;
private static string _deviceName;
private static GpuSlideComputer _slideComputer;
private static readonly object _slideLock = new object();
public static bool GpuAvailable
{
get
{
if (!_probed)
Probe();
return _gpuAvailable;
}
}
public static string DeviceName
{
get
{
if (!_probed)
Probe();
return _deviceName ?? "None";
}
}
public static IPairEvaluator Create(Drawing drawing, double spacing)
{
if (!GpuAvailable)
return null;
try
{
return new GpuPairEvaluator(drawing, spacing);
}
catch (Exception ex)
{
Debug.WriteLine($"[GpuEvaluatorFactory] GPU evaluator failed: {ex.Message}");
return null;
}
}
public static ISlideComputer CreateSlideComputer()
{
if (!GpuAvailable)
return null;
lock (_slideLock)
{
if (_slideComputer != null)
return _slideComputer;
try
{
_slideComputer = new GpuSlideComputer();
return _slideComputer;
}
catch (Exception ex)
{
Debug.WriteLine(
$"[GpuEvaluatorFactory] GPU slide computer failed: {ex.Message}"
);
return null;
}
}
}
private static void Probe()
{
_probed = true;
try
{
using var context = Context.CreateDefault();
foreach (var device in context.Devices)
{
if (
device.AcceleratorType == AcceleratorType.Cuda
|| device.AcceleratorType == AcceleratorType.OpenCL
)
{
_gpuAvailable = true;
_deviceName = device.Name;
Debug.WriteLine(
$"[GpuEvaluatorFactory] GPU found: {device.Name} ({device.AcceleratorType})"
);
return;
}
}
Debug.WriteLine("[GpuEvaluatorFactory] No GPU device found");
}
catch (Exception ex)
{
Debug.WriteLine($"[GpuEvaluatorFactory] GPU probe failed: {ex.Message}");
}
}
}
}
-331
View File
@@ -1,331 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ILGPU;
using ILGPU.Runtime;
using OpenNest.Converters;
using OpenNest.Engine.BestFit;
using OpenNest.Geometry;
namespace OpenNest.Gpu
{
public class GpuPairEvaluator : IPairEvaluator, IDisposable
{
private readonly Context _context;
private readonly Accelerator _accelerator;
private readonly Drawing _drawing;
private readonly double _spacing;
private readonly double _cellSize;
public GpuPairEvaluator(
Drawing drawing,
double spacing,
double cellSize = PartBitmap.DefaultCellSize
)
{
_drawing = drawing;
_spacing = spacing;
_cellSize = cellSize;
_context = Context.CreateDefault();
_accelerator = _context
.GetPreferredDevice(preferCPU: false)
.CreateAccelerator(_context);
}
public List<BestFitResult> EvaluateAll(List<PairCandidate> candidates)
{
if (candidates.Count == 0)
return new List<BestFitResult>();
// Rasterize A from a Part created at the origin — guarantees the
// bitmap coordinate system exactly matches Part.CreateAtOrigin.
var partA = Part.CreateAtOrigin(_drawing);
var bitmapA = PartBitmap.FromPart(partA, _cellSize);
if (bitmapA.Width == 0 || bitmapA.Height == 0)
return candidates.Select(c => MakeEmptyResult(c)).ToList();
// Pre-compute A vertices once for all rotation groups
var verticesA = GetPartVertices(partA);
// Group candidates by Part2Rotation so we rasterize B once per unique rotation
var groups = candidates
.Select((c, i) => new { Candidate = c, OriginalIndex = i })
.GroupBy(x => System.Math.Round(x.Candidate.Part2Rotation, 6));
var allResults = new BestFitResult[candidates.Count];
var trueArea = _drawing.Area * 2;
foreach (var group in groups)
{
var rotation = group.Key;
var groupItems = group.ToList();
// Rasterize B at this rotation from a Part created at origin
var partB = Part.CreateAtOrigin(_drawing, rotation);
var bitmapB = PartBitmap.FromPart(partB, _cellSize);
if (bitmapB.Width == 0 || bitmapB.Height == 0)
{
foreach (var item in groupItems)
allResults[item.OriginalIndex] = MakeEmptyResult(item.Candidate);
continue;
}
// Pre-compute B vertices at origin for this rotation group
var verticesB = GetPartVertices(partB);
var locationB = partB.Location;
// Use the max dimensions so both bitmaps fit on the same grid
var gridWidth = System.Math.Max(bitmapA.Width, bitmapB.Width);
var gridHeight = System.Math.Max(bitmapA.Height, bitmapB.Height);
var paddedA = PadBitmap(bitmapA, gridWidth, gridHeight);
var paddedB = PadBitmap(bitmapB, gridWidth, gridHeight);
// The CPU evaluator replaces partB.Location with Part2Offset,
// so the world-space shift from B's bitmap position is
// (Part2Offset - partB.Location). We convert that shift to
// pixel coordinates, adjusting for the bitmap origin difference.
var candidateCount = groupItems.Count;
var offsets = new int[candidateCount * 2];
for (var i = 0; i < candidateCount; i++)
{
var c = groupItems[i].Candidate;
var shiftX = c.Part2Offset.X - locationB.X;
var shiftY = c.Part2Offset.Y - locationB.Y;
offsets[i * 2 + 0] = (int)
System.Math.Round((shiftX + bitmapB.OriginX - bitmapA.OriginX) / _cellSize);
offsets[i * 2 + 1] = (int)
System.Math.Round((shiftY + bitmapB.OriginY - bitmapA.OriginY) / _cellSize);
}
var resultScores = new int[candidateCount];
using var gpuPaddedA = _accelerator.Allocate1D(paddedA);
using var gpuPaddedB = _accelerator.Allocate1D(paddedB);
using var gpuOffsets = _accelerator.Allocate1D(offsets);
using var gpuResults = _accelerator.Allocate1D(resultScores);
var kernel = _accelerator.LoadAutoGroupedStreamKernel<
Index1D,
ArrayView1D<int, Stride1D.Dense>,
ArrayView1D<int, Stride1D.Dense>,
ArrayView1D<int, Stride1D.Dense>,
ArrayView1D<int, Stride1D.Dense>,
int,
int
>(OverlapKernel);
kernel(
candidateCount,
gpuPaddedA.View,
gpuPaddedB.View,
gpuOffsets.View,
gpuResults.View,
gridWidth,
gridHeight
);
_accelerator.Synchronize();
gpuResults.CopyToCPU(resultScores);
// Process results in parallel — pre-computed vertices avoid
// per-candidate Part creation, and Parallel.For matches the
// CPU evaluator's Parallel.ForEach concurrency.
Parallel.For(
0,
candidateCount,
i =>
{
var item = groupItems[i];
var hasOverlap = resultScores[i] > 0;
if (hasOverlap)
{
allResults[item.OriginalIndex] = new BestFitResult
{
Candidate = item.Candidate,
RotatedArea = 0,
BoundingWidth = 0,
BoundingHeight = 0,
OptimalRotation = 0,
TrueArea = trueArea,
Keep = false,
Reason = "Overlap detected",
};
}
else
{
allResults[item.OriginalIndex] = ComputeBoundingResult(
item.Candidate,
trueArea,
verticesA,
verticesB,
locationB
);
}
}
);
}
return allResults.ToList();
}
/// <summary>
/// Overlap kernel using integer cell offsets pre-rounded on the CPU.
/// Shares one A and one B bitmap across all candidates — only the
/// integer offset varies per candidate.
/// </summary>
private static void OverlapKernel(
Index1D index,
ArrayView1D<int, Stride1D.Dense> partBitmapA,
ArrayView1D<int, Stride1D.Dense> partBitmapB,
ArrayView1D<int, Stride1D.Dense> candidateOffsets,
ArrayView1D<int, Stride1D.Dense> results,
int gridWidth,
int gridHeight
)
{
var offsetX = candidateOffsets[index * 2];
var offsetY = candidateOffsets[index * 2 + 1];
var overlapCount = 0;
for (var y = 0; y < gridHeight; y++)
{
for (var x = 0; x < gridWidth; x++)
{
var cellA = partBitmapA[y * gridWidth + x];
if (cellA != 1)
continue;
var bx = x - offsetX;
var by = y - offsetY;
if (bx >= 0 && bx < gridWidth && by >= 0 && by < gridHeight)
{
if (partBitmapB[by * gridWidth + bx] == 1)
overlapCount++;
}
}
}
results[index] = overlapCount;
}
private static int[] PadBitmap(PartBitmap bitmap, int targetWidth, int targetHeight)
{
if (bitmap.Width == targetWidth && bitmap.Height == targetHeight)
return bitmap.Cells;
var padded = new int[targetWidth * targetHeight];
for (var y = 0; y < bitmap.Height; y++)
{
for (var x = 0; x < bitmap.Width; x++)
{
padded[y * targetWidth + x] = bitmap.Cells[y * bitmap.Width + x];
}
}
return padded;
}
private const double ChordTolerance = 0.01;
private static BestFitResult ComputeBoundingResult(
PairCandidate candidate,
double trueArea,
List<Vector> verticesA,
List<Vector> verticesB,
Vector locationB
)
{
var shift = candidate.Part2Offset - locationB;
var allPoints = new List<Vector>(verticesA.Count + verticesB.Count);
allPoints.AddRange(verticesA);
foreach (var v in verticesB)
allPoints.Add(v + shift);
double bestArea,
bestWidth,
bestHeight,
bestRotation;
if (allPoints.Count >= 3)
{
var hull = ConvexHull.Compute(allPoints);
var result = RotatingCalipers.MinimumBoundingRectangle(hull);
bestArea = result.Area;
bestWidth = result.Width;
bestHeight = result.Height;
bestRotation = result.Angle;
}
else
{
bestArea = 0;
bestWidth = 0;
bestHeight = 0;
bestRotation = 0;
}
return new BestFitResult
{
Candidate = candidate,
RotatedArea = bestArea,
BoundingWidth = bestWidth,
BoundingHeight = bestHeight,
OptimalRotation = bestRotation,
TrueArea = trueArea,
Keep = true,
Reason = "Valid",
};
}
private static List<Vector> GetPartVertices(Part part)
{
var entities = ConvertProgram
.ToGeometry(part.Program)
.Where(e => SpecialLayers.IsMaterial(e.Layer));
var shapes = ShapeBuilder.GetShapes(entities);
var points = new List<Vector>();
foreach (var shape in shapes)
{
var polygon = shape.ToPolygonWithTolerance(ChordTolerance);
polygon.Offset(part.Location);
foreach (var vertex in polygon.Vertices)
points.Add(vertex);
}
return points;
}
private static BestFitResult MakeEmptyResult(PairCandidate candidate)
{
return new BestFitResult
{
Candidate = candidate,
RotatedArea = 0,
BoundingWidth = 0,
BoundingHeight = 0,
OptimalRotation = 0,
TrueArea = 0,
Keep = false,
Reason = "No geometry",
};
}
public void Dispose()
{
_accelerator?.Dispose();
_context?.Dispose();
}
}
}
-646
View File
@@ -1,646 +0,0 @@
#nullable enable
using System;
using System.Collections.Generic;
using ILGPU;
using ILGPU.Algorithms;
using ILGPU.Runtime;
using OpenNest.Engine.BestFit;
using OpenNest.Geometry;
using OpenNest.Math;
namespace OpenNest.Gpu
{
public class GpuSlideComputer : ISlideComputer
{
private readonly Context _context;
private readonly Accelerator _accelerator;
private readonly object _lock = new object();
// ── Kernels ──────────────────────────────────────────────────
private readonly Action<
Index1D,
ArrayView1D<double, Stride1D.Dense>, // stationaryPrep
ArrayView1D<double, Stride1D.Dense>, // movingPrep
ArrayView1D<double, Stride1D.Dense>, // offsets
ArrayView1D<ContactWitness, Stride1D.Dense>, // results
int,
int,
int
> _kernel;
private readonly Action<
Index1D,
ArrayView1D<double, Stride1D.Dense>, // stationaryPrep
ArrayView1D<double, Stride1D.Dense>, // movingPrep
ArrayView1D<double, Stride1D.Dense>, // offsets
ArrayView1D<ContactWitness, Stride1D.Dense>, // results
ArrayView1D<int, Stride1D.Dense>, // directions
int,
int
> _kernelMultiDir;
private readonly Action<
Index1D,
ArrayView1D<double, Stride1D.Dense>, // raw
ArrayView1D<double, Stride1D.Dense>, // prepared
int
> _prepareKernel;
// ── Buffers ──────────────────────────────────────────────────
private MemoryBuffer1D<double, Stride1D.Dense>? _gpuStationaryRaw;
private MemoryBuffer1D<double, Stride1D.Dense>? _gpuStationaryPrep;
private double[]? _lastStationaryData; // Active segment snapshot used for upload and contact topology
private MemoryBuffer1D<double, Stride1D.Dense>? _gpuMovingRaw;
private MemoryBuffer1D<double, Stride1D.Dense>? _gpuMovingPrep;
private double[]? _lastMovingData; // Active segment snapshot used for upload and contact topology
private MemoryBuffer1D<double, Stride1D.Dense>? _gpuOffsets;
private MemoryBuffer1D<ContactWitness, Stride1D.Dense>? _gpuResults;
private MemoryBuffer1D<int, Stride1D.Dense>? _gpuDirs;
private int _offsetCapacity;
public GpuSlideComputer() : this(preferCPU: false) { }
public GpuSlideComputer(bool preferCPU)
{
_context = Context.CreateDefault();
_accelerator = _context
.GetPreferredDevice(preferCPU)
.CreateAccelerator(_context);
_kernel = _accelerator.LoadAutoGroupedStreamKernel<
Index1D,
ArrayView1D<double, Stride1D.Dense>,
ArrayView1D<double, Stride1D.Dense>,
ArrayView1D<double, Stride1D.Dense>,
ArrayView1D<ContactWitness, Stride1D.Dense>,
int,
int,
int
>(SlideKernel);
_kernelMultiDir = _accelerator.LoadAutoGroupedStreamKernel<
Index1D,
ArrayView1D<double, Stride1D.Dense>,
ArrayView1D<double, Stride1D.Dense>,
ArrayView1D<double, Stride1D.Dense>,
ArrayView1D<ContactWitness, Stride1D.Dense>,
ArrayView1D<int, Stride1D.Dense>,
int,
int
>(SlideKernelMultiDir);
_prepareKernel = _accelerator.LoadAutoGroupedStreamKernel<
Index1D,
ArrayView1D<double, Stride1D.Dense>,
ArrayView1D<double, Stride1D.Dense>,
int
>(PrepareKernel);
}
public double[] ComputeBatch(
double[] stationarySegments,
int stationaryCount,
double[] movingTemplateSegments,
int movingCount,
double[] offsets,
int offsetCount,
PushDirection direction
)
{
var results = new double[offsetCount];
if (offsetCount == 0 || stationaryCount == 0 || movingCount == 0)
{
Array.Fill(results, double.MaxValue);
return results;
}
lock (_lock)
{
EnsureStationary(stationarySegments, stationaryCount);
EnsureMoving(movingTemplateSegments, movingCount);
EnsureOffsetBuffers(offsetCount);
_gpuOffsets!.View.SubView(0, offsetCount * 2).CopyFromCPU(
_accelerator.DefaultStream, (ReadOnlySpan<double>)offsets.AsSpan(0, offsetCount * 2));
_kernel(
offsetCount,
_gpuStationaryPrep!.View,
_gpuMovingPrep!.View,
_gpuOffsets.View.SubView(0, offsetCount * 2),
_gpuResults!.View.SubView(0, offsetCount),
stationaryCount,
movingCount,
(int)direction
);
_accelerator.Synchronize();
var witnesses = new ContactWitness[offsetCount];
_gpuResults.View.SubView(0, offsetCount).CopyToCPU(witnesses);
ResolveContacts(witnesses, offsets, results, direction, null);
}
return results;
}
public double[] ComputeBatchMultiDir(
double[] stationarySegments,
int stationaryCount,
double[] movingTemplateSegments,
int movingCount,
double[] offsets,
int offsetCount,
int[] directions
)
{
var results = new double[offsetCount];
if (offsetCount == 0 || stationaryCount == 0 || movingCount == 0)
{
Array.Fill(results, double.MaxValue);
return results;
}
lock (_lock)
{
EnsureStationary(stationarySegments, stationaryCount);
EnsureMoving(movingTemplateSegments, movingCount);
EnsureOffsetBuffers(offsetCount);
_gpuOffsets!.View.SubView(0, offsetCount * 2).CopyFromCPU(
_accelerator.DefaultStream, (ReadOnlySpan<double>)offsets.AsSpan(0, offsetCount * 2));
_gpuDirs!.View.SubView(0, offsetCount).CopyFromCPU(
_accelerator.DefaultStream, (ReadOnlySpan<int>)directions.AsSpan(0, offsetCount));
_kernelMultiDir(
offsetCount,
_gpuStationaryPrep!.View,
_gpuMovingPrep!.View,
_gpuOffsets.View.SubView(0, offsetCount * 2),
_gpuResults!.View.SubView(0, offsetCount),
_gpuDirs.View.SubView(0, offsetCount),
stationaryCount,
movingCount
);
_accelerator.Synchronize();
var witnesses = new ContactWitness[offsetCount];
_gpuResults.View.SubView(0, offsetCount).CopyToCPU(witnesses);
ResolveContacts(witnesses, offsets, results, default, directions);
}
return results;
}
public void InvalidateStationary()
{
lock (_lock)
_lastStationaryData = null;
}
public void InvalidateMoving()
{
lock (_lock)
_lastMovingData = null;
}
private void ResolveContacts(
ContactWitness[] witnesses,
double[] offsets,
double[] results,
PushDirection direction,
int[]? directions
)
{
var moving = default(List<Line>);
var stationary = default(List<Line>);
var contacts = default(SlideContactClassifier);
for (var i = 0; i < witnesses.Length; i++)
{
var witness = witnesses[i];
results[i] = witness.Distance;
if (witness.Distance == double.MaxValue)
continue;
// GPU finds the nearest event. Prepare the complete boundaries only
// once per batch, and share their material-side topology at each offset.
if (contacts == null)
{
moving = ToLines(_lastMovingData!);
stationary = ToLines(_lastStationaryData!);
contacts = SlideContactClassifier.FromLines(
moving, Vector.Zero, stationary, Vector.Zero).Prepare();
}
var offset = new Vector(offsets[i * 2], offsets[i * 2 + 1]);
var push = directions == null ? direction : (PushDirection)directions[i];
var unit = SpatialQuery.DirectionToOffset(push, 1);
var placed = contacts.At(offset, Vector.Zero);
if (placed.Blocks(
new Vector(witness.MovingX, witness.MovingY),
new Vector(witness.StationaryX, witness.StationaryY), unit.X, unit.Y))
continue;
// A departing or grazing event does not discard the obstacle: replay
// all events through the shared resolver to find the next blocking one,
// including another contact tied at the same distance.
results[i] = SpatialQuery.DirectionalDistance(
moving!, offset.X, offset.Y, stationary!, push, placed);
}
}
private static List<Line> ToLines(double[] segments)
{
var lines = new List<Line>(segments.Length / 4);
for (var i = 0; i < segments.Length; i += 4)
lines.Add(new Line(segments[i], segments[i + 1], segments[i + 2], segments[i + 3]));
return lines;
}
private void EnsureStationary(double[] data, int count)
{
// Cache the active prefix by value: callers may reuse an array with a
// different segment count or mutate its coordinates between batches.
var active = data.AsSpan(0, count * 4);
if (_gpuStationaryPrep != null && _lastStationaryData != null
&& active.SequenceEqual(_lastStationaryData))
return;
_gpuStationaryRaw?.Dispose();
_gpuStationaryPrep?.Dispose();
var snapshot = active.ToArray();
_gpuStationaryRaw = _accelerator.Allocate1D(snapshot);
_gpuStationaryPrep = _accelerator.Allocate1D<double>(count * 10);
_prepareKernel(count, _gpuStationaryRaw.View, _gpuStationaryPrep.View, count);
_accelerator.Synchronize();
_lastStationaryData = snapshot;
}
private void EnsureMoving(double[] data, int count)
{
// Cache the active prefix by value: callers may reuse an array with a
// different segment count or mutate its coordinates between batches.
var active = data.AsSpan(0, count * 4);
if (_gpuMovingPrep != null && _lastMovingData != null
&& active.SequenceEqual(_lastMovingData))
return;
_gpuMovingRaw?.Dispose();
_gpuMovingPrep?.Dispose();
var snapshot = active.ToArray();
_gpuMovingRaw = _accelerator.Allocate1D(snapshot);
_gpuMovingPrep = _accelerator.Allocate1D<double>(count * 10);
_prepareKernel(count, _gpuMovingRaw.View, _gpuMovingPrep.View, count);
_accelerator.Synchronize();
_lastMovingData = snapshot;
}
private void EnsureOffsetBuffers(int offsetCount)
{
if (_offsetCapacity >= offsetCount)
return;
var newCapacity = System.Math.Max(offsetCount, _offsetCapacity * 3 / 2);
_gpuOffsets?.Dispose();
_gpuResults?.Dispose();
_gpuDirs?.Dispose();
_gpuOffsets = _accelerator.Allocate1D<double>(newCapacity * 2);
_gpuResults = _accelerator.Allocate1D<ContactWitness>(newCapacity);
_gpuDirs = _accelerator.Allocate1D<int>(newCapacity);
_offsetCapacity = newCapacity;
}
// ── Preparation Kernel ───────────────────────────────────────
private static void PrepareKernel(
Index1D index,
ArrayView1D<double, Stride1D.Dense> raw,
ArrayView1D<double, Stride1D.Dense> prepared,
int count
)
{
if (index >= count)
return;
var x1 = raw[index * 4 + 0];
var y1 = raw[index * 4 + 1];
var x2 = raw[index * 4 + 2];
var y2 = raw[index * 4 + 3];
prepared[index * 10 + 0] = x1;
prepared[index * 10 + 1] = y1;
prepared[index * 10 + 2] = x2;
prepared[index * 10 + 3] = y2;
var dx = x2 - x1;
var dy = y2 - y1;
// invD is used for parameter 't'. We use a small epsilon for stability.
prepared[index * 10 + 4] = (XMath.Abs(dx) < Tolerance.Epsilon) ? 0 : 1.0 / dx;
prepared[index * 10 + 5] = (XMath.Abs(dy) < Tolerance.Epsilon) ? 0 : 1.0 / dy;
prepared[index * 10 + 6] = XMath.Min(x1, x2);
prepared[index * 10 + 7] = XMath.Max(x1, x2);
prepared[index * 10 + 8] = XMath.Min(y1, y2);
prepared[index * 10 + 9] = XMath.Max(y1, y2);
}
// ── Main Slide Kernels ───────────────────────────────────────
// Public because ILGPU's CPU backend emits kernel argument types in a separate assembly.
public struct ContactWitness
{
public double Distance;
public double MovingX;
public double MovingY;
public double StationaryX;
public double StationaryY;
}
private static void Consider(
ref ContactWitness nearest,
double distance,
double vx,
double vy,
int rayDirection,
bool vertexMoves
)
{
var snapped = distance > Tolerance.Epsilon ? distance : 0;
if (snapped >= nearest.Distance)
return;
// Use the unsnapped hit for incidence; snapping a tiny gap to zero must
// not move the witness off the other boundary.
var dirX = rayDirection == 2 ? -1 : rayDirection == 3 ? 1 : 0;
var dirY = rayDirection == 0 ? 1 : rayDirection == 1 ? -1 : 0;
var hx = vx + distance * dirX;
var hy = vy + distance * dirY;
nearest.Distance = snapped;
nearest.MovingX = vertexMoves ? vx : hx;
nearest.MovingY = vertexMoves ? vy : hy;
nearest.StationaryX = vertexMoves ? hx : vx;
nearest.StationaryY = vertexMoves ? hy : vy;
}
private static void SlideKernel(
Index1D index,
ArrayView1D<double, Stride1D.Dense> stationaryPrep,
ArrayView1D<double, Stride1D.Dense> movingPrep,
ArrayView1D<double, Stride1D.Dense> offsets,
ArrayView1D<ContactWitness, Stride1D.Dense> results,
int sCount,
int mCount,
int direction
)
{
if (index >= results.Length)
return;
var dx = offsets[index * 2];
var dy = offsets[index * 2 + 1];
results[index] = ComputeSlideLean(
stationaryPrep,
movingPrep,
dx,
dy,
sCount,
mCount,
direction
);
}
private static void SlideKernelMultiDir(
Index1D index,
ArrayView1D<double, Stride1D.Dense> stationaryPrep,
ArrayView1D<double, Stride1D.Dense> movingPrep,
ArrayView1D<double, Stride1D.Dense> offsets,
ArrayView1D<ContactWitness, Stride1D.Dense> results,
ArrayView1D<int, Stride1D.Dense> directions,
int sCount,
int mCount
)
{
if (index >= results.Length)
return;
var dx = offsets[index * 2];
var dy = offsets[index * 2 + 1];
var dir = directions[index];
results[index] = ComputeSlideLean(
stationaryPrep,
movingPrep,
dx,
dy,
sCount,
mCount,
dir
);
}
private static ContactWitness ComputeSlideLean(
ArrayView1D<double, Stride1D.Dense> sPrep,
ArrayView1D<double, Stride1D.Dense> mPrep,
double dx,
double dy,
int sCount,
int mCount,
int direction
)
{
const double eps = Tolerance.Epsilon;
var nearest = new ContactWitness { Distance = double.MaxValue };
var horizontal = direction >= 2;
var oppDir = direction ^ 1;
// ── Forward Pass: moving vertices vs stationary edges ─────
for (var i = 0; i < mCount; i++)
{
var m1x = mPrep[i * 10 + 0] + dx;
var m1y = mPrep[i * 10 + 1] + dy;
var m2x = mPrep[i * 10 + 2] + dx;
var m2y = mPrep[i * 10 + 3] + dy;
for (var j = 0; j < sCount; j++)
{
var sMin = horizontal ? sPrep[j * 10 + 8] : sPrep[j * 10 + 6];
var sMax = horizontal ? sPrep[j * 10 + 9] : sPrep[j * 10 + 7];
// Test moving vertex 1 against stationary edge j
var mv1 = horizontal ? m1y : m1x;
if (mv1 >= sMin - eps && mv1 <= sMax + eps)
{
var d = RayEdgeLean(m1x, m1y, sPrep, j, direction, eps);
Consider(ref nearest, d, m1x, m1y,
direction, vertexMoves: true);
}
// Test moving vertex 2 against stationary edge j
var mv2 = horizontal ? m2y : m2x;
if (mv2 >= sMin - eps && mv2 <= sMax + eps)
{
var d = RayEdgeLean(m2x, m2y, sPrep, j, direction, eps);
Consider(ref nearest, d, m2x, m2y,
direction, vertexMoves: true);
}
}
}
// ── Reverse Pass: stationary vertices vs moving edges ─────
for (var i = 0; i < sCount; i++)
{
var s1x = sPrep[i * 10 + 0];
var s1y = sPrep[i * 10 + 1];
var s2x = sPrep[i * 10 + 2];
var s2y = sPrep[i * 10 + 3];
for (var j = 0; j < mCount; j++)
{
var mMin = horizontal ? (mPrep[j * 10 + 8] + dy) : (mPrep[j * 10 + 6] + dx);
var mMax = horizontal ? (mPrep[j * 10 + 9] + dy) : (mPrep[j * 10 + 7] + dx);
// Test stationary vertex 1 against moving edge j
var sv1 = horizontal ? s1y : s1x;
if (sv1 >= mMin - eps && sv1 <= mMax + eps)
{
var d = RayEdgeLeanMoving(s1x, s1y, mPrep, j, dx, dy, oppDir, eps);
Consider(ref nearest, d, s1x, s1y,
oppDir, vertexMoves: false);
}
// Test stationary vertex 2 against moving edge j
var sv2 = horizontal ? s2y : s2x;
if (sv2 >= mMin - eps && sv2 <= mMax + eps)
{
var d = RayEdgeLeanMoving(s2x, s2y, mPrep, j, dx, dy, oppDir, eps);
Consider(ref nearest, d, s2x, s2y,
oppDir, vertexMoves: false);
}
}
}
return nearest;
}
private static double RayEdgeLean(
double vx,
double vy,
ArrayView1D<double, Stride1D.Dense> sPrep,
int j,
int direction,
double eps
)
{
var p1x = sPrep[j * 10 + 0];
var p1y = sPrep[j * 10 + 1];
var p2x = sPrep[j * 10 + 2];
var p2y = sPrep[j * 10 + 3];
if (direction >= 2) // Horizontal (Left=2, Right=3)
{
var invDy = sPrep[j * 10 + 5];
if (invDy == 0)
return double.MaxValue;
var t = (vy - p1y) * invDy;
if (t < -eps || t > 1.0 + eps)
return double.MaxValue;
var ix = p1x + t * (p2x - p1x);
var dist = (direction == 2) ? (vx - ix) : (ix - vx);
return dist >= -eps ? dist : double.MaxValue;
}
else // Vertical (Up=0, Down=1)
{
var invDx = sPrep[j * 10 + 4];
if (invDx == 0)
return double.MaxValue;
var t = (vx - p1x) * invDx;
if (t < -eps || t > 1.0 + eps)
return double.MaxValue;
var iy = p1y + t * (p2y - p1y);
var dist = (direction == 1) ? (vy - iy) : (iy - vy);
return dist >= -eps ? dist : double.MaxValue;
}
}
private static double RayEdgeLeanMoving(
double vx,
double vy,
ArrayView1D<double, Stride1D.Dense> mPrep,
int j,
double dx,
double dy,
int direction,
double eps
)
{
var p1x = mPrep[j * 10 + 0] + dx;
var p1y = mPrep[j * 10 + 1] + dy;
var p2x = mPrep[j * 10 + 2] + dx;
var p2y = mPrep[j * 10 + 3] + dy;
if (direction >= 2) // Horizontal
{
var invDy = mPrep[j * 10 + 5];
if (invDy == 0)
return double.MaxValue;
var t = (vy - p1y) * invDy;
if (t < -eps || t > 1.0 + eps)
return double.MaxValue;
var ix = p1x + t * (p2x - p1x);
var dist = (direction == 2) ? (vx - ix) : (ix - vx);
return dist >= -eps ? dist : double.MaxValue;
}
else // Vertical
{
var invDx = mPrep[j * 10 + 4];
if (invDx == 0)
return double.MaxValue;
var t = (vx - p1x) * invDx;
if (t < -eps || t > 1.0 + eps)
return double.MaxValue;
var iy = p1y + t * (p2y - p1y);
var dist = (direction == 1) ? (vy - iy) : (iy - vy);
return dist >= -eps ? dist : double.MaxValue;
}
}
public void Dispose()
{
_gpuStationaryRaw?.Dispose();
_gpuStationaryPrep?.Dispose();
_gpuMovingRaw?.Dispose();
_gpuMovingPrep?.Dispose();
_gpuOffsets?.Dispose();
_gpuResults?.Dispose();
_gpuDirs?.Dispose();
_accelerator?.Dispose();
_context?.Dispose();
}
}
}
-15
View File
@@ -1,15 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>OpenNest.Gpu</RootNamespace>
<AssemblyName>OpenNest.Gpu</AssemblyName>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\OpenNest.Core\OpenNest.Core.csproj" />
<ProjectReference Include="..\OpenNest.Engine\OpenNest.Engine.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ILGPU" Version="1.5.1" />
<PackageReference Include="ILGPU.Algorithms" Version="1.5.1" />
</ItemGroup>
</Project>
-294
View File
@@ -1,294 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using OpenNest.Converters;
using OpenNest.Geometry;
using OpenNest.Math;
namespace OpenNest.Gpu
{
public class PartBitmap
{
public int[] Cells { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public double CellSize { get; set; }
public double OriginX { get; set; }
public double OriginY { get; set; }
public const double DefaultCellSize = 0.05;
public static PartBitmap FromDrawing(
Drawing drawing,
double cellSize = DefaultCellSize,
double spacingDilation = 0
)
{
var polygons = GetClosedPolygons(drawing);
return Rasterize(polygons, cellSize, spacingDilation);
}
public static PartBitmap FromDrawingRotated(
Drawing drawing,
double rotation,
double cellSize = DefaultCellSize,
double spacingDilation = 0
)
{
var polygons = GetClosedPolygons(drawing);
if (!rotation.IsEqualTo(0))
{
foreach (var poly in polygons)
poly.Rotate(rotation);
}
return Rasterize(polygons, cellSize, spacingDilation);
}
/// <summary>
/// Rasterizes a Part that was created with Part.CreateAtOrigin.
/// Extracts polygons from the Part's program and offsets by Location,
/// guaranteeing the bitmap matches the exact coordinate space used
/// by the CPU PairEvaluator.
/// </summary>
public static PartBitmap FromPart(Part part, double cellSize = DefaultCellSize)
{
var entities = ConvertProgram
.ToGeometry(part.Program)
.ForNesting();
var shapes = ShapeBuilder.GetShapes(entities);
var polygons = new List<Polygon>();
foreach (var shape in shapes)
{
if (!shape.IsClosed())
continue;
var polygon = shape.ToPolygonWithTolerance(0.05);
polygon.Close();
polygon.Offset(part.Location);
polygons.Add(polygon);
}
return Rasterize(polygons, cellSize, 0);
}
private static PartBitmap Rasterize(
List<Polygon> polygons,
double cellSize,
double spacingDilation
)
{
if (polygons.Count == 0)
return new PartBitmap
{
Cells = Array.Empty<int>(),
Width = 0,
Height = 0,
CellSize = cellSize,
};
var minX = double.MaxValue;
var minY = double.MaxValue;
var maxX = double.MinValue;
var maxY = double.MinValue;
foreach (var poly in polygons)
{
poly.UpdateBounds();
var bb = poly.BoundingBox;
if (bb.Left < minX)
minX = bb.Left;
if (bb.Bottom < minY)
minY = bb.Bottom;
if (bb.Right > maxX)
maxX = bb.Right;
if (bb.Top > maxY)
maxY = bb.Top;
}
minX -= spacingDilation;
minY -= spacingDilation;
maxX += spacingDilation;
maxY += spacingDilation;
var width = (int)System.Math.Ceiling((maxX - minX) / cellSize);
var height = (int)System.Math.Ceiling((maxY - minY) / cellSize);
if (width <= 0 || height <= 0)
return new PartBitmap
{
Cells = Array.Empty<int>(),
Width = 0,
Height = 0,
CellSize = cellSize,
};
var cells = new int[width * height];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var px = minX + (x + 0.5) * cellSize;
var py = minY + (y + 0.5) * cellSize;
var pt = new Vector(px, py);
foreach (var poly in polygons)
{
if (poly.ContainsPoint(pt))
{
cells[y * width + x] = 1;
break;
}
}
}
}
var dilationCells = (int)System.Math.Ceiling(spacingDilation / cellSize);
if (dilationCells > 0)
Dilate(cells, width, height, dilationCells);
return new PartBitmap
{
Cells = cells,
Width = width,
Height = height,
CellSize = cellSize,
OriginX = minX,
OriginY = minY,
};
}
private static List<Polygon> GetClosedPolygons(Drawing drawing)
{
var entities = ConvertProgram
.ToGeometry(drawing.Program)
.ForNesting();
var shapes = ShapeBuilder.GetShapes(entities);
var polygons = new List<Polygon>();
foreach (var shape in shapes)
{
if (!shape.IsClosed())
continue;
var polygon = shape.ToPolygonWithTolerance(0.05);
polygon.Close();
polygons.Add(polygon);
}
return polygons;
}
/// <summary>
/// Blits two locally-rasterized bitmaps into a shared world-space grid.
/// B is placed at the given world-space offset. Returns two aligned int[]
/// arrays of identical dimensions with no fractional offset math.
/// </summary>
public static (int[] cellsA, int[] cellsB, int width, int height) BlitPair(
PartBitmap bitmapA,
PartBitmap bitmapB,
double offsetX,
double offsetY
)
{
var cellSize = bitmapA.CellSize;
// B's world-space origin when placed at the offset
var bWorldOriginX = bitmapB.OriginX + offsetX;
var bWorldOriginY = bitmapB.OriginY + offsetY;
// Combined world-space bounds
var combinedMinX = System.Math.Min(bitmapA.OriginX, bWorldOriginX);
var combinedMinY = System.Math.Min(bitmapA.OriginY, bWorldOriginY);
var combinedMaxX = System.Math.Max(
bitmapA.OriginX + bitmapA.Width * cellSize,
bWorldOriginX + bitmapB.Width * cellSize
);
var combinedMaxY = System.Math.Max(
bitmapA.OriginY + bitmapA.Height * cellSize,
bWorldOriginY + bitmapB.Height * cellSize
);
var sharedWidth = (int)System.Math.Ceiling((combinedMaxX - combinedMinX) / cellSize);
var sharedHeight = (int)System.Math.Ceiling((combinedMaxY - combinedMinY) / cellSize);
if (sharedWidth <= 0 || sharedHeight <= 0)
return (Array.Empty<int>(), Array.Empty<int>(), 0, 0);
var cellsA = new int[sharedWidth * sharedHeight];
var cellsB = new int[sharedWidth * sharedHeight];
// Integer cell offsets for A within the shared grid
var aOffX = (int)System.Math.Round((bitmapA.OriginX - combinedMinX) / cellSize);
var aOffY = (int)System.Math.Round((bitmapA.OriginY - combinedMinY) / cellSize);
// Integer cell offsets for B within the shared grid
var bOffX = (int)System.Math.Round((bWorldOriginX - combinedMinX) / cellSize);
var bOffY = (int)System.Math.Round((bWorldOriginY - combinedMinY) / cellSize);
// Blit A into the shared grid
for (var y = 0; y < bitmapA.Height; y++)
{
for (var x = 0; x < bitmapA.Width; x++)
{
if (bitmapA.Cells[y * bitmapA.Width + x] == 1)
{
var sx = aOffX + x;
var sy = aOffY + y;
if (sx >= 0 && sx < sharedWidth && sy >= 0 && sy < sharedHeight)
cellsA[sy * sharedWidth + sx] = 1;
}
}
}
// Blit B into the shared grid
for (var y = 0; y < bitmapB.Height; y++)
{
for (var x = 0; x < bitmapB.Width; x++)
{
if (bitmapB.Cells[y * bitmapB.Width + x] == 1)
{
var sx = bOffX + x;
var sy = bOffY + y;
if (sx >= 0 && sx < sharedWidth && sy >= 0 && sy < sharedHeight)
cellsB[sy * sharedWidth + sx] = 1;
}
}
}
return (cellsA, cellsB, sharedWidth, sharedHeight);
}
private static void Dilate(int[] cells, int width, int height, int radius)
{
var source = (int[])cells.Clone();
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
if (source[y * width + x] != 1)
continue;
for (var dy = -radius; dy <= radius; dy++)
{
for (var dx = -radius; dx <= radius; dx++)
{
var nx = x + dx;
var ny = y + dy;
if (nx >= 0 && nx < width && ny >= 0 && ny < height)
cells[ny * width + nx] = 1;
}
}
}
}
}
}
}
+2 -12
View File
@@ -196,23 +196,13 @@ public class SlideContactTests
}
[Fact]
public void GpuAdapter_ArbitraryDirectionUsesExactCpuFallback()
public void CpuLines_ArbitraryDirectionIsExact()
{
using var axesOnly = new RejectSlideComputer();
var distance = new GpuDistanceComputer(axesOnly).ComputeDistances(Rect(10, 10, 2, 2), Rect(0, 0, 2, 2),
var distance = new CpuDistanceComputer().ComputeDistances(Rect(10, 10, 2, 2), Rect(0, 0, 2, 2),
new[] { new SlideOffset(0, 0, 0.6, 0.8) })[0];
Assert.Equal(8 / 0.6, distance, 9);
}
private sealed class RejectSlideComputer : ISlideComputer
{
public double[] ComputeBatch(double[] s, int sc, double[] m, int mc, double[] o, int oc, PushDirection d) =>
throw new InvalidOperationException("Non-cardinal direction reached axis-only GPU");
public double[] ComputeBatchMultiDir(double[] s, int sc, double[] m, int mc, double[] o, int oc, int[] d) =>
throw new InvalidOperationException("Non-cardinal direction reached axis-only GPU");
public void Dispose() { }
}
[Fact]
public void OpenBoundaries_RemainConservative()
{
@@ -10,7 +10,6 @@
<ProjectReference Include="..\OpenNest.Core\OpenNest.Core.csproj" />
<ProjectReference Include="..\OpenNest.Engine\OpenNest.Engine.csproj" />
<ProjectReference Include="..\OpenNest.IO\OpenNest.IO.csproj" />
<ProjectReference Include="..\OpenNest.Gpu\OpenNest.Gpu.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.10" />
-12
View File
@@ -6,7 +6,6 @@ using OpenNest;
using OpenNest.Engine.BestFit;
using OpenNest.Engine.ML;
using OpenNest.Geometry;
using OpenNest.Gpu;
using OpenNest.IO;
using OpenNest.Training;
using Color = System.Drawing.Color;
@@ -51,17 +50,6 @@ if (string.IsNullOrEmpty(collectDir) || !Directory.Exists(collectDir))
return 1;
}
// Initialize GPU if available.
if (GpuEvaluatorFactory.GpuAvailable)
{
BestFitCache.CreateSlideComputer = () => GpuEvaluatorFactory.CreateSlideComputer();
Console.WriteLine($"GPU: {GpuEvaluatorFactory.DeviceName}");
}
else
{
Console.WriteLine("GPU: not available (using CPU)");
}
return RunDataCollection(collectDir, dbPath, saveNestsDir, spacing, templateFile);
int RunDataCollection(string dir, string dbPath, string saveDir, double s, string template)
@@ -1,308 +0,0 @@
using System.Reflection;
using ILGPU.Runtime;
using OpenNest.Geometry;
using OpenNest.Gpu;
using OpenNest.Math;
using Xunit;
using Xunit.Abstractions;
namespace OpenNest.WinForms.Tests;
// The real ILGPU kernels run on its deterministic CPU accelerator, not a mock or
// CpuDistanceComputer. This also runs without GPU hardware on Windows CI.
public sealed class GpuSlideContactFixture : IDisposable
{
public GpuSlideComputer Computer { get; } = new GpuSlideComputer(preferCPU: true);
public void Dispose() => Computer.Dispose();
}
public class GpuSlideContactTests : IClassFixture<GpuSlideContactFixture>
{
private readonly GpuSlideComputer computer;
private readonly ITestOutputHelper output;
public GpuSlideContactTests(GpuSlideContactFixture fixture, ITestOutputHelper output)
{
computer = fixture.Computer;
this.output = output;
}
public static IEnumerable<object[]> Paths()
{
foreach (var multiDir in new[] { false, true })
foreach (var reverse in new[] { false, true })
for (var turns = 0; turns < 4; turns++)
yield return new object[] { multiDir, reverse, turns };
}
[Fact]
public void Kernels_ExecuteOnCpuAccelerator()
{
var accelerator = Assert.IsAssignableFrom<Accelerator>(typeof(GpuSlideComputer)
.GetField("_accelerator", BindingFlags.Instance | BindingFlags.NonPublic)!
.GetValue(computer));
output.WriteLine($"ILGPU backend: {accelerator.AcceleratorType}; device: {accelerator.Name}");
Assert.Equal(AcceleratorType.CPU, accelerator.AcceleratorType);
}
[Theory]
[MemberData(nameof(Paths))]
public void TouchingRectangles_EnterBlocksButDepartureAndTangentsDoNot(
bool multiDir, bool reverse, int turns)
{
var stationary = Rect(0, 0, 2, 2);
var moving = Rect(2, 0, 2, 2);
AssertSlide(multiDir, reverse, turns, stationary, moving, PushDirection.Left, 0);
AssertSlide(multiDir, reverse, turns, stationary, moving, PushDirection.Right, double.MaxValue);
AssertSlide(multiDir, reverse, turns, stationary, moving, PushDirection.Up, double.MaxValue);
AssertSlide(multiDir, reverse, turns, stationary, moving, PushDirection.Down, double.MaxValue);
}
[Theory]
[MemberData(nameof(Paths))]
public void SlidingContact_StopsAtLaterHookOnSameObstacle(
bool multiDir, bool reverse, int turns)
{
var stationary = Loop((0, 0), (2, 0), (2, 4), (5, 4), (5, 6), (0, 6));
AssertSlide(multiDir, reverse, turns, stationary, Rect(2, 0, 1, 1), PushDirection.Up, 3);
}
[Theory]
[MemberData(nameof(Paths))]
public void PositiveGrazingContact_StopsAtLaterFeatureOnSameObstacle(
bool multiDir, bool reverse, int turns)
{
var stationary = Loop((4, 1), (10, 1), (10, -2), (12, -2), (12, 3), (4, 3));
AssertSlide(multiDir, reverse, turns, stationary, Rect(0, 0, 1, 1), PushDirection.Right, 9);
}
[Theory]
[MemberData(nameof(Paths))]
public void PositiveGrazingContact_WithoutLaterBlockerIsUnbounded(
bool multiDir, bool reverse, int turns)
{
AssertSlide(multiDir, reverse, turns, Rect(4, 1, 2, 2), Rect(0, 0, 1, 1),
PushDirection.Right, double.MaxValue);
}
[Theory]
[MemberData(nameof(Paths))]
public void HoleContact_LeavingWallStillStopsAtOppositeWall(
bool multiDir, bool reverse, int turns)
{
var stationary = Rect(0, 0, 10, 10);
stationary.AddRange(Rect(2, 2, 6, 6)); // Hole depth must not depend on winding.
AssertSlide(multiDir, reverse, turns, stationary, Rect(2, 3, 1, 1), PushDirection.Right, 5);
AssertSlide(multiDir, reverse, turns, stationary, Rect(2, 3, 1, 1), PushDirection.Up, 4);
}
[Theory]
[MemberData(nameof(Paths))]
public void ReverseRayWitness_StationaryVertexHitsMiddleOfMovingEdge(
bool multiDir, bool reverse, int turns)
{
// No moving vertex can hit the shorter stationary rectangle.
AssertSlide(multiDir, reverse, turns, Rect(5, 2, 1, 1), Rect(0, 0, 1, 6),
PushDirection.Right, 4);
}
[Theory]
[MemberData(nameof(Paths))]
public void SnappedZeroDistance_KeepsUnsnappedWitnessOnBothBoundaries(
bool multiDir, bool reverse, int turns)
{
var gap = Tolerance.Epsilon / 2;
AssertSlide(multiDir, reverse, turns, Rect(1 + gap, 0, 1, 1), Rect(0, 0, 1, 1),
PushDirection.Right, 0);
AssertSlide(multiDir, reverse, turns, Rect(1 + gap, 2, 1, 1), Rect(0, 0, 1, 6),
PushDirection.Right, 0);
}
[Theory]
[MemberData(nameof(Paths))]
public void ToleranceNearMiss_DoesNotBecomeABlockingWitness(
bool multiDir, bool reverse, int turns)
{
AssertSlide(multiDir, reverse, turns, Rect(4, 0, 1, 1),
Rect(0, 1 + Tolerance.Epsilon / 2, 1, 1), PushDirection.Right, double.MaxValue);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void NearParallelEdges_UseTheSharedAxisRayTolerance(bool multiDir)
{
var dy = Tolerance.Epsilon / 2;
AssertSlide(multiDir, false, 0,
new List<Line> { new Line(2, 0, 3, dy) },
new List<Line> { new Line(0, 0, 1, dy) }, PushDirection.Right, double.MaxValue);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TiedGrazingAndBlockingContacts_DoNotDropBlockingContact(bool multiDir)
{
var stationary = Rect(4, 1, 1, 1);
stationary.AddRange(Rect(4, -2, 1, 2.5));
var moving = Loop((1, 1), (0, 1), (0, 0), (1, 0));
AssertSlide(multiDir, false, 0, stationary, moving, PushDirection.Right, 3);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void OpenBoundaries_RemainConservative(bool multiDir)
{
AssertSlide(multiDir, false, 0,
new List<Line> { new Line(2, 0, 2, 2) },
new List<Line> { new Line(2, 0, 2, 2) }, PushDirection.Right, 0);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void EmptyGeometryAndOffsets_ReturnNoHitWithoutStaleResults(bool multiDir)
{
var rectangle = SpatialQuery.FlattenLines(Rect(0, 0, 1, 1));
var offsets = new[] { 0.0, 0.0, 2.0, 0.0 };
var directions = new[] { (int)PushDirection.Left, (int)PushDirection.Left };
Assert.Equal(new[] { 0.0, 1.0 },
Compute(multiDir, rectangle, 4, rectangle, 4, offsets, 2, directions, PushDirection.Left));
Assert.Empty(Compute(multiDir, rectangle, 4, rectangle, 4, offsets, 0, directions));
Assert.All(Compute(multiDir, Array.Empty<double>(), 0, rectangle, 4, offsets, 2, directions),
distance => Assert.Equal(double.MaxValue, distance));
Assert.All(Compute(multiDir, rectangle, 4, Array.Empty<double>(), 0, offsets, 2, directions),
distance => Assert.Equal(double.MaxValue, distance));
Assert.Equal(new[] { 0.0, 1.0 },
Compute(multiDir, rectangle, 4, rectangle, 4, offsets, 2, directions, PushDirection.Left));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ReusedOffsetBuffers_GrowShrinkAndRespectActivePrefixes(bool multiDir)
{
var stationary = Rect(0, 0, 2, 2);
var moving = Rect(0, 0, 1, 1);
var stationaryData = SpatialQuery.FlattenLines(stationary);
var movingData = SpatialQuery.FlattenLines(moving);
// Odd lengths exercise rounded-up thread groups and retained excess capacity.
foreach (var count in new[] { 1, 37, 3, 65, 2, 97, 0, 5, 129, 1 })
{
var offsets = new double[(count + 7) * 2];
var directions = new int[count + 7];
var expected = new double[count];
for (var i = 0; i < count; i++)
{
var dx = 2 + i % 4;
var dy = i % 3;
var direction = multiDir ? (PushDirection)(i % 4) : PushDirection.Left;
offsets[i * 2] = dx;
offsets[i * 2 + 1] = dy;
directions[i] = (int)direction;
expected[i] = SpatialQuery.DirectionalDistance(moving, dx, dy, stationary, direction);
}
var actual = Compute(multiDir, stationaryData, 4, movingData, 4, offsets, count,
directions, PushDirection.Left);
Assert.Equal(expected, actual);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ReusedSegmentArrays_ChangingCountsAndCoordinatesRefreshesBothCaches(bool multiDir)
{
var stationary = SpatialQuery.FlattenLines(Rect(4, 0, 1, 1).Concat(Rect(2, 0, 1, 1)).ToList());
var moving = SpatialQuery.FlattenLines(Rect(0, 0, 1, 1).Concat(Rect(2, 0, 1, 1)).ToList());
var offsets = new[] { 0.0, 0.0 };
var directions = new[] { (int)PushDirection.Right };
foreach (var counts in new[] { (4, 4, 3.0), (8, 4, 1.0), (4, 8, 1.0), (4, 4, 3.0) })
Assert.Equal(counts.Item3,
Compute(multiDir, stationary, counts.Item1, moving, counts.Item2, offsets, 1, directions)[0]);
for (var i = 0; i < stationary.Length; i += 2)
stationary[i] += 1;
Assert.Equal(4, Compute(multiDir, stationary, 4, moving, 4, offsets, 1, directions)[0]);
for (var i = 0; i < moving.Length; i += 2)
moving[i] -= 1;
Assert.Equal(5, Compute(multiDir, stationary, 4, moving, 4, offsets, 1, directions)[0]);
computer.InvalidateStationary();
computer.InvalidateMoving();
Assert.Equal(5, Compute(multiDir, stationary, 4, moving, 4, offsets, 1, directions)[0]);
}
[Fact]
public void MultiDir_UsesEachOffsetAndDirectionIndependently()
{
var stationary = SpatialQuery.FlattenLines(Rect(0, 0, 2, 2));
var moving = SpatialQuery.FlattenLines(Rect(0, 0, 1, 1));
var offsets = new[] { 2.0, 0.0, 2.0, 0.0, 2.0, 0.0, 2.0, 0.0, -3.0, 0.0, 0.0, -4.0 };
var directions = new[] { PushDirection.Left, PushDirection.Right, PushDirection.Up,
PushDirection.Down, PushDirection.Right, PushDirection.Up }.Select(d => (int)d).ToArray();
Assert.Equal(new[] { 0.0, double.MaxValue, double.MaxValue, double.MaxValue, 2.0, 3.0 },
computer.ComputeBatchMultiDir(stationary, 4, moving, 4, offsets, 6, directions));
}
private void AssertSlide(bool multiDir, bool reverse, int turns, List<Line> stationary,
List<Line> moving, PushDirection direction, double expected)
{
// Exact quarter turns cover all axis signs without trigonometric rounding.
// Offset the world and template independently to expose mixed-frame witnesses.
var origin = new Vector(13, -7);
stationary = Transform(stationary, turns, new Vector(17, -23), reverse);
moving = Transform(moving, turns, new Vector(17, -23) - origin, reverse);
for (var turn = 0; turn < turns; turn++)
direction = direction switch
{
PushDirection.Right => PushDirection.Up,
PushDirection.Up => PushDirection.Left,
PushDirection.Left => PushDirection.Down,
_ => PushDirection.Right,
};
Assert.Equal(expected,
SpatialQuery.DirectionalDistance(moving, origin.X, origin.Y, stationary, direction), 9);
var actual = Compute(multiDir, SpatialQuery.FlattenLines(stationary), stationary.Count,
SpatialQuery.FlattenLines(moving), moving.Count, new[] { origin.X, origin.Y }, 1,
new[] { (int)direction }, direction);
Assert.Single(actual);
Assert.Equal(expected, actual[0], 9);
}
private double[] Compute(bool multiDir, double[] stationary, int stationaryCount,
double[] moving, int movingCount, double[] offsets, int count, int[] directions,
PushDirection direction = PushDirection.Right) =>
multiDir
? computer.ComputeBatchMultiDir(stationary, stationaryCount, moving, movingCount,
offsets, count, directions)
: computer.ComputeBatch(stationary, stationaryCount, moving, movingCount,
offsets, count, direction);
private static List<Line> Transform(List<Line> lines, int turns, Vector origin, bool reverse)
{
Vector Map(Vector point)
{
for (var i = 0; i < turns; i++)
point = new Vector(-point.Y, point.X);
return point + origin;
}
var result = lines.Select(line => new Line(Map(line.StartPoint), Map(line.EndPoint))).ToList();
if (reverse)
{
result.Reverse();
foreach (var line in result)
line.Reverse();
}
return result;
}
private static List<Line> Rect(double x, double y, double width, double height) =>
Loop((x, y), (x + width, y), (x + width, y + height), (x, y + height));
private static List<Line> Loop(params (double X, double Y)[] points) =>
points.Select((point, i) => new Line(point.X, point.Y,
points[(i + 1) % points.Length].X, points[(i + 1) % points.Length].Y)).ToList();
}
@@ -15,7 +15,6 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\OpenNest\OpenNest.csproj" />
<ProjectReference Include="..\OpenNest.Gpu\OpenNest.Gpu.csproj" />
<Content Include="Fixtures\absolute-coordinate-parts.nest" CopyToOutputDirectory="PreserveNewest" />
<Compile Include="..\OpenNest.Tests\Data\InMemoryDrawingSets.cs" Link="Fixtures\InMemoryDrawingSets.cs" />
<Compile Include="..\OpenNest.Tests\Data\InMemoryDrawingLibrary.cs" Link="Fixtures\InMemoryDrawingLibrary.cs" />
-14
View File
@@ -12,8 +12,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenNest.Core", "OpenNest.C
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenNest.Engine", "OpenNest.Engine\OpenNest.Engine.csproj", "{0083B9CC-54AD-4085-A30D-56BC6834B71A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenNest.Gpu", "OpenNest.Gpu\OpenNest.Gpu.csproj", "{1F0DD58E-9E83-4F78-A9D9-0557C0B2D96F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenNest.IO", "OpenNest.IO\OpenNest.IO.csproj", "{1EFCF5FB-7ADE-4044-B55D-60F6F75C3A8B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenNest.Mcp", "OpenNest.Mcp\OpenNest.Mcp.csproj", "{61CC6F65-8B70-408A-B49A-F4E5F34FFD01}"
@@ -106,18 +104,6 @@ Global
{0083B9CC-54AD-4085-A30D-56BC6834B71A}.Release|x64.Build.0 = Release|Any CPU
{0083B9CC-54AD-4085-A30D-56BC6834B71A}.Release|x86.ActiveCfg = Release|Any CPU
{0083B9CC-54AD-4085-A30D-56BC6834B71A}.Release|x86.Build.0 = Release|Any CPU
{1F0DD58E-9E83-4F78-A9D9-0557C0B2D96F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1F0DD58E-9E83-4F78-A9D9-0557C0B2D96F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1F0DD58E-9E83-4F78-A9D9-0557C0B2D96F}.Debug|x64.ActiveCfg = Debug|Any CPU
{1F0DD58E-9E83-4F78-A9D9-0557C0B2D96F}.Debug|x64.Build.0 = Debug|Any CPU
{1F0DD58E-9E83-4F78-A9D9-0557C0B2D96F}.Debug|x86.ActiveCfg = Debug|Any CPU
{1F0DD58E-9E83-4F78-A9D9-0557C0B2D96F}.Debug|x86.Build.0 = Debug|Any CPU
{1F0DD58E-9E83-4F78-A9D9-0557C0B2D96F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1F0DD58E-9E83-4F78-A9D9-0557C0B2D96F}.Release|Any CPU.Build.0 = Release|Any CPU
{1F0DD58E-9E83-4F78-A9D9-0557C0B2D96F}.Release|x64.ActiveCfg = Release|Any CPU
{1F0DD58E-9E83-4F78-A9D9-0557C0B2D96F}.Release|x64.Build.0 = Release|Any CPU
{1F0DD58E-9E83-4F78-A9D9-0557C0B2D96F}.Release|x86.ActiveCfg = Release|Any CPU
{1F0DD58E-9E83-4F78-A9D9-0557C0B2D96F}.Release|x86.Build.0 = Release|Any CPU
{1EFCF5FB-7ADE-4044-B55D-60F6F75C3A8B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1EFCF5FB-7ADE-4044-B55D-60F6F75C3A8B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1EFCF5FB-7ADE-4044-B55D-60F6F75C3A8B}.Debug|x64.ActiveCfg = Debug|Any CPU
-1
View File
@@ -87,7 +87,6 @@ Run `dotnet run --project OpenNest.Console -- --help` for the complete options a
| **OpenNest.IO** | DXF/DWG/SVG, `.nest`, G-code, BOM I/O; CAD import |
| **OpenNest.Console** | Headless batch nesting |
| **OpenNest.Api / .Data** | Programmatic pipeline; machine & cutting-parameter data |
| **OpenNest.Gpu** | GPU-accelerated pair evaluation (ILGPU); currently unused by the apps and engines (only the Training tool wires it in) |
| **OpenNest.Benchmark** | Head-to-head engine comparison |
| **OpenNest.Mcp** | MCP server for AI tool integration |
| **Posts/** | Post-processor plugins (Cincinnati CL / CI Fiber lasers, Gravograph IS8000) |
+1 -2
View File
@@ -16,7 +16,6 @@ Open/incomplete chains and ambiguous contacts conservatively block. Loops are re
- CPU best-fit batches prepare contact topology once and use all vertices plus curve/line interior and curve/curve tangency events. The old leading-half vertex filter cannot establish the next blocker after a skipped touch.
- A batch (`CpuDistanceComputer`, through Core's `SlideBatch`) returns for every offset exactly the distance the per-slide query returns, bit for bit; it only does less work. The two boundaries are packed, and their vertices, contact topology and band indexes built, once per batch instead of once per slide (the per-slide indexes were most of the time and nearly all of the allocation); the pair search prepares each pair once for its first slides and its settling slides (`IPreparedDistanceComputer`). For a push along an exact axis it also passes over pairs that cannot change the answer: a vertex or curve outside the other boundary's whole extent across the push, which every band test would reject, and, while the nearest contact is searched for, a pair whose gap along the push already reaches the nearest distance found, which the search would discard. Both keep margins for the tolerances and rounding of the kernels they stand in for: a ray hits a line up to `Tolerance.Epsilon` of its length past its ends, so neither test may use a line's bare extent. A zero part spacing leaves a zero-radius arc at every corner of the offset boundary, which the contact topology cannot resolve, so every contact of such a pair blocks; the batch keeps that.
- The best-fit pair search (`RotationSlideStrategy`) starts each slide from an offset on its step grid, then slides every resting position sideways, both ways, and keeps the new resting positions as extra candidates. A pair that locks in a corner (two interlocking channels) therefore closes to the part spacing on both axes instead of stopping up to a step short. This relies on leaving an existing contact being legal.
- GPU kernels retain nearest-hit reduction and return unsnapped contact witnesses. The shared CPU classifier accepts a blocking witness or replays the full query after a nonblocking witness, preserving tied/later blockers. Both batch APIs honor active buffer lengths and refresh mutated/reused segment arrays. The GPU distance adapter sends only exact cardinal directions to the axis-only slide interface; arbitrary directions and native curves use the shared CPU path.
- Shift-click while cloning parts settles the copied group toward the plate quadrant. If its starting bounds overlap any placed part's bounds, it skips the coarse bounding-box pass and uses geometry directly; otherwise each axis order starts with a coarse box pass. Each candidate then alternates geometry pushes until movement is negligible (at most 20 iterations). The coarse pass remains useful for avoiding sawtooth/rung traps when the starting boxes do not overlap. A box push also stops at an obstacle whose box is beside the path but nearer than the part spacing, so the coarse pass cannot park the copy inside a neighbor's spacing. A push ignores a part the copy starts on, so a candidate can end clear of that part yet inside its spacing: a candidate that keeps the part spacing (measured on `NativeContours`, as the spacing review measures it) always beats one that does not, and a named order that ends too close falls back to the other order. When no order keeps the spacing the copy still lands too close; this is not overlap repair.
- Ctrl-click settles the same way on bounding boxes alone (`SettlePlacement(boundingBoxesOnly: true)`): every push stops at the part spacing from obstacles' boxes, so the copy never nests into a neighbor's shape. A group whose box already overlaps an obstacle's box does not move.
@@ -42,7 +41,7 @@ dotnet test OpenNest.Engine.Tests/OpenNest.Engine.Tests.csproj
dotnet test OpenNest.IO.Tests/OpenNest.IO.Tests.csproj
```
The isolated repair tree (excluding other sessions' fill-performance and spacing-expander work) passed 130 targeted cases and the full Debug suites: main 1758 passed / 21 skipped, engine 300 passed, IO 41 passed. The main Release suite passed 1728 / 21 skipped. Skips are not counted as passes. The 142 `GpuSlideContactTests` also pass in a net8 harness linking the production GPU class and test source, using ILGPU 1.5.1's CPU accelerator (not a mocked distance solver). The Windows desktop/test project cross-build passes in Release. Neither physical GPU execution nor Windows UI interaction was runtime-verified on Linux.
The isolated repair tree (excluding other sessions' fill-performance and spacing-expander work) passed 130 targeted cases and the full Debug suites: main 1758 passed / 21 skipped, engine 300 passed, IO 41 passed. The main Release suite passed 1728 / 21 skipped. Skips are not counted as passes. The Windows desktop/test project cross-build passes in Release. Windows UI interaction was not runtime-verified on Linux.
## Remaining hardening
+1 -1
View File
@@ -31,7 +31,7 @@ Measurements use raw material outlines tessellated at 1e-6 chord tolerance and i
- Kept-pair acceptance still checks raw overlap, not requested clearance. Interactive fill/group paths can trust an invalid seed. This repair does not add a final spacing gate or repair existing user placements.
- Serialized best-fit results have no algorithm-version invalidation. Loading previously saved candidates can retain old poses. The measurements above use newly imported drawings/fresh computation, not restored caches. Reimport/recompute when evaluating this fix; existing nests and DXFs are not rewritten.
- A zero-demand `PlateFillService.Nest` probe returns no parts and is **not** evidence of a valid whole-job nest. The nonempty cases verified here are pair generation, pair fill, interactive fill, and the quantity-two shortcut.
- GPU behavior and Windows desktop execution were not verified on this Linux host.
- Windows desktop execution was not verified on this Linux host.
Next hardening should re-measure the remaining angled candidates of the U-shaped part on material-only outlines and, if any are still too close, isolate the contact with a first-contact regression; then address clearance-aware seed acceptance and cache compatibility as separate changes. Do not conflate those with the unrelated unchanged-row validation-reuse performance work.
+1 -2
View File
@@ -91,8 +91,7 @@ material), even if the dialog is later canceled. There is no check during export
`OpenNest.Diagnostics.PlateOverlapAnalyzer` in OpenNest.Core checks a group of placed
parts and returns the shared material for each overlapping pair as connected
islands. It clips with Clipper2. Existing `Part.Intersects`, `PartOverlapChecker` and
engine validators are unchanged and still use the hand-written `Collision` kernel (its
GPU port is on hold). The console's overlap check and the MCP `check_overlaps` tool list
engine validators are unchanged and still use the hand-written `Collision` kernel. The console's overlap check and the MCP `check_overlaps` tool list
overlapping pairs through `PartOverlapChecker.FindOverlappingPairs`, which skips cut-off
parts and reports a contained or stacked part even though no outlines cross.
+1 -1
View File
@@ -37,7 +37,7 @@ be placed in the hole. Nesting and layout paths read material through
`NestingMaterial.ForNesting`, which drops any closed contour with tab spans so the slug
counts as part: part outlines and collision lines (`PartGeometry`, `Part`), the cutout
router (`JobPartGeometry`, whose material area then includes the slug), fill expansion,
best-fit, `NestLayoutCheck` and the GPU bitmaps. Programs without tab spans read exactly as
best-fit and `NestLayoutCheck`. Programs without tab spans read exactly as
before. A planned program has open pieces instead of a closed hole, so it bounds no hole
either way.