refactor(thermal): remove the graphics card heat map

With short steps only around the torch, the processor is faster than the
card at the quarter-inch cells full sheets use, and the card only gained
at a cell size they do not use. Drop OpenNest.Gpu, the ILGPU dependency
and the accelerator interface; the heat map runs the same on every
computer. The measured card timings stay in docs/plate-heat-map.md.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Fable 5.2 committed 2026-12-02 20:35:50 -05:00
1 parent 151a92088f
commit 85c4c8486e
21 files changed
+92 -959

No files matched your search

-1
View File
@@ -45,7 +45,6 @@ Releases: follow [the release procedure](docs/releasing.md) and `scripts/Publish
- `OpenNest.IO`: ACadSharp and SVG import/export and ZIP-based `.nest` persistence; depends on Core only (an IO.Tests guard enforces it). Best fits persist only when callers pass `BestFitCacheStore.Shared` as `NestReader`/`NestWriter.BestFitStore`. All DXF-to-Drawing conversion goes through `CadImporter`: `Import` + `BuildDrawing` for editable/reporting flows, `ImportDrawing` for headless callers. Preserve source offsets, entity IDs, suppressed entities and bends. Bend repair is opt-in, requires explicit source units and may not alter cut geometry or unrelated marks.
- `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.Gpu`: optional ILGPU accelerator for the [heat map](docs/plate-heat-map.md), referencing Core only; Core and Desktop stay free of it and everything must work without a card. Its kernels mirror the CPU heat code.
- `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.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.
@@ -1,75 +0,0 @@
using System;
namespace OpenNest.CNC.Thermal
{
/// <summary>
/// Runs the grid work of a <see cref="PlateHeatSimulation"/> on other hardware, such as a
/// graphics card. The simulation keeps the pieces, the timeline and the checkpoints; the
/// accelerator keeps the temperatures. Its results match the built-in CPU's closely but not
/// bit for bit.
/// </summary>
public interface IHeatAccelerator
{
/// <summary>The hardware, as shown to the user.</summary>
string Name { get; }
/// <summary>
/// A grid of <paramref name="columns"/> by <paramref name="rows"/> cells heated by
/// <paramref name="samples"/>, which are given in time order. Null when there is no
/// hardware, which leaves the grid on the processor; throws when the hardware cannot hold it.
/// </summary>
IHeatKernel Create(int columns, int rows, ReadOnlySpan<HeatSample> samples);
}
/// <summary>One grid on an <see cref="IHeatAccelerator"/>.</summary>
public interface IHeatKernel : IDisposable
{
/// <summary>Sets every temperature and peak to zero.</summary>
void Clear();
/// <summary>
/// Replaces every cell's piece and links. <paramref name="region"/> is -1 where material
/// fell away; <paramref name="links"/> has bit 0 for a link left, 1 right, 2 below and
/// 3 above.
/// </summary>
void SetCells(ReadOnlySpan<int> region, ReadOnlySpan<int> links);
/// <summary>
/// Changes the cells listed in <paramref name="cells"/> (each once), and drops the heat of
/// those whose region is -1.
/// </summary>
void ChangeCells(ReadOnlySpan<int> cells, ReadOnlySpan<int> region, ReadOnlySpan<int> links);
/// <summary>
/// Adds samples <paramref name="from"/> up to <paramref name="to"/>, each shared between
/// the cells around it that are in its cell's piece, as the CPU does.
/// </summary>
void AddSamples(int from, int to);
/// <summary>
/// One explicit step: each cell takes <paramref name="share"/> times its difference to
/// every linked neighbor, then keeps the given fraction of its rise. Peaks follow.
/// </summary>
/// <param name="share">Diffusion number of the step.</param>
/// <param name="keep">The fraction every cell keeps when <paramref name="cellKeep"/> is null.</param>
/// <param name="cellKeep">The fraction each cell keeps.</param>
/// <param name="keepKey">
/// Names <paramref name="cellKeep"/> so it need be copied only once; negative for an array
/// to copy every time.
/// </param>
void Step(float share, float keep, float[] cellKeep, int keepKey);
/// <summary>Copies the temperatures and peaks out, after all steps so far.</summary>
void Read(float[] temperature, float[] peak);
/// <summary>Replaces the temperatures and peaks.</summary>
void Write(float[] temperature, float[] peak);
}
/// <summary>
/// Heat from a moment of cutting: the cell under the torch, and the torch's position between
/// cell centers (<see cref="X"/> and <see cref="Y"/>, 0 to 1, from column
/// <see cref="Left"/> and row <see cref="Lower"/>).
/// </summary>
public readonly record struct HeatSample(int Cell, int Left, int Lower, float X, float Y, float Rise);
}
+9
View File
@@ -0,0 +1,9 @@
namespace OpenNest.CNC.Thermal
{
/// <summary>
/// Heat from a moment of cutting: the cell under the torch, and the torch's position between
/// cell centers (<see cref="X"/> and <see cref="Y"/>, 0 to 1, from column
/// <see cref="Left"/> and row <see cref="Lower"/>).
/// </summary>
internal readonly record struct HeatSample(int Cell, int Left, int Lower, float X, float Y, float Rise);
}
@@ -27,13 +27,10 @@ namespace OpenNest.CNC.Thermal
/// <para>
/// While the torch cuts, steps are short enough to follow it, but only the cells around the
/// torch take them; the rest of the plate takes one step as long as diffusion allows.
/// With <see cref="ThermalParameters.Accelerator"/> grids too fine for a full sheet's automatic
/// cells run on it, every cell taking the short steps, so its picture is close to the CPU's
/// (peaks within a few percent of the color scale) but not the same. Use one thread at a
/// time, and dispose to release it.
/// Use one thread at a time.
/// </para>
/// </summary>
public sealed class PlateHeatSimulation : IDisposable
public sealed class PlateHeatSimulation
{
private const int Removed = -1;
private const double ArcStepRadians = System.Math.PI / 18;
@@ -43,16 +40,10 @@ namespace OpenNest.CNC.Thermal
// Cell updates for a whole run, counting diffusion-limited steps, when the cell size is
// automatic. The first halving may take a few seconds for the longest cuts, so a full
// sheet gets quarter-inch cells for cuts of several hours. Finer cells have to be quick:
// on a full sheet their hot lines are too thin to see and stretch the color scale. The
// budgets are the same with or without an accelerator, so every computer draws the same
// picture.
// on a full sheet their hot lines are too thin to see and stretch the color scale.
private const double WorkBudget = 4_000_000_000;
private const double FinerWorkBudget = 60_000_000;
// Below this the processor is the faster: an accelerator spends longer starting each
// short step than the processor takes over the cells around the torch. A full sheet's
// quarter-inch cells (115,200) stay on the processor.
private const int AcceleratedCells = 250_000;
private const int MaxHalvings = 3;
// Explicit diffusion is stable below a quarter on a square grid; the cap keeps timing
@@ -134,9 +125,6 @@ namespace OpenNest.CNC.Thermal
private byte[] windowCells;
private readonly double maxStep;
private readonly HeatStepSchedule schedule;
private readonly IHeatKernel kernel;
// True while the accelerator is ahead of the arrays here.
private bool stale;
private bool onBoundary;
private readonly float[] leftLink;
private readonly float[] rightLink;
@@ -217,14 +205,7 @@ namespace OpenNest.CNC.Thermal
BuildDeposits(parameters.AbsorbedPower / (volumetricHeat * thickness * dx * dx));
BuildPieceEvents();
if (parameters.Accelerator != null && count >= AcceleratedCells)
{
var samples = new HeatSample[deposits.Count];
for (var i = 0; i < samples.Length; i++)
samples[i] = deposits[i].Sample;
kernel = parameters.Accelerator.Create(Columns, Rows, samples);
}
windowed = kernel == null && !parameters.WholePlateSteps;
windowed = !parameters.WholePlateSteps;
Reset();
}
@@ -248,27 +229,10 @@ namespace OpenNest.CNC.Thermal
public TimeSpan Time => TimeSpan.FromSeconds(time);
/// <summary>Temperature rise of each cell now, row by row from the bottom; zero where material fell away.</summary>
public ReadOnlySpan<float> Temperatures
{
get
{
Synchronize();
return temperature;
}
}
public ReadOnlySpan<float> Temperatures => temperature;
/// <summary>The highest rise each cell has reached so far.</summary>
public ReadOnlySpan<float> Peaks
{
get
{
Synchronize();
return peak;
}
}
/// <summary>True when the grid runs on <see cref="ThermalParameters.Accelerator"/>.</summary>
public bool IsAccelerated => kernel != null;
public ReadOnlySpan<float> Peaks => peak;
/// <summary>True when heat is also lost into the support bed (<see cref="ThermalParameters.SupportBed"/>).</summary>
public bool UsesSupportBed => contactFraction != null;
@@ -359,8 +323,6 @@ namespace OpenNest.CNC.Thermal
Array.Clear(temperature);
Array.Clear(peak);
ResetPieces();
kernel?.Clear();
stale = false;
depositCursor = 0;
time = 0;
onBoundary = true;
@@ -368,16 +330,6 @@ namespace OpenNest.CNC.Thermal
straightSteps = 0;
}
public void Dispose() => kernel?.Dispose();
private void Synchronize()
{
if (!stale)
return;
kernel.Read(temperature, peak);
stale = false;
}
/// <summary>Index of the largest value, or -1 when every value is zero or less.</summary>
public static int IndexOfMax(ReadOnlySpan<float> values)
{
@@ -600,15 +552,8 @@ namespace OpenNest.CNC.Thermal
var from = depositCursor;
while (depositCursor < deposits.Count && deposits[depositCursor].Time <= end)
depositCursor++;
if (kernel == null)
{
for (var i = from; i < depositCursor; i++)
Add(deposits[i].Sample, temperature);
}
else if (depositCursor > from)
{
kernel.AddSamples(from, depositCursor);
}
for (var i = from; i < depositCursor; i++)
Add(deposits[i].Sample, temperature);
while (eventCursor < events.Count && events[eventCursor].Time <= end)
Apply(events[eventCursor]);
@@ -617,15 +562,7 @@ namespace OpenNest.CNC.Thermal
var cellKeep = contactFraction == null ? null
: split > 0 ? SplitKeep(split)
: PartialStepKeep(seconds);
if (kernel == null)
{
Diffuse(share, keep, cellKeep);
}
else
{
kernel.Step(share, keep, cellKeep, split > 0 ? split : -1);
stale = true;
}
Diffuse(share, keep, cellKeep);
time = end;
}
@@ -886,50 +823,8 @@ namespace OpenNest.CNC.Thermal
ApplyToPieces(piece);
foreach (var cell in piece.Cells)
LinkAround(cell);
if (kernel != null)
SendChanged(piece.Cells);
}
private void SendChanged(int[] changed)
{
var around = new HashSet<int>();
foreach (var cell in changed)
{
around.Add(cell);
if (cell % Columns > 0)
around.Add(cell - 1);
if (cell % Columns < Columns - 1)
around.Add(cell + 1);
if (cell >= Columns)
around.Add(cell - Columns);
if (cell + Columns < region.Length)
around.Add(cell + Columns);
}
var cells = new int[around.Count];
around.CopyTo(cells);
var regions = new int[cells.Length];
var links = new int[cells.Length];
for (var i = 0; i < cells.Length; i++)
{
regions[i] = region[cells[i]];
links[i] = LinkBits(cells[i]);
}
kernel.ChangeCells(cells, regions, links);
}
private void SendAll()
{
if (kernel == null)
return;
var links = new int[region.Length];
for (var i = 0; i < links.Length; i++)
links[i] = LinkBits(i);
kernel.SetCells(region, links);
}
private int LinkBits(int i) => (leftLink[i] != 0 ? 1 : 0) | (rightLink[i] != 0 ? 2 : 0)
| (belowLink[i] != 0 ? 4 : 0) | (aboveLink[i] != 0 ? 8 : 0);
private void ApplyToPieces(PieceEvent piece)
{
@@ -965,7 +860,6 @@ namespace OpenNest.CNC.Thermal
eventCursor = 0;
nextRegion = 0;
LinkAll();
SendAll();
}
private void LinkAll()
@@ -1010,7 +904,6 @@ namespace OpenNest.CNC.Thermal
var last = checkpoints.Count == 0 ? 0 : checkpoints[^1].Number;
if (number <= last || checkpoints.Count >= maxCheckpoints)
return;
Synchronize();
checkpoints.Add(new Checkpoint(time, straightSteps, number, depositCursor, eventCursor,
(float[])temperature.Clone(), (float[])peak.Clone()));
}
@@ -1039,13 +932,10 @@ namespace OpenNest.CNC.Thermal
while (eventCursor < checkpoint.EventCursor)
ApplyToPieces(events[eventCursor]);
LinkAll();
SendAll();
}
checkpoint.Temperature.CopyTo(temperature, 0);
checkpoint.Peak.CopyTo(peak, 0);
kernel?.Write(temperature, peak);
stale = false;
depositCursor = checkpoint.DepositCursor;
time = checkpoint.Time;
onBoundary = true;
@@ -36,7 +36,7 @@ namespace OpenNest.CNC.Thermal
/// <summary>
/// Grid cell edge in <see cref="Units"/>. Zero picks one for the plate: 0.5 in (12 mm),
/// halved down to 1/16 in (1.5 mm) while the whole run stays quick to replay, so small
/// plates and short cuts get finer cells. An <see cref="Accelerator"/> does not change it.
/// plates and short cuts get finer cells.
/// </summary>
public double CellSize { get; init; }
@@ -64,14 +64,8 @@ namespace OpenNest.CNC.Thermal
public double GridContactSize { get; init; }
/// <summary>
/// Hardware to run large grids on, which also allows finer automatic cells; null runs on
/// the processor.
/// </summary>
public IHeatAccelerator Accelerator { get; init; }
/// <summary>
/// Takes the short steps of cutting over the whole plate instead of only around the torch,
/// as an <see cref="Accelerator"/> does. Slower; for comparing the two.
/// Takes the short steps of cutting over the whole plate instead of only around the torch.
/// Slower; for comparing the two.
/// </summary>
internal bool WholePlateSteps { get; init; }
-1
View File
@@ -7,7 +7,6 @@
<ItemGroup>
<InternalsVisibleTo Include="OpenNest.Tests" />
<InternalsVisibleTo Include="OpenNest.Engine" />
<InternalsVisibleTo Include="OpenNest.Gpu" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Clipper2" Version="2.0.0" />
@@ -7,49 +7,31 @@ namespace OpenNest.Desktop.Tests.Interaction;
public class HeatEstimateTests
{
private sealed class BrokenAccelerator : IHeatAccelerator
{
public int Asked { get; private set; }
public string Name => "broken";
public IHeatKernel Create(int columns, int rows, ReadOnlySpan<HeatSample> samples)
{
Asked++;
throw new InvalidOperationException("out of memory");
}
}
private static (Plate Plate, CutSimulation Simulation) Job(double x = 5)
{
var program = new OpenNest.CNC.Program();
program.Codes.Add(new RapidMove(0, 0));
program.Codes.Add(new LinearMove(20, 0));
var plate = new Plate(130, 130);
var plate = new Plate(80, 80);
plate.Parts.Add(new Part(new Drawing("part", program), new Vector(x, 5)));
return (plate, CutSimulation.Build(plate,
new CutParameters { Feedrate = 100, RapidTravelRate = 600, Units = Units.Inches }));
}
// 0.25 in cells on 130 in square: large enough to be accelerated.
private static ThermalParameters Parameters(IHeatAccelerator? accelerator) => new()
private static readonly ThermalParameters Parameters = new()
{
Thickness = 0.25,
Units = Units.Inches,
CellSize = 0.25,
Accelerator = accelerator,
};
[Fact]
public void AFailingAcceleratorFallsBackToTheProcessor()
public void AnEstimateIsRunForItsScaleAndLeftAtTheStart()
{
var (plate, simulation) = Job();
var broken = new BrokenAccelerator();
using var estimate = HeatEstimate.Run(plate, simulation, Parameters!, broken);
var estimate = HeatEstimate.Run(plate, simulation, Parameters);
Assert.Equal(1, broken.Asked);
Assert.Null(estimate.Device);
Assert.False(estimate.Heat.IsAccelerated);
Assert.True(estimate.Scale > 1);
Assert.Equal(TimeSpan.Zero, estimate.Heat.Time);
}
@@ -62,7 +44,7 @@ public class HeatEstimateTests
cancel.Cancel();
Assert.Throws<OperationCanceledException>(
() => HeatEstimate.Run(plate, simulation, Parameters!, null!, cancel.Token));
() => HeatEstimate.Run(plate, simulation, Parameters, cancel.Token));
}
[Fact]
+10 -47
View File
@@ -11,13 +11,12 @@ namespace OpenNest.Desktop.Interaction;
/// A heat model run over its whole cut, ready to play: what the cut simulator does off the UI
/// thread before it shows the heat layer.
/// </summary>
public sealed class HeatEstimate : IDisposable
public sealed class HeatEstimate
{
private HeatEstimate(PlateHeatSimulation heat, float scale, string device)
private HeatEstimate(PlateHeatSimulation heat, float scale)
{
Heat = heat;
Scale = scale;
Device = device;
}
/// <summary>The model, back at the start.</summary>
@@ -29,30 +28,16 @@ public sealed class HeatEstimate : IDisposable
/// </summary>
public float Scale { get; }
/// <summary>The graphics card the model runs on; null on the processor.</summary>
public string Device { get; }
/// <summary>
/// Builds and runs the model, on <paramref name="accelerator"/> when there is one and the
/// grid is large enough to gain from it, and on the processor when that fails.
/// </summary>
/// <param name="parameters">The model's inputs for the given accelerator, or none.</param>
public static HeatEstimate Run(Plate plate, CutSimulation simulation,
Func<IHeatAccelerator, ThermalParameters> parameters, IHeatAccelerator accelerator,
/// <summary>Builds and runs the model.</summary>
public static HeatEstimate Run(Plate plate, CutSimulation simulation, ThermalParameters parameters,
CancellationToken cancellationToken = default)
{
if (accelerator != null)
{
try
{
return Run(plate, simulation, parameters(accelerator), accelerator, cancellationToken);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// Out of card memory or a driver fault: the processor still can.
}
}
return Run(plate, simulation, parameters(null), null, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
var heat = new PlateHeatSimulation(plate, simulation, parameters);
heat.RunToEnd(cancellationToken: cancellationToken);
var scale = ColorScale(heat);
heat.Reset();
return new HeatEstimate(heat, scale);
}
/// <summary>True when both timelines cut and travel the same, at the same times.</summary>
@@ -60,31 +45,9 @@ public sealed class HeatEstimate : IDisposable
a != null && b != null && a.Steps.Count == b.Steps.Count
&& a.Steps.Zip(b.Steps).All(pair => Move(pair.First).Equals(Move(pair.Second)));
public void Dispose() => Heat.Dispose();
private static object Move(CutSimulationStep s) =>
(s.Kind, s.Start, s.End, s.IsArc, s.Center, s.Sweep, s.StartTime, s.Duration, (s.Layer, s.IsHole, s.ContourIndex));
private static HeatEstimate Run(Plate plate, CutSimulation simulation, ThermalParameters parameters,
IHeatAccelerator accelerator, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var heat = new PlateHeatSimulation(plate, simulation, parameters);
try
{
heat.RunToEnd(cancellationToken: cancellationToken);
var scale = ColorScale(heat);
heat.Reset();
// Asked only of an accelerator that ran, so one started on demand stays unstarted.
return new HeatEstimate(heat, scale, heat.IsAccelerated ? accelerator.Name : null);
}
catch
{
heat.Dispose();
throw;
}
}
private static float ColorScale(PlateHeatSimulation heat)
{
var all = heat.Peaks;
-98
View File
@@ -1,98 +0,0 @@
using System;
using ILGPU;
using ILGPU.Runtime;
using ILGPU.Runtime.CPU;
using ILGPU.Runtime.Cuda;
using ILGPU.Runtime.OpenCL;
using OpenNest.CNC.Thermal;
namespace OpenNest.Gpu;
/// <summary>
/// Runs <see cref="PlateHeatSimulation"/> grids on a graphics card through ILGPU: CUDA on
/// NVIDIA cards, otherwise OpenCL where the driver offers what ILGPU needs. One instance serves
/// every simulation of the process.
/// </summary>
public sealed class GpuHeatAccelerator : IHeatAccelerator, IDisposable
{
private static readonly Lazy<GpuHeatAccelerator> Shared = new(Create);
private readonly Context context;
private GpuHeatAccelerator(Context context, Accelerator accelerator)
{
this.context = context;
Accelerator = accelerator;
Kernels = new HeatKernels(accelerator);
}
/// <summary>
/// This computer's graphics card, or null when there is none ILGPU can use. The first call
/// takes a few tenths of a second, so make it off the UI thread.
/// </summary>
public static GpuHeatAccelerator Default => Shared.Value;
/// <summary>
/// <see cref="Default"/>, started by the first grid that asks for it, so a simulation whose
/// grids all stay on the processor never waits for the card.
/// </summary>
public static IHeatAccelerator OnDemand { get; } = new Deferred();
public string Name => Accelerator.Name;
internal Accelerator Accelerator { get; }
internal HeatKernels Kernels { get; }
// The device and its stream take one caller at a time.
internal object Gate { get; } = new();
public IHeatKernel Create(int columns, int rows, ReadOnlySpan<HeatSample> samples)
{
lock (Gate)
{
Accelerator.Bind();
return new GpuHeatKernel(this, columns, rows, samples);
}
}
/// <summary>ILGPU's emulation on the processor, so tests run the kernels without a card.</summary>
internal static GpuHeatAccelerator Emulated()
{
var context = Context.Create(builder => builder.CPU());
return new GpuHeatAccelerator(context, context.CreateCPUAccelerator(0));
}
public void Dispose()
{
Accelerator.Dispose();
context.Dispose();
}
private sealed class Deferred : IHeatAccelerator
{
public string Name => Default?.Name;
public IHeatKernel Create(int columns, int rows, ReadOnlySpan<HeatSample> samples) =>
Default?.Create(columns, rows, samples);
}
private static GpuHeatAccelerator Create()
{
Context context = null;
try
{
context = Context.Create(builder => builder.Cuda().OpenCL());
Accelerator accelerator = context.GetCudaDevices().Count > 0 ? context.CreateCudaAccelerator(0)
: context.GetCLDevices().Count > 0 ? context.CreateCLAccelerator(0)
: null;
if (accelerator != null)
return new GpuHeatAccelerator(context, accelerator);
}
catch (Exception)
{
// A missing or broken driver only means there is no card to use.
}
context?.Dispose();
return null;
}
}
-183
View File
@@ -1,183 +0,0 @@
using System;
using System.Collections.Generic;
using ILGPU;
using ILGPU.Runtime;
using OpenNest.CNC.Thermal;
namespace OpenNest.Gpu;
/// <summary>One simulation's grid in the card's memory.</summary>
internal sealed class GpuHeatKernel : IHeatKernel
{
// The driver queues steps; wait now and then so the queue stays short.
private const int StepsPerWait = 256;
private readonly GpuHeatAccelerator owner;
private readonly int columns;
private readonly int rows;
private readonly List<MemoryBuffer> buffers = new();
private readonly Dictionary<int, MemoryBuffer1D<float, Stride1D.Dense>> keeps = new();
private readonly MemoryBuffer1D<float, Stride1D.Dense> peak;
private readonly MemoryBuffer1D<float, Stride1D.Dense> noKeep;
private readonly MemoryBuffer1D<int, Stride1D.Dense> region;
private readonly MemoryBuffer1D<int, Stride1D.Dense> links;
private readonly MemoryBuffer1D<HeatSample, Stride1D.Dense> samples;
private MemoryBuffer1D<float, Stride1D.Dense> current;
private MemoryBuffer1D<float, Stride1D.Dense> next;
private MemoryBuffer1D<float, Stride1D.Dense> partialKeep;
// Cell numbers, regions and links of a change, one after another.
private MemoryBuffer1D<int, Stride1D.Dense> changes;
private int steps;
public GpuHeatKernel(GpuHeatAccelerator owner, int columns, int rows, ReadOnlySpan<HeatSample> source)
{
this.owner = owner;
this.columns = columns;
this.rows = rows;
var count = columns * rows;
try
{
current = Allocate<float>(count);
next = Allocate<float>(count);
peak = Allocate<float>(count);
noKeep = Allocate<float>(1);
region = Allocate<int>(count);
links = Allocate<int>(count);
samples = Allocate<HeatSample>(System.Math.Max(1, source.Length));
if (source.Length > 0)
samples.View.SubView(0, source.Length).CopyFromCPU(Stream, source.ToArray());
}
catch
{
Release();
throw;
}
}
private AcceleratorStream Stream => owner.Accelerator.DefaultStream;
public void Clear() => Locked(() =>
{
current.MemSetToZero(Stream);
next.MemSetToZero(Stream);
peak.MemSetToZero(Stream);
});
public void SetCells(ReadOnlySpan<int> newRegion, ReadOnlySpan<int> newLinks)
{
var regions = newRegion.ToArray();
var linked = newLinks.ToArray();
Locked(() =>
{
region.View.CopyFromCPU(Stream, regions);
links.View.CopyFromCPU(Stream, linked);
Stream.Synchronize();
});
}
public void ChangeCells(ReadOnlySpan<int> cells, ReadOnlySpan<int> newRegion, ReadOnlySpan<int> newLinks)
{
var count = cells.Length;
if (count == 0)
return;
var packed = new int[count * 3];
cells.CopyTo(packed);
newRegion.CopyTo(packed.AsSpan(count));
newLinks.CopyTo(packed.AsSpan(count * 2));
Locked(() =>
{
if (changes == null || changes.Length < packed.Length)
{
Free(changes);
changes = Allocate<int>(System.Math.Max(packed.Length, 4096));
}
changes.View.SubView(0, packed.Length).CopyFromCPU(Stream, packed);
owner.Kernels.Change(Stream, count, current.View, region.View, links.View,
changes.View.SubView(0, count), changes.View.SubView(count, count),
changes.View.SubView(count * 2, count));
Stream.Synchronize();
});
}
public void AddSamples(int from, int to) => Locked(() =>
owner.Kernels.Add(Stream, 1, current.View, region.View, samples.View,
new SampleRange(from, to, columns, rows)));
public void Step(float share, float keep, float[] cellKeep, int keepKey) => Locked(() =>
{
var perCell = cellKeep == null ? null : Keep(cellKeep, keepKey);
var views = new StepViews(current.View, next.View, peak.View, (perCell ?? noKeep).View, links.View);
owner.Kernels.Diffuse(Stream, columns * rows, views, columns, share, keep, perCell == null ? 0 : 1);
(current, next) = (next, current);
if (++steps % StepsPerWait == 0)
Stream.Synchronize();
});
public void Read(float[] temperature, float[] peaks) => Locked(() =>
{
current.View.CopyToCPU(Stream, temperature);
peak.View.CopyToCPU(Stream, peaks);
Stream.Synchronize();
});
public void Write(float[] temperature, float[] peaks) => Locked(() =>
{
current.View.CopyFromCPU(Stream, temperature);
peak.View.CopyFromCPU(Stream, peaks);
Stream.Synchronize();
});
public void Dispose() => Locked(Release);
private MemoryBuffer1D<float, Stride1D.Dense> Keep(float[] values, int key)
{
if (key < 0)
{
partialKeep ??= Allocate<float>(values.Length);
partialKeep.View.CopyFromCPU(Stream, values);
Stream.Synchronize();
return partialKeep;
}
if (!keeps.TryGetValue(key, out var buffer))
{
buffer = Allocate<float>(values.Length);
buffer.View.CopyFromCPU(Stream, values);
Stream.Synchronize();
keeps[key] = buffer;
}
return buffer;
}
private MemoryBuffer1D<T, Stride1D.Dense> Allocate<T>(long length)
where T : unmanaged
{
var buffer = owner.Accelerator.Allocate1D<T>(length);
buffers.Add(buffer);
return buffer;
}
private void Free(MemoryBuffer buffer)
{
if (buffer == null)
return;
buffers.Remove(buffer);
buffer.Dispose();
}
private void Release()
{
foreach (var buffer in buffers)
buffer.Dispose();
buffers.Clear();
}
private void Locked(Action action)
{
lock (owner.Gate)
{
owner.Accelerator.Bind();
action();
}
}
}
-104
View File
@@ -1,104 +0,0 @@
using System;
using ILGPU;
using ILGPU.Runtime;
using OpenNest.CNC.Thermal;
using Floats = ILGPU.Runtime.ArrayView1D<float, ILGPU.Stride1D.Dense>;
using Ints = ILGPU.Runtime.ArrayView1D<int, ILGPU.Stride1D.Dense>;
using Samples = ILGPU.Runtime.ArrayView1D<OpenNest.CNC.Thermal.HeatSample, ILGPU.Stride1D.Dense>;
namespace OpenNest.Gpu;
/// <summary>The views one diffusion step reads and writes.</summary>
internal readonly struct StepViews(Floats current, Floats next, Floats peak, Floats cellKeep, Ints links)
{
public readonly Floats Current = current;
public readonly Floats Next = next;
public readonly Floats Peak = peak;
public readonly Floats CellKeep = cellKeep;
public readonly Ints Links = links;
}
/// <summary>The device programs, compiled once. Each mirrors the CPU code it is named after.</summary>
internal sealed class HeatKernels
{
public HeatKernels(Accelerator accelerator)
{
Diffuse = accelerator.LoadAutoGroupedKernel<Index1D, StepViews, int, float, float, int>(DiffuseCell);
Add = accelerator.LoadAutoGroupedKernel<Index1D, Floats, Ints, Samples, SampleRange>(AddSamples);
Change = accelerator.LoadAutoGroupedKernel<Index1D, Floats, Ints, Ints, Ints, Ints, Ints>(ChangeCell);
}
public Action<AcceleratorStream, Index1D, StepViews, int, float, float, int> Diffuse { get; }
public Action<AcceleratorStream, Index1D, Floats, Ints, Samples, SampleRange> Add { get; }
public Action<AcceleratorStream, Index1D, Floats, Ints, Ints, Ints, Ints, Ints> Change { get; }
// PlateHeatSimulation.DiffuseCells. A missing link reads the cell itself, so its term is zero
// and the index stays in the grid.
private static void DiffuseCell(Index1D index, StepViews views, int columns, float share, float keep, int perCell)
{
int i = index;
var links = views.Links[i];
var t = views.Current[i];
var left = views.Current[(links & 1) != 0 ? i - 1 : i];
var right = views.Current[(links & 2) != 0 ? i + 1 : i];
var below = views.Current[(links & 4) != 0 ? i - columns : i];
var above = views.Current[(links & 8) != 0 ? i + columns : i];
var flow = (left - t) + (right - t) + (below - t) + (above - t);
var value = (t + share * flow) * (perCell != 0 ? views.CellKeep[i] : keep);
if (value < PlateHeatSimulation.Negligible)
value = 0;
views.Next[i] = value;
if (value > views.Peak[i])
views.Peak[i] = value;
}
// PlateHeatSimulation.Add, for the samples of one step. One thread takes them in order, since
// neighboring samples share cells; a step has only a few.
private static void AddSamples(Index1D one, Floats temperature, Ints region, Samples samples, SampleRange range)
{
for (var i = range.From; i < range.To; i++)
{
var sample = samples[i];
var piece = region[sample.Cell];
if (piece == -1)
continue;
var columns = range.Columns;
var left = sample.Left;
var right = left + 1 < columns ? left + 1 : columns - 1;
var lower = sample.Lower * columns;
var upper = (sample.Lower + 1 < range.Rows ? sample.Lower + 1 : range.Rows - 1) * columns;
var x = sample.X;
var y = sample.Y;
var lowerLeft = region[lower + left] == piece ? (1 - x) * (1 - y) : 0f;
var lowerRight = region[lower + right] == piece ? x * (1 - y) : 0f;
var upperLeft = region[upper + left] == piece ? (1 - x) * y : 0f;
var upperRight = region[upper + right] == piece ? x * y : 0f;
var rise = sample.Rise / (lowerLeft + lowerRight + upperLeft + upperRight);
temperature[lower + left] += rise * lowerLeft;
temperature[lower + right] += rise * lowerRight;
temperature[upper + left] += rise * upperLeft;
temperature[upper + right] += rise * upperRight;
}
}
// New piece and links for a listed cell, and no heat where material fell away.
private static void ChangeCell(Index1D k, Floats temperature, Ints region, Ints links,
Ints cells, Ints newRegion, Ints newLinks)
{
var cell = cells[k];
region[cell] = newRegion[k];
links[cell] = newLinks[k];
if (newRegion[k] == -1)
temperature[cell] = 0;
}
}
internal readonly struct SampleRange(int from, int to, int columns, int rows)
{
public readonly int From = from;
public readonly int To = to;
public readonly int Columns = columns;
public readonly int Rows = rows;
}
-18
View File
@@ -1,18 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>OpenNest.Gpu</RootNamespace>
<AssemblyName>OpenNest.Gpu</AssemblyName>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="OpenNest.Tests" />
<!-- ILGPU emits the code that passes kernel arguments into its own assembly. -->
<InternalsVisibleTo Include="ILGPURuntime" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\OpenNest.Core\OpenNest.Core.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ILGPU" Version="1.5.1" />
</ItemGroup>
</Project>
@@ -1,185 +0,0 @@
using OpenNest.CNC;
using OpenNest.CNC.Thermal;
using OpenNest.Geometry;
using OpenNest.Gpu;
using OpenNest.Support;
namespace OpenNest.Tests.CNC;
public class GpuHeatAcceleratorTests
{
// A framed part on slats: shared samples, a dropped slug, a part cut free and contact decay.
// The kernels take every step over the whole plate, so that is what they are compared with.
private static (Plate Plate, CutSimulation Simulation, Func<IHeatAccelerator?, ThermalParameters> Thermal) Job(
SupportBed? bed, bool wholePlateSteps = false)
{
var program = new Program();
foreach (var (x, y, size) in new[] { (3.0, 3.0, 4.0), (0.0, 0.0, 10.0) })
{
program.Codes.Add(new RapidMove(x, y));
program.Codes.Add(new LinearMove(x + size, y));
program.Codes.Add(new LinearMove(x + size, y + size));
program.Codes.Add(new LinearMove(x, y + size));
program.Codes.Add(new LinearMove(x, y));
}
var plate = new Plate(130, 130);
plate.Parts.Add(new Part(new Drawing("part", program), new Vector(8, 8)));
var simulation = CutSimulation.Build(plate, new CutParameters
{
Feedrate = 100,
RapidTravelRate = 600,
PierceTime = TimeSpan.FromSeconds(1),
Units = Units.Inches,
});
// 0.25 in cells on 130 in square are 270,400 cells, enough to be accelerated.
return (plate, simulation, accelerator => new ThermalParameters
{
Material = ThermalMaterial.MildSteel,
Thickness = 0.25,
Units = Units.Inches,
CellSize = 0.25,
SupportBed = bed,
Accelerator = accelerator,
WholePlateSteps = wholePlateSteps,
});
}
private static void AssertClose(ReadOnlySpan<float> expected, ReadOnlySpan<float> actual)
{
Assert.Equal(expected.Length, actual.Length);
for (var i = 0; i < expected.Length; i++)
{
// Devices may fuse a multiply and an add, which rounds once instead of twice.
var allowed = 0.001f + 1e-5f * System.Math.Abs(expected[i]);
if (System.Math.Abs(expected[i] - actual[i]) > allowed)
Assert.Fail($"cell {i}: {actual[i]} instead of {expected[i]}");
}
}
private static void AssertMatchesTheProcessor(IHeatAccelerator accelerator, SupportBed? bed)
{
var (plate, simulation, thermal) = Job(bed, wholePlateSteps: true);
var processor = new PlateHeatSimulation(plate, simulation, thermal(null));
using var heat = new PlateHeatSimulation(plate, simulation, thermal(accelerator));
Assert.True(heat.IsAccelerated);
// To the end, back past checkpoints, forward in frames that cut steps short, and cooling.
TimeSpan At(double fraction) => TimeSpan.FromTicks((long)(simulation.TotalTime.Ticks * fraction));
foreach (var target in new[] { At(1), At(0.4), At(0.4) + TimeSpan.FromSeconds(0.04), At(0.7), At(1.2) })
{
processor.AdvanceTo(target);
heat.AdvanceTo(target);
AssertClose(processor.Temperatures, heat.Temperatures);
AssertClose(processor.Peaks, heat.Peaks);
}
Assert.True(heat.IsRemoved(heat.CellAt(new Vector(13, 13))));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void KernelsMatchTheProcessor(bool slats)
{
using var accelerator = GpuHeatAccelerator.Emulated();
AssertMatchesTheProcessor(accelerator,
slats ? new SupportSlats(SlatAxis.X, pitch: 4, thickness: 1, offset: 2) : null);
}
// Runs on a computer with a usable graphics card only; build agents have none.
[SkippableFact]
public void TheGraphicsCardMatchesTheProcessor()
{
var accelerator = GpuHeatAccelerator.Default;
Skip.If(accelerator == null, "No graphics card ILGPU can use.");
AssertMatchesTheProcessor(accelerator!, new SupportSlats(SlatAxis.X, pitch: 4, thickness: 1, offset: 2));
}
// Every computer draws the same picture, so a card must not change the cells.
[Theory]
[InlineData(3600, 0.25)]
[InlineData(20_000, 0.25)]
[InlineData(80_000, 0.5)]
public void AnAcceleratorDoesNotChangeTheAutomaticCellSize(double seconds, double expected)
{
using var accelerator = GpuHeatAccelerator.Emulated();
ThermalParameters Parameters(IHeatAccelerator? hardware) => new()
{
Material = ThermalMaterial.MildSteel,
Thickness = 0.25,
Units = Units.Inches,
Accelerator = hardware,
};
var sheet = new Box(0, 0, 120, 60);
Assert.Equal(expected, PlateHeatSimulation.AutomaticCellSize(sheet, seconds, Parameters(null)));
Assert.Equal(expected, PlateHeatSimulation.AutomaticCellSize(sheet, seconds, Parameters(accelerator)));
}
private sealed class CountingAccelerator : IHeatAccelerator
{
public int Asked { get; private set; }
public string Name => "counting";
public IHeatKernel Create(int columns, int rows, ReadOnlySpan<HeatSample> samples)
{
Asked++;
return null!;
}
}
// The processor is the faster for a full sheet's quarter-inch cells, so the card is not
// even asked: asking is what starts it.
[Fact]
public void AFullSheetsQuarterInchCellsStayOnTheProcessor()
{
var accelerator = new CountingAccelerator();
var plate = new Plate(60, 120);
plate.Parts.Add(new Part(Job(null).Plate.Parts[0].BaseDrawing, new Vector(8, 8)));
var simulation = CutSimulation.Build(plate, new CutParameters { Feedrate = 100, Units = Units.Inches });
using var heat = new PlateHeatSimulation(plate, simulation, new ThermalParameters
{
Thickness = 0.25,
Units = Units.Inches,
CellSize = 0.25,
Accelerator = accelerator,
});
Assert.False(heat.IsAccelerated);
Assert.Equal(0, accelerator.Asked);
}
[Fact]
public void AnAcceleratorWithNoHardwareLeavesTheGridOnTheProcessor()
{
var accelerator = new CountingAccelerator();
var (plate, simulation, thermal) = Job(null);
using var heat = new PlateHeatSimulation(plate, simulation, thermal(accelerator));
var processor = new PlateHeatSimulation(plate, simulation, thermal(null));
heat.RunToEnd();
processor.RunToEnd();
Assert.Equal(1, accelerator.Asked);
Assert.False(heat.IsAccelerated);
Assert.Equal(processor.Temperatures.ToArray(), heat.Temperatures.ToArray());
}
[Fact]
public void ACancelledRunStopsAndFinishesExactlyLater()
{
var (plate, simulation, thermal) = Job(null);
var heat = new PlateHeatSimulation(plate, simulation, thermal(null));
using var cancel = new CancellationTokenSource();
cancel.Cancel();
Assert.Throws<OperationCanceledException>(() => heat.RunToEnd(cancellationToken: cancel.Token));
Assert.True(heat.Time < simulation.TotalTime);
heat.RunToEnd();
var straight = new PlateHeatSimulation(plate, simulation, thermal(null));
straight.RunToEnd();
Assert.Equal(straight.Temperatures.ToArray(), heat.Temperatures.ToArray());
}
}
@@ -162,6 +162,43 @@ public class PlateHeatSimulationTests
Assert.Equal(0.5, PlateHeatSimulation.AutomaticCellSize(new Box(0, 0, 120, 60), 40_000, p));
}
// Quarter-inch cells hold for cuts of hours, so every full sheet compares at one cell size.
[Theory]
[InlineData(3600, 0.25)]
[InlineData(20_000, 0.25)]
[InlineData(80_000, 0.5)]
public void FullSheetKeepsQuarterInchCellsForCutsOfHours(double seconds, double expected)
{
var p = new ThermalParameters { Material = ThermalMaterial.MildSteel, Thickness = 0.25, Units = Units.Inches };
Assert.Equal(expected, PlateHeatSimulation.AutomaticCellSize(new Box(0, 0, 120, 60), seconds, p));
}
[Fact]
public void ACancelledRunStopsAndFinishesExactlyLater()
{
var plate = FullSheet();
var simulation = CutSimulation.Build(plate, new CutParameters { Feedrate = 100, Units = Units.Inches });
PlateHeatSimulation Heat() => new(plate, simulation, new ThermalParameters
{
Material = ThermalMaterial.MildSteel,
Thickness = 0.25,
Units = Units.Inches,
CellSize = 0.5,
});
var heat = Heat();
using var cancel = new CancellationTokenSource();
cancel.Cancel();
Assert.Throws<OperationCanceledException>(() => heat.RunToEnd(cancellationToken: cancel.Token));
Assert.True(heat.Time < simulation.TotalTime);
heat.RunToEnd();
var straight = Heat();
straight.RunToEnd();
Assert.Equal(straight.Temperatures.ToArray(), heat.Temperatures.ToArray());
}
// Half an inch past the budget, a run is cut into longer steps than the torch needs.
[Fact]
public void OnlyCuttingTimeTakesShortSteps()
-1
View File
@@ -28,7 +28,6 @@
<ProjectReference Include="..\OpenNest.Data\OpenNest.Data.csproj" />
<ProjectReference Include="..\OpenNest.Core\OpenNest.Core.csproj" />
<ProjectReference Include="..\OpenNest.Engine\OpenNest.Engine.csproj" />
<ProjectReference Include="..\OpenNest.Gpu\OpenNest.Gpu.csproj" />
<ProjectReference Include="..\OpenNest.IO\OpenNest.IO.csproj" />
<ProjectReference Include="..\OpenNest.Reporting\OpenNest.Reporting.csproj" />
<ProjectReference Include="..\Posts\OpenNest.Posts.Cincinnati\OpenNest.Posts.Cincinnati.csproj" />
-14
View File
@@ -58,8 +58,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenNest.Avalonia", "OpenNe
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenNest.Server.Worker", "OpenNest.Server.Worker\OpenNest.Server.Worker.csproj", "{DFE6F33C-4BB7-4F6A-8062-6D5521423B74}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenNest.Gpu", "OpenNest.Gpu\OpenNest.Gpu.csproj", "{3FCAADA5-C98D-4DEC-8C81-F0E489EA1977}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -370,18 +368,6 @@ Global
{DFE6F33C-4BB7-4F6A-8062-6D5521423B74}.Release|x64.Build.0 = Release|Any CPU
{DFE6F33C-4BB7-4F6A-8062-6D5521423B74}.Release|x86.ActiveCfg = Release|Any CPU
{DFE6F33C-4BB7-4F6A-8062-6D5521423B74}.Release|x86.Build.0 = Release|Any CPU
{3FCAADA5-C98D-4DEC-8C81-F0E489EA1977}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3FCAADA5-C98D-4DEC-8C81-F0E489EA1977}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3FCAADA5-C98D-4DEC-8C81-F0E489EA1977}.Debug|x64.ActiveCfg = Debug|Any CPU
{3FCAADA5-C98D-4DEC-8C81-F0E489EA1977}.Debug|x64.Build.0 = Debug|Any CPU
{3FCAADA5-C98D-4DEC-8C81-F0E489EA1977}.Debug|x86.ActiveCfg = Debug|Any CPU
{3FCAADA5-C98D-4DEC-8C81-F0E489EA1977}.Debug|x86.Build.0 = Debug|Any CPU
{3FCAADA5-C98D-4DEC-8C81-F0E489EA1977}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3FCAADA5-C98D-4DEC-8C81-F0E489EA1977}.Release|Any CPU.Build.0 = Release|Any CPU
{3FCAADA5-C98D-4DEC-8C81-F0E489EA1977}.Release|x64.ActiveCfg = Release|Any CPU
{3FCAADA5-C98D-4DEC-8C81-F0E489EA1977}.Release|x64.Build.0 = Release|Any CPU
{3FCAADA5-C98D-4DEC-8C81-F0E489EA1977}.Release|x86.ActiveCfg = Release|Any CPU
{3FCAADA5-C98D-4DEC-8C81-F0E489EA1977}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
+3 -23
View File
@@ -124,33 +124,13 @@ internal sealed class CutSimulationOverlay : IDisposable
/// <summary>The heat model shown under the trail, run along with the playhead; null for none.</summary>
public PlateHeatSimulation Heat => heat;
/// <summary>
/// Raised when the heat model could not run on (its graphics card failed); it is no longer
/// shown.
/// </summary>
public event EventHandler HeatFailed;
/// <summary>
/// Brings the heat model to <paramref name="time"/>, with its values ready to read. False
/// when there is none or it failed.
/// </summary>
/// <summary>Brings the heat model to <paramref name="time"/>. False when there is none.</summary>
public bool AdvanceHeat(TimeSpan time)
{
if (heat == null)
return false;
try
{
heat.AdvanceTo(time);
// Reading fetches them from an accelerator, so that fails here too, if it will.
_ = heat.Temperatures;
return true;
}
catch (Exception) when (heat.IsAccelerated)
{
heat = null;
HeatFailed?.Invoke(this, EventArgs.Empty);
return false;
}
heat.AdvanceTo(time);
return true;
}
public HeatView HeatMode
+5 -26
View File
@@ -10,7 +10,6 @@ using OpenNest.Controls;
using OpenNest.Data;
using OpenNest.Desktop;
using OpenNest.Desktop.Interaction;
using OpenNest.Gpu;
using OpenNest.Support;
using NumericUpDown = OpenNest.Controls.NumericUpDown;
@@ -52,7 +51,6 @@ namespace OpenNest.Forms
private HeatEstimate heatEstimate;
private HeatInput heatInput;
private CancellationTokenSource heatRun;
private bool acceleratorFailed;
public CutSimulatorForm(EditNestForm nestForm)
{
@@ -235,7 +233,6 @@ namespace OpenNest.Forms
overlay.Speed = Speeds[speedBox.SelectedIndex];
overlay.Changed += Overlay_Changed;
overlay.HeatFailed += Overlay_HeatFailed;
nestForm.PlateChanged += NestForm_PlateChanged;
nestForm.FormClosed += NestForm_FormClosed;
AttachPlate(nestForm.PlateView.Plate);
@@ -408,27 +405,25 @@ namespace OpenNest.Forms
ReleaseHeat();
heatLabel.Text = "Estimating heat…";
heatRun = new CancellationTokenSource();
EstimateHeat(plate, overlay.Simulation, input, !acceleratorFailed, heatRun.Token);
EstimateHeat(plate, overlay.Simulation, input, heatRun.Token);
}
private async void EstimateHeat(Plate subject, CutSimulation simulation, HeatInput input,
bool accelerate, CancellationToken cancellationToken)
CancellationToken cancellationToken)
{
HeatEstimate estimate;
try
{
// The graphics card starts inside the run, and only for a grid fine enough to use it.
estimate = await Task.Run(() => HeatEstimate.Run(subject, simulation,
accelerator => new ThermalParameters
new ThermalParameters
{
Material = input.Material,
Thickness = input.Thickness,
Units = input.Units,
AbsorbedPower = input.Power,
SupportBed = input.SupportBed,
Accelerator = accelerator,
},
accelerate ? GpuHeatAccelerator.OnDemand : null, cancellationToken), cancellationToken);
cancellationToken), cancellationToken);
}
catch (OperationCanceledException)
{
@@ -443,10 +438,7 @@ namespace OpenNest.Forms
// A newer run, or a closed window, makes this one worthless.
if (cancellationToken.IsCancellationRequested || IsDisposed)
{
estimate.Dispose();
return;
}
heatEstimate = estimate;
heatInput = input;
ShowHeat();
@@ -460,28 +452,16 @@ namespace OpenNest.Forms
: heatInput.SupportBed is SupportSlats ? "cooled by air and slats" : "cooled by air and the support grid";
heatScaleText = $"{heatInput.Material.Name}, {cooling}; red is {heatEstimate.Scale:0} °C above ambient";
var units = heatInput.Units == Units.Millimeters ? "mm" : "in";
tips.SetToolTip(heatLabel, $"{heat.CellSize:0.####} {units} cells, computed on "
+ (heatEstimate.Device ?? "the processor"));
tips.SetToolTip(heatLabel, $"{heat.CellSize:0.####} {units} cells");
UpdateHeatLabel(force: true);
}
private void ReleaseHeat()
{
heatEstimate?.Dispose();
heatEstimate = null;
heatInput = null;
}
// The graphics card gave out during playback: estimate again on the processor.
private void Overlay_HeatFailed(object sender, EventArgs e) => BeginInvoke(() =>
{
if (IsDisposed)
return;
acceleratorFailed = true;
ReleaseHeat();
LoadHeat();
});
private string heatScaleText = "";
// While playing, the hottest temperature would change every frame, too fast to read.
@@ -631,7 +611,6 @@ namespace OpenNest.Forms
SavedCutParameters.Save(GetCutParameters());
overlay.Changed -= Overlay_Changed;
overlay.HeatFailed -= Overlay_HeatFailed;
heatRun?.Cancel();
nestForm.PlateChanged -= NestForm_PlateChanged;
nestForm.FormClosed -= NestForm_FormClosed;
-1
View File
@@ -22,7 +22,6 @@
<ProjectReference Include="..\OpenNest.Core\OpenNest.Core.csproj" />
<ProjectReference Include="..\OpenNest.Data\OpenNest.Data.csproj" />
<ProjectReference Include="..\OpenNest.Engine\OpenNest.Engine.csproj" />
<ProjectReference Include="..\OpenNest.Gpu\OpenNest.Gpu.csproj" />
<ProjectReference Include="..\OpenNest.IO\OpenNest.IO.csproj" />
<ProjectReference Include="..\OpenNest.Reporting\OpenNest.Reporting.csproj" />
<ProjectReference Include="..\OpenNest.Desktop\OpenNest.Desktop.csproj" />
+1 -1
View File
@@ -13,7 +13,7 @@ A Windows desktop application for CNC nesting — imports DXF, DWG and SVG drawi
- **Nesting** — automatic multi-plate/multi-material jobs, interlocking pair evaluation, and built-in or plug-in engines. [Choose an engine](docs/nesting-engines.md).
- **Plate operations** — manual sheet cut-offs, [plate- or nest-wide automatic scrap cutoffs](docs/automatic-scrap-cutoffs.md) that cut the skeleton into strips sized for your scrap hopper while keeping a reusable tail, oversized-part splitting (straight, weld-gap tabs, spike-groove), interactive editing, and spacing-aware pushes that can slide along or away from touching parts.
- **Visual overlap check** — highlight shared material on the active plate, rechecked automatically after edits, including containment and cutouts, with area shading, pair markers, and hover details through View > Overlap Check. [Usage and limitations](docs/geometry/visual-overlap-check.md).
- **Cut simulator** — Plate > Simulate Cutting replays the active plate in cut order: the torch traces each cut, rapid and pierce at adjustable feed, rapid and pierce settings, with play/pause, scrubbing, a click on the plate to jump to when the torch passes there, 1×–250× speed and previous/next part (Page Up/Down) and cutout (Ctrl+Left/Right) jumps. Parts the torch has not reached stay grayed. A heat map (Heat: Now or Peak so far) estimates how heat builds up in the sheet as the torch cuts, cooled by air and the support slats or grid, with the temperature rise under the cursor; the heat input is set on the Settings tab. With a supported graphics card (NVIDIA; others unverified) it uses finer cells. It is uncalibrated, so use it to compare cut orders of one plate, not as real temperatures ([heat model](docs/plate-heat-map.md)). It and Calculate Cut Time use separate outside and hole feeds, skip etch-only contours like the CI Fiber post, and apply the chosen machine's acceleration and corner limits from Machine Configuration (placeholder values until you enter the controller's). [Timing model](docs/cut-time-estimates.md).
- **Cut simulator** — Plate > Simulate Cutting replays the active plate in cut order: the torch traces each cut, rapid and pierce at adjustable feed, rapid and pierce settings, with play/pause, scrubbing, a click on the plate to jump to when the torch passes there, 1×–250× speed and previous/next part (Page Up/Down) and cutout (Ctrl+Left/Right) jumps. Parts the torch has not reached stay grayed. A heat map (Heat: Now or Peak so far) estimates how heat builds up in the sheet as the torch cuts, cooled by air and the support slats or grid, with the temperature rise under the cursor; the heat input is set on the Settings tab. It is uncalibrated, so use it to compare cut orders of one plate, not as real temperatures ([heat model](docs/plate-heat-map.md)). It and Calculate Cut Time use separate outside and hole feeds, skip etch-only contours like the CI Fiber post, and apply the chosen machine's acceleration and corner limits from Machine Configuration (placeholder values until you enter the controller's). [Timing model](docs/cut-time-estimates.md).
- **CNC output** — configurable lead-ins/outs and tabs, [support-bed checks that tab only the parts the grid or slats can't hold level](docs/support-tabs.md), contour editing, etched part-number labels with grain-based bend group letters so parts needing the same press brake angle correction can be formed together ([label box](docs/label-box.md)), user-defined G-code variables (`$name` → `#200+` machine variables), plugin post-processors (Cincinnati CL-707/800/900/940/CLX included). [Pre-post verification](docs/post-verification.md) checks overlaps, missing lead-ins, and rapid crossings, with explicit risk acknowledgment required to bypass warnings.
## Requirements
+10 -30
View File
@@ -16,9 +16,7 @@ a removed heat-aware sequencer used a cheaper estimate of the same physics ([Seq
costs up to sixteen times the work, since diffusion shortens the time step with the cell's
area. Automatic grids have at most 700,000 cells, and any size asked for is made coarser past
that. Each cell holds its temperature rise above ambient. Finer cells hold the torch's heat in
less metal, so cells along the cut read hotter; compare cut orders at one cell size. An
[accelerator](#graphics-card) does not change the cell size, so every computer draws the same
picture.
less metal, so cells along the cut read hotter; compare cut orders at one cell size.
- Heat in: while the torch is on (cuts and pierces), `AbsorbedPower` watts go into the sheet at
the torch, in proportion to the time spent there. The path is sampled four times per cell, and
each sample is shared between the four cells whose centers surround it, by closeness, among
@@ -33,7 +31,7 @@ a removed heat-aware sequencer used a cheaper estimate of the same physics ([Seq
are insulated. A rise below 1e-30 °C is set to zero: the front of the spreading heat would
otherwise pass through subnormal floats, which make each step several times slower. It changes
no cell above about 1e-18 °C.
- Short steps only around the torch: on the processor, the short steps of a slot are taken only by
- Short steps only around the torch: the short steps of a slot are taken only by
the window of cells within four cells of where the torch put heat during those steps or during
the slot before them (which keeps the cells beside a fresh cut on short steps until their own
peak has passed). The cells touching the window hold their starting values meanwhile, and every
@@ -95,34 +93,16 @@ The simulator builds and runs the model off the UI thread (`HeatEstimate`) and s
"Estimating heat…" meanwhile. A changed setting cancels the run in progress; a rebuilt timeline
with the same moves and settings keeps the model it has.
## Graphics card
## Timings
`ThermalParameters.Accelerator` runs grids of 250,000 cells or more elsewhere; smaller ones stay
on the processor, which is the faster for them: a card takes longer to start each short step than
the processor takes over the cells around the torch. A 5×10 ft sheet's 0.25 in cells (115,200)
therefore run on the processor on every computer, and the card serves only finer grids, which
automatic cell sizes seldom reach (a `CellSize` of 0.125 in on a full sheet does). The cut
simulator passes `GpuHeatAccelerator.OnDemand`, which starts the card (about half a second, once)
only when a grid first asks for it. `OpenNest.Gpu`
is the one implementation: ILGPU, using CUDA on an NVIDIA card, otherwise OpenCL where ILGPU
accepts the driver (not verified on AMD or Intel cards; Apple graphics are not supported). Without
a usable card, or when it fails while building or playing (out of memory, driver fault), the model
runs on the processor.
Measured on a Ryzen 7 3700X, 5×10 ft nests, 0.25 in and 16 gauge mild steel at 100 to 1600 in/min,
whole run: 0.25 in cells took 0.9-2.9 s before the window and take 0.23-0.45 s with it; a cut of
several hours takes about 3 s. 0.125 in cells take 1.3-6.2 s (11-22 s before).
The simulation keeps the pieces, timeline and checkpoints and the card keeps the temperatures.
On the card every cell takes the short steps, so its picture differs from the processor's by what
the window costs (above). Against the processor taking whole-plate steps too, its results are
within one part in a million, not bit for bit (devices may fuse a multiply and an add). The
processor stays the reference. `GpuHeatAcceleratorTests` compares the card with whole-plate steps
on the processor within a tolerance, running the card's programs on ILGPU's processor emulation
everywhere and on a real card where there is one (skipped otherwise, as on build agents). A
change to `DiffuseCells` or `Add` needs the same change in `OpenNest.Gpu/HeatKernels.cs`.
Measured on a Ryzen 7 3700X and an RTX 4060, 5×10 ft nests, 0.25 in and 16 gauge mild steel at
100 to 1600 in/min, whole run: 0.25 in cells took 0.9-2.9 s on the processor before the window
and take 0.23-0.45 s with it; the card takes 0.45-1.0 s, most of it the fixed cost of starting
two programs per step, which is why this cell size stays on the processor. 0.125 in
cells take 1.3-6.2 s on the processor (11-22 s before) and 1.1-2.7 s on the card.
A graphics card version (ILGPU, every cell taking the short steps) was built and measured on an
RTX 4060, then removed: at 0.25 in cells it took 0.45-1.0 s, slower than the processor, since
starting its two programs per step costs more than the step; at 0.125 in it took 1.1-2.7 s, a
cell size full sheets do not use.
## Display