mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-12-04 07:19:24 -05:00
feat(thermal): finer heat map, on a graphics card when there is one
Split only cutting time into short steps, raise the automatic resolution, add an optional ILGPU accelerator with CPU fallback, and estimate heat off the UI thread. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4cc43578f3
commit
f9f5299d16
22 files changed
+1396
-138
No files matched your search
@@ -45,6 +45,7 @@ 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.
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
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. 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);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace OpenNest.CNC.Thermal
|
||||
{
|
||||
/// <summary>
|
||||
/// The time steps of a <see cref="PlateHeatSimulation"/> run. Time is divided into slots as
|
||||
/// long as the diffusion limit allows, and a slot in which the torch cuts is split into equal
|
||||
/// steps short enough for that move's speed, so only the time that needs short steps pays for
|
||||
/// them. The boundaries depend on the timeline alone, so a replay takes the same steps.
|
||||
/// </summary>
|
||||
internal sealed class HeatStepSchedule
|
||||
{
|
||||
// Slots are split only into these counts, so a run has few distinct step lengths and
|
||||
// each one's decay factors can be kept.
|
||||
private static readonly int[] Splits = { 1, 2, 3, 4, 5, 6, 8, 10, 12, 16, 20, 24, 32, 40, 48, 64, 80, 96, 128, 160, 200 };
|
||||
|
||||
// Two times closer than this share of a slot are the same boundary.
|
||||
private const double Tolerance = 1e-9;
|
||||
|
||||
private readonly int[] splits;
|
||||
|
||||
/// <param name="simulation">The timeline.</param>
|
||||
/// <param name="slotSeconds">The longest step the diffusion allows.</param>
|
||||
/// <param name="cellSize">Cell edge in the plate's units.</param>
|
||||
/// <param name="travelCells">The most cells the torch may cross in one step.</param>
|
||||
/// <param name="minSeconds">No step is split shorter than this for the torch's sake.</param>
|
||||
public HeatStepSchedule(CutSimulation simulation, double slotSeconds, double cellSize,
|
||||
double travelCells, double minSeconds)
|
||||
{
|
||||
SlotSeconds = slotSeconds;
|
||||
var total = simulation.TotalTime.TotalSeconds;
|
||||
splits = new int[(int)System.Math.Max(0, System.Math.Ceiling(total / slotSeconds))];
|
||||
Array.Fill(splits, 1);
|
||||
|
||||
foreach (var step in simulation.Steps)
|
||||
{
|
||||
var seconds = step.Duration.TotalSeconds;
|
||||
if (step.Kind != CutSimulationStepKind.Cut || seconds <= 0 || step.Length <= 0)
|
||||
continue;
|
||||
|
||||
var limit = System.Math.Max(minSeconds, travelCells * cellSize * seconds / step.Length);
|
||||
var split = SplitFor(slotSeconds / limit);
|
||||
if (split == 1)
|
||||
continue;
|
||||
|
||||
var start = step.StartTime.TotalSeconds;
|
||||
var first = (int)System.Math.Floor(start / slotSeconds + Tolerance);
|
||||
var last = (int)System.Math.Ceiling((start + seconds) / slotSeconds - Tolerance) - 1;
|
||||
for (var slot = System.Math.Max(0, first); slot <= System.Math.Min(splits.Length - 1, last); slot++)
|
||||
splits[slot] = System.Math.Max(splits[slot], split);
|
||||
}
|
||||
|
||||
foreach (var split in splits)
|
||||
StepCount += split;
|
||||
}
|
||||
|
||||
public double SlotSeconds { get; }
|
||||
|
||||
/// <summary>Steps from the start to the end of the cut.</summary>
|
||||
public long StepCount { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The first step boundary after <paramref name="time"/>, with the count its slot is
|
||||
/// split into. Past the cut, slots are whole.
|
||||
/// </summary>
|
||||
public (double Time, int Split) Next(double time)
|
||||
{
|
||||
var slot = (long)System.Math.Floor(time / SlotSeconds + Tolerance);
|
||||
while (true)
|
||||
{
|
||||
var split = slot < splits.Length ? splits[slot] : 1;
|
||||
var start = slot * SlotSeconds;
|
||||
var index = System.Math.Max(1, (long)System.Math.Floor((time - start) / SlotSeconds * split + Tolerance) + 1);
|
||||
if (index <= split)
|
||||
{
|
||||
var boundary = index == split ? (slot + 1) * SlotSeconds : start + SlotSeconds * index / split;
|
||||
return (boundary, split);
|
||||
}
|
||||
slot++;
|
||||
}
|
||||
}
|
||||
|
||||
private static int SplitFor(double needed)
|
||||
{
|
||||
foreach (var split in Splits)
|
||||
{
|
||||
if (split >= needed - 1e-6)
|
||||
return split;
|
||||
}
|
||||
return Splits[^1];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using OpenNest.Geometry;
|
||||
using OpenNest.Support;
|
||||
@@ -23,17 +24,27 @@ namespace OpenNest.CNC.Thermal
|
||||
/// estimates for comparing cut orders, not calibrated temperatures; see
|
||||
/// docs/plate-heat-map.md.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// With <see cref="ThermalParameters.Accelerator"/> large grids run on it, close to the CPU's
|
||||
/// results but not bit for bit. Use one thread at a time, and dispose to release it.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class PlateHeatSimulation
|
||||
public sealed class PlateHeatSimulation : IDisposable
|
||||
{
|
||||
private const int Removed = -1;
|
||||
private const double ArcStepRadians = System.Math.PI / 18;
|
||||
private const int MaxCells = 400_000;
|
||||
private const int MaxCells = 700_000;
|
||||
private const int MaxSamplesPerStep = 10_000;
|
||||
|
||||
// Cell updates for a whole run, counting diffusion-limited steps, when the cell size is
|
||||
// automatic. The torch travel limit below can multiply the actual steps a few times.
|
||||
private const double WorkBudget = 60_000_000;
|
||||
// automatic: on the processor about a second, so a full sheet gets quarter-inch cells; on
|
||||
// an accelerator a couple of seconds, for eighth-inch cells. The torch travel limit can
|
||||
// multiply the actual steps a few times.
|
||||
private const double WorkBudget = 800_000_000;
|
||||
private const double AcceleratedWorkBudget = 20_000_000_000;
|
||||
|
||||
// Below this an accelerator spends longer starting each step than the step takes.
|
||||
private const int AcceleratedCells = 100_000;
|
||||
private const int MaxHalvings = 3;
|
||||
|
||||
// Explicit diffusion is stable below a quarter on a square grid; the cap keeps timing
|
||||
@@ -42,10 +53,13 @@ namespace OpenNest.CNC.Thermal
|
||||
private const double MaxStepSeconds = 1.0;
|
||||
|
||||
// A step adds all its heat at once, so one in which the torch crosses several cells
|
||||
// lays it down in lumps that show as stripes along a straight cut. A step is therefore
|
||||
// no longer than the torch takes to cross this many cells at its fastest, though never
|
||||
// shortened below the floor (a very high feed over fine cells).
|
||||
// lays it down in lumps that show as stripes along a straight cut. A step while cutting
|
||||
// is therefore no longer than the torch takes to cross this many cells, though never
|
||||
// shortened below the floor (a very high feed over fine cells). Cells this fine need half
|
||||
// that where the diffusion step alone would let a slow torch cross a whole cell.
|
||||
private const double MaxTravelCells = 1.0;
|
||||
private const double FineTravelCells = 0.5;
|
||||
private const double FineCellMeters = 0.004;
|
||||
private const double MinStepSeconds = 0.005;
|
||||
|
||||
// Samples of the torch's path per cell; fewer leave some cells with more than others.
|
||||
@@ -55,7 +69,10 @@ namespace OpenNest.CNC.Thermal
|
||||
// back costs at most that much stepping, and share at most this much memory (temperature
|
||||
// and peak per cell); a long run on a large grid spaces them further apart.
|
||||
private const double CheckpointWork = 500_000;
|
||||
private const long CheckpointBytes = 32L << 20;
|
||||
private const long CheckpointBytes = 128L << 20;
|
||||
|
||||
// A cancellable run looks for a request this often.
|
||||
private const int CancelCheckSteps = 64;
|
||||
|
||||
// Going forward, a checkpoint this many steps past the current time beats stepping there.
|
||||
private const int SkipAheadSteps = 8;
|
||||
@@ -63,12 +80,12 @@ namespace OpenNest.CNC.Thermal
|
||||
// A rise below this is set to zero. The front of the spreading heat passes through
|
||||
// subnormal floats, which cost the processor about a hundred times a normal operation;
|
||||
// dropping them changes no cell above about 1e-18 K.
|
||||
private const float Negligible = 1e-30f;
|
||||
internal const float Negligible = 1e-30f;
|
||||
|
||||
// Grids this large split each step's cells across processors.
|
||||
private const int ParallelCells = 65_536;
|
||||
|
||||
private readonly List<Deposit> deposits = new();
|
||||
private readonly List<(double Time, HeatSample Sample)> deposits = new();
|
||||
private readonly List<PieceEvent> events = new();
|
||||
private readonly int[] region;
|
||||
private float[] temperature;
|
||||
@@ -78,10 +95,16 @@ namespace OpenNest.CNC.Thermal
|
||||
private readonly double lossRate;
|
||||
private readonly float[] contactFraction;
|
||||
private readonly double contactRate;
|
||||
private readonly float[] fullStepKeep;
|
||||
// Each cell's decay for a scheduled step, by the count its slot is split into.
|
||||
private readonly Dictionary<int, float[]> splitKeeps = new();
|
||||
private readonly float[] partialStepKeep;
|
||||
private double partialStepSeconds = -1;
|
||||
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;
|
||||
private readonly float[] belowLink;
|
||||
@@ -137,9 +160,8 @@ namespace OpenNest.CNC.Thermal
|
||||
diffusionRate = material.Diffusivity / (dx * dx);
|
||||
lossRate = 2 * parameters.SurfaceCoefficient / (volumetricHeat * thickness);
|
||||
maxStep = System.Math.Min(MaxStepSeconds, StabilityFactor / diffusionRate);
|
||||
var fastest = FastestCut(simulation);
|
||||
if (fastest > 0)
|
||||
maxStep = System.Math.Min(maxStep, System.Math.Max(MinStepSeconds, MaxTravelCells * cell / fastest));
|
||||
schedule = new HeatStepSchedule(simulation, maxStep, cell,
|
||||
dx < FineCellMeters ? FineTravelCells : MaxTravelCells, MinStepSeconds);
|
||||
|
||||
if (parameters.SupportBed != null && parameters.ContactCoefficient > 0)
|
||||
{
|
||||
@@ -149,19 +171,25 @@ namespace OpenNest.CNC.Thermal
|
||||
{
|
||||
// Through the bottom face only.
|
||||
contactRate = parameters.ContactCoefficient / (volumetricHeat * thickness);
|
||||
fullStepKeep = ContactKeep(maxStep, new float[count]);
|
||||
partialStepKeep = new float[count];
|
||||
}
|
||||
}
|
||||
|
||||
maxCheckpoints = (int)System.Math.Max(1, CheckpointBytes / (8L * count));
|
||||
var runSteps = System.Math.Ceiling(simulation.TotalTime.TotalSeconds / maxStep);
|
||||
var runSteps = (double)schedule.StepCount;
|
||||
checkpointInterval = (int)System.Math.Clamp(System.Math.Max(
|
||||
System.Math.Ceiling(CheckpointWork / count), System.Math.Ceiling(runSteps / maxCheckpoints)),
|
||||
1, int.MaxValue);
|
||||
|
||||
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);
|
||||
}
|
||||
Reset();
|
||||
}
|
||||
|
||||
@@ -185,10 +213,27 @@ 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 => temperature;
|
||||
public ReadOnlySpan<float> Temperatures
|
||||
{
|
||||
get
|
||||
{
|
||||
Synchronize();
|
||||
return temperature;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The highest rise each cell has reached so far.</summary>
|
||||
public ReadOnlySpan<float> Peaks => peak;
|
||||
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;
|
||||
|
||||
/// <summary>True when heat is also lost into the support bed (<see cref="ThermalParameters.SupportBed"/>).</summary>
|
||||
public bool UsesSupportBed => contactFraction != null;
|
||||
@@ -218,9 +263,9 @@ namespace OpenNest.CNC.Thermal
|
||||
/// <summary>
|
||||
/// Runs the model to <paramref name="target"/>. Going back in time, or far ahead, resumes
|
||||
/// from the latest checkpoint a straight run from the start would have passed, so the
|
||||
/// state is exactly that run's.
|
||||
/// state is exactly that run's. A cancelled run stops between two steps.
|
||||
/// </summary>
|
||||
public void AdvanceTo(TimeSpan target)
|
||||
public void AdvanceTo(TimeSpan target, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var seconds = target.TotalSeconds;
|
||||
var checkpoint = CheckpointBefore(seconds);
|
||||
@@ -236,35 +281,58 @@ namespace OpenNest.CNC.Thermal
|
||||
Restore(checkpoint);
|
||||
}
|
||||
|
||||
var taken = 0;
|
||||
while (time < seconds)
|
||||
{
|
||||
var step = System.Math.Min(maxStep, seconds - time);
|
||||
var previous = time;
|
||||
Step(step);
|
||||
if (step != maxStep)
|
||||
if (++taken % CancelCheckSteps == 0)
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var (boundary, split) = schedule.Next(time);
|
||||
var reaches = boundary <= seconds;
|
||||
var end = reaches ? boundary : seconds;
|
||||
// A whole scheduled step has exactly the nominal length, whatever the rounding
|
||||
// of its ends, so every run through it computes the same.
|
||||
var whole = reaches && onBoundary;
|
||||
Step(whole ? maxStep / split : end - time, end, whole ? split : 0);
|
||||
onBoundary = reaches;
|
||||
if (!whole)
|
||||
{
|
||||
straight = false;
|
||||
continue;
|
||||
}
|
||||
if (straight && ++straightSteps % checkpointInterval == 0)
|
||||
Record(previous);
|
||||
Record();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Runs the whole cut, then <paramref name="cooling"/> more.</summary>
|
||||
public void RunToEnd(TimeSpan cooling = default) => AdvanceTo(Simulation.TotalTime + cooling);
|
||||
public void RunToEnd(TimeSpan cooling = default, CancellationToken cancellationToken = default) =>
|
||||
AdvanceTo(Simulation.TotalTime + cooling, cancellationToken);
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
Array.Clear(temperature);
|
||||
Array.Clear(peak);
|
||||
ResetPieces();
|
||||
kernel?.Clear();
|
||||
stale = false;
|
||||
depositCursor = 0;
|
||||
time = 0;
|
||||
onBoundary = true;
|
||||
straight = true;
|
||||
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)
|
||||
{
|
||||
@@ -282,19 +350,21 @@ namespace OpenNest.CNC.Thermal
|
||||
}
|
||||
|
||||
// The finest cell, from the coarsest default halved down to the finest, whose whole run
|
||||
// (every cell, every diffusion-limited step) stays within the work budget. Halving the cell costs up
|
||||
// to sixteen times the work: four times the cells and, once diffusion limits the step,
|
||||
// four times the steps. The budget keeps the first run, which also sets the color scale,
|
||||
// short (going back resumes from a checkpoint); large sheets stay at the coarsest. The
|
||||
// torch travel limit is left out so that feed does not change the picture's resolution.
|
||||
// (every cell, every diffusion-limited step) stays within the work budget. Halving the cell
|
||||
// costs up to sixteen times the work: four times the cells and, once diffusion limits the
|
||||
// step, four times the steps. The budget keeps the first run, which also sets the color
|
||||
// scale, short (going back resumes from a checkpoint). The torch travel limit is left out
|
||||
// so that feed does not change the picture's resolution.
|
||||
internal static double AutomaticCellSize(Box bounds, double seconds, ThermalParameters parameters)
|
||||
{
|
||||
var coarsest = parameters.Units == Units.Millimeters ? 12 : 0.5;
|
||||
var budget = parameters.Accelerator == null ? WorkBudget : AcceleratedWorkBudget;
|
||||
var cell = coarsest;
|
||||
for (var halvings = 0; halvings < MaxHalvings; halvings++)
|
||||
{
|
||||
var finer = cell / 2;
|
||||
if (RunWork(bounds, seconds, finer, parameters) > WorkBudget)
|
||||
// Twelve millimeter halves to 3 mm, a little under an eighth inch.
|
||||
if (CellCount(bounds, finer) > MaxCells || RunWork(bounds, seconds, finer, parameters) > budget)
|
||||
break;
|
||||
cell = finer;
|
||||
}
|
||||
@@ -312,24 +382,45 @@ namespace OpenNest.CNC.Thermal
|
||||
(long)System.Math.Max(1, System.Math.Ceiling(bounds.Length / cell))
|
||||
* (long)System.Math.Max(1, System.Math.Ceiling(bounds.Width / cell));
|
||||
|
||||
private void Step(double seconds)
|
||||
// split names the scheduled step length, or is zero for a step cut short.
|
||||
private void Step(double seconds, double end, int split)
|
||||
{
|
||||
var end = time + seconds;
|
||||
var from = depositCursor;
|
||||
while (depositCursor < deposits.Count && deposits[depositCursor].Time <= end)
|
||||
depositCursor++;
|
||||
if (kernel == null)
|
||||
{
|
||||
Add(deposits[depositCursor++]);
|
||||
for (var i = from; i < depositCursor; i++)
|
||||
Add(deposits[i].Sample);
|
||||
}
|
||||
else if (depositCursor > from)
|
||||
{
|
||||
kernel.AddSamples(from, depositCursor);
|
||||
}
|
||||
while (eventCursor < events.Count && events[eventCursor].Time <= end)
|
||||
Apply(events[eventCursor]);
|
||||
|
||||
Diffuse(seconds);
|
||||
var share = (float)(diffusionRate * seconds);
|
||||
var keep = (float)System.Math.Exp(-lossRate * seconds);
|
||||
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;
|
||||
}
|
||||
time = end;
|
||||
}
|
||||
|
||||
// Shares a sample between the four cells whose centers surround the torch, by how close
|
||||
// it is to each, so heat moves smoothly across the grid with the torch. Only cells of
|
||||
// the piece under the torch take a share, which keeps heat from crossing a kerf.
|
||||
private void Add(Deposit deposit)
|
||||
private void Add(HeatSample deposit)
|
||||
{
|
||||
var piece = region[deposit.Cell];
|
||||
if (piece == Removed)
|
||||
@@ -359,14 +450,8 @@ namespace OpenNest.CNC.Thermal
|
||||
// (and for every link of a removed cell, which holds no heat), so the sum runs without
|
||||
// branches. A missing link adds a zero, leaving the sum exactly as if it were skipped,
|
||||
// which keeps the results bit for bit those of the cell-by-cell form.
|
||||
private void Diffuse(double seconds)
|
||||
private void Diffuse(float share, float keep, float[] cellKeep)
|
||||
{
|
||||
var share = (float)(diffusionRate * seconds);
|
||||
var keep = (float)System.Math.Exp(-lossRate * seconds);
|
||||
var cellKeep = contactFraction == null ? null
|
||||
: seconds == maxStep ? fullStepKeep
|
||||
: PartialStepKeep(seconds);
|
||||
|
||||
// Vectors cover the rows with a neighbor above and below; the first and last rows,
|
||||
// and any remainder, go cell by cell.
|
||||
var count = temperature.Length;
|
||||
@@ -460,8 +545,15 @@ namespace OpenNest.CNC.Thermal
|
||||
}
|
||||
|
||||
// Each cell's decay over one step: the air from both faces plus the bed under it. An
|
||||
// exponential factor stays stable however strong the contact. Most steps are full
|
||||
// length; playback ends each frame on a shorter one, kept until its length changes.
|
||||
// exponential factor stays stable however strong the contact. Most steps are scheduled
|
||||
// ones; playback ends each frame on a shorter one, kept until its length changes.
|
||||
private float[] SplitKeep(int split)
|
||||
{
|
||||
if (!splitKeeps.TryGetValue(split, out var keep))
|
||||
splitKeeps[split] = keep = ContactKeep(maxStep / split, new float[temperature.Length]);
|
||||
return keep;
|
||||
}
|
||||
|
||||
private float[] PartialStepKeep(double seconds)
|
||||
{
|
||||
if (seconds != partialStepSeconds)
|
||||
@@ -546,8 +638,51 @@ 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)
|
||||
{
|
||||
eventCursor++;
|
||||
@@ -582,6 +717,7 @@ namespace OpenNest.CNC.Thermal
|
||||
eventCursor = 0;
|
||||
nextRegion = 0;
|
||||
LinkAll();
|
||||
SendAll();
|
||||
}
|
||||
|
||||
private void LinkAll()
|
||||
@@ -616,25 +752,25 @@ namespace OpenNest.CNC.Thermal
|
||||
aboveLink[i] = alive && i + Columns < region.Length && region[i + Columns] == piece ? 1f : 0f;
|
||||
}
|
||||
|
||||
// Checkpoints: the state after every checkpointInterval full steps of a straight run from
|
||||
// Checkpoints: the state after every checkpointInterval steps of a straight run from
|
||||
// the start (one never cut short by an earlier target), kept as the run passes them. A
|
||||
// straight run to any later target takes exactly the same steps up to there.
|
||||
private void Record(double previousTime)
|
||||
private void Record()
|
||||
{
|
||||
var index = straightSteps / checkpointInterval - 1;
|
||||
if (index != checkpoints.Count || index >= maxCheckpoints)
|
||||
return;
|
||||
checkpoints.Add(new Checkpoint(time, previousTime, straightSteps, depositCursor, eventCursor,
|
||||
Synchronize();
|
||||
checkpoints.Add(new Checkpoint(time, straightSteps, depositCursor, eventCursor,
|
||||
(float[])temperature.Clone(), (float[])peak.Clone()));
|
||||
}
|
||||
|
||||
// The latest checkpoint a straight run to the target passes: its last step was a full
|
||||
// one, so the run had at least a full step left before it.
|
||||
// The latest checkpoint a straight run to the target passes.
|
||||
private Checkpoint CheckpointBefore(double seconds)
|
||||
{
|
||||
for (var i = checkpoints.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (seconds - checkpoints[i].PreviousTime >= maxStep)
|
||||
if (checkpoints[i].Time <= seconds)
|
||||
return checkpoints[i];
|
||||
}
|
||||
return null;
|
||||
@@ -653,12 +789,16 @@ 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;
|
||||
straight = true;
|
||||
straightSteps = checkpoint.StraightSteps;
|
||||
}
|
||||
@@ -705,20 +845,7 @@ namespace OpenNest.CNC.Thermal
|
||||
var y = System.Math.Clamp((point.Y - OriginY) / CellSize - 0.5, 0, Rows - 1);
|
||||
var left = (int)x;
|
||||
var lower = (int)y;
|
||||
deposits.Add(new Deposit(at, cell, left, lower, (float)(x - left), (float)(y - lower), (float)rise));
|
||||
}
|
||||
|
||||
// The highest average speed of any cutting move, in plate units per second.
|
||||
private static double FastestCut(CutSimulation simulation)
|
||||
{
|
||||
var fastest = 0.0;
|
||||
foreach (var step in simulation.Steps)
|
||||
{
|
||||
var seconds = step.Duration.TotalSeconds;
|
||||
if (step.Kind == CutSimulationStepKind.Cut && seconds > 0)
|
||||
fastest = System.Math.Max(fastest, step.Length / seconds);
|
||||
}
|
||||
return fastest;
|
||||
deposits.Add((at, new HeatSample(cell, left, lower, (float)(x - left), (float)(y - lower), (float)rise)));
|
||||
}
|
||||
|
||||
// Each closed contour changes the pieces when it finishes: a cutout drops its slug, an
|
||||
@@ -817,12 +944,7 @@ namespace OpenNest.CNC.Thermal
|
||||
return inside;
|
||||
}
|
||||
|
||||
// A sample of the torch's heat: the cell it is over, and its position between cell
|
||||
// centers (X and Y, 0 to 1, from column Left and row Lower).
|
||||
private readonly record struct Deposit(double Time, int Cell, int Left, int Lower,
|
||||
float X, float Y, float Rise);
|
||||
|
||||
private sealed record Checkpoint(double Time, double PreviousTime, int StraightSteps,
|
||||
private sealed record Checkpoint(double Time, int StraightSteps,
|
||||
int DepositCursor, int EventCursor, float[] Temperature, float[] Peak);
|
||||
|
||||
private sealed record PieceEvent(double Time, int[] Cells, bool IsCutout);
|
||||
|
||||
@@ -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.
|
||||
/// plates, short cuts and an <see cref="Accelerator"/> get finer cells.
|
||||
/// </summary>
|
||||
public double CellSize { get; init; }
|
||||
|
||||
@@ -63,6 +63,12 @@ namespace OpenNest.CNC.Thermal
|
||||
/// </summary>
|
||||
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; }
|
||||
|
||||
internal double MetersPerUnit => Units == Units.Millimeters ? 0.001 : 0.0254;
|
||||
|
||||
internal double EffectiveGridContactSize =>
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="OpenNest.Tests" />
|
||||
<InternalsVisibleTo Include="OpenNest.Engine" />
|
||||
<InternalsVisibleTo Include="OpenNest.Gpu" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Clipper2" Version="2.0.0" />
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
using OpenNest.CNC;
|
||||
using OpenNest.CNC.Thermal;
|
||||
using OpenNest.Desktop.Interaction;
|
||||
using OpenNest.Geometry;
|
||||
|
||||
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(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 80 in square: large enough to be accelerated.
|
||||
private static ThermalParameters Parameters(IHeatAccelerator? accelerator) => new()
|
||||
{
|
||||
Thickness = 0.25,
|
||||
Units = Units.Inches,
|
||||
CellSize = 0.25,
|
||||
Accelerator = accelerator,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void AFailingAcceleratorFallsBackToTheProcessor()
|
||||
{
|
||||
var (plate, simulation) = Job();
|
||||
var broken = new BrokenAccelerator();
|
||||
|
||||
using var estimate = HeatEstimate.Run(plate, simulation, Parameters!, broken);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ACancelledEstimateThrows()
|
||||
{
|
||||
var (plate, simulation) = Job();
|
||||
using var cancel = new CancellationTokenSource();
|
||||
cancel.Cancel();
|
||||
|
||||
Assert.Throws<OperationCanceledException>(
|
||||
() => HeatEstimate.Run(plate, simulation, Parameters!, null!, cancel.Token));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARebuiltTimelineWithTheSameMovesMatches()
|
||||
{
|
||||
var (_, first) = Job();
|
||||
var (_, again) = Job();
|
||||
var (_, moved) = Job(x: 6);
|
||||
|
||||
Assert.True(HeatEstimate.SameMoves(first, again));
|
||||
Assert.False(HeatEstimate.SameMoves(first, moved));
|
||||
Assert.False(HeatEstimate.SameMoves(first, null!));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using OpenNest.CNC;
|
||||
using OpenNest.CNC.Thermal;
|
||||
|
||||
namespace OpenNest.Desktop.Interaction;
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
{
|
||||
private HeatEstimate(PlateHeatSimulation heat, float scale, string device)
|
||||
{
|
||||
Heat = heat;
|
||||
Scale = scale;
|
||||
Device = device;
|
||||
}
|
||||
|
||||
/// <summary>The model, back at the start.</summary>
|
||||
public PlateHeatSimulation Heat { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The rise to color as hottest. Pierces leave single very hot cells, and scaling to them
|
||||
/// would wash out the areas where heat builds up, so this is the hottest half percent.
|
||||
/// </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 on the
|
||||
/// processor (with the coarser cells that suit it) 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,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (accelerator != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Run(plate, simulation, parameters(accelerator), accelerator.Name, 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);
|
||||
}
|
||||
|
||||
/// <summary>True when both timelines cut and travel the same, at the same times.</summary>
|
||||
public static bool SameMoves(CutSimulation a, CutSimulation b) =>
|
||||
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,
|
||||
string device, CancellationToken cancellationToken)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var heat = new PlateHeatSimulation(plate, simulation, parameters);
|
||||
try
|
||||
{
|
||||
heat.RunToEnd(cancellationToken: cancellationToken);
|
||||
var scale = ColorScale(heat);
|
||||
heat.Reset();
|
||||
return new HeatEstimate(heat, scale, heat.IsAccelerated ? device : null);
|
||||
}
|
||||
catch
|
||||
{
|
||||
heat.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static float ColorScale(PlateHeatSimulation heat)
|
||||
{
|
||||
var all = heat.Peaks;
|
||||
var peaks = new List<float>();
|
||||
for (var i = 0; i < all.Length; i++)
|
||||
{
|
||||
if (!heat.IsRemoved(i) && all[i] > 0)
|
||||
peaks.Add(all[i]);
|
||||
}
|
||||
peaks.Sort();
|
||||
return peaks.Count == 0 ? 1f : peaks[(int)(0.995 * (peaks.Count - 1))];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
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;
|
||||
|
||||
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 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<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>
|
||||
@@ -0,0 +1,144 @@
|
||||
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.
|
||||
private static (Plate Plate, CutSimulation Simulation, Func<IHeatAccelerator?, ThermalParameters> Thermal) Job(
|
||||
SupportBed? bed)
|
||||
{
|
||||
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(80, 80);
|
||||
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 80 in square are 102,400 cells, just 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,
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
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));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AcceleratorAllowsEighthInchCellsOnAFullSheet()
|
||||
{
|
||||
using var accelerator = GpuHeatAccelerator.Emulated();
|
||||
var p = new ThermalParameters
|
||||
{
|
||||
Material = ThermalMaterial.MildSteel,
|
||||
Thickness = 0.25,
|
||||
Units = Units.Inches,
|
||||
Accelerator = accelerator,
|
||||
};
|
||||
|
||||
Assert.Equal(0.125, PlateHeatSimulation.AutomaticCellSize(new Box(0, 0, 120, 60), 3600, p));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SmallGridsStayOnTheProcessor()
|
||||
{
|
||||
using var accelerator = GpuHeatAccelerator.Emulated();
|
||||
var (plate, simulation, _) = Job(null);
|
||||
using var heat = new PlateHeatSimulation(plate, simulation, new ThermalParameters
|
||||
{
|
||||
Thickness = 0.25,
|
||||
Units = Units.Inches,
|
||||
CellSize = 0.5,
|
||||
Accelerator = accelerator,
|
||||
});
|
||||
|
||||
Assert.False(heat.IsAccelerated);
|
||||
}
|
||||
|
||||
[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());
|
||||
}
|
||||
}
|
||||
@@ -140,16 +140,50 @@ public class PlateHeatSimulationTests
|
||||
Assert.Equal(0.5 / 8, Automatic(plate).CellSize);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LargePlateWithALongCutKeepsHalfInchCells()
|
||||
// A 5x10 sheet of eight 25 in squares: about half an hour of cutting.
|
||||
private static Plate FullSheet()
|
||||
{
|
||||
var plate = new Plate(60, 120);
|
||||
var drawing = new Drawing("part", Square(25));
|
||||
for (var x = 0; x < 2; x++)
|
||||
for (var y = 0; y < 4; y++)
|
||||
plate.Parts.Add(new Part(drawing, new Vector(2 + x * 28, 2 + y * 28)));
|
||||
return plate;
|
||||
}
|
||||
|
||||
Assert.Equal(0.5, Automatic(plate).CellSize);
|
||||
[Fact]
|
||||
public void FullSheetGetsQuarterInchCells() => Assert.Equal(0.25, Automatic(FullSheet()).CellSize);
|
||||
|
||||
[Fact]
|
||||
public void FullSheetWithAVeryLongCutKeepsHalfInchCells()
|
||||
{
|
||||
var p = new ThermalParameters { Material = ThermalMaterial.Aluminum, Thickness = 0.25, Units = Units.Inches };
|
||||
|
||||
Assert.Equal(0.5, PlateHeatSimulation.AutomaticCellSize(new Box(0, 0, 120, 60), 40_000, p));
|
||||
}
|
||||
|
||||
// Half an inch past the budget, a run is cut into longer steps than the torch needs.
|
||||
[Fact]
|
||||
public void OnlyCuttingTimeTakesShortSteps()
|
||||
{
|
||||
var (_, simulation) = Cut(Line(20), new Vector(10, 80));
|
||||
var cut = simulation.Steps.Where(s => s.Kind == CutSimulationStepKind.Cut).ToArray();
|
||||
var from = cut[0].StartTime.TotalSeconds;
|
||||
var to = cut[^1].EndTime.TotalSeconds;
|
||||
// 100 in/min crosses 0.25 in cells in 0.15 s.
|
||||
var schedule = new HeatStepSchedule(simulation, 0.6, 0.25, 1, 0.005);
|
||||
|
||||
var time = 0.0;
|
||||
while (time < simulation.TotalTime.TotalSeconds)
|
||||
{
|
||||
var (next, split) = schedule.Next(time);
|
||||
Assert.True(next > time);
|
||||
if (time >= from && next <= to)
|
||||
Assert.True(next - time <= 0.15 + 1e-9, $"{next - time} s step while cutting");
|
||||
if (next <= from - 0.6 || time >= to + 0.6)
|
||||
Assert.Equal(1, split);
|
||||
time = next;
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -173,10 +207,13 @@ public class PlateHeatSimulationTests
|
||||
|
||||
// Feeds that cross a whole and a fractional number of cells per diffusion-limited step.
|
||||
[Theory]
|
||||
[InlineData(47)]
|
||||
[InlineData(97)]
|
||||
[InlineData(283)]
|
||||
public void AStraightCutPeaksEvenlyAlongItsLength(double feedrate)
|
||||
[InlineData(47, 0.25)]
|
||||
[InlineData(97, 0.25)]
|
||||
[InlineData(283, 0.25)]
|
||||
[InlineData(47, 0.125)]
|
||||
[InlineData(97, 0.125)]
|
||||
[InlineData(283, 0.125)]
|
||||
public void AStraightCutPeaksEvenlyAlongItsLength(double feedrate, double cell)
|
||||
{
|
||||
var plate = new Plate(48, 96);
|
||||
plate.Parts.Add(new Part(new Drawing("part", Line(23.7)), new Vector(10.03, 10.31)));
|
||||
@@ -191,14 +228,14 @@ public class PlateHeatSimulationTests
|
||||
Material = ThermalMaterial.MildSteel,
|
||||
Thickness = 0.135,
|
||||
Units = Units.Inches,
|
||||
CellSize = 0.25,
|
||||
CellSize = cell,
|
||||
});
|
||||
|
||||
heat.RunToEnd(TimeSpan.FromSeconds(10));
|
||||
|
||||
// The middle of the cut, clear of the warm-up and the end.
|
||||
var peaks = new List<float>();
|
||||
for (var x = 18.125; x < 28; x += 0.25)
|
||||
for (var x = 18 + cell / 2; x < 28; x += cell)
|
||||
peaks.Add(heat.Peaks[heat.CellAt(new Vector(x, 10.31))]);
|
||||
var ripple = (peaks.Max() - peaks.Min()) / peaks.Average();
|
||||
Assert.True(ripple < 0.1, $"peaks vary {ripple:P0} along the cut");
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
<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" />
|
||||
|
||||
@@ -102,6 +102,44 @@ public class CutSimulatorFormTests
|
||||
}
|
||||
});
|
||||
|
||||
[Fact]
|
||||
public void TheHeatLayerAppearsOnceItsBackgroundRunFinishes() => RunSta(() =>
|
||||
{
|
||||
using var editor = Editor();
|
||||
editor.Nest.Thickness = 0.135;
|
||||
editor.Show();
|
||||
editor.PlateManager.LoadAt(0);
|
||||
editor.SimulateCutting();
|
||||
var simulator = (CutSimulatorForm)typeof(EditNestForm)
|
||||
.GetField("cutSimulatorForm", BindingFlags.Instance | BindingFlags.NonPublic)!
|
||||
.GetValue(editor)!;
|
||||
try
|
||||
{
|
||||
Field<ComboBox>(simulator, "heatBox").SelectedIndex = 1;
|
||||
var overlay = editor.PlateView.CutSimulation;
|
||||
var label = Field<Label>(simulator, "heatLabel");
|
||||
var wait = System.Diagnostics.Stopwatch.StartNew();
|
||||
while (overlay.Heat == null && wait.Elapsed < TimeSpan.FromSeconds(20))
|
||||
{
|
||||
Application.DoEvents();
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
|
||||
Assert.NotNull(overlay.Heat);
|
||||
Assert.StartsWith("Hottest", label.Text);
|
||||
|
||||
// A rebuilt timeline with the same moves shows the same model at once.
|
||||
var shown = overlay.Heat;
|
||||
typeof(CutSimulatorForm).GetMethod("Rebuild", BindingFlags.Instance | BindingFlags.NonPublic)!
|
||||
.Invoke(simulator, null);
|
||||
Assert.Same(shown, overlay.Heat);
|
||||
}
|
||||
finally
|
||||
{
|
||||
simulator.Close();
|
||||
}
|
||||
});
|
||||
|
||||
// Everything needed to tell which column grew, and whether the measurement or the layout moved.
|
||||
private static string DescribeLayout(TabControl tabs, TabPage page)
|
||||
{
|
||||
|
||||
@@ -58,6 +58,8 @@ 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
|
||||
@@ -368,6 +370,18 @@ 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
|
||||
|
||||
@@ -124,6 +124,35 @@ 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>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
public HeatView HeatMode
|
||||
{
|
||||
get => heatMode;
|
||||
@@ -293,17 +322,17 @@ internal sealed class CutSimulationOverlay : IDisposable
|
||||
// One image pixel per model cell, stretched over the plate with smoothing.
|
||||
private void DrawHeat(Graphics graphics, TimeSpan time)
|
||||
{
|
||||
if (heat == null || heatMode == HeatView.Off)
|
||||
if (heat == null || heatMode == HeatView.Off || !AdvanceHeat(time))
|
||||
return;
|
||||
|
||||
heat.AdvanceTo(time);
|
||||
var values = heatMode == HeatView.Peak ? heat.Peaks : heat.Temperatures;
|
||||
var columns = heat.Columns;
|
||||
var rows = heat.Rows;
|
||||
// Premultiplied pixels draw several times faster, which a fine grid needs.
|
||||
if (heatImage == null || heatImage.Width != columns || heatImage.Height != rows)
|
||||
{
|
||||
heatImage?.Dispose();
|
||||
heatImage = new Bitmap(columns, rows, PixelFormat.Format32bppArgb);
|
||||
heatImage = new Bitmap(columns, rows, PixelFormat.Format32bppPArgb);
|
||||
}
|
||||
|
||||
var pixels = new int[columns * rows];
|
||||
@@ -314,10 +343,10 @@ internal sealed class CutSimulationOverlay : IDisposable
|
||||
for (var column = 0; column < columns; column++)
|
||||
{
|
||||
var cell = row * columns + column;
|
||||
pixels[line + column] = heat.IsRemoved(cell) ? 0 : HeatColor(values[cell] / heatScale);
|
||||
pixels[line + column] = heat.IsRemoved(cell) ? 0 : PremultipliedHeatColor(values[cell] / heatScale);
|
||||
}
|
||||
}
|
||||
var data = heatImage.LockBits(new Rectangle(0, 0, columns, rows), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
|
||||
var data = heatImage.LockBits(new Rectangle(0, 0, columns, rows), ImageLockMode.WriteOnly, PixelFormat.Format32bppPArgb);
|
||||
try
|
||||
{
|
||||
System.Runtime.InteropServices.Marshal.Copy(pixels, 0, data.Scan0, pixels.Length);
|
||||
@@ -432,6 +461,27 @@ internal sealed class CutSimulationOverlay : IDisposable
|
||||
(1f, Color.FromArgb(220, 0, 0)),
|
||||
};
|
||||
|
||||
// HeatColor premultiplied, in steps too fine to see: working it out per cell is too slow
|
||||
// for a fine grid redrawn every frame.
|
||||
private const int HeatShades = 1024;
|
||||
|
||||
private static readonly int[] Shades = BuildShades();
|
||||
|
||||
private static int PremultipliedHeatColor(float fraction) =>
|
||||
fraction > 0 ? Shades[(int)(System.Math.Min(1f, fraction) * (HeatShades - 1))] : 0;
|
||||
|
||||
private static int[] BuildShades()
|
||||
{
|
||||
var shades = new int[HeatShades];
|
||||
for (var i = 0; i < HeatShades; i++)
|
||||
{
|
||||
var color = Color.FromArgb(HeatColor((float)i / (HeatShades - 1)));
|
||||
shades[i] = Color.FromArgb(color.A, color.R * color.A / 255, color.G * color.A / 255,
|
||||
color.B * color.A / 255).ToArgb();
|
||||
}
|
||||
return shades;
|
||||
}
|
||||
|
||||
// Cool cells fade out so the plate shows through; hotter ones turn opaque and red.
|
||||
internal static int HeatColor(float fraction)
|
||||
{
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using OpenNest.CNC;
|
||||
using OpenNest.CNC.Thermal;
|
||||
@@ -8,6 +10,7 @@ using OpenNest.Controls;
|
||||
using OpenNest.Data;
|
||||
using OpenNest.Desktop;
|
||||
using OpenNest.Desktop.Interaction;
|
||||
using OpenNest.Gpu;
|
||||
using OpenNest.Support;
|
||||
using NumericUpDown = OpenNest.Controls.NumericUpDown;
|
||||
|
||||
@@ -44,6 +47,12 @@ namespace OpenNest.Forms
|
||||
private Plate plate;
|
||||
private bool updatingTrack;
|
||||
private bool rebuildQueued;
|
||||
private readonly ToolTip tips;
|
||||
// The heat model shown, kept to show again when a rebuilt timeline has the same moves.
|
||||
private HeatEstimate heatEstimate;
|
||||
private HeatInput heatInput;
|
||||
private CancellationTokenSource heatRun;
|
||||
private bool acceleratorFailed;
|
||||
|
||||
public CutSimulatorForm(EditNestForm nestForm)
|
||||
{
|
||||
@@ -208,7 +217,7 @@ namespace OpenNest.Forms
|
||||
};
|
||||
heatPowerBox.ValueChanged += (_, _) => Rebuild();
|
||||
|
||||
var tips = new ToolTip();
|
||||
tips = new ToolTip();
|
||||
tips.SetToolTip(restartButton, "Restart");
|
||||
tips.SetToolTip(playButton, "Play / pause (Space)");
|
||||
tips.SetToolTip(endButton, "Jump to end");
|
||||
@@ -226,6 +235,7 @@ 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);
|
||||
@@ -364,10 +374,17 @@ namespace OpenNest.Forms
|
||||
LoadHeat();
|
||||
}
|
||||
|
||||
// The colors are scaled to the hottest any cell gets over the whole cut.
|
||||
// Everything the model is built from, apart from the timeline.
|
||||
private sealed record HeatInput(double Length, double Width, int Quadrant, ThermalMaterial Material,
|
||||
double Thickness, Units Units, double Power, SupportBed SupportBed);
|
||||
|
||||
// Runs the whole cut off the UI thread to color the layer, then shows it.
|
||||
private void LoadHeat()
|
||||
{
|
||||
heatRun?.Cancel();
|
||||
heatRun = null;
|
||||
heatLabel.Text = "";
|
||||
tips.SetToolTip(heatLabel, null);
|
||||
if (heatBox.SelectedIndex == 0 || overlay.Simulation == null)
|
||||
return;
|
||||
|
||||
@@ -378,34 +395,93 @@ namespace OpenNest.Forms
|
||||
return;
|
||||
}
|
||||
|
||||
var material = ThermalMaterial.ForName($"{nest.Material?.Name} {nest.Material?.Grade}");
|
||||
var heat = new PlateHeatSimulation(plate, overlay.Simulation, new ThermalParameters
|
||||
var bounds = plate.BoundingBox(includeParts: false);
|
||||
var input = new HeatInput(bounds.Length, bounds.Width, plate.Quadrant,
|
||||
ThermalMaterial.ForName($"{nest.Material?.Name} {nest.Material?.Grade}"),
|
||||
nest.Thickness, nest.Units, (double)heatPowerBox.Value, plate.SupportBed);
|
||||
if (input == heatInput && HeatEstimate.SameMoves(heatEstimate.Heat.Simulation, overlay.Simulation))
|
||||
{
|
||||
Material = material,
|
||||
Thickness = nest.Thickness,
|
||||
Units = nest.Units,
|
||||
AbsorbedPower = (double)heatPowerBox.Value,
|
||||
SupportBed = plate.SupportBed,
|
||||
});
|
||||
heat.RunToEnd();
|
||||
// Pierces leave single very hot cells; scaling to them would wash out the areas
|
||||
// where heat builds up, so red is the hottest half percent of the sheet instead.
|
||||
var peaks = new List<float>();
|
||||
for (var i = 0; i < heat.Peaks.Length; i++)
|
||||
{
|
||||
if (!heat.IsRemoved(i) && heat.Peaks[i] > 0)
|
||||
peaks.Add(heat.Peaks[i]);
|
||||
ShowHeat();
|
||||
return;
|
||||
}
|
||||
peaks.Sort();
|
||||
var scale = peaks.Count == 0 ? 1f : peaks[(int)(0.995 * (peaks.Count - 1))];
|
||||
heat.Reset();
|
||||
overlay.LoadHeat(heat, scale);
|
||||
|
||||
ReleaseHeat();
|
||||
heatLabel.Text = "Estimating heat…";
|
||||
heatRun = new CancellationTokenSource();
|
||||
EstimateHeat(plate, overlay.Simulation, input, !acceleratorFailed, heatRun.Token);
|
||||
}
|
||||
|
||||
private async void EstimateHeat(Plate subject, CutSimulation simulation, HeatInput input,
|
||||
bool accelerate, CancellationToken cancellationToken)
|
||||
{
|
||||
HeatEstimate estimate;
|
||||
try
|
||||
{
|
||||
// Finding the graphics card takes a moment the first time, so that waits here too.
|
||||
estimate = await Task.Run(() => HeatEstimate.Run(subject, simulation,
|
||||
accelerator => new ThermalParameters
|
||||
{
|
||||
Material = input.Material,
|
||||
Thickness = input.Thickness,
|
||||
Units = input.Units,
|
||||
AbsorbedPower = input.Power,
|
||||
SupportBed = input.SupportBed,
|
||||
Accelerator = accelerator,
|
||||
},
|
||||
accelerate ? GpuHeatAccelerator.Default : null, cancellationToken), cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (!cancellationToken.IsCancellationRequested && !IsDisposed)
|
||||
heatLabel.Text = $"Could not estimate heat: {ex.Message}";
|
||||
return;
|
||||
}
|
||||
|
||||
// A newer run, or a closed window, makes this one worthless.
|
||||
if (cancellationToken.IsCancellationRequested || IsDisposed)
|
||||
{
|
||||
estimate.Dispose();
|
||||
return;
|
||||
}
|
||||
heatEstimate = estimate;
|
||||
heatInput = input;
|
||||
ShowHeat();
|
||||
}
|
||||
|
||||
private void ShowHeat()
|
||||
{
|
||||
var heat = heatEstimate.Heat;
|
||||
overlay.LoadHeat(heat, heatEstimate.Scale);
|
||||
var cooling = !heat.UsesSupportBed ? "cooled by air only (no support bed)"
|
||||
: plate.SupportBed is SupportSlats ? "cooled by air and slats" : "cooled by air and the support grid";
|
||||
heatScaleText = $"{material.Name}, {cooling}; red is {scale:0} °C above ambient";
|
||||
: 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"));
|
||||
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.
|
||||
@@ -414,14 +490,15 @@ namespace OpenNest.Forms
|
||||
|
||||
private void UpdateHeatLabel(bool force = false)
|
||||
{
|
||||
var heat = overlay.Heat;
|
||||
if (heat == null || heatBox.SelectedIndex == 0)
|
||||
if (overlay.Heat == null || heatBox.SelectedIndex == 0)
|
||||
return;
|
||||
var now = Environment.TickCount64;
|
||||
if (!force && overlay.IsPlaying && now - heatLabelUpdatedAt < HeatLabelIntervalMs)
|
||||
return;
|
||||
heatLabelUpdatedAt = now;
|
||||
heat.AdvanceTo(overlay.Time);
|
||||
if (!overlay.AdvanceHeat(overlay.Time))
|
||||
return;
|
||||
var heat = overlay.Heat;
|
||||
var values = heatBox.SelectedIndex == 2 ? heat.Peaks : heat.Temperatures;
|
||||
var hottest = PlateHeatSimulation.IndexOfMax(values);
|
||||
var hottestNow = hottest < 0 ? 0 : values[hottest];
|
||||
@@ -554,6 +631,8 @@ namespace OpenNest.Forms
|
||||
SavedCutParameters.Save(GetCutParameters());
|
||||
|
||||
overlay.Changed -= Overlay_Changed;
|
||||
overlay.HeatFailed -= Overlay_HeatFailed;
|
||||
heatRun?.Cancel();
|
||||
nestForm.PlateChanged -= NestForm_PlateChanged;
|
||||
nestForm.FormClosed -= NestForm_FormClosed;
|
||||
AttachPlate(null);
|
||||
@@ -562,6 +641,7 @@ namespace OpenNest.Forms
|
||||
overlay.Clear();
|
||||
nestForm.PlateView.InspectionCloseRequested = null;
|
||||
}
|
||||
ReleaseHeat();
|
||||
|
||||
base.OnFormClosed(e);
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
<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" />
|
||||
|
||||
@@ -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. 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. 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).
|
||||
- **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
|
||||
|
||||
+50
-23
@@ -9,25 +9,29 @@ a removed heat-aware sequencer used a cheaper estimate of the same physics ([Seq
|
||||
|
||||
- A grid over the plate's bounds. Unless `CellSize` is set, cells start at 0.5 in (12 mm) and
|
||||
halve, down to 1/16 in (1.5 mm), while the whole run (cells times diffusion-limited time steps)
|
||||
stays within 60 million cell updates. Halving costs up to sixteen times
|
||||
the work, since diffusion shortens the time step with the cell's area, so small plates and short
|
||||
cuts get fine cells and full sheets keep 0.5 in. Any size is made coarser on sheets that would
|
||||
need more than 400,000 cells. 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.
|
||||
stays within a work budget: 800 million cell updates on the processor, about a second, which
|
||||
gives a 5×10 ft sheet 0.25 in cells; 20 billion with an [accelerator](#graphics-card), which
|
||||
gives it 0.125 in cells. Halving costs up to sixteen times the work, since diffusion shortens the
|
||||
time step with the cell's area, so small plates and short cuts get finer cells and long cuts
|
||||
coarser ones. 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, so on one
|
||||
kind of hardware.
|
||||
- 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
|
||||
those in the same piece as the cell under the torch. Scribes add nothing.
|
||||
- Conduction: explicit finite differences between the four neighbors of the same piece, with the
|
||||
time step kept below the stability limit and at most 1 s, and no longer than the torch takes to
|
||||
cross one cell at its fastest cutting move (but not below 5 ms for that). A step adds its heat
|
||||
all at once, so a longer one shows stripes along a straight cut. This limit does not enter the
|
||||
choice of cell size, so a fast feed can take a few times longer to run (about 0.3 s in the
|
||||
worst case measured). Sheet edges 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.
|
||||
- Conduction: explicit finite differences between the four neighbors of the same piece. Time is
|
||||
divided into slots as long as the stability limit allows (at most 1 s). A slot in which the torch
|
||||
cuts is split into equal steps, so that none is longer than the torch takes to cross one cell at
|
||||
that move's speed (half a cell where cells are under 4 mm), but not shorter than 5 ms for that.
|
||||
A step adds its heat all at once, so a longer one shows stripes along a straight cut; rapids and
|
||||
pierces keep the long steps (`HeatStepSchedule`). Splits come from a short list of counts, and
|
||||
the boundaries depend on the timeline alone, so a replay takes the same steps. This limit does
|
||||
not enter the choice of cell size, so a fast feed can take a few times longer to run. Sheet edges
|
||||
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.
|
||||
- Loss: convection from both faces at `SurfaceCoefficient` (W/m²·K), plus, when
|
||||
`ThermalParameters.SupportBed` is given, contact with the bed through the bottom face at
|
||||
`ContactCoefficient` (W/m²·K) times each cell's share of area over the bed. The share is the
|
||||
@@ -63,19 +67,42 @@ Each step runs a vector of cells at a time, with the links between neighbors of
|
||||
precomputed as 1 or 0 whenever the pieces change; grids of 65,536 cells or more split each
|
||||
step across processors. Neither changes a result bit.
|
||||
|
||||
A straight run from the start (one never stopped short of a full step) keeps checkpoints of the
|
||||
temperatures, peaks and event cursors, about every 500,000 cell updates and within 32 MB, more
|
||||
widely spaced on large grids. The simulator's first run to the end, made to set the color
|
||||
A straight run from the start (one never stopped short of a scheduled step) keeps checkpoints of
|
||||
the temperatures, peaks and event cursors, about every 500,000 cell updates and within 128 MB,
|
||||
more widely spaced on large grids. The simulator's first run to the end, made to set the color
|
||||
scale, lays them down. Going back in time, or more than eight steps ahead, resumes from the
|
||||
latest checkpoint that a straight run to the target passes, so a seek steps through at most one
|
||||
checkpoint's interval (about a millisecond on a small plate) instead of the whole run, and gives
|
||||
exactly the state a straight run from the start gives. The pieces are rebuilt from the event
|
||||
cursor rather than stored. Playing forward frame by frame continues from the current state, as
|
||||
before.
|
||||
checkpoint's interval instead of the whole run, and gives exactly the state a straight run from
|
||||
the start gives. The pieces are rebuilt from the event cursor rather than stored. Playing forward
|
||||
frame by frame continues from the current state.
|
||||
|
||||
The simulator builds and runs the model off the UI thread (`HeatEstimate`) and shows
|
||||
"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
|
||||
|
||||
`ThermalParameters.Accelerator` runs grids of 100,000 cells or more elsewhere; smaller ones stay
|
||||
on the processor, as a card takes longer to start each step than such a step takes. `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 with the cell size that suits it.
|
||||
|
||||
The simulation keeps the pieces, timeline and checkpoints and the card keeps the temperatures.
|
||||
Its results are not bit for bit the processor's (devices may fuse a multiply and an add): measured
|
||||
within one part in a million. The processor stays the reference. `GpuHeatAcceleratorTests`
|
||||
compares the two 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, two 5×10 ft nests, 100 and 400 in/min: 0.125 in
|
||||
cells took 9-23 s on the processor and 0.8-1.6 s on the card with the previous step schedule,
|
||||
which took more steps than this one.
|
||||
|
||||
## Display
|
||||
|
||||
The simulator colors the field against the 99.5th percentile of the whole cut's peaks: a pierce
|
||||
The tooltip on the heat label names the cell size and the hardware. The simulator colors the field against the 99.5th percentile of the whole cut's peaks: a pierce
|
||||
puts its energy into a single cell, and scaling to that cell would hide the areas where heat
|
||||
builds up. Cells whose slug fell away are transparent. Cool cells are translucent, so while the
|
||||
layer shows, every cut or cutting part is filled with one neutral gray set apart from the sheet
|
||||
|
||||
Reference in new issue
Block a user