Files
OpenNest/OpenNest.Gpu/GpuEvaluatorFactory.cs
AJ Isaacs 97dfe27953 feat: add ISlideComputer interface and GPU implementation
ISlideComputer abstracts batched directional-distance computation so GPU
implementations can process all slide offsets in a single kernel launch.
GpuSlideComputer uses ILGPU with prepared edge data (precomputed inverse
deltas and min/max bounds) and caches stationary/moving buffers across
calls. GpuEvaluatorFactory exposes a singleton factory method.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 20:29:43 -04:00

102 lines
2.8 KiB
C#

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}");
}
}
}
}