Skip to content

Interactive 2D wave optics simulator. Turn any image into a refractive scene, add sources, watch waves refract, diffract and interfere. Probes, intensity maps, video export.

C#

The scratch runner keeps its engine across a scene edit of the same grid: TryReplaceScene re-uploads the scene

Alexander Graef7569808d5fa3
diff --git a/CLAUDE.md b/CLAUDE.md
index 6eb3946..cbf15a3 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -137,7 +137,11 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDA
.NET-pinned array is pageable to the driver, which drained the queue and copied on the stepping thread inside the
"non-blocking" enqueue, 2.9 of a full-HD frame's 2.96 ms (the old note blamed the single queue: a second queue alone
changed nothing). The scratch runner's snapshots stay ordinary, since a result outlives its engine;
- `Reset`, `SetEmitters`, `SetProbes`. Numerics are Jeroen's (dx = dt = 1, leapfrog, 9-point or 4th-order
+ `Reset`, `SetEmitters`, `SetProbes`, `TryReplaceScene` (another scene of the same grid, edges and image-source count
+ swapped into the kept engine: the GPU re-uploads c², damping and the source tables into its buffers and keeps the
+ compiled program, the sub-steps re-derived; 2026-11-03, the user's choice: the scratch runner uses it, 55 ms for
+ Example 16 against the 180–350 ms OpenCL build every part edit had cost; `library_check` proves a replaced engine
+ steps like a fresh one on both engines). Numerics are Jeroen's (dx = dt = 1, leapfrog, 9-point or 4th-order
Laplacian, soft sources, EMA intensity; a scene pixel with red 0 is a mirror, n = 1000, his V0.30 rule,
2026-10-18), verified CPU = GPU by the harness; seeds from `Pcg32` make CPU = GPU
bit for bit on random gaps. A source's frequency level, amplitude and phase take decimals (2026-10-19, Jeroen's point 10); the
@@ -186,7 +190,9 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDA
## The app's rules
- **Live editing**: a simulation edit (scene, solver, seed, sources) marks the run stale, **stops playback and any
- active run**, requests a scratch frame for the position (120 ms debounce) and re-runs automatically after 1.5 s
+ active run**, requests a scratch frame for the position (120 ms debounce; the scratch runner keeps its engine across a
+ scene edit of the same grid, `TryReplaceScene`, and rebuilds only for another grid, edges or options) and re-runs
+ automatically after 1.5 s
of quiet (setting, default on); an automatic run never moves the preview. A probe edit never starts a run: only
the recordings are stale, the scratch frame refreshes the graph; except that an active probe the run does not
record (switched on, added) is a simulation edit (2026-10-18). No scratch frame while playback runs. Any run
@@ -441,13 +447,19 @@ Example 7 (2880×1080 in a 458×172 picture, both layers, playing): 16-bit 7.3
10–11 (its bitmaps are canvas-sized). Presenter about 7 ms a frame quiet, 20 during a run. JPEG 1080p at 4:4:4: WIC 26 ms a frame
single-threaded (9 ms a frame in a sequence job on half the cores), in-house 9.8 ms on ten cores (15 in a job);
MP4 job 16 ms a frame. Part painter on a Full HD canvas (ten cores): a 400 × 330 outline 30 ms, a 400 px lens 5, a hexagon 8, an S-bent fibre across the canvas 51 (156 chords on the cell grid; 1.3 s without it);
-the glowing edges 22 ms; the preview's scene pictures about 100 ms more, so the scene rebuild is coalesced at background priority. Laptop (2 cores, HD 520, HDD): iGPU 4.3 ms a step against CPU 14.7; the ball
+the glowing edges 22 ms; the preview's scene pictures about 100 ms more, so the scene rebuild is coalesced at background priority.
+**Dragging a part is choppy because of that composition** (2026-11-03, the log of a drag in Example 16: every coalesced
+update repaints all four rectangles, one the whole canvas, "composed in 115–270 ms" on the UI thread, then 20–30 ms of
+pictures; the painter spends 35–60 ns a pixel on ten cores even on a plain rectangle); the remedies on the table are a
+worker thread with a snapshot of the parts (`OpticalPart.Clone` copies the point and node lists), a faster painter
+(profile first), or no repaint while the mouse button is held; not an incremental painter, since a coating's band rises
+from the index beneath it. Laptop (2 cores, HD 520, HDD): iGPU 4.3 ms a step against CPU 14.7; the ball
lens run 105 s full quality (disk-bound), 61 s at half resolution with every second frame, in RAM. Settled by these
numbers: no GPU JPEG, no OpenCL colouring at presentation, no `Vector256`, no Direct3D display path.
## Harnesses
-`library_check` (100+ checks: engines, store, renderer, half tables, screen path, schemes, probes, scratch, reduced preview, importer, export, parts, group move, open edges, work groups on a prime grid, ranges, XOR gate, zone plate, gate port follower, history, clipboard, the project file's DTD, the first start's tiers, the engine's page-locked snapshots).
+`library_check` (100+ checks: engines, store, renderer, half tables, screen path, schemes, probes, scratch, reduced preview, importer, export, parts, group move, open edges, work groups on a prime grid, ranges, XOR gate, zone plate, gate port follower, history, clipboard, the project file's DTD, the first start's tiers, the engine's page-locked snapshots, scene replacement).
UI, all on `Common.ps1`, with their check counts: `PreviewCheck` 43, `RunCheck` 71, `LanguageCheck` 11,
`ProbeGraphCheck` 39, `ImportCheck` 10, `ExportCheck` 44, `PreviewQualityCheck` 35, `SceneImageCheck` 8,
`ColorPickerCheck` 13, `KeyboardCheck` 13, `AboutCheck` 18, `SelectionCheck` 10. Test projects `tiny*.wdproj` sit beside them. The
diff --git a/WaveDudeNext/Engine/GpuWaveSimulator.cs b/WaveDudeNext/Engine/GpuWaveSimulator.cs
index 04ffea4..a4a9958 100644
--- a/WaveDudeNext/Engine/GpuWaveSimulator.cs
+++ b/WaveDudeNext/Engine/GpuWaveSimulator.cs
@@ -147,6 +147,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
_stride = _width + 2;
_cells = _stride * (_height + 2);
_track = options.TrackIntensity;
+ _fourthOrder = options.FourthOrderLaplacian;
_sourceCount = scene.SourceCount;
if (device.MaxAllocation > 0L && (long)_cells * 4L > device.MaxAllocation)
{
@@ -386,6 +387,84 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
OpenClApi.Check(OpenClApi.clEnqueueWriteBufferFloat(_queue, buffer, 1U, IntPtr.Zero, new IntPtr((long)count * 4L), data, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueWriteBuffer (reset)");
}
+ /// <inheritdoc/>
+ public bool TryReplaceScene(SceneData scene)
+ {
+ if (scene.Width != _width || scene.Height != _height || scene.Rim != _rim || scene.OpenEdges != _openEdges || scene.SourceCount != _sourceCount)
+ {
+ return false;
+ }
+ OpenClApi.Check(OpenClApi.clFinish(_queue), "clFinish");
+ (float[] c2, float[] damping, float c2Mult) = SceneMaps(scene);
+ Upload(_c2Buffer, c2, _cells);
+ Upload(_dBuffer, damping, _cells);
+ for (int k = 0; k <= 1; k++)
+ {
+ SetFloat(_stepKernel[k], 9U, c2Mult);
+ if (_openEdges)
+ {
+ SetFloat(_edgeKernel[k], 6U, c2Mult);
+ }
+ }
+ (int[] indices, int[] levels) = SourceTables(scene);
+ if (_sourceCount > 0)
+ {
+ OpenClApi.Check(OpenClApi.clEnqueueWriteBufferInt(_queue, _sourceIndexBuffer, 1U, IntPtr.Zero, new IntPtr((long)_sourceCount * 4L), indices, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueWriteBuffer (source indices)");
+ OpenClApi.Check(OpenClApi.clEnqueueWriteBufferInt(_queue, _sourceLevelBuffer, 1U, IntPtr.Zero, new IntPtr((long)_sourceCount * 4L), levels, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueWriteBuffer (source levels)");
+ }
+ // Reset re-derives the intensity constant from the levels now in use, through SetEmitters
+ Reset();
+ Logger.Debug("Scene replaced on {Device}: {Stencil}", _device.Name, WaveSimulator.StencilText(_fourthOrder, _subSteps));
+ return true;
+ }
+
+ /// <summary>
+ /// The scene's per-cell maps in the padded layout (a border of one cell, like the CPU engine), with the sub-steps
+ /// (<see cref="_subSteps"/>, set here) and their corrections: sub-stepping keeps the 4th-order stencil stable without
+ /// changing the physical wave speed or damping, and stays at 1 unless the stencil is in use and this scene's highest
+ /// c² needs it. The damping is pre-scaled to its 1 / sub-steps-th root (unchanged at 1 sub-step), as the CPU engine's,
+ /// and the c² multiplier is 1 / sub-steps², exactly 1f at one sub-step (a bit-for-bit no-op multiply in the kernel).
+ /// </summary>
+ private (float[] C2, float[] Damping, float C2Mult) SceneMaps(SceneData scene)
+ {
+ float[] c2 = new float[_cells];
+ float[] damping = new float[_cells];
+ for (int y = 0; y < _height; y++)
+ {
+ Array.Copy(scene.C2, y * _width, c2, (y + 1) * _stride + 1, _width);
+ Array.Copy(scene.D, y * _width, damping, (y + 1) * _stride + 1, _width);
+ }
+ _subSteps = _fourthOrder ? WaveSimulator.ComputeSubSteps(WaveSimulator.MaxOf(c2)) : 1;
+ float c2Mult = 1f;
+ if (_subSteps > 1)
+ {
+ // Damping is applied once per sub-step, so take the sub-step root to keep the per-step decay unchanged.
+ double exponent = 1.0 / _subSteps;
+ for (int i = 0; i < damping.Length; i++)
+ {
+ damping[i] = (float)Math.Pow(damping[i], exponent);
+ }
+ // A sub-step is 1/subSteps long, so c²·dt² shrinks by 1/subSteps².
+ c2Mult = 1f / (_subSteps * _subSteps);
+ }
+ return (c2, damping, c2Mult);
+ }
+
+ /// <summary>The image sources (the green channel of the scene image) as the kernel's tables, cell index and level per source, noting the levels in use in <see cref="_levelUsed"/> afresh.</summary>
+ private (int[] Indices, int[] Levels) SourceTables(SceneData scene)
+ {
+ int[] indices = new int[_sourceCount];
+ int[] levels = new int[_sourceCount];
+ Array.Clear(_levelUsed);
+ for (int i = 0; i < _sourceCount; i++)
+ {
+ indices[i] = (scene.SourceY[i] + 1) * _stride + scene.SourceX[i] + 1;
+ levels[i] = scene.SourceLevel[i];
+ _levelUsed[scene.SourceLevel[i]] = true;
+ }
+ return (indices, levels);
+ }
+
/// <summary>
/// Creates the context and queue, compiles <see cref="KernelSource"/>, uploads every buffer for the scene
/// and binds the kernel arguments. Mirrors the <see cref="WaveSimulator"/> constructor: c² and damping are
@@ -417,34 +496,9 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
OpenClApi.Check(err, "clCreateCommandQueue (transfer)");
_scene.Program = BuildProgram(KernelSource(use4thOrderLaplacian), "the program for the GPU");
- // the scene, with a border of one cell like the CPU engine (padded layout)
- float[] c2 = new float[_cells];
- float[] damping = new float[_cells];
- for (int y = 0; y < _height; y++)
- {
- Array.Copy(scene.C2, y * _width, c2, (y + 1) * _stride + 1, _width);
- Array.Copy(scene.D, y * _width, damping, (y + 1) * _stride + 1, _width);
- }
- // see the class summary: sub-stepping keeps the 4th order stencil stable without changing the physical
- // wave speed or damping - _subSteps stays 1 (no sub-stepping) unless the 4th order stencil is in use and
- // this scene's highest c² actually needs it. The d buffer uploaded below is pre-scaled to match (its
- // 1 / _subSteps-th root, or unchanged when _subSteps = 1), same as WaveSimulator's _dEffective on the CPU.
- _subSteps = use4thOrderLaplacian ? WaveSimulator.ComputeSubSteps(WaveSimulator.MaxOf(c2)) : 1;
- // 1 / _subSteps², or exactly 1f when _subSteps = 1 (a bit-for-bit no-op multiply in the kernel)
- float c2Mult = 1f;
- if (_subSteps > 1)
- {
- // Damping is applied once per sub-step, so take the sub-step root to keep the per-step decay unchanged.
- double exponent = 1.0 / _subSteps;
- for (int i = 0; i < damping.Length; i++)
- {
- damping[i] = (float)Math.Pow(damping[i], exponent);
- }
- // A sub-step is 1/subSteps long, so c²·dt² shrinks by 1/subSteps².
- c2Mult = 1f / (_subSteps * _subSteps);
- }
- IntPtr c2Buffer = CreateBuffer(c2, _scene);
- IntPtr dBuffer = CreateBuffer(damping, _scene);
+ (float[] c2, float[] damping, float c2Mult) = SceneMaps(scene);
+ IntPtr c2Buffer = _c2Buffer = CreateBuffer(c2, _scene);
+ IntPtr dBuffer = _dBuffer = CreateBuffer(damping, _scene);
float[] zeros = new float[_cells];
_field[0] = CreateBuffer(zeros, _scene);
_field[1] = CreateBuffer(zeros, _scene);
@@ -464,15 +518,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
frequencies[level] = (float)(level / 255.0 * 0.5 * sourceFrequencyScale);
}
_frequencyBuffer = CreateBuffer(frequencies, _scene);
- // the image sources (from the green channel of the scene image)
- int[] indices = new int[_sourceCount];
- int[] levels = new int[_sourceCount];
- for (int i = 0; i < _sourceCount; i++)
- {
- indices[i] = (scene.SourceY[i] + 1) * _stride + scene.SourceX[i] + 1;
- levels[i] = scene.SourceLevel[i];
- _levelUsed[scene.SourceLevel[i]] = true;
- }
+ (int[] indices, int[] levels) = SourceTables(scene);
// the intensity's averaging time constant scales inversely with the frequency of the slowest active source
// (image or object; a level of 0 means "no source" and is excluded) - see WaveSimulator's identical
// computation (CPU engine) and Simulation.TimeDecay's comment for why. This exponential-average decay
@@ -520,8 +566,8 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
_device.Name, _width, _height, _canvasWidth, _canvasHeight, _rim, _openEdges ? "open" : "reflective", _stride, GroupText(_stepLocal), WaveSimulator.StencilText(use4thOrderLaplacian, _subSteps));
if (_sourceCount > 0)
{
- IntPtr indexBuffer = CreateBuffer(indices, _scene);
- IntPtr levelBuffer = CreateBuffer(levels, _scene);
+ IntPtr indexBuffer = _sourceIndexBuffer = CreateBuffer(indices, _scene);
+ IntPtr levelBuffer = _sourceLevelBuffer = CreateBuffer(levels, _scene);
for (int k = 0; k <= 1; k++)
{
IntPtr kernel = _sourceKernel[k] = CreateKernel(_scene, "apply_sources");
@@ -1772,6 +1818,9 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
/// <summary>Whether the intensity is tracked; when false the intensity buffers are 1-float dummies and <see cref="IntensityData"/> is null.</summary>
private readonly bool _track;
+ /// <summary>Whether the program was compiled for the 4th-order stencil (the sub-steps follow the scene's highest c² then).</summary>
+ private readonly bool _fourthOrder;
+
/// <summary>Number of image (green-channel) sources in the scene.</summary>
private readonly int _sourceCount;
@@ -1793,6 +1842,14 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
/// <summary>The level-to-frequency table (256 floats), shared by the image and the object sources.</summary>
private IntPtr _frequencyBuffer;
+ /// <summary>The padded c² and pre-scaled damping maps bound to the step and edge kernels; refilled by <see cref="TryReplaceScene"/>.</summary>
+ private IntPtr _c2Buffer;
+ private IntPtr _dBuffer;
+
+ /// <summary>The image sources' cell indices and levels bound to <c>apply_sources</c> (unset without image sources); refilled by <see cref="TryReplaceScene"/>.</summary>
+ private IntPtr _sourceIndexBuffer;
+ private IntPtr _sourceLevelBuffer;
+
/// <summary>The two cascaded intensity stages (1-float dummies when not tracking), kept so <see cref="Reset"/> can zero them.</summary>
private IntPtr _intensityBuffer;
private IntPtr _intensityStage1Buffer;
diff --git a/WaveDudeNext/Engine/IWaveEngine.cs b/WaveDudeNext/Engine/IWaveEngine.cs
index 9868c71..afdf57c 100644
--- a/WaveDudeNext/Engine/IWaveEngine.cs
+++ b/WaveDudeNext/Engine/IWaveEngine.cs
@@ -108,6 +108,16 @@ public interface IWaveEngine
/// </summary>
void Reset();
+ /// <summary>
+ /// Swaps in another scene of the same grid (size, rim, edges) with the same number of image sources: the per-cell
+ /// maps and the image sources are replaced, the sub-steps re-derived, and the engine is <see cref="Reset"/> (the
+ /// emitters and options kept; the probes removed as by Reset). The GPU engine keeps its compiled program and buffers,
+ /// which saves the 180–350 ms build a scene edit cost the preview (2026-11-03). False, and nothing changed, when the
+ /// scene differs in a way that needs a new engine. Any capture in flight must have been awaited.
+ /// </summary>
+ /// <param name="scene">The new scene.</param>
+ bool TryReplaceScene(SceneData scene);
+
/// <summary>
/// Replaces the object-source emitters, keeping the scene and the image sources; emitters outside the
/// canvas are dropped as at construction. Takes effect from the next step; the emitters' cycle state
diff --git a/WaveDudeNext/Engine/WaveSimulator.cs b/WaveDudeNext/Engine/WaveSimulator.cs
index f67e17a..410fd7d 100644
--- a/WaveDudeNext/Engine/WaveSimulator.cs
+++ b/WaveDudeNext/Engine/WaveSimulator.cs
@@ -119,51 +119,16 @@ public sealed class WaveSimulator : IWaveEngine, IDisposable
_u = new float[cellCount];
_uPrev = new float[cellCount];
_c2 = new float[cellCount];
- float[] damping = new float[cellCount];
+ _damping = new float[cellCount];
if (trackIntensity)
{
_intensity = new float[cellCount];
_intensityStage1 = new float[cellCount];
_intensityOut = new float[cellCount];
}
- for (int y = 0; y < _height; y++)
- {
- Array.Copy(scene.C2, y * _width, _c2, (y + 1) * _stride + 1, _width);
- Array.Copy(scene.D, y * _width, damping, (y + 1) * _stride + 1, _width);
- }
-
- // see the class remarks: sub-stepping keeps the 4th order stencil stable without changing the physical
- // wave speed or damping - _subSteps stays 1 (no sub-stepping) unless the 4th order stencil is in use and
- // this scene's highest c² actually needs it
- _subSteps = use4thOrderLaplacian ? ComputeSubSteps(MaxOf(_c2)) : 1;
- if (_subSteps > 1)
- {
- // Damping is applied once per sub-step, so take the sub-step root to keep the per-step decay unchanged
- // (_subSteps applications of it compound back to the original d).
- _damping = new float[cellCount];
- double exponent = 1.0 / _subSteps;
- for (int i = 0; i < cellCount; i++)
- {
- _damping[i] = (float)Math.Pow(damping[i], exponent);
- }
- // A sub-step is 1/subSteps long, so c²·dt² shrinks by 1/subSteps².
- _c2Mult = 1f / (_subSteps * _subSteps);
- }
- else
- {
- _damping = damping;
- _c2Mult = 1f;
- }
-
- int sourceCount = scene.SourceCount;
- _sourceIndex = new int[sourceCount];
- _sourceLevel = new byte[sourceCount];
- for (int i = 0; i < sourceCount; i++)
- {
- _sourceIndex[i] = (scene.SourceY[i] + 1) * _stride + scene.SourceX[i] + 1;
- _sourceLevel[i] = scene.SourceLevel[i];
- _levelUsed[scene.SourceLevel[i]] = true;
- }
+ _sourceIndex = new int[scene.SourceCount];
+ _sourceLevel = new byte[scene.SourceCount];
+ LoadScene(scene);
for (int level = 0; level <= 255; level++)
{
_levelFrequency[level] = level / 255.0 * 0.5 * sourceFrequencyScale;
@@ -236,6 +201,62 @@ public sealed class WaveSimulator : IWaveEngine, IDisposable
SetProbes(null);
}
+ /// <inheritdoc/>
+ public bool TryReplaceScene(SceneData scene)
+ {
+ if (scene.Width != _width || scene.Height != _height || scene.Rim != _rim || scene.OpenEdges != _openEdges || scene.SourceCount != _sourceIndex.Length)
+ {
+ return false;
+ }
+ LoadScene(scene);
+ Reset();
+ // Reset keeps the emitters' definitions; their intensity constant follows the new image sources' levels
+ SetEmitters(_objSources);
+ return true;
+ }
+
+ /// <summary>
+ /// Fills the per-cell maps and the image-source tables from <paramref name="scene"/>, which must have this engine's
+ /// grid and source count: c² and d into the padded layout, the sub-steps and the per-sub-step damping and c² corrections
+ /// for the 4th-order stencil, the sources indexed, the levels in use noted. The constructor's and <see cref="TryReplaceScene"/>'s.
+ /// </summary>
+ private void LoadScene(SceneData scene)
+ {
+ int cellCount = _c2.Length;
+ for (int y = 0; y < _height; y++)
+ {
+ Array.Copy(scene.C2, y * _width, _c2, (y + 1) * _stride + 1, _width);
+ Array.Copy(scene.D, y * _width, _damping, (y + 1) * _stride + 1, _width);
+ }
+ // see the class remarks: sub-stepping keeps the 4th order stencil stable without changing the physical
+ // wave speed or damping - _subSteps stays 1 (no sub-stepping) unless the 4th order stencil is in use and
+ // this scene's highest c² actually needs it
+ _subSteps = _use4thOrderLaplacian ? ComputeSubSteps(MaxOf(_c2)) : 1;
+ if (_subSteps > 1)
+ {
+ // Damping is applied once per sub-step, so take the sub-step root to keep the per-step decay unchanged
+ // (_subSteps applications of it compound back to the original d).
+ double exponent = 1.0 / _subSteps;
+ for (int i = 0; i < cellCount; i++)
+ {
+ _damping[i] = (float)Math.Pow(_damping[i], exponent);
+ }
+ // A sub-step is 1/subSteps long, so c²·dt² shrinks by 1/subSteps².
+ _c2Mult = 1f / (_subSteps * _subSteps);
+ }
+ else
+ {
+ _c2Mult = 1f;
+ }
+ Array.Clear(_levelUsed);
+ for (int i = 0; i < _sourceIndex.Length; i++)
+ {
+ _sourceIndex[i] = (scene.SourceY[i] + 1) * _stride + scene.SourceX[i] + 1;
+ _sourceLevel[i] = scene.SourceLevel[i];
+ _levelUsed[scene.SourceLevel[i]] = true;
+ }
+ }
+
/// <summary>An ordinary snapshot (pinned arrays): the CPU converts into it on the awaiting thread, and no memory is faster for that.</summary>
public FrameSnapshot CreateSnapshot(FrameShape shape, bool withIntensity) => new(shape, withIntensity);
@@ -945,7 +966,7 @@ public sealed class WaveSimulator : IWaveEngine, IDisposable
/// Leapfrog sub-steps per simulation step (see the class remarks); 1 (no sub-stepping) unless the 4th-order
/// stencil is on and this scene's highest c² needs it.
/// </summary>
- private readonly int _subSteps;
+ private int _subSteps;
/// <summary>
/// Per-cell damping applied per sub-step (padded), 1 = lossless: the scene's map itself when
@@ -959,7 +980,7 @@ public sealed class WaveSimulator : IWaveEngine, IDisposable
private readonly bool _openEdges;
/// <summary>1/<see cref="_subSteps"/>², scaling c² for the shorter sub-step (or exactly 1.0F when _subSteps = 1, a bit-for-bit no-op multiply).</summary>
- private readonly float _c2Mult;
+ private float _c2Mult;
/// <summary>
/// The intensity's exponential-average decay factor for this simulation (replaces the old fixed 0.98F) - see
diff --git a/WaveDudeNext/Runs/RunSpec.cs b/WaveDudeNext/Runs/RunSpec.cs
index 04f4c54..590d8f4 100644
--- a/WaveDudeNext/Runs/RunSpec.cs
+++ b/WaveDudeNext/Runs/RunSpec.cs
@@ -194,6 +194,10 @@ public sealed class RunSpec
/// <summary>Whether the object sources are the same emitters, value for value.</summary>
public bool SameEmittersAs(RunSpec other) => Emitters.AsSpan().SequenceEqual(other.Emitters.AsSpan());
+ /// <summary>Whether the engine built for <paramref name="other"/> can take this spec's scene through <see cref="Engine.IWaveEngine.TryReplaceScene"/>: the same grid, edges, options and engine choice, the scene's pixels or background aside.</summary>
+ public bool SameGridAs(RunSpec other) =>
+ Width == other.Width && Height == other.Height && DampingEdge == other.DampingEdge && Edges == other.Edges && Engine == other.Engine && PreferGpu == other.PreferGpu;
+
/// <summary>Builds the engine's scene input from the snapshot. Worker; allocates the per-pixel maps.</summary>
internal SceneData BuildScene() => Image is { } image
? SceneData.FromBgra(image.Bgra, image.Width, image.Height, image.StrideBytes, ImageSources, DampingEdge, Edges == EdgeMode.Open)
diff --git a/WaveDudeNext/Runs/ScratchRunner.cs b/WaveDudeNext/Runs/ScratchRunner.cs
index 34c042a..cb8897e 100644
--- a/WaveDudeNext/Runs/ScratchRunner.cs
+++ b/WaveDudeNext/Runs/ScratchRunner.cs
@@ -209,18 +209,36 @@ public sealed class ScratchRunner : IDisposable
Post(new ScratchResult(spec, frame, snapshot, clock.Elapsed, traces));
}
- /// <summary>The kept engine, reset to step 0 and given the spec's emitters; rebuilt when the scene or the options differ.</summary>
+ /// <summary>
+ /// The kept engine, reset to step 0 and given the spec's emitters; given the new scene when only the scene's pixels or
+ /// background changed (<see cref="IWaveEngine.TryReplaceScene"/>, 2026-11-03: a moved part had cost the OpenCL build of
+ /// 180–350 ms before every preview frame); rebuilt when the grid or the options differ.
+ /// </summary>
private IWaveEngine EngineFor(RunSpec spec)
{
- if (_engine != null && _engineSpec != null && _engineSpec.SameSceneAs(spec))
+ if (_engine != null && _engineSpec != null)
{
- _engine.Reset();
- if (!_engineSpec.SameEmittersAs(spec))
+ if (_engineSpec.SameSceneAs(spec))
{
- _engine.SetEmitters(spec.Emitters);
+ _engine.Reset();
+ }
+ else if (_engineSpec.SameGridAs(spec) && ReplaceScene(spec))
+ {
+ // replaced, and reset by that
+ }
+ else
+ {
+ _engineSpec = null;
+ }
+ if (_engineSpec != null)
+ {
+ if (!_engineSpec.SameEmittersAs(spec))
+ {
+ _engine.SetEmitters(spec.Emitters);
+ }
+ _engineSpec = spec;
+ return _engine;
}
- _engineSpec = spec;
- return _engine;
}
(_engine as IDisposable)?.Dispose();
_engine = null;
@@ -231,6 +249,18 @@ public sealed class ScratchRunner : IDisposable
return _engine;
}
+ /// <summary>Gives the kept engine the spec's scene; false when the engine wants a rebuild instead.</summary>
+ private bool ReplaceScene(RunSpec spec)
+ {
+ var clock = Stopwatch.StartNew();
+ bool replaced = _engine!.TryReplaceScene(spec.BuildScene());
+ if (replaced)
+ {
+ Logger.Debug("Preview engine: scene replaced in {Elapsed:0} ms", clock.ElapsedMilliseconds);
+ }
+ return replaced;
+ }
+
/// <summary>A snapshot of the spec's shape, alternating between two so the one handed out last stays valid while the next is computed.</summary>
private FrameSnapshot NextSnapshot(RunSpec spec)
{
diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.cs
index 8d28a29..17dcdc7 100644
--- a/_tools/library_check/Program.cs
+++ b/_tools/library_check/Program.cs
@@ -262,6 +262,7 @@ internal static class Program
CheckEngines(scene, W, H, Steps);
CheckCaptureResetEmitters(scene, W, H);
+ CheckSceneReplacement();
CheckDeterminism(scene);
CheckEmitterMapping();
CheckMirror(W, H);
@@ -1388,6 +1389,42 @@ internal static class Program
/// whole groups, and the surplus work items must change nothing: the field with the open ring, and both capture
/// formats, agree with the CPU.
/// </summary>
+ /// <summary>TryReplaceScene (2026-11-03): an engine given another scene of its grid steps like a fresh one on it, on both engines; another grid is refused.</summary>
+ private static void CheckSceneReplacement()
+ {
+ Console.WriteLine("--- scene replacement");
+ const int W = 96, H = 64;
+ // 4th order, so the sub-steps follow the scene's highest c²: index 1 needs 3, index 1.6 fewer
+ var options = new EngineOptions(1.0, 1.0, true, true, 10.0, 1.0);
+ SceneData first = SceneData.Empty(W, H, -8, 1.0, true);
+ SceneData second = SceneData.Empty(W, H, -8, 1.6, true);
+ SceneData otherGrid = SceneData.Empty(W + 1, H, -8, 1.0, true);
+ List<Emitter> emitters = [Make(W / 2, H / 2, 120, 1.0)];
+ var reference = new WaveSimulator(second, options, emitters);
+ Run(reference, 60);
+ GpuWaveSimulator? gpu = GpuWaveSimulator.TryCreate(first, options, emitters, out string problems);
+ if (gpu == null)
+ {
+ Console.WriteLine(" skip GPU: " + problems);
+ }
+ foreach ((IWaveEngine engine, string name) in new (IWaveEngine, string)[] { (new WaveSimulator(first, options, emitters), "CPU"), (gpu!, "GPU") })
+ {
+ if (engine == null)
+ {
+ continue;
+ }
+ Run(engine, 30);
+ Check(!engine.TryReplaceScene(otherGrid), name + ": a scene of another grid is refused");
+ Check(engine.TryReplaceScene(second), name + ": a scene of the same grid is taken");
+ Run(engine, 60);
+ engine.PrepareFrame(true, true);
+ float tolerance = name == "CPU" ? 0f : 2e-3f * Math.Max(1f, MaxAbs(reference.FieldData));
+ float diff = MaxDiff(reference.FieldData, engine.FieldData);
+ Check(diff <= tolerance && MaxAbs(engine.FieldData) > 0f, name + ": after the replacement the engine steps like a fresh one on the new scene (max diff " + diff + ")");
+ (engine as IDisposable)?.Dispose();
+ }
+ }
+
private static void CheckWorkGroups()
{
Console.WriteLine("--- work groups on a prime grid");