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#

Reduced preview: resolution, stored frames and 8-bit samples as View menu settings

Alexander Graeff9010acd315e
diff --git a/CLAUDE.md b/CLAUDE.md
index ee2198d..dde37d7 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -57,6 +57,42 @@ WPF shell as it stands:
- **Taskbar progress** (2026-10-14, the user's rule): the status bar's busy bar (an export's frames, or the
marquee while an export waits for its run or a scratch frame computes) is mirrored on the taskbar button
through WPF's `TaskbarItemInfo` (`MainWindow.Taskbar.cs`, fed from `UpdateBusy`).
+- **Reduced preview** (2026-10-15, the user's design for weaker machines and a first step towards a browser
+ build; three View menu entries, persisted user settings, all default Full): View > Preview resolution
+ (Full/Half/Quarter, `PreviewResolution` 1/2/4: the canvas divisor), Preview frames (Full/Half/Quarter,
+ `PreviewFrames` 1/2/4: only every n-th frame is stored) and Preview samples (16-bit float /
+ 8-bit palette index, `PreviewSampleBytes` 2/1); ids `MenuPreviewResolution<n>`, `MenuPreviewFrames<n>`,
+ `MenuPreviewSamples<n>`, `Commands/ViewCommands`. The **simulation always runs at the canvas size**: only
+ what is captured, stored and shown shrinks. **The timeline never changes** (the user's rule, 2026-10-15:
+ `VisualizeEvery` means "a frame every n steps" and the settings only leave frames out to save memory, nothing
+ else): `RunSpec.VisualizeEvery` and `FrameCount` stay the project's, `FrameStride` (the frame divisor) says
+ that only every stride-th frame is captured (`CaptureEvery` steps apart, `StoredFrameCount` of them, the
+ store's capacity) and `SimulationRun.Frames` (a `StridedFrameSource` over the store when the stride is above
+ 1) hands the preview timeline frame k as stored frame ⌊k / stride⌋, so a stored frame stands in for the
+ frames up to the next one; `SimulationRun.FrameCount` counts covered timeline frames; probe profiles are
+ still collected per timeline frame; the scratch runner computes the exact frame asked for. The pane, the
+ in/out points, the step readout, playback and exports know nothing of the stride. `Runs/PreviewQuality`
+ (resolution divisor, frame divisor, `FrameFormat`) goes into `RunSpec.Create(…, quality)`; the spec's
+ `Engine/FrameShape` (canvas, divisor, format, the display brightness of both layers)
+ is what every `FrameSnapshot` and the `FrameStore` are made with (`FrameStore.Create(path, shape, …)`,
+ header version 3 with format, divisor and canvas; `IFrameSource` has `CanvasWidth/Height`, `Format` and a
+ byte `CopyLayer` primitive, the `Half` overloads refuse an index store). The capture averages every divisor ×
+ divisor block (clipped at the edges; `Engine/FrameConversion` is the reference, the CPU engine converts on
+ the awaiting thread, the GPU's `capture_half`/`capture_index` kernels replaced `to_half` and match it bit
+ for bit in the harness). **The 8-bit format is the renderer's palette index with the brightness baked in**
+ (`ColorLut.FieldIndex`/`IntensityIndex`), not a float8: the display is 8-bit linear already, and a float8
+ with 3 mantissa bits would band above 6 % of full scale. Palette and black level still recolour such a run
+ (`FrameRenderer.RenderIndexed`, a table lookup per pixel); a brightness edit in that mode counts as a
+ simulation edit (`MainWindow.Live.IsBrightnessBaked`: stale, scratch, re-run). A quality change stales the
+ run and redoes the scratch frame (`OnPreviewQualityChanged`); the scratch runner uses the same shape, so the
+ picture never jumps between shapes. The handles and boxes map canvas pixels onto the
+ smaller picture through `IFrameSource.CanvasWidth/Height`. **An export always uses a full run**
+ (`EnsureRunForExport`'s reason "the run is a reduced preview", `StartRun(fullQuality: true)`, `ExportJob`
+ refuses an index store). Sizes for the full-HD
+ run of 2500 steps every 2 with both planes: 10.4 GB full, 2.6 at half resolution, 1.3 with 8-bit samples,
+ 0.33 with every fourth frame too. Not done, on purpose: simulating on a coarser grid (eight times cheaper but
+ other physics: half the cells per wavelength; the only lever for CPU stepping, which none of the three
+ touches) and an automatic mode.
- **Simulation** (2026-10-09): menu Simulation > Run (F5), Pause/Resume (F6), Stop (Shift+F5, also
Esc). `OnRun` decodes the scene image (`Rendering/SceneImageLoader`, WPF decoders → BGRA bytes),
snapshots the project into a `RunSpec`, checks the cache drive, creates the `FrameStore` and
@@ -536,7 +572,12 @@ passing harnesses for comfort, never all of them after an edit.
probe yielding one profile per frame, the box attached to the probe following it and a detached one staying put, and a
scratch frame's traces matching the run's bit for bit (series up to the step, the frame's profile, a second
request on the kept engine with an integrated line probe starting its sums afresh, and the same on the GPU
- after the cancelled GPU run), and a rotated 3 × 1 array; the
+ after the cancelled GPU run), and a rotated 3 × 1 array; the **reduced preview** (2026-10-15: `FrameConversion`'s
+ block means for divisors 2 and 3 (the clipped last column) and its index mapping equal to the renderer's, the
+ CPU captures of every shape equal to it and the GPU's within one index / the half tolerance (actual: bit for
+ bit), a store of half-size index bytes written three ways and read back, its `Half` read and an `ExportJob`
+ on it refused, a spec with a quality (interval × 2, 50 frames, the shape with the display brightness), and a
+ headless run plus a scratch frame in that shape equal to a fresh engine's capture); the
**export** (`ExportChecks.cs`, 2026-10-14, `-- export` runs just these in a few seconds): PNG decoded in-house
(inflate + unfilter, CRCs) and by the ffmpeg found on the PATH (skipped without one; this machine has one in
`C:\Windows` and under ImageMagick), JPEG at quality 90 above 30 dB, MPEG-1 (frame rate codes, quantiser
@@ -614,6 +655,18 @@ The two legacy harnesses are console programs compiled with `csc` against the `W
**harness hooks** in the app, read from the environment: `WAVEDUDE_EXPORT_PATH` replaces the Save dialog
(`{name}` = the suggested name) and `WAVEDUDE_DISCARD_EDITS=1` skips the save question on closing
(`Start-App` sets it), because posted keys cannot drive a common dialog or a message box.
+ `_tools/ui_check/PreviewQualityCheck.ps1` (2026-10-15, 34 checks, about 90 s) drives View > Preview
+ resolution / frames / samples by keyboard on `tiny.wdproj`: a full run (the log line says "100 of 100 frames
+ stored as 64×48 (full)", frames 97, 98 and 99 all differ), then each choice marks the run stale and the
+ automatic re-run follows: with every second frame stored the timeline still ends at 99 / step 198 and frame 99
+ shows the same picture as 98 while 97 differs (the log's "50 of 100 frames stored"), at half resolution the
+ source marker stays at the source's canvas position on the half-size picture, then 8-bit; a restart keeps the
+ settings, and the menu puts everything back to Full (the three frames differ again). The log file next to the
+ exe is read with a shared `FileStream` (the app keeps it open); the script builds the "×" from its character
+ code, since a script file is read as ANSI. Focus is put on the Play button before F5 and before the frame
+ steps: a window that was never activated has no focused element, so a routed gesture or the pane's own key
+ bindings go nowhere (the menu's F10 works regardless), and the menu leaves the focus on the tree. The second
+ start got a pause and a `Park` retry after coming up active once.
`_tools/ui_check/SceneImageCheck.ps1` (2026-10-15, 6 checks, about 25 s: the app ends dirty, so the close
runs into the save prompt and `Stop-App` kills it after 8 s) builds a project in a temporary folder whose
embedded image (the ball lens) differs from the file its path names (the race track): opening it takes the
@@ -654,7 +707,7 @@ MainWindow.OnRun: FrameCache.CheckSpace -> FrameStore.Create -> new SimulationRu
SimulationRun (Task.Run worker; ManualResetEventSlim pause gate, CancellationTokenSource stop)
|- SceneData.FromBgra / Empty -> WaveEngineFactory.Create -> IWaveEngine (WaveSimulator CPU | GpuWaveSimulator OpenCL)
|- per step: AdvanceOneStep, SampleProbes; every VisualizeEvery steps: PrepareFrame -> FrameStore.Write (float -> Half)
- |- per frame: engine.CaptureFrame(snapshot) (GPU: to_half kernel + non-blocking read into a pinned FrameSnapshot;
+ |- per frame: engine.CaptureFrame(snapshot) (GPU: capture_half / capture_index kernel in the spec's FrameShape + non-blocking read into a pinned FrameSnapshot;
| CPU: row copy) -> writer task: engine.AwaitFrame -> FrameStore.Write -> snapshot back to a pool of 3
|- ProbeSampler/ProbeCollector -> ProbeUpdate batches (<= 20 Hz) applied to run.Traces on the UI context
'- State/StepsDone/FrameCount/EngineDescription posted to the UI context (INotifyPropertyChanged, bindable)
@@ -693,10 +746,11 @@ FrameStore (temporary file in %LOCALAPPDATA%\WaveDude\cache, DeleteOnClose, pre-
- **Engine contract** (`IWaveEngine`): padded grid (`Stride = Width + 2`), one driver thread at a
time, `PrepareFrame` before reading, CPU `FieldData` is a different array every sub-step, GPU
`FieldData` a host copy. Added 2026-10-09: `CaptureFrame(FrameSnapshot, needIntensity)` /
- `AwaitFrame` (the frame as `Half` planes without padding; the GPU converts on the card with the
- `to_half` kernel and reads asynchronously with OpenCL events into pinned arrays, `AwaitFrame` may
- run on another thread; the CPU copies rows at capture and converts at await, so the stepping
- thread pays little), `Reset()` (step 0; probes removed) and `SetEmitters()` (new object sources on
+ `AwaitFrame` (the frame as planes of the snapshot's `FrameShape` without padding: halves or palette
+ index bytes, the canvas shrunk by the divisor, since 2026-10-15; the GPU converts on the card with the
+ `capture_half` / `capture_index` kernels and reads asynchronously with OpenCL events into pinned arrays,
+ `AwaitFrame` may run on another thread; the CPU copies rows at capture and converts at await
+ (`FrameConversion`), so the stepping thread pays little), `Reset()` (step 0; probes removed) and `SetEmitters()` (new object sources on
the same scene; the GPU keeps them in their own `Resources` group and rebinds the intensity
retention). Engines take `SceneData`, `EngineOptions` and
`IReadOnlyList<Emitter>`; `Emitter.FromSource` resolves a model `Source` + `SourceElement`
@@ -714,8 +768,10 @@ FrameStore (temporary file in %LOCALAPPDATA%\WaveDude\cache, DeleteOnClose, pre-
- **FrameStore, two tiers** (2026-10-14): the first frames of a run, as many as the memory budget holds
(`RamFrames`), live in native memory (`NativeMemory.Alloc` per frame, one block of all planes); the
rest go to a temporary file created only when the run does not fit (`FirstSpilledFrame`, `HasFile`),
- pre-sized for the spilled frames, 64-byte header (`WDFS`, version 2, width, height, layers, every,
- capacity, first frame in the file) then fixed-size frames, planes in `FrameLayer` order, only those
+ pre-sized for the spilled frames, 64-byte header (`WDFS`, version 3 since 2026-10-15: width, height, layers,
+ every, capacity, first frame in the file, sample format, divisor, canvas width and height) then fixed-size
+ frames in the run's `FrameShape` (halves, or palette index bytes; the canvas shrunk by the divisor, see
+ "Reduced preview" in the WPF shell list), planes in `FrameLayer` order, only those
present (`RunSpec.Layers`: field always; intensity when the intensity preview or export is on or a
probe needs it). The budget is `FrameMemory.Budget(percent)`: the user's share of the physical RAM
(Simulation > Frames kept in memory: a quarter, half, three quarters; setting `FrameMemoryPercent`,
@@ -995,6 +1051,63 @@ pan (roadmap); Help > About has no content; dock pane titles are not exposed to
Deferred, possibly never: filmstrip thumbnails behind the bar (needs cached frames).
6. Retire `Wave_Dude_2D` once the WPF app covers it.
+## Rebrand and licensing (designed 2026-10-15, **not applied yet**)
+
+The WPF app becomes **WaveDude Next** (agreed with Jeroen Vleggaar by mail 2026-10-15; he proposed
+"Pro", the user chose "Next" since Pro/Plus suggests a paid tier). Project, namespaces, the GitHub
+repo, About and installer take that name. The new icon is `Branding/Icons/05_rainbow_rings.svg`,
+installed as `WaveDude.WPF/App.svg|png|ico` (the candidates and `make_icons.py` stay in `Branding/Icons/`).
+
+**People**: Alexander Graef (author of WaveDude Next; "Gräf" in his mail signature, "Graef" in code);
+JJM (Jeroen) Vleggaar, Huygens Optics (author of Wave Dude 2D, GPL-3.0-or-later, Copyright (C) 2026);
+Manuel, GitHub `0x23`, YouTube "Diffraction Limited" (author of WaveSimulator2D, the Python/CuPy
+numerics Jeroen's engine took its design from; surname not public; the 0x23 = Manuel link comes from
+Jeroen's mail of 2026-10-08, which also says Manuel consented to publication and will add an MIT
+licence to his repo). Private addresses stay out of files.
+
+**Source header** (accepted 2026-10-15; the same text in every file, `'` in VB, `//` in C#,
+`<!-- -->` in XAML, `#` in PowerShell/Python; no per-file provenance, no "ported from / modified by"):
+
+```
+' SPDX-License-Identifier: GPL-3.0-or-later
+' Copyright (C) 2026 Alexander Graef <[email protected]>
+'
+' This file is part of WaveDude Next, a 2D wave simulator.
+'
+' Based on the work of
+' JJM Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026
+' <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>
+' Manuel (0x23, Diffraction Limited), author of WaveSimulator2D
+' <https://www.youtube.com/@DiffractionLimited>, <https://github.com/0x23/WaveSimulator2D>
+'
+' WaveDude Next is free software: you can redistribute it and/or modify it under
+' the terms of the GNU General Public License as published by the Free Software
+' Foundation, either version 3 of the License, or (at your option) any later
+' version. It is distributed WITHOUT ANY WARRANTY; see the LICENSE.md file or
+' <https://www.gnu.org/licenses/>.
+```
+
+Jeroen's line carries his copyright so the GPL's notice-preservation rule (sections 4 and 5) is met
+on the files that descend from his code without a separate notice. The author's own VB tree
+(`2D_wave_sim_V01/`) keeps his header and is not touched.
+
+**LICENSE.md** (written 2026-10-15, the user's call): a short attribution block on top (the project
+name, the copyright line, the same "Based on the work of" list as the header, one GPL sentence, a
+rule), then the FSF's own Markdown of the licence, <https://www.gnu.org/licenses/gpl-3.0.md>,
+**verbatim** (34,893 bytes, md5 `ba29b1da0f9c28e2a9e072aba46cf040`; `tail -n +19 LICENSE.md | md5sum`
+must give that). The block is about 2 % of the file, which should stay inside the near-exact match
+GitHub's licence detection (licensee) needs to label the repo "GPL-3.0"; **check the sidebar after the
+first push** and move the block into the README if the label is missing. The licence text itself is
+never edited (the FSF allows verbatim copies only). `LICENSE.md` is the name the header points at
+(GitHub also accepts `LICENSE` and `COPYING`; one file, one name).
+
+**Companions when applied**: `<Authors>Alexander Graef</Authors>`, `<Copyright>Copyright (C) 2026
+Alexander Graef</Copyright>`, `<PackageLicenseExpression>GPL-3.0-or-later</PackageLicenseExpression>`
+in both SDK projects (About and the file properties read them); a README with a Credits section
+naming the three people as in the header; `file_header_template` in `.editorconfig` so the IDE adds
+the header to new files. Applying all of this is a separate step, after the coding session that is
+running on the source today.
+
## Conventions
- Style: modern concise C# — expression-bodied accessors, **no `this.` qualification**, no
diff --git a/WaveDude.WPF/Commands/ViewCommands.cs b/WaveDude.WPF/Commands/ViewCommands.cs
new file mode 100644
index 0000000..fc1cedb
--- /dev/null
+++ b/WaveDude.WPF/Commands/ViewCommands.cs
@@ -0,0 +1,21 @@
+using System.Windows.Input;
+
+namespace WaveDude.WPF.Commands;
+
+/// <summary>
+/// Commands of the View menu's preview quality entries (2026-10-15), bound on the main window (handlers in
+/// <c>MainWindow.xaml.cs</c>): each sets one persisted user setting from its parameter, a number as text.
+/// The settings describe the machine, not the project: the simulation is the same, only what the preview
+/// captures and keeps changes, and an export always uses a full run.
+/// </summary>
+public static class ViewCommands
+{
+ /// <summary>Sets the preview resolution: the parameter is the divisor of the canvas along each axis (1, 2 or 4).</summary>
+ public static readonly RoutedUICommand SetPreviewResolution = new("Preview resolution", nameof(SetPreviewResolution), typeof(ViewCommands));
+
+ /// <summary>Sets the preview's frame share: the parameter multiplies the project's visualisation interval (1, 2 or 4).</summary>
+ public static readonly RoutedUICommand SetPreviewFrames = new("Preview frames", nameof(SetPreviewFrames), typeof(ViewCommands));
+
+ /// <summary>Sets the preview's sample size: the parameter is the bytes per sample (2 for halves, 1 for palette indices).</summary>
+ public static readonly RoutedUICommand SetPreviewSamples = new("Preview samples", nameof(SetPreviewSamples), typeof(ViewCommands));
+}
diff --git a/WaveDude.WPF/MainWindow.Export.cs b/WaveDude.WPF/MainWindow.Export.cs
index 2c028ae..3cafc71 100644
--- a/WaveDude.WPF/MainWindow.Export.cs
+++ b/WaveDude.WPF/MainWindow.Export.cs
@@ -269,11 +269,12 @@ public partial class MainWindow
{
SimulationRun? run = Run;
string? reason = run == null ? "no run" : IsRunStale ? "the run is stale" : IsProbesStale ? "the probes were edited since the run"
+ : !run.Spec.Quality.IsFull ? "the run is a reduced preview (View menu)"
: intensity && !run.Store.Has(FrameLayer.Intensity) ? "the run has no intensity plane" : !run.IsActive && run.State != RunState.Completed ? "the run did not complete" : null;
if (reason != null)
{
Logger.Debug("Export: a run is started first ({Reason})", reason);
- StartRun(automatic: true, trackIntensity: intensity);
+ StartRun(automatic: true, trackIntensity: intensity, fullQuality: true);
run = Run;
}
else if (run!.IsActive)
diff --git a/WaveDude.WPF/MainWindow.Live.cs b/WaveDude.WPF/MainWindow.Live.cs
index 384d3a9..ef962df 100644
--- a/WaveDude.WPF/MainWindow.Live.cs
+++ b/WaveDude.WPF/MainWindow.Live.cs
@@ -154,7 +154,7 @@ public partial class MainWindow
ScheduleScratch();
return;
}
- if (!change.AffectsSimulation)
+ if (!change.AffectsSimulation && !IsBrightnessBaked(change))
{
return;
}
@@ -180,6 +180,34 @@ public partial class MainWindow
ScheduleRerun();
}
+ /// <summary>
+ /// Whether a display edit changes the stored frames after all: a layer's brightness while the preview's
+ /// samples are 8-bit palette indices (View > Preview samples), which bake the brightness in at capture time.
+ /// Such an edit then counts as a simulation edit: stale run, scratch frame, automatic re-run.
+ /// </summary>
+ private static bool IsBrightnessBaked(ProjectChange change) =>
+ change.Item is DisplayLayer && change.Property == nameof(DisplayLayer.Brightness) && Settings.Default.PreviewSampleBytes == 1;
+
+ /// <summary>
+ /// View > Preview resolution / frames / samples changed: the run and the scratch frame on screen were made
+ /// with the old shape, so both are redone as after an edit (the run marked stale, an automatic one stopped,
+ /// the position's frame requested, the re-run scheduled).
+ /// </summary>
+ private void OnPreviewQualityChanged()
+ {
+ if (Run != null)
+ {
+ IsRunStale = true;
+ if (Run is { IsAutomatic: true, IsActive: true })
+ {
+ Logger.Debug("The automatic run is stopped: the preview quality changed");
+ Run.Stop();
+ }
+ }
+ ScheduleScratch();
+ ScheduleRerun();
+ }
+
/// <summary>Whether the store cannot show the preview's position, or its recordings are stale: no run, a stale one, stale probes, or a run that has not reached it.</summary>
private bool NeedsScratch => Run == null || IsRunStale || IsProbesStale || Run.FrameCount <= PreviewPosition;
@@ -317,7 +345,7 @@ public partial class MainWindow
{
try
{
- return RunSpec.Create(Project, LoadSceneImage(), Settings.Default.UseGpu);
+ return RunSpec.Create(Project, LoadSceneImage(), Settings.Default.UseGpu, quality: PreviewQualitySetting);
}
catch (Exception ex) when (ex is RunSpecException or IOException or UnauthorizedAccessException or NotSupportedException)
{
diff --git a/WaveDude.WPF/MainWindow.Simulation.cs b/WaveDude.WPF/MainWindow.Simulation.cs
index d93866b..1589b03 100644
--- a/WaveDude.WPF/MainWindow.Simulation.cs
+++ b/WaveDude.WPF/MainWindow.Simulation.cs
@@ -1,6 +1,7 @@
using System.IO;
using System.Windows;
using System.Windows.Input;
+using WaveDude.Engine;
using WaveDude.Model;
using WaveDude.Runs;
using WaveDude.WPF.Properties;
@@ -43,26 +44,38 @@ public partial class MainWindow
}
}
+ /// <summary>
+ /// The preview quality chosen in the View menu (persisted user settings, 2026-10-15): how much of a run is
+ /// captured and kept, for weaker machines. Applied to the preview's runs and scratch frames; an export's run
+ /// is always <see cref="PreviewQuality.Full"/>.
+ /// </summary>
+ private static PreviewQuality PreviewQualitySetting => new(
+ Math.Max(1, Settings.Default.PreviewResolution),
+ Math.Max(1, Settings.Default.PreviewFrames),
+ Settings.Default.PreviewSampleBytes == 1 ? FrameFormat.Index : FrameFormat.Half);
+
/// <summary>Decodes the scene image, snapshots the project, checks the disk, creates the store and starts the worker.</summary>
/// <param name="automatic">Started after an edit rather than by the user: the preview keeps its position.</param>
/// <param name="trackIntensity">Store the intensity plane whatever the project needs (an export of the intensity asks for it).</param>
- private void StartRun(bool automatic = false, bool trackIntensity = false)
+ /// <param name="fullQuality">Capture every cell of every frame as a half whatever the View menu says (an export needs that).</param>
+ private void StartRun(bool automatic = false, bool trackIntensity = false, bool fullQuality = false)
{
if (!Settings.Default.UseGpu)
{
Logger.Info("Running on the CPU: 'Use the GPU' is off in the Simulation menu");
}
- RunSpec spec = RunSpec.Create(Project, LoadSceneImage(), Settings.Default.UseGpu, trackIntensity);
+ PreviewQuality quality = fullQuality ? PreviewQuality.Full : PreviewQualitySetting;
+ RunSpec spec = RunSpec.Create(Project, LoadSceneImage(), Settings.Default.UseGpu, trackIntensity, quality);
// the frames stay in memory up to the budget (the user's share of the RAM, capped by what is free now); only
// the rest needs room on the cache drive (2026-10-14)
long budget = FrameMemory.Budget(Settings.Default.FrameMemoryPercent);
- int ramFrames = Math.Min(spec.FrameCount, FrameStore.FramesInBudget(spec.Width, spec.Height, spec.Layers, budget));
- if (ramFrames < spec.FrameCount)
+ int ramFrames = Math.Min(spec.StoredFrameCount, FrameStore.FramesInBudget(spec.Shape, spec.Layers, budget));
+ if (ramFrames < spec.StoredFrameCount)
{
- FrameCache.CheckSpace(FrameStore.SizeOf(spec.Width, spec.Height, spec.Layers, spec.FrameCount - ramFrames));
+ FrameCache.CheckSpace(FrameStore.SizeOf(spec.Shape, spec.Layers, spec.StoredFrameCount - ramFrames));
}
DiscardRun();
- FrameStore store = FrameStore.Create(FrameCache.NewPath(), spec.Width, spec.Height, spec.Layers, spec.FrameCount, spec.VisualizeEvery, budget);
+ FrameStore store = FrameStore.Create(FrameCache.NewPath(), spec.Shape, spec.Layers, spec.StoredFrameCount, spec.CaptureEvery, budget);
var run = new SimulationRun(spec, store, SynchronizationContext.Current, automatic);
run.PropertyChanged += (_, args) =>
{
@@ -72,8 +85,8 @@ public partial class MainWindow
}
};
run.Finished += (_, _) => OnRunFinished();
- Logger.Info("{Kind} started: {Steps} steps, {Frames} frames of {Width}×{Height}, {RamFrames} in memory ({RamBytes}) and {DiskFrames} on disk; edits made from now on do not affect it",
- automatic ? "Re-run" : "Run", spec.Steps, spec.FrameCount, spec.Width, spec.Height, store.RamFrames, FrameMemory.Gigabytes(store.RamBytes), spec.FrameCount - store.RamFrames);
+ Logger.Info("{Kind} started: {Steps} steps, {Stored} of {Frames} frames stored as {Width}×{Height} ({Quality}), {RamFrames} in memory ({RamBytes}) and {DiskFrames} on disk; edits made from now on do not affect it",
+ automatic ? "Re-run" : "Run", spec.Steps, spec.StoredFrameCount, spec.FrameCount, spec.Shape.Width, spec.Shape.Height, spec.Quality, store.RamFrames, FrameMemory.Gigabytes(store.RamBytes), spec.StoredFrameCount - store.RamFrames);
IsRunStale = false;
IsProbesStale = false;
Run = run;
diff --git a/WaveDude.WPF/MainWindow.xaml b/WaveDude.WPF/MainWindow.xaml
index 6d4f467..d1acb17 100644
--- a/WaveDude.WPF/MainWindow.xaml
+++ b/WaveDude.WPF/MainWindow.xaml
@@ -124,6 +124,10 @@
<CommandBinding Command="{x:Static commands:ExportCommands.IntensityFrame}" CanExecute="CanExport" Executed="OnExportIntensityFrame" />
<CommandBinding Command="{x:Static commands:SimulationCommands.EnsureRun}" Executed="OnEnsureRun" />
<CommandBinding Command="{x:Static commands:SimulationCommands.SetFrameMemory}" Executed="OnSetFrameMemory" />
+ <!-- the preview quality (View menu); handlers in MainWindow.xaml.cs -->
+ <CommandBinding Command="{x:Static commands:ViewCommands.SetPreviewResolution}" Executed="OnSetPreviewResolution" />
+ <CommandBinding Command="{x:Static commands:ViewCommands.SetPreviewFrames}" Executed="OnSetPreviewFrames" />
+ <CommandBinding Command="{x:Static commands:ViewCommands.SetPreviewSamples}" Executed="OnSetPreviewSamples" />
<!-- project structure; handlers in MainWindow.Project.cs -->
<CommandBinding Command="{x:Static commands:ProjectCommands.AddSource}" Executed="OnAddSource" />
@@ -181,6 +185,39 @@
<MenuItem Header="{DynamicResource MenuViewLanguage}"
ItemsSource="{Binding Options, Source={x:Static localization:LanguageController.Instance}}"
ItemContainerStyle="{StaticResource LanguageMenuItemStyle}" />
+ <Separator />
+ <!-- the reduced preview (2026-10-15): how much of a run is captured and kept, for weaker machines; user
+ settings, never the project's, and an export always uses a full run -->
+ <MenuItem Header="{DynamicResource MenuViewResolution}" AutomationProperties.AutomationId="MenuPreviewResolution">
+ <MenuItem Header="{DynamicResource MenuViewResolutionFull}" Command="{x:Static commands:ViewCommands.SetPreviewResolution}" CommandParameter="1"
+ IsChecked="{Binding Source={x:Static p:Settings.Default}, Path=PreviewResolution, Converter={StaticResource IntEquals}, ConverterParameter=1, Mode=OneWay}"
+ AutomationProperties.AutomationId="MenuPreviewResolution1" />
+ <MenuItem Header="{DynamicResource MenuViewResolutionHalf}" Command="{x:Static commands:ViewCommands.SetPreviewResolution}" CommandParameter="2"
+ IsChecked="{Binding Source={x:Static p:Settings.Default}, Path=PreviewResolution, Converter={StaticResource IntEquals}, ConverterParameter=2, Mode=OneWay}"
+ AutomationProperties.AutomationId="MenuPreviewResolution2" />
+ <MenuItem Header="{DynamicResource MenuViewResolutionQuarter}" Command="{x:Static commands:ViewCommands.SetPreviewResolution}" CommandParameter="4"
+ IsChecked="{Binding Source={x:Static p:Settings.Default}, Path=PreviewResolution, Converter={StaticResource IntEquals}, ConverterParameter=4, Mode=OneWay}"
+ AutomationProperties.AutomationId="MenuPreviewResolution4" />
+ </MenuItem>
+ <MenuItem Header="{DynamicResource MenuViewFrames}" AutomationProperties.AutomationId="MenuPreviewFrames">
+ <MenuItem Header="{DynamicResource MenuViewFramesFull}" Command="{x:Static commands:ViewCommands.SetPreviewFrames}" CommandParameter="1"
+ IsChecked="{Binding Source={x:Static p:Settings.Default}, Path=PreviewFrames, Converter={StaticResource IntEquals}, ConverterParameter=1, Mode=OneWay}"
+ AutomationProperties.AutomationId="MenuPreviewFrames1" />
+ <MenuItem Header="{DynamicResource MenuViewFramesHalf}" Command="{x:Static commands:ViewCommands.SetPreviewFrames}" CommandParameter="2"
+ IsChecked="{Binding Source={x:Static p:Settings.Default}, Path=PreviewFrames, Converter={StaticResource IntEquals}, ConverterParameter=2, Mode=OneWay}"
+ AutomationProperties.AutomationId="MenuPreviewFrames2" />
+ <MenuItem Header="{DynamicResource MenuViewFramesQuarter}" Command="{x:Static commands:ViewCommands.SetPreviewFrames}" CommandParameter="4"
+ IsChecked="{Binding Source={x:Static p:Settings.Default}, Path=PreviewFrames, Converter={StaticResource IntEquals}, ConverterParameter=4, Mode=OneWay}"
+ AutomationProperties.AutomationId="MenuPreviewFrames4" />
+ </MenuItem>
+ <MenuItem Header="{DynamicResource MenuViewSamples}" AutomationProperties.AutomationId="MenuPreviewSamples">
+ <MenuItem Header="{DynamicResource MenuViewSamples16}" Command="{x:Static commands:ViewCommands.SetPreviewSamples}" CommandParameter="2"
+ IsChecked="{Binding Source={x:Static p:Settings.Default}, Path=PreviewSampleBytes, Converter={StaticResource IntEquals}, ConverterParameter=2, Mode=OneWay}"
+ AutomationProperties.AutomationId="MenuPreviewSamples2" />
+ <MenuItem Header="{DynamicResource MenuViewSamples8}" Command="{x:Static commands:ViewCommands.SetPreviewSamples}" CommandParameter="1"
+ IsChecked="{Binding Source={x:Static p:Settings.Default}, Path=PreviewSampleBytes, Converter={StaticResource IntEquals}, ConverterParameter=1, Mode=OneWay}"
+ AutomationProperties.AutomationId="MenuPreviewSamples1" />
+ </MenuItem>
</MenuItem>
<MenuItem Header="{DynamicResource MenuSimulation}">
<MenuItem Command="{x:Static commands:SimulationCommands.Run}" Header="{DynamicResource MenuSimulationRun}" InputGestureText="F5" />
diff --git a/WaveDude.WPF/MainWindow.xaml.cs b/WaveDude.WPF/MainWindow.xaml.cs
index 54eeba5..436fdc9 100644
--- a/WaveDude.WPF/MainWindow.xaml.cs
+++ b/WaveDude.WPF/MainWindow.xaml.cs
@@ -85,6 +85,11 @@ public partial class MainWindow : Window
{
Logger.Info("Frames kept in memory: {Percent} % of the RAM, {Budget} right now (Simulation menu)", Settings.Default.FrameMemoryPercent, FrameMemory.Gigabytes(FrameMemory.Budget(Settings.Default.FrameMemoryPercent)));
}
+ else if (args.PropertyName is nameof(Settings.PreviewResolution) or nameof(Settings.PreviewFrames) or nameof(Settings.PreviewSampleBytes))
+ {
+ Logger.Info("Preview quality: {Quality} (View menu)", PreviewQualitySetting);
+ OnPreviewQualityChanged();
+ }
};
Closing += (_, e) =>
{
@@ -329,11 +334,23 @@ public partial class MainWindow : Window
}
/// <summary>Simulation > Frames kept in memory: the chosen share of the RAM, applied to the next run.</summary>
- private void OnSetFrameMemory(object sender, ExecutedRoutedEventArgs e)
+ private void OnSetFrameMemory(object sender, ExecutedRoutedEventArgs e) => SetIntSetting(e, percent => Settings.Default.FrameMemoryPercent = percent);
+
+ /// <summary>View > Preview resolution: the canvas divisor (1, 2, 4), applied to the next scratch frame and run.</summary>
+ private void OnSetPreviewResolution(object sender, ExecutedRoutedEventArgs e) => SetIntSetting(e, divisor => Settings.Default.PreviewResolution = divisor);
+
+ /// <summary>View > Preview frames: the multiplier of the project's visualisation interval (1, 2, 4).</summary>
+ private void OnSetPreviewFrames(object sender, ExecutedRoutedEventArgs e) => SetIntSetting(e, divisor => Settings.Default.PreviewFrames = divisor);
+
+ /// <summary>View > Preview samples: the bytes per sample (2 halves, 1 palette indices).</summary>
+ private void OnSetPreviewSamples(object sender, ExecutedRoutedEventArgs e) => SetIntSetting(e, bytes => Settings.Default.PreviewSampleBytes = bytes);
+
+ /// <summary>A menu choice carried as a number in the command parameter: stores it and saves the settings.</summary>
+ private static void SetIntSetting(ExecutedRoutedEventArgs e, Action<int> apply)
{
- if (e.Parameter is string text && int.TryParse(text, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int percent))
+ if (e.Parameter is string text && int.TryParse(text, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int value))
{
- Settings.Default.FrameMemoryPercent = percent;
+ apply(value);
SaveSettings();
}
}
diff --git a/WaveDude.WPF/Panes/PreviewPane.xaml.cs b/WaveDude.WPF/Panes/PreviewPane.xaml.cs
index 2f22e19..dabf8ab 100644
--- a/WaveDude.WPF/Panes/PreviewPane.xaml.cs
+++ b/WaveDude.WPF/Panes/PreviewPane.xaml.cs
@@ -117,6 +117,7 @@ public partial class PreviewPane : UserControl
public static readonly DependencyProperty FpsProperty = DependencyProperty.Register(
nameof(Fps), typeof(int), typeof(PreviewPane), new PropertyMetadata(Video.DefaultFps, null, (_, value) => Math.Max(1, (int)value)));
+
/// <summary>Identifies the <see cref="InPoint"/> property.</summary>
public static readonly DependencyProperty InPointProperty = DependencyProperty.Register(
nameof(InPoint), typeof(int), typeof(PreviewPane), new PropertyMetadata(0));
@@ -258,7 +259,9 @@ public partial class PreviewPane : UserControl
InitializeComponent();
_presenter = new FramePresenter(Dispatcher);
- // frames = ceil(steps / visualize every); re-evaluated whenever the project or its settings change
+ // frames = ceil(steps / visualize every); re-evaluated whenever the project or its settings change. The
+ // timeline is always the project's: a reduced preview (View > Preview frames) stores fewer frames, but
+ // the run's Frames source stands a stored frame in for the ones left out (2026-10-15)
SetBinding(FrameCountProperty, new MultiBinding
{
Converter = new FrameCountConverter(),
@@ -637,10 +640,11 @@ public partial class PreviewPane : UserControl
}
else if (run != null && run.FrameCount > Position)
{
- _presenter.Source = run.Store;
+ // the run's frames in timeline numbering (a reduced preview stands a stored frame in for the ones left out)
+ _presenter.Source = run.Frames;
// the stored frame is right even with the probes stale; the graphs then take the scratch recording for this position once it is there
GraphScratch = IsProbesStale && scratch is { Snapshot: not null } && scratch.Frame == Position ? scratch : null;
- UpdateCanvas(run.Store);
+ UpdateCanvas(run.Frames);
_presenter.Show(Position);
}
else if (run == null && scratch == null && _presenter.Source != null)
@@ -661,9 +665,11 @@ public partial class PreviewPane : UserControl
private void UpdateCanvas(IFrameSource? source)
{
- // the scene image's size wins over the project's numbers, which only apply to a blank canvas
- int width = Math.Max(1, source?.Width ?? Run?.Spec.Width ?? ScenePixels?.Width ?? (int)GetValue(SceneWidthProperty));
- int height = Math.Max(1, source?.Height ?? Run?.Spec.Height ?? ScenePixels?.Height ?? (int)GetValue(SceneHeightProperty));
+ // the scene image's size wins over the project's numbers, which only apply to a blank canvas; a frame
+ // source knows the canvas it was shrunk from (the handles and boxes live in canvas pixels, whatever the
+ // picture's own size is)
+ int width = Math.Max(1, source?.CanvasWidth ?? Run?.Spec.Width ?? ScenePixels?.Width ?? (int)GetValue(SceneWidthProperty));
+ int height = Math.Max(1, source?.CanvasHeight ?? Run?.Spec.Height ?? ScenePixels?.Height ?? (int)GetValue(SceneHeightProperty));
CanvasWidth = width;
CanvasHeight = height;
if (_blackFrame.PixelWidth != width || _blackFrame.PixelHeight != height)
diff --git a/WaveDude.WPF/Properties/Settings.Designer.cs b/WaveDude.WPF/Properties/Settings.Designer.cs
index 4b6f0a0..b7e084e 100644
--- a/WaveDude.WPF/Properties/Settings.Designer.cs
+++ b/WaveDude.WPF/Properties/Settings.Designer.cs
@@ -189,6 +189,42 @@ namespace WaveDude.WPF.Properties {
}
}
+ [global::System.Configuration.UserScopedSettingAttribute()]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Configuration.DefaultSettingValueAttribute("1")]
+ public int PreviewResolution {
+ get {
+ return ((int)(this["PreviewResolution"]));
+ }
+ set {
+ this["PreviewResolution"] = value;
+ }
+ }
+
+ [global::System.Configuration.UserScopedSettingAttribute()]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Configuration.DefaultSettingValueAttribute("1")]
+ public int PreviewFrames {
+ get {
+ return ((int)(this["PreviewFrames"]));
+ }
+ set {
+ this["PreviewFrames"] = value;
+ }
+ }
+
+ [global::System.Configuration.UserScopedSettingAttribute()]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Configuration.DefaultSettingValueAttribute("2")]
+ public int PreviewSampleBytes {
+ get {
+ return ((int)(this["PreviewSampleBytes"]));
+ }
+ set {
+ this["PreviewSampleBytes"] = value;
+ }
+ }
+
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
diff --git a/WaveDude.WPF/Properties/Settings.settings b/WaveDude.WPF/Properties/Settings.settings
index db89a87..766a931 100644
--- a/WaveDude.WPF/Properties/Settings.settings
+++ b/WaveDude.WPF/Properties/Settings.settings
@@ -44,6 +44,15 @@
<Setting Name="FrameMemoryPercent" Type="System.Int32" Scope="User">
<Value Profile="(Default)">50</Value>
</Setting>
+ <Setting Name="PreviewResolution" Type="System.Int32" Scope="User">
+ <Value Profile="(Default)">1</Value>
+ </Setting>
+ <Setting Name="PreviewFrames" Type="System.Int32" Scope="User">
+ <Value Profile="(Default)">1</Value>
+ </Setting>
+ <Setting Name="PreviewSampleBytes" Type="System.Int32" Scope="User">
+ <Value Profile="(Default)">2</Value>
+ </Setting>
<Setting Name="LastExportFolder" Type="System.String" Scope="User">
<Value Profile="(Default)" />
</Setting>
diff --git a/WaveDude.WPF/Rendering/FramePresenter.cs b/WaveDude.WPF/Rendering/FramePresenter.cs
index 8ef6b60..f1a73d8 100644
--- a/WaveDude.WPF/Rendering/FramePresenter.cs
+++ b/WaveDude.WPF/Rendering/FramePresenter.cs
@@ -4,6 +4,7 @@ using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using NLog;
+using WaveDude.Engine;
using WaveDude.Rendering;
using WaveDude.Runs;
@@ -52,7 +53,10 @@ public sealed class FramePresenter
public IFrameSource Source { get; } = source;
public WriteableBitmap?[] Bitmaps { get; } = [field, intensity];
public LayerSettings[] Settings { get; } = settings;
- public Half[] Values { get; } = new Half[source.Width * source.Height];
+ /// <summary>The plane read from the source as halves (a <see cref="FrameFormat.Half"/> source), else null.</summary>
+ public Half[]? Halves { get; } = source.Format == FrameFormat.Half ? new Half[source.Width * source.Height] : null;
+ /// <summary>The plane read from the source as palette indices (a <see cref="FrameFormat.Index"/> source), else null.</summary>
+ public byte[]? Indices { get; } = source.Format == FrameFormat.Index ? new byte[source.Width * source.Height] : null;
public int[] Pixels { get; } = new int[source.Width * source.Height];
}
@@ -71,7 +75,7 @@ public sealed class FramePresenter
return;
}
bool sameShape = _source != null && value != null && _source.Width == value.Width && _source.Height == value.Height
- && _source.Has(FrameLayer.Intensity) == value.Has(FrameLayer.Intensity);
+ && _source.Format == value.Format && _source.Has(FrameLayer.Intensity) == value.Has(FrameLayer.Intensity);
Logger.Trace("Presenter source: {Source} (same shape {Same})", value?.GetType().Name ?? "none", sameShape);
_source = value;
if (!sameShape)
@@ -177,17 +181,27 @@ public sealed class FramePresenter
{
LayerSettings settings = job.Settings[(int)layer];
WriteableBitmap? bitmap = job.Bitmaps[(int)layer];
- if (!settings.Enabled || bitmap == null || !job.Source.Has(layer) || !job.Source.CopyLayer(frame, layer, job.Values))
+ if (!settings.Enabled || bitmap == null || !job.Source.Has(layer))
{
continue;
}
- if (layer == FrameLayer.Field)
+ bool copied = job.Indices != null ? job.Source.CopyLayer(frame, layer, job.Indices.AsSpan()) : job.Source.CopyLayer(frame, layer, job.Halves.AsSpan());
+ if (!copied)
{
- FrameRenderer.RenderField(job.Values, width, height, settings.Lut, settings.Brightness, job.Pixels);
+ continue;
+ }
+ if (job.Indices != null)
+ {
+ // palette indices: the brightness was applied when the frame was captured, only the palette is looked up
+ FrameRenderer.RenderIndexed(job.Indices, width, height, settings.Lut, job.Pixels);
+ }
+ else if (layer == FrameLayer.Field)
+ {
+ FrameRenderer.RenderField(job.Halves, width, height, settings.Lut, settings.Brightness, job.Pixels);
}
else
{
- FrameRenderer.RenderIntensity(job.Values, width, height, settings.Lut, settings.Brightness, job.Pixels);
+ FrameRenderer.RenderIntensity(job.Halves, width, height, settings.Lut, settings.Brightness, job.Pixels);
}
// the bitmap belongs to the UI thread; wait for the copy so the pixel buffer can be reused
_dispatcher.Invoke(() => bitmap.WritePixels(new Int32Rect(0, 0, width, height), job.Pixels, width * 4, 0), DispatcherPriority.Render);
diff --git a/WaveDude.WPF/Strings/Strings.DE.xaml b/WaveDude.WPF/Strings/Strings.DE.xaml
index c294875..3291fe4 100644
--- a/WaveDude.WPF/Strings/Strings.DE.xaml
+++ b/WaveDude.WPF/Strings/Strings.DE.xaml
@@ -25,6 +25,17 @@
<s:String x:Key="MenuViewPanes">_Fenster</s:String>
<s:String x:Key="MenuViewTheme">_Design</s:String>
<s:String x:Key="MenuViewLanguage">_Sprache</s:String>
+ <s:String x:Key="MenuViewResolution">Vorschau_auflösung</s:String>
+ <s:String x:Key="MenuViewResolutionFull">_Voll</s:String>
+ <s:String x:Key="MenuViewResolutionHalf">_Halb</s:String>
+ <s:String x:Key="MenuViewResolutionQuarter">V_iertel</s:String>
+ <s:String x:Key="MenuViewFrames">Vorschau_bilder</s:String>
+ <s:String x:Key="MenuViewFramesFull">_Alle</s:String>
+ <s:String x:Key="MenuViewFramesHalf">_Halb (jedes zweite Bild)</s:String>
+ <s:String x:Key="MenuViewFramesQuarter">V_iertel (jedes vierte Bild)</s:String>
+ <s:String x:Key="MenuViewSamples">Vorschau_werte</s:String>
+ <s:String x:Key="MenuViewSamples16">_16-Bit-Gleitkomma</s:String>
+ <s:String x:Key="MenuViewSamples8">_8-Bit-Palettenindex (Helligkeit beim Start des Laufs festgelegt)</s:String>
<s:String x:Key="LanguageSystem">System</s:String>
<s:String x:Key="MenuSimulation">_Simulation</s:String>
<s:String x:Key="MenuSimulationRun">_Starten</s:String>
diff --git a/WaveDude.WPF/Strings/Strings.EN.xaml b/WaveDude.WPF/Strings/Strings.EN.xaml
index 90738ea..0dabfbd 100644
--- a/WaveDude.WPF/Strings/Strings.EN.xaml
+++ b/WaveDude.WPF/Strings/Strings.EN.xaml
@@ -25,6 +25,17 @@
<s:String x:Key="MenuViewPanes">_Panes</s:String>
<s:String x:Key="MenuViewTheme">_Theme</s:String>
<s:String x:Key="MenuViewLanguage">_Language</s:String>
+ <s:String x:Key="MenuViewResolution">Preview _resolution</s:String>
+ <s:String x:Key="MenuViewResolutionFull">_Full</s:String>
+ <s:String x:Key="MenuViewResolutionHalf">_Half</s:String>
+ <s:String x:Key="MenuViewResolutionQuarter">_Quarter</s:String>
+ <s:String x:Key="MenuViewFrames">Preview _frames</s:String>
+ <s:String x:Key="MenuViewFramesFull">_Full</s:String>
+ <s:String x:Key="MenuViewFramesHalf">_Half (every second frame)</s:String>
+ <s:String x:Key="MenuViewFramesQuarter">_Quarter (every fourth frame)</s:String>
+ <s:String x:Key="MenuViewSamples">Preview _samples</s:String>
+ <s:String x:Key="MenuViewSamples16">_16-bit float</s:String>
+ <s:String x:Key="MenuViewSamples8">_8-bit palette index (brightness fixed when the run starts)</s:String>
<s:String x:Key="LanguageSystem">System</s:String>
<s:String x:Key="MenuSimulation">_Simulation</s:String>
<s:String x:Key="MenuSimulationRun">_Run</s:String>
diff --git a/WaveDude.WPF/Strings/Strings.FR.xaml b/WaveDude.WPF/Strings/Strings.FR.xaml
index 1b719c5..7a73df3 100644
--- a/WaveDude.WPF/Strings/Strings.FR.xaml
+++ b/WaveDude.WPF/Strings/Strings.FR.xaml
@@ -25,6 +25,17 @@
<s:String x:Key="MenuViewPanes">_Panneaux</s:String>
<s:String x:Key="MenuViewTheme">_Thème</s:String>
<s:String x:Key="MenuViewLanguage">_Langue</s:String>
+ <s:String x:Key="MenuViewResolution">_Résolution de l'aperçu</s:String>
+ <s:String x:Key="MenuViewResolutionFull">_Complète</s:String>
+ <s:String x:Key="MenuViewResolutionHalf">_Moitié</s:String>
+ <s:String x:Key="MenuViewResolutionQuarter">_Quart</s:String>
+ <s:String x:Key="MenuViewFrames">_Images de l'aperçu</s:String>
+ <s:String x:Key="MenuViewFramesFull">_Toutes</s:String>
+ <s:String x:Key="MenuViewFramesHalf">_Moitié (une image sur deux)</s:String>
+ <s:String x:Key="MenuViewFramesQuarter">_Quart (une image sur quatre)</s:String>
+ <s:String x:Key="MenuViewSamples">Éc_hantillons de l'aperçu</s:String>
+ <s:String x:Key="MenuViewSamples16">Flottant _16 bits</s:String>
+ <s:String x:Key="MenuViewSamples8">Index de palette _8 bits (luminosité fixée au départ du calcul)</s:String>
<s:String x:Key="LanguageSystem">Système</s:String>
<s:String x:Key="MenuSimulation">_Simulation</s:String>
<s:String x:Key="MenuSimulationRun">_Lancer</s:String>
diff --git a/WaveDude.WPF/Strings/Strings.NL.xaml b/WaveDude.WPF/Strings/Strings.NL.xaml
index 22bcec3..146a77c 100644
--- a/WaveDude.WPF/Strings/Strings.NL.xaml
+++ b/WaveDude.WPF/Strings/Strings.NL.xaml
@@ -25,6 +25,17 @@
<s:String x:Key="MenuViewPanes">_Panelen</s:String>
<s:String x:Key="MenuViewTheme">_Thema</s:String>
<s:String x:Key="MenuViewLanguage">Taa_l</s:String>
+ <s:String x:Key="MenuViewResolution">Voorbeeld_resolutie</s:String>
+ <s:String x:Key="MenuViewResolutionFull">_Volledig</s:String>
+ <s:String x:Key="MenuViewResolutionHalf">_Half</s:String>
+ <s:String x:Key="MenuViewResolutionQuarter">_Kwart</s:String>
+ <s:String x:Key="MenuViewFrames">Voorbeeld_frames</s:String>
+ <s:String x:Key="MenuViewFramesFull">_Alle</s:String>
+ <s:String x:Key="MenuViewFramesHalf">_Half (elk tweede frame)</s:String>
+ <s:String x:Key="MenuViewFramesQuarter">_Kwart (elk vierde frame)</s:String>
+ <s:String x:Key="MenuViewSamples">Voorbeeld_samples</s:String>
+ <s:String x:Key="MenuViewSamples16">_16-bits zwevende komma</s:String>
+ <s:String x:Key="MenuViewSamples8">_8-bits paletindex (helderheid vastgelegd bij de start van de run)</s:String>
<s:String x:Key="LanguageSystem">Systeem</s:String>
<s:String x:Key="MenuSimulation">_Simulatie</s:String>
<s:String x:Key="MenuSimulationRun">_Starten</s:String>
diff --git a/WaveDude/Engine/FrameShape.cs b/WaveDude/Engine/FrameShape.cs
new file mode 100644
index 0000000..48e36c4
--- /dev/null
+++ b/WaveDude/Engine/FrameShape.cs
@@ -0,0 +1,168 @@
+using System.Numerics.Tensors;
+using System.Runtime.InteropServices;
+using WaveDude.Rendering;
+
+namespace WaveDude.Engine;
+
+/// <summary>How the samples of a captured frame are stored.</summary>
+public enum FrameFormat
+{
+ /// <summary>One <see cref="System.Half"/> per sample: the raw amplitude or intensity, coloured at display time with any brightness.</summary>
+ Half = 0,
+
+ /// <summary>
+ /// One byte per sample: the palette index (0..254) the renderer would compute with the brightness the frame was
+ /// captured with (<see cref="FrameShape.FieldBrightness"/>, <see cref="FrameShape.IntensityBrightness"/>), so the
+ /// display's own quantisation is what is stored, at half the size of <see cref="Half"/> and with a table lookup
+ /// per pixel to show. The palette and the black level still recolour such a frame; the brightness is baked in.
+ /// </summary>
+ Index = 1,
+}
+
+/// <summary>
+/// The geometry and format of the frames a run captures (2026-10-15, the reduced preview for weaker machines):
+/// the canvas of the simulation, the divisor that shrinks it (every <see cref="Divisor"/> × <see cref="Divisor"/>
+/// block of cells averaged into one sample), the sample format and, for <see cref="FrameFormat.Index"/>, the
+/// brightness of each layer at capture time. The simulation itself always runs at the canvas size; only what is
+/// captured, stored and shown shrinks. Immutable; compared by value.
+/// </summary>
+/// <param name="CanvasWidth">Width of the simulated canvas in cells.</param>
+/// <param name="CanvasHeight">Height of the simulated canvas in cells.</param>
+/// <param name="Divisor">Cells per sample along each axis, at least 1; the last block of a row or column may be smaller and is averaged over the cells it has.</param>
+/// <param name="Format">The sample format.</param>
+/// <param name="FieldBrightness">Gain applied to the field before the palette index is taken (<see cref="FrameFormat.Index"/> only).</param>
+/// <param name="IntensityBrightness">Gain applied to the compressed intensity before the palette index is taken (<see cref="FrameFormat.Index"/> only).</param>
+public sealed record FrameShape(int CanvasWidth, int CanvasHeight, int Divisor, FrameFormat Format, float FieldBrightness, float IntensityBrightness)
+{
+ /// <summary>The full-quality shape of a canvas: every cell as a <see cref="FrameFormat.Half"/>.</summary>
+ public static FrameShape Full(int canvasWidth, int canvasHeight) => new(canvasWidth, canvasHeight, 1, FrameFormat.Half, 1f, 1f);
+
+ /// <summary>Frame width in samples: ⌈<see cref="CanvasWidth"/> / <see cref="Divisor"/>⌉.</summary>
+ public int Width => (CanvasWidth + Divisor - 1) / Divisor;
+
+ /// <summary>Frame height in samples: ⌈<see cref="CanvasHeight"/> / <see cref="Divisor"/>⌉.</summary>
+ public int Height => (CanvasHeight + Divisor - 1) / Divisor;
+
+ /// <summary>Bytes per sample: 2 for <see cref="FrameFormat.Half"/>, 1 for <see cref="FrameFormat.Index"/>.</summary>
+ public int SampleBytes => Format == FrameFormat.Half ? 2 : 1;
+
+ /// <summary>Bytes of one plane of a frame.</summary>
+ public long PlaneBytes => (long)Width * Height * SampleBytes;
+
+ /// <summary>Whether this is the full-quality shape (no shrinking, <see cref="FrameFormat.Half"/>); the brightness does not count then.</summary>
+ public bool IsFull => Divisor == 1 && Format == FrameFormat.Half;
+
+ /// <summary>The brightness baked into a plane: the field's or the intensity's.</summary>
+ public float BrightnessOf(bool intensity) => intensity ? IntensityBrightness : FieldBrightness;
+
+ /// <summary>Whether frames of this shape and of <paramref name="other"/> have the same size and format (the brightness may differ).</summary>
+ public bool SameLayoutAs(FrameShape other) => Width == other.Width && Height == other.Height && Format == other.Format;
+
+ /// <summary>Validates the record: the canvas at least 1 × 1, the divisor at least 1.</summary>
+ /// <exception cref="ArgumentOutOfRangeException">A dimension or the divisor is below 1.</exception>
+ public FrameShape Validate()
+ {
+ ArgumentOutOfRangeException.ThrowIfLessThan(CanvasWidth, 1, nameof(CanvasWidth));
+ ArgumentOutOfRangeException.ThrowIfLessThan(CanvasHeight, 1, nameof(CanvasHeight));
+ ArgumentOutOfRangeException.ThrowIfLessThan(Divisor, 1, nameof(Divisor));
+ return this;
+ }
+}
+
+/// <summary>
+/// Turns a float plane of the canvas into a frame plane of a <see cref="FrameShape"/>: the reference
+/// implementation of the shrinking and of the <see cref="FrameFormat.Index"/> mapping, used by the CPU engine
+/// (on the thread that awaits a capture) and by the checks that hold the GPU kernels to it. Rows run in
+/// parallel; the caller owns the buffers.
+/// </summary>
+public static class FrameConversion
+{
+ /// <summary>
+ /// Converts one plane. For a divisor of 1 a <see cref="FrameFormat.Half"/> plane is the vectorised
+ /// float-to-half conversion; otherwise every block of <see cref="FrameShape.Divisor"/>² cells (fewer at the
+ /// right and bottom edges) is averaged first, then the sample is taken as a half or as the palette index
+ /// (<see cref="ColorLut.FieldIndex"/> or <see cref="ColorLut.IntensityIndex(float, float)"/> with the shape's brightness).
+ /// </summary>
+ /// <param name="source">The float values; row y of the canvas starts at <paramref name="offset"/> + y × <paramref name="stride"/>.</param>
+ /// <param name="offset">Index of the canvas's first cell in <paramref name="source"/> (stride + 1 for an engine's padded buffer, 0 for a packed plane).</param>
+ /// <param name="stride">Row pitch of <paramref name="source"/>.</param>
+ /// <param name="shape">The frame's shape; its canvas size is the plane's.</param>
+ /// <param name="intensity">Whether the plane is the intensity (its brightness, its index mapping) rather than the field.</param>
+ /// <param name="destination">Receives <see cref="FrameShape.PlaneBytes"/> bytes, row-major samples.</param>
+ /// <exception cref="ArgumentOutOfRangeException">The destination is too small.</exception>
+ public static void Convert(float[] source, int offset, int stride, FrameShape shape, bool intensity, Memory<byte> destination)
+ {
+ int width = shape.Width;
+ int height = shape.Height;
+ if (destination.Length < shape.PlaneBytes)
+ {
+ throw new ArgumentOutOfRangeException(nameof(destination), "The destination is smaller than a plane.");
+ }
+ int divisor = shape.Divisor;
+ float brightness = shape.BrightnessOf(intensity);
+ if (divisor == 1 && shape.Format == FrameFormat.Half)
+ {
+ Parallel.For(0, height, y =>
+ TensorPrimitives.ConvertToHalf(source.AsSpan(offset + y * stride, width), MemoryMarshal.Cast<byte, Half>(destination.Span.Slice(y * width * 2, width * 2))));
+ return;
+ }
+ int canvasWidth = shape.CanvasWidth;
+ int canvasHeight = shape.CanvasHeight;
+ Parallel.For(0, height, () => new float[width], (y, _, row) =>
+ {
+ if (divisor == 1)
+ {
+ source.AsSpan(offset + y * stride, width).CopyTo(row);
+ }
+ else
+ {
+ Average(source, offset, stride, canvasWidth, canvasHeight, divisor, y, row);
+ }
+ if (shape.Format == FrameFormat.Half)
+ {
+ TensorPrimitives.ConvertToHalf(row, MemoryMarshal.Cast<byte, Half>(destination.Span.Slice(y * width * 2, width * 2)));
+ }
+ else
+ {
+ Span<byte> target = destination.Span.Slice(y * width, width);
+ if (intensity)
+ {
+ for (int x = 0; x < width; x++)
+ {
+ target[x] = (byte)ColorLut.IntensityIndex(row[x], brightness);
+ }
+ }
+ else
+ {
+ for (int x = 0; x < width; x++)
+ {
+ target[x] = (byte)ColorLut.FieldIndex(row[x], brightness);
+ }
+ }
+ }
+ return row;
+ }, _ => { });
+ }
+
+ /// <summary>One output row of block averages: the mean of every divisor × divisor block of the canvas, clipped at its right and bottom edges.</summary>
+ private static void Average(float[] source, int offset, int stride, int canvasWidth, int canvasHeight, int divisor, int y, float[] row)
+ {
+ int rowStart = y * divisor;
+ int rowEnd = Math.Min(canvasHeight, rowStart + divisor);
+ for (int x = 0; x < row.Length; x++)
+ {
+ int columnStart = x * divisor;
+ int columnEnd = Math.Min(canvasWidth, columnStart + divisor);
+ float sum = 0f;
+ for (int cy = rowStart; cy < rowEnd; cy++)
+ {
+ int at = offset + cy * stride;
+ for (int cx = columnStart; cx < columnEnd; cx++)
+ {
+ sum += source[at + cx];
+ }
+ }
+ row[x] = sum / ((rowEnd - rowStart) * (columnEnd - columnStart));
+ }
+ }
+}
diff --git a/WaveDude/Engine/FrameSnapshot.cs b/WaveDude/Engine/FrameSnapshot.cs
index f9c7ebc..53b385e 100644
--- a/WaveDude/Engine/FrameSnapshot.cs
+++ b/WaveDude/Engine/FrameSnapshot.cs
@@ -4,38 +4,58 @@ namespace WaveDude.Engine;
/// <summary>
/// A host-side copy of one frame in the frame store's format: the field and, optionally, the intensity as
-/// <see cref="Half"/> planes of <see cref="Width"/> × <see cref="Height"/> values, row-major, without the
-/// engine's padding. Filled by <see cref="IWaveEngine.CaptureFrame"/> and complete after
+/// planes of a <see cref="FrameShape"/> (<see cref="Width"/> × <see cref="Height"/> samples row-major, the
+/// engine's padding stripped, the canvas shrunk by the shape's divisor, each sample a <see cref="Half"/> or a
+/// palette index byte). Filled by <see cref="IWaveEngine.CaptureFrame"/> and complete after
/// <see cref="IWaveEngine.AwaitFrame"/>; the arrays live on the pinned object heap so the GPU can copy into
/// them asynchronously. Reusable: a pool of two or three lets a run convert and store one frame while the
/// engine computes the next. Not thread-safe; one owner at a time.
/// </summary>
public sealed class FrameSnapshot
{
+ /// <param name="shape">What to capture: the canvas, the shrinking, the format and the brightness baked into an index frame.</param>
+ /// <param name="withIntensity">Whether to allocate the intensity plane.</param>
+ public FrameSnapshot(FrameShape shape, bool withIntensity)
+ {
+ Shape = shape.Validate();
+ int bytes = checked((int)shape.PlaneBytes);
+ FieldBytes = GC.AllocateArray<byte>(bytes, pinned: true);
+ IntensityBytes = withIntensity ? GC.AllocateArray<byte>(bytes, pinned: true) : null;
+ }
+
+ /// <summary>A full-quality snapshot of a canvas: every cell as a <see cref="Half"/>.</summary>
/// <param name="width">Canvas width in pixels.</param>
/// <param name="height">Canvas height in pixels.</param>
/// <param name="withIntensity">Whether to allocate the intensity plane.</param>
public FrameSnapshot(int width, int height, bool withIntensity)
+ : this(FrameShape.Full(width, height), withIntensity)
{
- Width = width;
- Height = height;
- Field = GC.AllocateArray<Half>(width * height, pinned: true);
- Intensity = withIntensity ? GC.AllocateArray<Half>(width * height, pinned: true) : null;
}
- /// <summary>Canvas width in pixels.</summary>
- public int Width { get; }
+ /// <summary>The frame's geometry and format; the engine captures accordingly.</summary>
+ public FrameShape Shape { get; }
+
+ /// <summary>Frame width in samples (<see cref="FrameShape.Width"/>).</summary>
+ public int Width => Shape.Width;
- /// <summary>Canvas height in pixels.</summary>
- public int Height { get; }
+ /// <summary>Frame height in samples (<see cref="FrameShape.Height"/>).</summary>
+ public int Height => Shape.Height;
- /// <summary>The field plane; valid after <see cref="IWaveEngine.AwaitFrame"/>.</summary>
- public Half[] Field { get; }
+ /// <summary>The field plane's bytes (<see cref="FrameShape.PlaneBytes"/>); valid after <see cref="IWaveEngine.AwaitFrame"/>.</summary>
+ public byte[] FieldBytes { get; }
- /// <summary>The intensity plane, or null when the snapshot was created without one.</summary>
- public Half[]? Intensity { get; }
+ /// <summary>The intensity plane's bytes, or null when the snapshot was created without one.</summary>
+ public byte[]? IntensityBytes { get; }
- /// <summary>Whether the last capture filled <see cref="Intensity"/> (the engine may have been asked for the field only).</summary>
+ /// <summary>The field plane as <see cref="Half"/> values; only for a <see cref="FrameFormat.Half"/> shape.</summary>
+ /// <exception cref="InvalidOperationException">The shape's samples are not halves.</exception>
+ public Span<Half> Field => Halves(FieldBytes);
+
+ /// <summary>The intensity plane as <see cref="Half"/> values; only for a <see cref="FrameFormat.Half"/> shape with an intensity plane.</summary>
+ /// <exception cref="InvalidOperationException">The shape's samples are not halves, or there is no intensity plane.</exception>
+ public Span<Half> Intensity => Halves(IntensityBytes ?? throw new InvalidOperationException("The snapshot has no intensity plane."));
+
+ /// <summary>Whether the last capture filled <see cref="IntensityBytes"/> (the engine may have been asked for the field only).</summary>
public bool HasIntensity { get; internal set; }
/// <summary>The frame index the owner captured into this snapshot; a tag for the pipeline, not used by the engines.</summary>
@@ -50,7 +70,7 @@ public sealed class FrameSnapshot
/// <summary>Number of valid entries in <see cref="Events"/>.</summary>
internal int EventCount { get; set; }
- /// <summary>The CPU engine's staging: the planes as floats, copied at capture time and converted in <see cref="IWaveEngine.AwaitFrame"/> (on the awaiting thread, off the stepping thread).</summary>
+ /// <summary>The CPU engine's staging: the canvas planes as floats, copied at capture time and converted in <see cref="IWaveEngine.AwaitFrame"/> (on the awaiting thread, off the stepping thread).</summary>
internal float[]? FieldFloats { get; set; }
/// <summary>Intensity staging of the CPU engine; see <see cref="FieldFloats"/>.</summary>
@@ -59,6 +79,15 @@ public sealed class FrameSnapshot
/// <summary>Whether <see cref="FieldFloats"/> (and <see cref="IntensityFloats"/> when <see cref="HasIntensity"/>) hold a capture not yet converted.</summary>
internal bool PendingConversion { get; set; }
- /// <summary>Address of a plane's first element, stable because the arrays are pinned.</summary>
- internal static IntPtr AddressOf(Half[] plane) => Marshal.UnsafeAddrOfPinnedArrayElement(plane, 0);
+ /// <summary>Address of a plane's first byte, stable because the arrays are pinned.</summary>
+ internal static IntPtr AddressOf(byte[] plane) => Marshal.UnsafeAddrOfPinnedArrayElement(plane, 0);
+
+ private Span<Half> Halves(byte[] plane)
+ {
+ if (Shape.Format != FrameFormat.Half)
+ {
+ throw new InvalidOperationException("The snapshot's samples are palette indices, not halves.");
+ }
+ return MemoryMarshal.Cast<byte, Half>(plane.AsSpan());
+ }
}
diff --git a/WaveDude/Engine/GpuWaveSimulator.cs b/WaveDude/Engine/GpuWaveSimulator.cs
index 4d560e8..91d3698 100644
--- a/WaveDude/Engine/GpuWaveSimulator.cs
+++ b/WaveDude/Engine/GpuWaveSimulator.cs
@@ -200,9 +200,10 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
/// <inheritdoc/>
public void CaptureFrame(FrameSnapshot snapshot, bool needIntensity)
{
- if (snapshot.Width != _width || snapshot.Height != _height)
+ FrameShape shape = snapshot.Shape;
+ if (shape.CanvasWidth != _width || shape.CanvasHeight != _height)
{
- throw new ArgumentException("The snapshot does not match the engine's size.", nameof(snapshot));
+ throw new ArgumentException("The snapshot's canvas does not match the engine's size.", nameof(snapshot));
}
if (snapshot.EventCount > 0)
{
@@ -210,32 +211,56 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
}
if (_stagingField == IntPtr.Zero)
{
- // lazily: most engines never capture (the harness, the probes-only paths)
+ // lazily: most engines never capture (the harness, the probes-only paths). The staging planes have room
+ // for any shape: a plane is at most the whole canvas as halves
_stagingField = CreateBuffer((long)_width * _height * 2, _scene);
_stagingIntensity = _track ? CreateBuffer((long)_width * _height * 2, _scene) : IntPtr.Zero;
- _toHalfKernel = CreateKernel(_scene, _scene.Program, "to_half");
- SetInt(_toHalfKernel, 2U, _width);
- SetInt(_toHalfKernel, 3U, _height);
- SetInt(_toHalfKernel, 4U, _stride);
+ _captureHalfKernel = CreateKernel(_scene, _scene.Program, "capture_half");
+ _captureIndexKernel = CreateKernel(_scene, _scene.Program, "capture_index");
+ foreach (IntPtr kernel in new[] { _captureHalfKernel, _captureIndexKernel })
+ {
+ SetInt(kernel, 2U, _width);
+ SetInt(kernel, 3U, _height);
+ SetInt(kernel, 4U, _stride);
+ }
+ }
+ if (_captureShape == null || _captureShape.Divisor != shape.Divisor || !_captureShape.SameLayoutAs(shape))
+ {
+ // the shape's geometry, set once per shape (every capture of a run shares one)
+ _captureShape = shape;
+ _captureGrid = [new IntPtr(shape.Width), new IntPtr(shape.Height)];
+ foreach (IntPtr kernel in new[] { _captureHalfKernel, _captureIndexKernel })
+ {
+ SetInt(kernel, 5U, shape.Divisor);
+ SetInt(kernel, 6U, shape.Width);
+ SetInt(kernel, 7U, shape.Height);
+ }
}
snapshot.EventCount = 0;
- EnqueueCapture(_field[_current], _stagingField, snapshot.Field, snapshot);
- snapshot.HasIntensity = needIntensity && _track && snapshot.Intensity != null;
+ EnqueueCapture(_field[_current], _stagingField, snapshot.FieldBytes, snapshot, false);
+ snapshot.HasIntensity = needIntensity && _track && snapshot.IntensityBytes != null;
if (snapshot.HasIntensity)
{
- EnqueueCapture(_intensityOutBuffer, _stagingIntensity, snapshot.Intensity!, snapshot);
+ EnqueueCapture(_intensityOutBuffer, _stagingIntensity, snapshot.IntensityBytes!, snapshot, true);
}
// the reads flush the queue once they run; nothing piles up behind them
_sinceFinish = 0;
}
- /// <summary>Converts a padded float buffer to a half plane on the card and enqueues its non-blocking read into the pinned plane.</summary>
- private void EnqueueCapture(IntPtr source, IntPtr staging, Half[] plane, FrameSnapshot snapshot)
+ /// <summary>Shrinks and converts a padded float buffer to a plane of the snapshot's shape on the card and enqueues its non-blocking read into the pinned plane.</summary>
+ private void EnqueueCapture(IntPtr source, IntPtr staging, byte[] plane, FrameSnapshot snapshot, bool intensity)
{
- SetMem(_toHalfKernel, 0U, source);
- SetMem(_toHalfKernel, 1U, staging);
- Enqueue(_toHalfKernel, _grid2D, "to_half");
- OpenClApi.Check(OpenClApi.clEnqueueReadBufferPtr(_queue, staging, 0U, IntPtr.Zero, new IntPtr((long)plane.Length * 2), FrameSnapshot.AddressOf(plane), 0U, IntPtr.Zero, out IntPtr evt), "clEnqueueReadBuffer (capture)");
+ FrameShape shape = snapshot.Shape;
+ IntPtr kernel = shape.Format == FrameFormat.Half ? _captureHalfKernel : _captureIndexKernel;
+ SetMem(kernel, 0U, source);
+ SetMem(kernel, 1U, staging);
+ if (shape.Format == FrameFormat.Index)
+ {
+ SetFloat(kernel, 8U, shape.BrightnessOf(intensity));
+ SetInt(kernel, 9U, intensity ? 1 : 0);
+ }
+ Enqueue(kernel, _captureGrid!, "capture");
+ OpenClApi.Check(OpenClApi.clEnqueueReadBufferPtr(_queue, staging, 0U, IntPtr.Zero, new IntPtr(plane.Length), FrameSnapshot.AddressOf(plane), 0U, IntPtr.Zero, out IntPtr evt), "clEnqueueReadBuffer (capture)");
snapshot.Events[snapshot.EventCount++] = evt;
}
@@ -678,15 +703,48 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
source.AppendLine(" u[p] = u[p] * 0.9f + v * 0.1f;");
source.AppendLine("}");
source.AppendLine();
- // to_half: the interior of a padded float buffer as a tightly packed half plane (the frame store's
- // format), so a frame crosses the bus at half the size and the host converts nothing. vstore_half is
- // core OpenCL C; only half arithmetic would need cl_khr_fp16.
- source.AppendLine("__kernel void to_half(__global const float* src, __global half* dst, const int w, const int h, const int stride)");
+ // capture_half / capture_index: the interior of a padded float buffer as a tightly packed plane of the
+ // frame store's shape (FrameConversion is the reference): every div × div block of cells, clipped at the
+ // right and bottom edges, averaged into one sample, stored as a half or as the palette index the renderer
+ // would compute at the given brightness; so a frame crosses the bus at half the size or less and the host
+ // converts nothing. vstore_half is core OpenCL C; only half arithmetic would need cl_khr_fp16.
+ source.AppendLine("float capture_sample(__global const float* src, const int w, const int h, const int stride, const int div, const int x, const int y)");
+ source.AppendLine("{");
+ source.AppendLine(" if (div == 1) return src[(y + 1) * stride + x + 1];");
+ source.AppendLine(" int x0 = x * div, y0 = y * div;");
+ source.AppendLine(" int x1 = min(w, x0 + div), y1 = min(h, y0 + div);");
+ source.AppendLine(" float sum = 0.0f;");
+ source.AppendLine(" for (int cy = y0; cy < y1; cy++)");
+ source.AppendLine(" for (int cx = x0; cx < x1; cx++)");
+ source.AppendLine(" sum += src[(cy + 1) * stride + cx + 1];");
+ source.AppendLine(" return sum / (float)((y1 - y0) * (x1 - x0));");
+ source.AppendLine("}");
+ source.AppendLine();
+ source.AppendLine("__kernel void capture_half(__global const float* src, __global half* dst, const int w, const int h, const int stride, const int div, const int fw, const int fh)");
source.AppendLine("{");
source.AppendLine(" int x = get_global_id(0);");
source.AppendLine(" int y = get_global_id(1);");
- source.AppendLine(" if (x >= w || y >= h) return;");
- source.AppendLine(" vstore_half(src[(y + 1) * stride + x + 1], y * w + x, dst);");
+ source.AppendLine(" if (x >= fw || y >= fh) return;");
+ source.AppendLine(" vstore_half(capture_sample(src, w, h, stride, div, x, y), y * fw + x, dst);");
+ source.AppendLine("}");
+ source.AppendLine();
+ // the index mapping of ColorLut.FieldIndex / IntensityIndex: a NaN field gives the centre, a NaN or
+ // non-positive intensity 0; the sqrt is the card's single-precision one, so an index may differ by one
+ // from the host's double at a boundary
+ source.AppendLine("__kernel void capture_index(__global const float* src, __global uchar* dst, const int w, const int h, const int stride, const int div, const int fw, const int fh, const float brightness, const int intensity)");
+ source.AppendLine("{");
+ source.AppendLine(" int x = get_global_id(0);");
+ source.AppendLine(" int y = get_global_id(1);");
+ source.AppendLine(" if (x >= fw || y >= fh) return;");
+ source.AppendLine(" float v = capture_sample(src, w, h, stride, div, x, y);");
+ source.AppendLine(" int index;");
+ source.AppendLine(" if (intensity)");
+ source.AppendLine(" index = v > 0.0f ? (int)(fmin(sqrt(v) * brightness, 1.0f) * 254.0f) : 0;");
+ source.AppendLine(" else {");
+ source.AppendLine(" float s = v * brightness;");
+ source.AppendLine(" index = isnan(s) ? 127 : (int)(clamp(s, -1.0f, 1.0f) * 127.0f + 127.0f);");
+ source.AppendLine(" }");
+ source.AppendLine(" dst[y * fw + x] = (uchar)index;");
source.AppendLine("}");
return source.ToString();
}
@@ -1372,10 +1430,15 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
private IntPtr _intensityBuffer;
private IntPtr _intensityStage1Buffer;
- /// <summary>Half planes the <c>to_half</c> kernel writes for <see cref="CaptureFrame"/>; created on first use.</summary>
+ /// <summary>Planes the capture kernels write for <see cref="CaptureFrame"/>; created on first use, sized for any shape.</summary>
private IntPtr _stagingField;
private IntPtr _stagingIntensity;
- private IntPtr _toHalfKernel;
+ private IntPtr _captureHalfKernel;
+ private IntPtr _captureIndexKernel;
+
+ /// <summary>The shape the capture kernels' geometry arguments are set for, and the matching global work size.</summary>
+ private FrameShape? _captureShape;
+ private IntPtr[]? _captureGrid;
/// <summary>
/// Leapfrog sub-steps per simulation step - see the class summary; 1 (no sub-stepping) unless the 4th-order
diff --git a/WaveDude/Engine/IWaveEngine.cs b/WaveDude/Engine/IWaveEngine.cs
index c72b061..3ec9d23 100644
--- a/WaveDude/Engine/IWaveEngine.cs
+++ b/WaveDude/Engine/IWaveEngine.cs
@@ -50,12 +50,13 @@ public interface IWaveEngine
/// <summary>
/// Copies the newest field (and the intensity when asked and tracked) into <paramref name="snapshot"/> as
- /// <see cref="Half"/> planes without padding. The CPU engine converts synchronously; the GPU engine converts on
- /// the card and enqueues the reads without waiting, so the driver can keep stepping while they land. The
- /// snapshot must not be touched until <see cref="AwaitFrame"/> returned, and a capture must be awaited before
- /// the engine is disposed.
+ /// planes of its <see cref="FrameShape"/>: the padding stripped, the canvas shrunk by the shape's divisor,
+ /// the samples as halves or palette indices (<see cref="FrameConversion"/> is the reference). The CPU engine
+ /// copies the floats now and converts in <see cref="AwaitFrame"/>; the GPU engine converts on the card and
+ /// enqueues the reads without waiting, so the driver can keep stepping while they land. The snapshot must not
+ /// be touched until <see cref="AwaitFrame"/> returned, and a capture must be awaited before the engine is disposed.
/// </summary>
- /// <param name="snapshot">A snapshot of this engine's size; its planes receive the data.</param>
+ /// <param name="snapshot">A snapshot whose shape has this engine's canvas; its planes receive the data.</param>
/// <param name="needIntensity">Also copy the intensity (needs tracking and a snapshot with an intensity plane).</param>
void CaptureFrame(FrameSnapshot snapshot, bool needIntensity);
diff --git a/WaveDude/Engine/WaveSimulator.cs b/WaveDude/Engine/WaveSimulator.cs
index 18b5efd..6807485 100644
--- a/WaveDude/Engine/WaveSimulator.cs
+++ b/WaveDude/Engine/WaveSimulator.cs
@@ -214,14 +214,14 @@ public sealed class WaveSimulator : IWaveEngine, IDisposable
/// </summary>
public void CaptureFrame(FrameSnapshot snapshot, bool needIntensity)
{
- if (snapshot.Width != _width || snapshot.Height != _height)
+ if (snapshot.Shape.CanvasWidth != _width || snapshot.Shape.CanvasHeight != _height)
{
- throw new ArgumentException("The snapshot does not match the engine's size.", nameof(snapshot));
+ throw new ArgumentException("The snapshot's canvas does not match the engine's size.", nameof(snapshot));
}
int cells = _width * _height;
snapshot.FieldFloats ??= new float[cells];
CopyInterior(_u, snapshot.FieldFloats);
- snapshot.HasIntensity = needIntensity && _intensityOut != null && snapshot.Intensity != null;
+ snapshot.HasIntensity = needIntensity && _intensityOut != null && snapshot.IntensityBytes != null;
if (snapshot.HasIntensity)
{
snapshot.IntensityFloats ??= new float[cells];
@@ -238,10 +238,11 @@ public sealed class WaveSimulator : IWaveEngine, IDisposable
return;
}
snapshot.PendingConversion = false;
- Convert(snapshot.FieldFloats!, snapshot.Field);
+ // the shape's shrinking and format (FrameConversion), on the awaiting thread
+ FrameConversion.Convert(snapshot.FieldFloats!, 0, _width, snapshot.Shape, false, snapshot.FieldBytes);
if (snapshot.HasIntensity)
{
- Convert(snapshot.IntensityFloats!, snapshot.Intensity!);
+ FrameConversion.Convert(snapshot.IntensityFloats!, 0, _width, snapshot.Shape, true, snapshot.IntensityBytes!);
}
}
@@ -253,13 +254,6 @@ public sealed class WaveSimulator : IWaveEngine, IDisposable
Parallel.For(0, _height, y => source.AsSpan((y + 1) * stride + 1, width).CopyTo(target.AsSpan(y * width, width)));
}
- /// <summary>A packed float plane to <see cref="Half"/>, rows in parallel.</summary>
- private void Convert(float[] source, Half[] target)
- {
- int width = _width;
- Parallel.For(0, _height, y => TensorPrimitives.ConvertToHalf(source.AsSpan(y * width, width), target.AsSpan(y * width, width)));
- }
-
/// <summary>Scene width in cells (canvas pixels), excluding the padding.</summary>
public int Width => _width;
diff --git a/WaveDude/Export/ExportJob.cs b/WaveDude/Export/ExportJob.cs
index 89a11b1..760e8e5 100644
--- a/WaveDude/Export/ExportJob.cs
+++ b/WaveDude/Export/ExportJob.cs
@@ -3,6 +3,7 @@ using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using NLog;
+using WaveDude.Engine;
using WaveDude.Rendering;
using WaveDude.Runs;
@@ -89,6 +90,11 @@ public sealed class ExportJob : INotifyPropertyChanged
{
throw new ArgumentOutOfRangeException(nameof(lastFrame), "The range is empty.");
}
+ if (store.Format != FrameFormat.Half)
+ {
+ // a reduced preview run bakes the brightness into index bytes; an export renders from the raw samples (the window starts a full run first)
+ throw new ArgumentException("An export needs a full-quality run; this store holds palette indices.", nameof(store));
+ }
Store = store;
FirstFrame = firstFrame;
LastFrame = lastFrame;
diff --git a/WaveDude/Rendering/ColorLut.cs b/WaveDude/Rendering/ColorLut.cs
index b986b8a..163236f 100644
--- a/WaveDude/Rendering/ColorLut.cs
+++ b/WaveDude/Rendering/ColorLut.cs
@@ -98,6 +98,22 @@ public sealed class ColorLut
return (int)(Math.Clamp(scaled, -1f, 1f) * 127f + 127f);
}
+ /// <summary>
+ /// The square-root case of <see cref="IntensityIndex(float, float, float)"/>, the arithmetic
+ /// <see cref="FrameRenderer.RenderIntensity"/> uses per pixel: <c>min(sqrt(intensity) · brightness, 1) · 254</c>,
+ /// 0 for NaN or a non-positive intensity. Also the mapping baked into a <see cref="Engine.FrameFormat.Index"/> frame.
+ /// </summary>
+ /// <param name="intensity">Accumulated intensity from the engine.</param>
+ /// <param name="brightness">Gain applied after the square root.</param>
+ public static int IntensityIndex(float intensity, float brightness)
+ {
+ if (!(intensity > 0f))
+ {
+ return 0;
+ }
+ return (int)(Math.Min(Math.Sqrt(intensity) * brightness, 1.0) * 254.0);
+ }
+
/// <summary>
/// Maps a non-negative intensity to a palette index 0..254, like <c>render_intensity</c>:
/// <c>clip(intensity ^ exponent * brightness, 0, 1) * 254</c>. NaN or non-positive
diff --git a/WaveDude/Rendering/FrameRenderer.cs b/WaveDude/Rendering/FrameRenderer.cs
index 50cc401..fe20ed6 100644
--- a/WaveDude/Rendering/FrameRenderer.cs
+++ b/WaveDude/Rendering/FrameRenderer.cs
@@ -55,18 +55,35 @@ public static class FrameRenderer
Span<int> target = pixels.Span.Slice(y * width, width);
for (int x = 0; x < width; x++)
{
- float value = row[x];
- int index = 0;
- if (value > 0f)
- {
- index = (int)(Math.Min(Math.Sqrt(value) * brightness, 1.0) * 254.0);
- }
- target[x] = Colorize(index, lut);
+ target[x] = Colorize(ColorLut.IntensityIndex(row[x], brightness), lut);
}
return row;
}, _ => { });
}
+ /// <summary>
+ /// Renders a plane of palette indices (an <see cref="Engine.FrameFormat.Index"/> frame, the brightness already
+ /// applied when it was captured): every byte is looked up in the palette, nothing else. The cheapest picture there
+ /// is, a table lookup per pixel.
+ /// </summary>
+ /// <param name="indices">Palette indices 0..254, row-major, <paramref name="width"/> × <paramref name="height"/>.</param>
+ /// <param name="width">Frame width in pixels.</param>
+ /// <param name="height">Frame height in pixels.</param>
+ /// <param name="lut">ARGB palette indexed 0..254, or null for greyscale.</param>
+ /// <param name="pixels">Destination, at least <paramref name="width"/> × <paramref name="height"/> packed BGRA32 pixels, row-major.</param>
+ public static void RenderIndexed(ReadOnlyMemory<byte> indices, int width, int height, int[]? lut, Memory<int> pixels)
+ {
+ Parallel.For(0, height, y =>
+ {
+ ReadOnlySpan<byte> row = indices.Span.Slice(y * width, width);
+ Span<int> target = pixels.Span.Slice(y * width, width);
+ for (int x = 0; x < width; x++)
+ {
+ target[x] = Colorize(Math.Min((int)row[x], ColorLut.Size - 1), lut);
+ }
+ });
+ }
+
/// <summary>Looks up a palette index in <paramref name="lut"/>, or builds an opaque grey of that level when there is no LUT.</summary>
public static int Colorize(int index, int[]? lut) =>
lut != null ? lut[index] : unchecked((int)0xFF000000) | (index << 16) | (index << 8) | index;
diff --git a/WaveDude/Runs/FrameStore.cs b/WaveDude/Runs/FrameStore.cs
index 5b003ec..cb26751 100644
--- a/WaveDude/Runs/FrameStore.cs
+++ b/WaveDude/Runs/FrameStore.cs
@@ -1,14 +1,16 @@
using System.Collections.Concurrent;
-using System.Numerics.Tensors;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using NLog;
+using WaveDude.Engine;
namespace WaveDude.Runs;
/// <summary>
-/// The frames of one run: per frame one <see cref="Half"/> plane per layer (<see cref="Layers"/>),
-/// <see cref="Width"/> × <see cref="Height"/> values row-major with the engine's padding stripped. Two tiers
+/// The frames of one run: per frame one plane per layer (<see cref="Layers"/>) in the run's <see cref="Shape"/>:
+/// <see cref="Width"/> × <see cref="Height"/> samples row-major with the engine's padding stripped, the canvas
+/// shrunk by the shape's divisor, each sample a <see cref="Half"/> or a palette index byte (<see cref="Format"/>,
+/// 2026-10-15; the reduced preview). Two tiers
/// (2026-10-14): the first frames of the run, as many as the memory budget given at creation holds
/// (<see cref="RamFrames"/>), live in native memory; the rest go to a temporary file that is created only when
/// a run does not fit. A run that fits never touches the disk, so it is bound by the engine and not by the
@@ -30,8 +32,9 @@ namespace WaveDude.Runs;
/// them (<see cref="PrepareBlocks"/>): a fresh block costs a page fault per 4 KB on first touch, 8 to 14 ms
/// for a full-HD frame, which would make the writer slower than the engine; prepared, a frame is a plain copy.
/// File layout: a <see cref="HeaderSize"/>-byte header ("WDFS", version, width, height, layers,
-/// visualize-every, capacity, first frame in the file), then one <see cref="FrameBytes"/> record per spilled
-/// frame; within a frame the planes follow the order of <see cref="FrameLayer"/>, only those present.
+/// visualize-every, capacity, first frame in the file, format, divisor, canvas width, canvas height), then one
+/// <see cref="FrameBytes"/> record per spilled frame; within a frame the planes follow the order of
+/// <see cref="FrameLayer"/>, only those present.
/// </remarks>
public sealed unsafe class FrameStore : IFrameSource, IDisposable
{
@@ -41,7 +44,7 @@ public sealed unsafe class FrameStore : IFrameSource, IDisposable
public const int HeaderSize = 64;
private const uint Magic = 0x53464457; // "WDFS" as little-endian bytes
- private const int Version = 2;
+ private const int Version = 3;
/// <summary>Value of <see cref="_firstSpilled"/> while no frame goes to the file.</summary>
private const int NoSpill = int.MaxValue;
@@ -57,18 +60,17 @@ public sealed unsafe class FrameStore : IFrameSource, IDisposable
private readonly BlockingCollection<IntPtr> _prepared = new(PrepareDepth);
private readonly CancellationTokenSource _prepareCancel = new();
private readonly Task _preparer;
- private readonly Half[] _staging;
- private Half[]? _staging2;
+ private readonly byte[] _staging;
+ private byte[]? _staging2;
private FileStream? _file;
private SafeFileHandle? _handle;
private volatile int _firstSpilled = NoSpill;
private int _count;
private bool _disposed;
- private FrameStore(string path, int width, int height, FrameLayers layers, int capacity, int visualizeEvery, long ramBudget)
+ private FrameStore(string path, FrameShape shape, FrameLayers layers, int capacity, int visualizeEvery, long ramBudget)
{
- ArgumentOutOfRangeException.ThrowIfLessThan(width, 1);
- ArgumentOutOfRangeException.ThrowIfLessThan(height, 1);
+ shape.Validate();
ArgumentOutOfRangeException.ThrowIfLessThan(capacity, 1);
ArgumentOutOfRangeException.ThrowIfLessThan(visualizeEvery, 1);
if (layers == FrameLayers.None)
@@ -76,15 +78,14 @@ public sealed unsafe class FrameStore : IFrameSource, IDisposable
throw new ArgumentException("A store needs at least one layer.", nameof(layers));
}
Path = path;
- Width = width;
- Height = height;
+ Shape = shape;
Layers = layers;
Capacity = capacity;
VisualizeEvery = visualizeEvery;
LayerCount = (Has(FrameLayer.Field) ? 1 : 0) + (Has(FrameLayer.Intensity) ? 1 : 0);
- RamFrames = Math.Min(capacity, FramesInBudget(width, height, layers, ramBudget));
+ RamFrames = Math.Min(capacity, FramesInBudget(shape, layers, ramBudget));
_ram = new IntPtr[RamFrames];
- _staging = new Half[width * height];
+ _staging = new byte[shape.PlaneBytes];
if (RamFrames < capacity)
{
// the run will not fit: the file for the rest is made now, so a lack of disk space shows at the start
@@ -155,37 +156,52 @@ public sealed unsafe class FrameStore : IFrameSource, IDisposable
/// bytes, the rest in the file at <paramref name="path"/> (which must not exist; it is only created when needed).
/// </summary>
/// <param name="path">File path for the spilled frames, normally from <see cref="FrameCache.NewPath"/>.</param>
- /// <param name="width">Frame width in pixels.</param>
- /// <param name="height">Frame height in pixels.</param>
+ /// <param name="shape">The frames' geometry and format (<see cref="RunSpec.Shape"/>).</param>
/// <param name="layers">The planes every frame holds; at least one.</param>
/// <param name="capacity">Number of frames the run produces (<see cref="RunSpec.FrameCount"/>).</param>
/// <param name="visualizeEvery">Steps per frame, kept for <see cref="StepOf"/>.</param>
/// <param name="ramBudget">Bytes of memory the frames may take; null takes <see cref="FrameMemory.Budget"/> at the default share.</param>
/// <exception cref="IOException">The file cannot be created or sized (for instance no disk space).</exception>
+ public static FrameStore Create(string path, FrameShape shape, FrameLayers layers, int capacity, int visualizeEvery, long? ramBudget = null) =>
+ new(path, shape, layers, capacity, visualizeEvery, ramBudget ?? FrameMemory.Budget(FrameMemory.DefaultPercent));
+
+ /// <summary>Creates a full-quality store (every cell as a <see cref="Half"/>) for a canvas of <paramref name="width"/> × <paramref name="height"/>; see <see cref="Create(string, FrameShape, FrameLayers, int, int, long?)"/>.</summary>
public static FrameStore Create(string path, int width, int height, FrameLayers layers, int capacity, int visualizeEvery, long? ramBudget = null) =>
- new(path, width, height, layers, capacity, visualizeEvery, ramBudget ?? FrameMemory.Budget(FrameMemory.DefaultPercent));
+ Create(path, FrameShape.Full(width, height), layers, capacity, visualizeEvery, ramBudget);
- /// <summary>Bytes a file holding <paramref name="capacity"/> frames of these dimensions takes, for <see cref="FrameCache.CheckSpace"/> (the spilled part of a run).</summary>
- public static long SizeOf(int width, int height, FrameLayers layers, int capacity) => HeaderSize + (long)capacity * FrameBytesOf(width, height, layers);
+ /// <summary>Bytes a file holding <paramref name="capacity"/> frames of this shape takes, for <see cref="FrameCache.CheckSpace"/> (the spilled part of a run).</summary>
+ public static long SizeOf(FrameShape shape, FrameLayers layers, int capacity) => HeaderSize + capacity * FrameBytesOf(shape, layers);
- /// <summary>How many frames of these dimensions fit into <paramref name="budget"/> bytes of memory.</summary>
- public static int FramesInBudget(int width, int height, FrameLayers layers, long budget) =>
- (int)Math.Clamp(Math.Max(0, budget) / FrameBytesOf(width, height, layers), 0, int.MaxValue);
+ /// <summary>How many frames of this shape fit into <paramref name="budget"/> bytes of memory.</summary>
+ public static int FramesInBudget(FrameShape shape, FrameLayers layers, long budget) =>
+ (int)Math.Clamp(Math.Max(0, budget) / FrameBytesOf(shape, layers), 0, int.MaxValue);
- private static long FrameBytesOf(int width, int height, FrameLayers layers)
+ private static long FrameBytesOf(FrameShape shape, FrameLayers layers)
{
int layerCount = ((layers & FrameLayers.Field) != 0 ? 1 : 0) + ((layers & FrameLayers.Intensity) != 0 ? 1 : 0);
- return (long)layerCount * width * height * 2;
+ return layerCount * shape.PlaneBytes;
}
/// <summary>Full path of the file for the spilled frames; it exists only once a frame went there (<see cref="HasFile"/>).</summary>
public string Path { get; }
- /// <summary>Frame width in pixels.</summary>
- public int Width { get; }
+ /// <summary>The frames' geometry and format.</summary>
+ public FrameShape Shape { get; }
+
+ /// <summary>Frame width in samples.</summary>
+ public int Width => Shape.Width;
+
+ /// <summary>Frame height in samples.</summary>
+ public int Height => Shape.Height;
- /// <summary>Frame height in pixels.</summary>
- public int Height { get; }
+ /// <inheritdoc/>
+ public int CanvasWidth => Shape.CanvasWidth;
+
+ /// <inheritdoc/>
+ public int CanvasHeight => Shape.CanvasHeight;
+
+ /// <inheritdoc/>
+ public FrameFormat Format => Shape.Format;
/// <summary>The planes every frame holds.</summary>
public FrameLayers Layers { get; }
@@ -217,8 +233,8 @@ public sealed unsafe class FrameStore : IFrameSource, IDisposable
/// <summary>Whether the file for spilled frames exists.</summary>
public bool HasFile => _file != null;
- /// <summary>Bytes of one plane: <see cref="Width"/> × <see cref="Height"/> × 2.</summary>
- public long PlaneBytes => (long)Width * Height * 2;
+ /// <summary>Bytes of one plane: <see cref="Width"/> × <see cref="Height"/> × the sample size (<see cref="FrameShape.PlaneBytes"/>).</summary>
+ public long PlaneBytes => Shape.PlaneBytes;
/// <summary>Bytes of one frame: <see cref="PlaneBytes"/> × <see cref="LayerCount"/>.</summary>
public long FrameBytes => PlaneBytes * LayerCount;
@@ -243,47 +259,54 @@ public sealed unsafe class FrameStore : IFrameSource, IDisposable
/// <summary>
/// Stores the next frame from the engine's padded buffers (row y starts at <c>(y + 1) × stride + 1</c>),
- /// converting to <see cref="Half"/> in parallel over the rows first. Writer thread only; frames must arrive
- /// in order. The run itself uses the <see cref="Half"/> overload with the engine's own captures.
+ /// converting them to the store's shape first (<see cref="FrameConversion"/>, rows in parallel). Writer thread
+ /// only; frames must arrive in order. The run itself uses the snapshot overload with the engine's own captures.
/// </summary>
/// <param name="frame">Index of the frame; must equal <see cref="Count"/>.</param>
- /// <param name="field">Padded field buffer, <c>stride × (Height + 2)</c> floats.</param>
+ /// <param name="field">Padded field buffer, <c>stride × (canvas height + 2)</c> floats.</param>
/// <param name="intensity">Padded intensity buffer, or null when the store has no intensity plane.</param>
- /// <param name="stride">Row pitch of the padded buffers (<see cref="Width"/> + 2).</param>
+ /// <param name="stride">Row pitch of the padded buffers (<see cref="CanvasWidth"/> + 2).</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="frame"/> is not the next frame or beyond <see cref="Capacity"/>.</exception>
/// <exception cref="ArgumentNullException">The store has an intensity plane but <paramref name="intensity"/> is null.</exception>
/// <exception cref="ObjectDisposedException">The store is disposed.</exception>
public void Write(int frame, float[] field, float[]? intensity, int stride)
{
- int width = Width;
- Half[] fieldPlane = _staging;
- Parallel.For(0, Height, y => TensorPrimitives.ConvertToHalf(field.AsSpan((y + 1) * stride + 1, width), fieldPlane.AsSpan(y * width, width)));
- Half[]? intensityPlane = null;
+ byte[] fieldPlane = _staging;
+ FrameConversion.Convert(field, stride + 1, stride, Shape, false, fieldPlane);
+ byte[]? intensityPlane = null;
if (Has(FrameLayer.Intensity))
{
ArgumentNullException.ThrowIfNull(intensity);
- intensityPlane = _staging2 ??= new Half[Width * Height];
- Parallel.For(0, Height, y => TensorPrimitives.ConvertToHalf(intensity.AsSpan((y + 1) * stride + 1, width), intensityPlane.AsSpan(y * width, width)));
+ intensityPlane = _staging2 ??= new byte[Shape.PlaneBytes];
+ FrameConversion.Convert(intensity, stride + 1, stride, Shape, true, intensityPlane);
}
Write(frame, fieldPlane, intensityPlane);
}
+ /// <summary>Stores the next frame from <see cref="Half"/> planes; the store's samples must be halves (<see cref="Format"/>). See <see cref="Write(int, ReadOnlySpan{byte}, ReadOnlySpan{byte})"/>.</summary>
+ /// <exception cref="InvalidOperationException">The store's samples are palette indices.</exception>
+ public void Write(int frame, ReadOnlySpan<Half> field, ReadOnlySpan<Half> intensity)
+ {
+ RequireHalves();
+ Write(frame, MemoryMarshal.AsBytes(field), MemoryMarshal.AsBytes(intensity));
+ }
+
/// <summary>
- /// Stores the next frame from <see cref="Half"/> planes in the store's own layout (what
- /// <see cref="Engine.IWaveEngine.CaptureFrame"/> produces): a copy into memory while the budget lasts, one
- /// positional write per plane into the file beyond it. Any thread, but only one writer at a time; frames
- /// must arrive in order. When the memory for a frame within the budget cannot be had after all (the
- /// commit limit of the machine), that frame and every later one go to the file instead, noted once.
+ /// Stores the next frame from planes in the store's own layout (what <see cref="Engine.IWaveEngine.CaptureFrame"/>
+ /// produces for the store's <see cref="Shape"/>): a copy into memory while the budget lasts, one positional
+ /// write per plane into the file beyond it. Any thread, but only one writer at a time; frames must arrive in
+ /// order. When the memory for a frame within the budget cannot be had after all (the commit limit of the
+ /// machine), that frame and every later one go to the file instead, noted once.
/// </summary>
/// <param name="frame">Index of the frame; must equal <see cref="Count"/>.</param>
- /// <param name="field">Field plane, <see cref="Width"/> × <see cref="Height"/> values.</param>
- /// <param name="intensity">Intensity plane, or null when the store has no intensity plane.</param>
+ /// <param name="field">Field plane, <see cref="PlaneBytes"/> bytes.</param>
+ /// <param name="intensity">Intensity plane, or empty when the store has no intensity plane.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="frame"/> is not the next frame or beyond <see cref="Capacity"/>, or a plane is too short.</exception>
- /// <exception cref="ArgumentNullException">The store has an intensity plane but <paramref name="intensity"/> is null.</exception>
+ /// <exception cref="ArgumentNullException">The store has an intensity plane but <paramref name="intensity"/> is missing.</exception>
/// <exception cref="ObjectDisposedException">The store is disposed.</exception>
- public void Write(int frame, ReadOnlySpan<Half> field, ReadOnlySpan<Half> intensity)
+ public void Write(int frame, ReadOnlySpan<byte> field, ReadOnlySpan<byte> intensity)
{
- int length = Width * Height;
+ int length = (int)PlaneBytes;
_lifetime.EnterReadLock();
try
{
@@ -323,11 +346,11 @@ public sealed unsafe class FrameStore : IFrameSource, IDisposable
{
if (Has(FrameLayer.Field))
{
- RandomAccess.Write(_handle!, MemoryMarshal.AsBytes(field[..length]), PlaneOffset(frame, FrameLayer.Field));
+ RandomAccess.Write(_handle!, field[..length], PlaneOffset(frame, FrameLayer.Field));
}
if (Has(FrameLayer.Intensity))
{
- RandomAccess.Write(_handle!, MemoryMarshal.AsBytes(intensity[..length]), PlaneOffset(frame, FrameLayer.Intensity));
+ RandomAccess.Write(_handle!, intensity[..length], PlaneOffset(frame, FrameLayer.Intensity));
}
}
Volatile.Write(ref _count, frame + 1);
@@ -339,29 +362,37 @@ public sealed unsafe class FrameStore : IFrameSource, IDisposable
FrameWritten?.Invoke(frame + 1);
}
- /// <summary>Stores a captured frame (<see cref="Engine.IWaveEngine.CaptureFrame"/>, awaited); the snapshot's size must match.</summary>
- /// <exception cref="ArgumentException">The snapshot has another size.</exception>
- public void Write(int frame, Engine.FrameSnapshot snapshot)
+ /// <summary>Stores a captured frame (<see cref="Engine.IWaveEngine.CaptureFrame"/>, awaited); the snapshot's size and format must match the store's.</summary>
+ /// <exception cref="ArgumentException">The snapshot has another layout.</exception>
+ public void Write(int frame, FrameSnapshot snapshot)
{
- if (snapshot.Width != Width || snapshot.Height != Height)
+ if (!snapshot.Shape.SameLayoutAs(Shape))
{
- throw new ArgumentException("The snapshot does not match the store's size.", nameof(snapshot));
+ throw new ArgumentException("The snapshot does not match the store's size or format.", nameof(snapshot));
}
- Write(frame, snapshot.Field, snapshot.HasIntensity ? snapshot.Intensity : null);
+ Write(frame, snapshot.FieldBytes, snapshot.HasIntensity ? snapshot.IntensityBytes : null);
+ }
+
+ /// <summary>Reads one plane as <see cref="Half"/> values; the store's samples must be halves (<see cref="Format"/>). See <see cref="CopyLayer(int, FrameLayer, Span{byte})"/>.</summary>
+ /// <exception cref="InvalidOperationException">The store's samples are palette indices.</exception>
+ public bool CopyLayer(int frame, FrameLayer layer, Span<Half> destination)
+ {
+ RequireHalves();
+ return CopyLayer(frame, layer, MemoryMarshal.AsBytes(destination));
}
/// <summary>
- /// Reads one plane of a stored frame into <paramref name="destination"/> (at least <see cref="Width"/> ×
- /// <see cref="Height"/> values), from memory or from the file. Safe against a concurrent <see cref="Dispose"/>;
- /// returns false instead of reading when the store is already disposed.
+ /// Reads one plane of a stored frame into <paramref name="destination"/> (at least <see cref="PlaneBytes"/>
+ /// bytes), from memory or from the file. Safe against a concurrent <see cref="Dispose"/>; returns false
+ /// instead of reading when the store is already disposed.
/// </summary>
/// <param name="frame">Frame index below <see cref="Count"/>.</param>
/// <param name="layer">A plane the store holds.</param>
- /// <param name="destination">Receives the values row-major.</param>
+ /// <param name="destination">Receives the samples row-major.</param>
/// <exception cref="ArgumentOutOfRangeException">The frame is not written yet, the plane is not stored, or the destination is too small.</exception>
- public bool CopyLayer(int frame, FrameLayer layer, Span<Half> destination)
+ public bool CopyLayer(int frame, FrameLayer layer, Span<byte> destination)
{
- int length = Width * Height;
+ int length = (int)PlaneBytes;
if (destination.Length < length)
{
throw new ArgumentOutOfRangeException(nameof(destination), "The destination is smaller than a plane.");
@@ -386,7 +417,7 @@ public sealed unsafe class FrameStore : IFrameSource, IDisposable
Plane((void*)_ram[frame], layer).CopyTo(destination);
return true;
}
- Span<byte> bytes = MemoryMarshal.AsBytes(destination[..length]);
+ Span<byte> bytes = destination[..length];
long offset = PlaneOffset(frame, layer);
while (bytes.Length > 0)
{
@@ -415,7 +446,7 @@ public sealed unsafe class FrameStore : IFrameSource, IDisposable
/// Frees the memory tier and closes the file, which deletes it. Marks the store disposed and frees the frames
/// under the lock (so no read or write starts on freed memory) but closes the file outside it: deleting a
/// large file can take a second, and a reader must not wait for that. A file read or write in flight ends
- /// with <see cref="ObjectDisposedException"/>, which <see cref="CopyLayer"/> turns into false.
+ /// with <see cref="ObjectDisposedException"/>, which <see cref="CopyLayer(int, FrameLayer, Span{byte})"/> turns into false.
/// </summary>
public void Dispose()
{
@@ -459,8 +490,18 @@ public sealed unsafe class FrameStore : IFrameSource, IDisposable
}
/// <summary>A plane of a frame kept in memory, as a span over the native block.</summary>
- private Span<Half> Plane(void* frameMemory, FrameLayer layer) =>
- new((byte*)frameMemory + PlaneIndex(layer) * PlaneBytes, Width * Height);
+ private Span<byte> Plane(void* frameMemory, FrameLayer layer) =>
+ new((byte*)frameMemory + PlaneIndex(layer) * PlaneBytes, (int)PlaneBytes);
+
+ /// <summary>The <see cref="Half"/> overloads only apply to a store of halves.</summary>
+ /// <exception cref="InvalidOperationException">The store's samples are palette indices.</exception>
+ private void RequireHalves()
+ {
+ if (Format != FrameFormat.Half)
+ {
+ throw new InvalidOperationException("The store's samples are palette indices, not halves.");
+ }
+ }
/// <summary>Byte offset of a plane in the file; the file holds the frames from <see cref="_firstSpilled"/> on.</summary>
private long PlaneOffset(int frame, FrameLayer layer) =>
@@ -533,6 +574,10 @@ public sealed unsafe class FrameStore : IFrameSource, IDisposable
BitConverter.TryWriteBytes(header[20..], VisualizeEvery);
BitConverter.TryWriteBytes(header[24..], Capacity);
BitConverter.TryWriteBytes(header[28..], firstFrame);
+ BitConverter.TryWriteBytes(header[32..], (int)Format);
+ BitConverter.TryWriteBytes(header[36..], Shape.Divisor);
+ BitConverter.TryWriteBytes(header[40..], CanvasWidth);
+ BitConverter.TryWriteBytes(header[44..], CanvasHeight);
RandomAccess.Write(_handle!, header, 0);
}
}
diff --git a/WaveDude/Runs/IFrameSource.cs b/WaveDude/Runs/IFrameSource.cs
index 9c10107..56730db 100644
--- a/WaveDude/Runs/IFrameSource.cs
+++ b/WaveDude/Runs/IFrameSource.cs
@@ -1,26 +1,43 @@
+using System.Runtime.InteropServices;
using WaveDude.Engine;
namespace WaveDude.Runs;
/// <summary>
/// Something a frame can be read from for display: the <see cref="FrameStore"/> of a run, or a single
-/// captured <see cref="FrameSnapshot"/>. Readers call <see cref="CopyLayer"/> from any thread.
+/// captured <see cref="FrameSnapshot"/>. Frames are planes of <see cref="Width"/> × <see cref="Height"/>
+/// samples in <see cref="Format"/>, shrunk from a canvas of <see cref="CanvasWidth"/> × <see cref="CanvasHeight"/>
+/// (the coordinate system of sources and probes). Readers call <see cref="CopyLayer(int, FrameLayer, Span{byte})"/>
+/// from any thread.
/// </summary>
public interface IFrameSource
{
- /// <summary>Frame width in pixels.</summary>
+ /// <summary>Frame width in samples.</summary>
int Width { get; }
- /// <summary>Frame height in pixels.</summary>
+ /// <summary>Frame height in samples.</summary>
int Height { get; }
+ /// <summary>Width of the simulated canvas the frames were shrunk from, in cells; equals <see cref="Width"/> at full resolution.</summary>
+ int CanvasWidth { get; }
+
+ /// <summary>Height of the simulated canvas, in cells.</summary>
+ int CanvasHeight { get; }
+
+ /// <summary>The sample format of every plane.</summary>
+ FrameFormat Format { get; }
+
/// <summary>Frames available: indices 0..Count-1 may be read.</summary>
int Count { get; }
/// <summary>Whether the frames hold the given plane.</summary>
bool Has(FrameLayer layer);
- /// <summary>Reads one plane of a frame into <paramref name="destination"/>; false when the source is gone.</summary>
+ /// <summary>Reads one plane of a frame as bytes (<see cref="Width"/> × <see cref="Height"/> samples of <see cref="Format"/>) into <paramref name="destination"/>; false when the source is gone.</summary>
+ bool CopyLayer(int frame, FrameLayer layer, Span<byte> destination);
+
+ /// <summary>Reads one plane of a frame as <see cref="Half"/> values into <paramref name="destination"/>; false when the source is gone.</summary>
+ /// <exception cref="InvalidOperationException">The samples are not halves (<see cref="Format"/>).</exception>
bool CopyLayer(int frame, FrameLayer layer, Span<Half> destination);
}
@@ -36,6 +53,15 @@ public sealed class SnapshotFrameSource(FrameSnapshot snapshot) : IFrameSource
/// <inheritdoc/>
public int Height => Snapshot.Height;
+ /// <inheritdoc/>
+ public int CanvasWidth => Snapshot.Shape.CanvasWidth;
+
+ /// <inheritdoc/>
+ public int CanvasHeight => Snapshot.Shape.CanvasHeight;
+
+ /// <inheritdoc/>
+ public FrameFormat Format => Snapshot.Shape.Format;
+
/// <inheritdoc/>
public int Count => 1;
@@ -43,9 +69,9 @@ public sealed class SnapshotFrameSource(FrameSnapshot snapshot) : IFrameSource
public bool Has(FrameLayer layer) => layer == FrameLayer.Field || Snapshot.HasIntensity;
/// <inheritdoc/>
- public bool CopyLayer(int frame, FrameLayer layer, Span<Half> destination)
+ public bool CopyLayer(int frame, FrameLayer layer, Span<byte> destination)
{
- Half[]? plane = layer == FrameLayer.Field ? Snapshot.Field : Snapshot.HasIntensity ? Snapshot.Intensity : null;
+ byte[]? plane = layer == FrameLayer.Field ? Snapshot.FieldBytes : Snapshot.HasIntensity ? Snapshot.IntensityBytes : null;
if (plane == null)
{
return false;
@@ -53,4 +79,14 @@ public sealed class SnapshotFrameSource(FrameSnapshot snapshot) : IFrameSource
plane.AsSpan().CopyTo(destination);
return true;
}
+
+ /// <inheritdoc/>
+ public bool CopyLayer(int frame, FrameLayer layer, Span<Half> destination)
+ {
+ if (Format != FrameFormat.Half)
+ {
+ throw new InvalidOperationException("The snapshot's samples are palette indices, not halves.");
+ }
+ return CopyLayer(frame, layer, MemoryMarshal.AsBytes(destination));
+ }
}
diff --git a/WaveDude/Runs/PreviewQuality.cs b/WaveDude/Runs/PreviewQuality.cs
new file mode 100644
index 0000000..fa4f022
--- /dev/null
+++ b/WaveDude/Runs/PreviewQuality.cs
@@ -0,0 +1,37 @@
+using WaveDude.Engine;
+
+namespace WaveDude.Runs;
+
+/// <summary>
+/// How much of a run is kept for the preview (2026-10-15, the user's design for weaker machines and a first
+/// step towards a browser build): the frames shrunk by <see cref="ResolutionDivisor"/> along each axis, only
+/// every <see cref="FrameDivisor"/>-th frame of the timeline stored (the others are stood in for by the last
+/// stored one; the timeline itself keeps the project's numbering), each sample a <see cref="FrameFormat.Half"/>
+/// or a palette index byte. An application setting, not part of the project: the simulation itself is the
+/// same, only what is captured, stored and shown changes, and an export always uses a <see cref="Full"/> run.
+/// Immutable; compared by value.
+/// </summary>
+/// <param name="ResolutionDivisor">Cells per sample along each axis (1, 2, 4: full, half, quarter resolution).</param>
+/// <param name="FrameDivisor">Timeline frames per stored frame (1, 2, 4: every frame, every second, every fourth); see <see cref="RunSpec.FrameStride"/>.</param>
+/// <param name="Format">The sample format; <see cref="FrameFormat.Index"/> bakes the display brightness into the frames.</param>
+public sealed record PreviewQuality(int ResolutionDivisor, int FrameDivisor, FrameFormat Format)
+{
+ /// <summary>Every cell of every frame as a <see cref="FrameFormat.Half"/>: what an export needs and the default.</summary>
+ public static readonly PreviewQuality Full = new(1, 1, FrameFormat.Half);
+
+ /// <summary>Whether this is <see cref="Full"/>.</summary>
+ public bool IsFull => this == Full;
+
+ /// <summary>Validates the record: both divisors at least 1.</summary>
+ /// <exception cref="ArgumentOutOfRangeException">A divisor is below 1.</exception>
+ public PreviewQuality Validate()
+ {
+ ArgumentOutOfRangeException.ThrowIfLessThan(ResolutionDivisor, 1, nameof(ResolutionDivisor));
+ ArgumentOutOfRangeException.ThrowIfLessThan(FrameDivisor, 1, nameof(FrameDivisor));
+ return this;
+ }
+
+ /// <inheritdoc/>
+ public override string ToString() =>
+ IsFull ? "full" : $"1/{ResolutionDivisor} resolution, every {FrameDivisor}. frame, {(Format == FrameFormat.Half ? "16-bit" : "8-bit")}";
+}
diff --git a/WaveDude/Runs/RunSpec.cs b/WaveDude/Runs/RunSpec.cs
index ec20fff..4d2d10a 100644
--- a/WaveDude/Runs/RunSpec.cs
+++ b/WaveDude/Runs/RunSpec.cs
@@ -23,11 +23,13 @@ public sealed class RunSpec
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
- private RunSpec(Project project, ScenePixels? image, int width, int height, bool trackIntensity, bool preferGpu)
+ private RunSpec(Project project, ScenePixels? image, int width, int height, bool trackIntensity, bool preferGpu, PreviewQuality quality)
{
Seed = project.Seed;
Steps = project.Simulation.Steps;
+ Quality = quality.Validate();
VisualizeEvery = Math.Max(1, project.Simulation.VisualizeEvery);
+ Shape = new FrameShape(width, height, quality.ResolutionDivisor, quality.Format, (float)project.Display.Field.Brightness, (float)project.Display.Intensity.Brightness);
PreferGpu = preferGpu;
Engine = EngineOptions.From(project.Simulation, project.Scene, trackIntensity);
Image = image;
@@ -46,12 +48,34 @@ public sealed class RunSpec
/// <summary>Number of simulation steps to run.</summary>
public int Steps { get; }
- /// <summary>A frame is recorded every this many steps (at least 1).</summary>
+ /// <summary>A frame is due every this many steps (at least 1): the project's interval, the timeline's unit whatever the <see cref="Quality"/>.</summary>
public int VisualizeEvery { get; }
- /// <summary>Number of frames the run produces: ⌈<see cref="Steps"/> / <see cref="VisualizeEvery"/>⌉.</summary>
+ /// <summary>Number of frames of the run on the timeline: ⌈<see cref="Steps"/> / <see cref="VisualizeEvery"/>⌉, the same for every quality.</summary>
public int FrameCount => (Steps + VisualizeEvery - 1) / VisualizeEvery;
+ /// <summary>How much of the run is kept: the application's preview quality, or <see cref="PreviewQuality.Full"/> for an export's run.</summary>
+ public PreviewQuality Quality { get; }
+
+ /// <summary>
+ /// Only every this many-th frame is captured and stored (the quality's frame divisor, 1 for all of them); a
+ /// stored frame stands in for the frames up to the next one, so the timeline does not change (the user's rule,
+ /// 2026-10-15: the setting silently leaves frames out to save memory and time, nothing else).
+ /// </summary>
+ public int FrameStride => Quality.FrameDivisor;
+
+ /// <summary>Steps between two stored frames: <see cref="VisualizeEvery"/> × <see cref="FrameStride"/>.</summary>
+ public int CaptureEvery => VisualizeEvery * FrameStride;
+
+ /// <summary>Number of frames actually stored: ⌈<see cref="FrameCount"/> / <see cref="FrameStride"/>⌉ (the store's capacity).</summary>
+ public int StoredFrameCount => (FrameCount + FrameStride - 1) / FrameStride;
+
+ /// <summary>Index in the store of the frame that shows timeline frame <paramref name="frame"/>: the last stored one at or before it.</summary>
+ public int StoredIndexOf(int frame) => frame / FrameStride;
+
+ /// <summary>The frames' geometry and format: the canvas shrunk by the quality's resolution divisor, in its sample format, with the display brightness of the moment for index frames.</summary>
+ public FrameShape Shape { get; }
+
/// <summary>Try the OpenCL engine first; an application setting, not part of the project.</summary>
public bool PreferGpu { get; }
@@ -96,8 +120,9 @@ public sealed class RunSpec
/// <param name="image">The decoded scene image when <see cref="Scene.Mode"/> is <see cref="SceneMode.Image"/>; ignored otherwise.</param>
/// <param name="preferGpu">Try the OpenCL engine first (the application's choice; the CPU is the fallback either way).</param>
/// <param name="trackIntensity">Store the intensity plane even when nothing in the project needs it (an export of the intensity asks for it).</param>
+ /// <param name="quality">How much of the run to keep (the application's preview setting); null is <see cref="PreviewQuality.Full"/>.</param>
/// <exception cref="RunSpecException">The project cannot run: no image for an image scene, or no steps.</exception>
- public static RunSpec Create(Project project, ScenePixels? image, bool preferGpu = true, bool trackIntensity = false)
+ public static RunSpec Create(Project project, ScenePixels? image, bool preferGpu = true, bool trackIntensity = false, PreviewQuality? quality = null)
{
project.Normalize();
if (project.Simulation.Steps < 1)
@@ -127,7 +152,7 @@ public sealed class RunSpec
}
trackIntensity |= project.Display.Intensity.Preview
|| project.Probes.Any(probe => probe.Active && probe.Measurement != ProbeMeasurement.Amplitude);
- return new RunSpec(project, image, width, height, trackIntensity, preferGpu);
+ return new RunSpec(project, image, width, height, trackIntensity, preferGpu, quality ?? PreviewQuality.Full);
}
/// <summary>
diff --git a/WaveDude/Runs/ScratchRunner.cs b/WaveDude/Runs/ScratchRunner.cs
index b0919de..2fb2391 100644
--- a/WaveDude/Runs/ScratchRunner.cs
+++ b/WaveDude/Runs/ScratchRunner.cs
@@ -237,15 +237,15 @@ public sealed class ScratchRunner : IDisposable
return _engine;
}
- /// <summary>A snapshot of the spec's size, alternating between two so the one handed out last stays valid while the next is computed.</summary>
+ /// <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)
{
int index = _nextSnapshot;
_nextSnapshot = (index + 1) % _snapshots.Length;
FrameSnapshot? snapshot = _snapshots[index];
- if (snapshot == null || snapshot.Width != spec.Width || snapshot.Height != spec.Height || (spec.TrackIntensity && snapshot.Intensity == null))
+ if (snapshot == null || snapshot.Shape != spec.Shape || (spec.TrackIntensity && snapshot.IntensityBytes == null))
{
- snapshot = _snapshots[index] = new FrameSnapshot(spec.Width, spec.Height, spec.TrackIntensity);
+ snapshot = _snapshots[index] = new FrameSnapshot(spec.Shape, spec.TrackIntensity);
}
return snapshot;
}
diff --git a/WaveDude/Runs/SimulationRun.cs b/WaveDude/Runs/SimulationRun.cs
index 8804f3b..e7ddb0d 100644
--- a/WaveDude/Runs/SimulationRun.cs
+++ b/WaveDude/Runs/SimulationRun.cs
@@ -60,12 +60,13 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposable
public SimulationRun(RunSpec spec, FrameStore store, SynchronizationContext? context, bool isAutomatic = false)
{
IsAutomatic = isAutomatic;
- if (store.Width != spec.Width || store.Height != spec.Height || store.Layers != spec.Layers || store.Capacity < spec.FrameCount)
+ if (!store.Shape.SameLayoutAs(spec.Shape) || store.Layers != spec.Layers || store.Capacity < spec.StoredFrameCount)
{
throw new ArgumentException("The frame store does not fit the run.", nameof(store));
}
Spec = spec;
Store = store;
+ Frames = spec.FrameStride == 1 ? store : new StridedFrameSource(store, spec.FrameStride, spec.FrameCount);
_context = context;
Traces = new ProbeTrace[spec.Probes.Length];
for (int i = 0; i < Traces.Length; i++)
@@ -86,9 +87,15 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposable
/// <summary>What is being run.</summary>
public RunSpec Spec { get; }
- /// <summary>Where the frames are; readable from any thread up to <see cref="FrameStore.Count"/>.</summary>
+ /// <summary>Where the stored frames are (every <see cref="RunSpec.FrameStride"/>-th one); readable from any thread up to <see cref="FrameStore.Count"/>.</summary>
public FrameStore Store { get; }
+ /// <summary>
+ /// The frames in timeline numbering, what the preview reads: the store itself when every frame is stored,
+ /// else a <see cref="StridedFrameSource"/> in which a stored frame stands in for the frames up to the next one.
+ /// </summary>
+ public IFrameSource Frames { get; }
+
/// <summary>Whether the application started the run on its own (re-run after an edit); the preview then keeps its position instead of following.</summary>
public bool IsAutomatic { get; }
@@ -115,7 +122,7 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposable
/// <summary>Steps the run will do.</summary>
public int TotalSteps => Spec.Steps;
- /// <summary>Frames written to the store so far (equals <see cref="FrameStore.Count"/> once the post has arrived).</summary>
+ /// <summary>Timeline frames that can be shown so far: the stored frames × <see cref="RunSpec.FrameStride"/>, capped at <see cref="RunSpec.FrameCount"/> (equals <see cref="IFrameSource.Count"/> of <see cref="Frames"/> once the post has arrived).</summary>
public int FrameCount
{
get => _frameCount;
@@ -236,6 +243,7 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposable
Post(() => State = RunState.Running);
int every = Spec.VisualizeEvery;
+ int captureEvery = Spec.CaptureEvery;
bool trackIntensity = Spec.TrackIntensity;
int frame = 0;
long lastProgressMs = 0;
@@ -249,7 +257,7 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposable
var pool = new BlockingCollection<FrameSnapshot>();
for (int i = 0; i < SnapshotPoolSize; i++)
{
- pool.Add(new FrameSnapshot(Store.Width, Store.Height, trackIntensity));
+ pool.Add(new FrameSnapshot(Spec.Shape, trackIntensity));
}
var pending = new BlockingCollection<FrameSnapshot>();
IWaveEngine captured = engine;
@@ -270,7 +278,7 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposable
captured.AwaitFrame(snapshot);
long w1 = Stopwatch.GetTimestamp();
Store.Write(snapshot.Frame, snapshot);
- PublishFrameCount(snapshot.Frame + 1);
+ PublishFrameCount(CoveredFrames(snapshot.Frame + 1));
Interlocked.Add(ref writerWaitTicks, w1 - w0);
Interlocked.Add(ref storeTicks, Stopwatch.GetTimestamp() - w1);
pool.Add(snapshot);
@@ -302,12 +310,15 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposable
stepsDone = i + 1;
long t1 = Stopwatch.GetTimestamp();
computeTicks += t1 - t0;
- if (i % every == 0 && frame < Store.Capacity)
+ if (i % every == 0)
{
- // the series up to this step and the line profiles of this frame (kept per frame, so the
- // preview shows the profile of the frame it scrubs to)
+ // the series up to this step and the line profiles of this timeline frame (kept per frame, stored
+ // or not, so the preview shows the profile of the frame it scrubs to)
collector?.Collect(engine, stepsDone);
collector?.CollectProfiles(engine, stepsDone);
+ }
+ if (i % captureEvery == 0 && frame < Store.Capacity)
+ {
// a free snapshot (waiting here is the back pressure when the writer lags), captured
// without waiting for the copy; the writer awaits and stores it
FrameSnapshot snapshot = pool.Take(token);
@@ -373,7 +384,7 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposable
stopwatch.Stop();
TimeSpan elapsed = stopwatch.Elapsed;
int finalSteps = stepsDone;
- int finalFrames = Store.Count;
+ int finalFrames = CoveredFrames(Store.Count);
Post(() =>
{
StepsDone = finalSteps;
@@ -417,6 +428,9 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposable
});
}
+ /// <summary>Timeline frames covered by the first <paramref name="stored"/> stored frames: each stands for <see cref="RunSpec.FrameStride"/> of them, never beyond the run.</summary>
+ private int CoveredFrames(int stored) => (int)Math.Min((long)stored * Spec.FrameStride, Spec.FrameCount);
+
/// <summary>Posts the frame count, coalescing: never more than one post in flight, the handler reads the newest value.</summary>
private void PublishFrameCount(int count)
{
diff --git a/WaveDude/Runs/StridedFrameSource.cs b/WaveDude/Runs/StridedFrameSource.cs
new file mode 100644
index 0000000..062255b
--- /dev/null
+++ b/WaveDude/Runs/StridedFrameSource.cs
@@ -0,0 +1,48 @@
+using WaveDude.Engine;
+
+namespace WaveDude.Runs;
+
+/// <summary>
+/// A run's store seen in timeline frames when only every <see cref="Stride"/>-th frame was stored
+/// (<see cref="RunSpec.FrameStride"/>, 2026-10-15): timeline frame k reads stored frame ⌊k / stride⌋, so a stored
+/// frame stands in for the frames up to the next one and the timeline keeps the project's numbering. Thread-safe
+/// like the store it wraps.
+/// </summary>
+/// <param name="store">The run's store, holding every stride-th frame in order.</param>
+/// <param name="stride">Timeline frames per stored frame, at least 1.</param>
+/// <param name="frameCount">Frames of the timeline (<see cref="RunSpec.FrameCount"/>), the upper bound of <see cref="Count"/>.</param>
+public sealed class StridedFrameSource(FrameStore store, int stride, int frameCount) : IFrameSource
+{
+ /// <summary>The store read.</summary>
+ public FrameStore Store { get; } = store;
+
+ /// <summary>Timeline frames per stored frame.</summary>
+ public int Stride { get; } = Math.Max(1, stride);
+
+ /// <inheritdoc/>
+ public int Width => Store.Width;
+
+ /// <inheritdoc/>
+ public int Height => Store.Height;
+
+ /// <inheritdoc/>
+ public int CanvasWidth => Store.CanvasWidth;
+
+ /// <inheritdoc/>
+ public int CanvasHeight => Store.CanvasHeight;
+
+ /// <inheritdoc/>
+ public FrameFormat Format => Store.Format;
+
+ /// <summary>Timeline frames that can be shown: every stored frame covers <see cref="Stride"/> of them, never beyond the run's frame count.</summary>
+ public int Count => (int)Math.Min((long)Store.Count * Stride, frameCount);
+
+ /// <inheritdoc/>
+ public bool Has(FrameLayer layer) => Store.Has(layer);
+
+ /// <inheritdoc/>
+ public bool CopyLayer(int frame, FrameLayer layer, Span<byte> destination) => Store.CopyLayer(frame / Stride, layer, destination);
+
+ /// <inheritdoc/>
+ public bool CopyLayer(int frame, FrameLayer layer, Span<Half> destination) => Store.CopyLayer(frame / Stride, layer, destination);
+}
diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.cs
index 0306d6f..6b2f852 100644
--- a/_tools/library_check/Program.cs
+++ b/_tools/library_check/Program.cs
@@ -1,8 +1,10 @@
using System.Globalization;
using System.Diagnostics;
using System.Numerics.Tensors;
+using System.Runtime.InteropServices;
using NLog;
using WaveDude.Engine;
+using WaveDude.Export;
using WaveDude.Model;
using WaveDude.Probes;
using WaveDude.Rendering;
@@ -51,6 +53,16 @@ internal static class Program
return m;
}
+ private static float MaxAbs(ReadOnlySpan<Half> a)
+ {
+ float m = 0f;
+ foreach (Half v in a)
+ {
+ m = Math.Max(m, Math.Abs((float)v));
+ }
+ return m;
+ }
+
private static float MaxDiff(ReadOnlySpan<float> a, ReadOnlySpan<float> b)
{
float m = 0f;
@@ -179,6 +191,7 @@ internal static class Program
CheckDeterminism(scene);
CheckEmitterMapping();
CheckFrameStore(scene);
+ CheckPreviewQuality(scene, W, H);
CheckRenderer();
CheckColorSchemes();
CheckProbeGraph();
@@ -331,7 +344,7 @@ internal static class Program
(fallback as IDisposable)?.Dispose();
}
- private static float MaxDiff(ReadOnlySpan<float> padded, int stride, int w, int h, Half[] plane)
+ private static float MaxDiff(ReadOnlySpan<float> padded, int stride, int w, int h, ReadOnlySpan<Half> plane)
{
float m = 0f;
for (int y = 0; y < h; y++)
@@ -389,7 +402,7 @@ internal static class Program
engine.Reset();
engine.CaptureFrame(a, true);
engine.AwaitFrame(a);
- Check(MaxAbs(a.Field.Select(h => (float)h).ToArray()) == 0f && MaxAbs(a.Intensity!.Select(h => (float)h).ToArray()) == 0f, name + ": reset clears field and intensity");
+ Check(MaxAbs(a.Field) == 0f && MaxAbs(a.Intensity) == 0f, name + ": reset clears field and intensity");
Run(engine, 100);
engine.CaptureFrame(a, false);
engine.AwaitFrame(a);
@@ -546,8 +559,10 @@ internal static class Program
Check(threw, "write beyond the capacity is rejected");
}
Check(!File.Exists(path), "file deleted on dispose");
- Check(FrameStore.SizeOf(1920, 1080, FrameLayers.Field | FrameLayers.Intensity, 1250) == 64 + 1250L * 2 * 1920 * 1080 * 2, "SizeOf matches the layout");
- Check(FrameStore.FramesInBudget(1920, 1080, FrameLayers.Field | FrameLayers.Intensity, 1L << 30) == 129 && FrameStore.FramesInBudget(64, 48, FrameLayers.Field, 0) == 0, "FramesInBudget: 129 full-HD frames of both planes per GB");
+ FrameShape fullHd = FrameShape.Full(1920, 1080);
+ Check(FrameStore.SizeOf(fullHd, FrameLayers.Field | FrameLayers.Intensity, 1250) == 64 + 1250L * 2 * 1920 * 1080 * 2, "SizeOf matches the layout");
+ Check(FrameStore.FramesInBudget(fullHd, FrameLayers.Field | FrameLayers.Intensity, 1L << 30) == 129 && FrameStore.FramesInBudget(FrameShape.Full(64, 48), FrameLayers.Field, 0) == 0, "FramesInBudget: 129 full-HD frames of both planes per GB");
+ Check(FrameStore.FramesInBudget(fullHd with { Divisor = 2, Format = FrameFormat.Index }, FrameLayers.Field | FrameLayers.Intensity, 1L << 30) == 1035, "FramesInBudget: eight times as many half-size index frames (1035 per GB)");
// the two tiers: a budget for two of five frames; the first two stay in memory, the other three go to the file
path = Path.Combine(Path.GetTempPath(), "library_check-tiers-" + Guid.NewGuid().ToString("N") + FrameCache.Extension);
@@ -635,6 +650,264 @@ internal static class Program
Check(disposeMs < 1500, "disposing a 1 GB store does not flush it to disk (" + disposeMs.ToString("0") + " ms)");
}
+ /// <summary>
+ /// The reduced preview (2026-10-15): FrameConversion against the renderer's index mapping and the block means,
+ /// the CPU captures of every shape equal to it and the GPU's within the card's arithmetic, a store of index
+ /// bytes, the export's refusal of it, a spec with a quality, and a headless run plus a scratch frame in that shape.
+ /// </summary>
+ private static void CheckPreviewQuality(SceneData scene, int W, int H)
+ {
+ Console.WriteLine("--- preview quality (shrunk and 8-bit frames)");
+ var options = new EngineOptions(1.0, 1.0, true, false, 10.0, 1.0);
+ var cpu = new WaveSimulator(scene, options, Sources());
+ Run(cpu, 100);
+ float[] field = (float[])cpu.FieldData.Clone();
+ float[] inten = (float[])cpu.IntensityData!.Clone();
+ int stride = cpu.Stride;
+ FrameShape full = FrameShape.Full(W, H);
+ FrameShape half = full with { Divisor = 2 };
+ FrameShape third = full with { Divisor = 3 };
+ FrameShape index = full with { Format = FrameFormat.Index, FieldBrightness = 30f, IntensityBrightness = 5f };
+ FrameShape halfIndex = half with { Format = FrameFormat.Index, FieldBrightness = 30f, IntensityBrightness = 5f };
+ Check(half.Width == 32 && half.Height == 24 && third.Width == 22 && third.Height == 16 && index.SampleBytes == 1 && halfIndex.PlaneBytes == 32 * 24 && full.IsFull && !half.IsFull,
+ "shapes: 64x48 halves to 32x24, thirds to 22x16, an index sample is one byte");
+ float tolerance = 2e-3f * Math.Max(1f, MaxAbs(field));
+
+ // the reference conversion: the full shape is the plain float-to-half conversion
+ var fullBytes = new byte[full.PlaneBytes];
+ FrameConversion.Convert(field, stride + 1, stride, full, false, fullBytes);
+ Check(MaxDiff(field, stride, W, H, MemoryMarshal.Cast<byte, Half>(fullBytes)) < tolerance, "full shape: the plain half conversion");
+ // a half-size frame holds the 2 x 2 block means
+ var halfBytes = new byte[half.PlaneBytes];
+ FrameConversion.Convert(field, stride + 1, stride, half, false, halfBytes);
+ ReadOnlySpan<Half> halves = MemoryMarshal.Cast<byte, Half>(halfBytes);
+ float worst = 0f;
+ for (int y = 0; y < 24; y++)
+ {
+ for (int x = 0; x < 32; x++)
+ {
+ float mean = (field[(2 * y + 1) * stride + 2 * x + 1] + field[(2 * y + 1) * stride + 2 * x + 2] + field[(2 * y + 2) * stride + 2 * x + 1] + field[(2 * y + 2) * stride + 2 * x + 2]) / 4f;
+ worst = Math.Max(worst, Math.Abs(mean - (float)halves[y * 32 + x]));
+ }
+ }
+ Check(worst < tolerance, "half shape: every sample is the mean of its 2 x 2 block (worst " + worst + ")");
+ // a divisor that does not divide the canvas: the last column is one cell wide and averaged over the cells it has
+ var thirdBytes = new byte[third.PlaneBytes];
+ FrameConversion.Convert(field, stride + 1, stride, third, false, thirdBytes);
+ ReadOnlySpan<Half> thirds = MemoryMarshal.Cast<byte, Half>(thirdBytes);
+ worst = 0f;
+ for (int y = 0; y < 16; y++)
+ {
+ float mean = (field[(3 * y + 1) * stride + 64] + field[(3 * y + 2) * stride + 64] + field[(3 * y + 3) * stride + 64]) / 3f;
+ worst = Math.Max(worst, Math.Abs(mean - (float)thirds[y * 22 + 21]));
+ }
+ Check(worst < tolerance, "third shape: the clipped last column is the mean of its 1 x 3 block (worst " + worst + ")");
+ // an index frame is the renderer's palette index of every cell, bit for bit
+ var indexField = new byte[index.PlaneBytes];
+ var indexInten = new byte[index.PlaneBytes];
+ FrameConversion.Convert(field, stride + 1, stride, index, false, indexField);
+ FrameConversion.Convert(inten, stride + 1, stride, index, true, indexInten);
+ bool same = true;
+ for (int y = 0; y < H && same; y++)
+ {
+ for (int x = 0; x < W; x++)
+ {
+ int at = (y + 1) * stride + x + 1;
+ if (indexField[y * W + x] != ColorLut.FieldIndex(field[at], 30f) || indexInten[y * W + x] != ColorLut.IntensityIndex(inten[at], 5f))
+ {
+ same = false;
+ break;
+ }
+ }
+ }
+ Check(same && indexField.Max() > 127 && indexField.Min() < 127 && indexInten.Max() > 0, "index shape: the renderer's palette index of every cell at brightness 30 and 5, both sides of the centre used");
+
+ // the CPU engine's captures of every shape equal the reference conversion of its own floats
+ foreach (FrameShape shape in new[] { half, third, index, halfIndex })
+ {
+ var expectedField = new byte[shape.PlaneBytes];
+ var expectedInten = new byte[shape.PlaneBytes];
+ FrameConversion.Convert(field, stride + 1, stride, shape, false, expectedField);
+ FrameConversion.Convert(inten, stride + 1, stride, shape, true, expectedInten);
+ var snapshot = new FrameSnapshot(shape, true);
+ cpu.CaptureFrame(snapshot, true);
+ cpu.AwaitFrame(snapshot);
+ Check(snapshot.HasIntensity && snapshot.FieldBytes.AsSpan().SequenceEqual(expectedField) && snapshot.IntensityBytes!.AsSpan().SequenceEqual(expectedInten),
+ $"CPU capture of 1/{shape.Divisor} {shape.Format} equals the reference conversion");
+ }
+ // the GPU's within the card's arithmetic: halves within the tolerance, indices within one
+ GpuWaveSimulator? gpu = GpuWaveSimulator.TryCreate(scene, options, Sources(), out string problems);
+ if (gpu == null)
+ {
+ Console.WriteLine(" skip GPU: " + problems);
+ }
+ else
+ {
+ using (gpu)
+ {
+ Run(gpu, 100);
+ gpu.PrepareFrame(true, true);
+ float[] gpuField = (float[])gpu.FieldData.Clone();
+ float[] gpuInten = (float[])gpu.IntensityData!.Clone();
+ foreach (FrameShape shape in new[] { half, third, index, halfIndex })
+ {
+ var expectedField = new byte[shape.PlaneBytes];
+ var expectedInten = new byte[shape.PlaneBytes];
+ FrameConversion.Convert(gpuField, stride + 1, stride, shape, false, expectedField);
+ FrameConversion.Convert(gpuInten, stride + 1, stride, shape, true, expectedInten);
+ var snapshot = new FrameSnapshot(shape, true);
+ gpu.CaptureFrame(snapshot, true);
+ gpu.AwaitFrame(snapshot);
+ int worstIndex = 0;
+ float worstHalf = 0f;
+ if (shape.Format == FrameFormat.Index)
+ {
+ for (int i = 0; i < expectedField.Length; i++)
+ {
+ worstIndex = Math.Max(worstIndex, Math.Max(Math.Abs(snapshot.FieldBytes[i] - expectedField[i]), Math.Abs(snapshot.IntensityBytes![i] - expectedInten[i])));
+ }
+ }
+ else
+ {
+ ReadOnlySpan<Half> gotField = snapshot.Field;
+ ReadOnlySpan<Half> wantField = MemoryMarshal.Cast<byte, Half>(expectedField);
+ ReadOnlySpan<Half> gotInten = snapshot.Intensity;
+ ReadOnlySpan<Half> wantInten = MemoryMarshal.Cast<byte, Half>(expectedInten);
+ for (int i = 0; i < gotField.Length; i++)
+ {
+ worstHalf = Math.Max(worstHalf, Math.Max(Math.Abs((float)gotField[i] - (float)wantField[i]), Math.Abs((float)gotInten[i] - (float)wantInten[i])));
+ }
+ }
+ Check(snapshot.HasIntensity && worstIndex <= 1 && worstHalf < tolerance,
+ $"GPU capture of 1/{shape.Divisor} {shape.Format} matches the reference conversion (index off by at most {worstIndex}, halves by {worstHalf})");
+ }
+ }
+ }
+
+ // a store of half-size index bytes: the float, snapshot and byte writes agree, the half overloads refuse it, the export refuses it
+ string path = Path.Combine(Path.GetTempPath(), "library_check-index-" + Guid.NewGuid().ToString("N") + FrameCache.Extension);
+ using (var store = FrameStore.Create(path, halfIndex, FrameLayers.Field | FrameLayers.Intensity, 3, 2, ramBudget: 0))
+ {
+ Check(store.Format == FrameFormat.Index && store.Width == 32 && store.Height == 24 && store.CanvasWidth == 64 && store.CanvasHeight == 48 && store.PlaneBytes == 768 && store.FileBytes == FrameStore.HeaderSize + 3 * 2 * 768,
+ "index store: 32x24 bytes per plane of a 64x48 canvas, the file sized for them");
+ var expectedField = new byte[halfIndex.PlaneBytes];
+ var expectedInten = new byte[halfIndex.PlaneBytes];
+ FrameConversion.Convert(field, stride + 1, stride, halfIndex, false, expectedField);
+ FrameConversion.Convert(inten, stride + 1, stride, halfIndex, true, expectedInten);
+ store.Write(0, cpu.FieldData, cpu.IntensityData, stride);
+ var snapshot = new FrameSnapshot(halfIndex, true);
+ cpu.CaptureFrame(snapshot, true);
+ cpu.AwaitFrame(snapshot);
+ store.Write(1, snapshot);
+ store.Write(2, expectedField, expectedInten);
+ var read = new byte[halfIndex.PlaneBytes];
+ bool allSame = true;
+ for (int frame = 0; frame < 3; frame++)
+ {
+ allSame &= store.CopyLayer(frame, FrameLayer.Field, read.AsSpan()) && read.AsSpan().SequenceEqual(expectedField);
+ allSame &= store.CopyLayer(frame, FrameLayer.Intensity, read.AsSpan()) && read.AsSpan().SequenceEqual(expectedInten);
+ }
+ Check(store.Count == 3 && allSame, "index store: the float, snapshot and byte writes read back as the same bytes");
+ bool refused = false;
+ try
+ {
+ store.CopyLayer(0, FrameLayer.Field, new Half[32 * 24]);
+ }
+ catch (InvalidOperationException)
+ {
+ refused = true;
+ }
+ Check(refused, "index store: the Half read is refused");
+ refused = false;
+ try
+ {
+ _ = new ExportJob(store, 0, 0, [], null);
+ }
+ catch (ArgumentException)
+ {
+ refused = true;
+ }
+ Check(refused, "an export refuses a store of palette indices");
+ refused = false;
+ try
+ {
+ store.Write(3, new FrameSnapshot(half, true));
+ }
+ catch (ArgumentException)
+ {
+ refused = true;
+ }
+ Check(refused, "a snapshot of another format is refused");
+ }
+ Check(!File.Exists(path), "index store file deleted on dispose");
+
+ // a spec with a quality: the interval multiplied, the frames fewer, the shape from the display brightness; a run and a scratch frame in it
+ var project = new Project();
+ project.Scene.Width = W;
+ project.Scene.Height = H;
+ project.Scene.DampingEdge = 4;
+ project.Simulation.Steps = 200;
+ project.Simulation.VisualizeEvery = 2;
+ project.Display.Field.Brightness = 25;
+ project.Display.Intensity.Brightness = 4;
+ Source source = project.AddSource();
+ source.X = 20;
+ source.Y = 24;
+ source.Frequency = 120;
+ Probe lineProbe = project.AddProbe();
+ lineProbe.Kind = ProbeKind.Line;
+ lineProbe.AX = 5;
+ lineProbe.AY = 5;
+ lineProbe.BX = 40;
+ lineProbe.BY = 30;
+ var quality = new PreviewQuality(2, 2, FrameFormat.Index);
+ RunSpec spec = RunSpec.Create(project, null, preferGpu: false, quality: quality);
+ RunSpec fullSpec = RunSpec.Create(project, null, preferGpu: false);
+ Check(spec.VisualizeEvery == 2 && spec.FrameCount == 100 && spec.FrameStride == 2 && spec.CaptureEvery == 4 && spec.StoredFrameCount == 50 && spec.StoredIndexOf(99) == 49
+ && spec.Quality == quality && !spec.Quality.IsFull && fullSpec.Quality.IsFull && fullSpec.FrameStride == 1 && fullSpec.StoredFrameCount == 100,
+ "spec with a quality of 1/2, every 2nd frame, index: the timeline keeps 100 frames every 2 steps, 50 of them stored every 4 steps; the full spec stores all 100");
+ Check(spec.Shape == new FrameShape(W, H, 2, FrameFormat.Index, 25f, 4f) && spec.Shape.Width == 32 && fullSpec.Shape.IsFull, "the spec's shape: half the canvas, index bytes, the display brightness of both layers");
+ Check(spec.SameSceneAs(fullSpec), "the quality does not change the scene, so an engine serves both");
+ path = Path.Combine(Path.GetTempPath(), "library_check-quality-" + Guid.NewGuid().ToString("N") + FrameCache.Extension);
+ using (var store = FrameStore.Create(path, spec.Shape, spec.Layers, spec.StoredFrameCount, spec.CaptureEvery))
+ {
+ var run = new SimulationRun(spec, store, null);
+ run.Start();
+ Check(run.Completion.Wait(30000) && run.State == RunState.Completed && store.Count == 50 && store.StepOf(49) == 196 && run.FrameCount == 100 && run.Frames.Count == 100,
+ "a run in that quality completes with 50 stored frames of 32x24 index bytes covering all 100 timeline frames");
+ // stored frame 49 is timeline frame 98, step 196: an engine stepped 197 times and captured in the shape gives the same bytes,
+ // and timeline frame 99 (not stored) reads the same stored frame
+ IWaveEngine reference = WaveEngineFactory.Create(SceneData.Empty(W, H, spec.DampingEdge, spec.RefractiveIndex), spec.Engine, false, spec.Emitters, out _);
+ Run(reference, 197);
+ var expected = new FrameSnapshot(spec.Shape, spec.TrackIntensity);
+ reference.CaptureFrame(expected, spec.TrackIntensity);
+ reference.AwaitFrame(expected);
+ var stored = new byte[spec.Shape.PlaneBytes];
+ var shown = new byte[spec.Shape.PlaneBytes];
+ Check(store.CopyLayer(49, FrameLayer.Field, stored.AsSpan()) && stored.AsSpan().SequenceEqual(expected.FieldBytes) && stored.Max() > 127 && stored.Min() < 127,
+ "stored frame 49 equals a fresh engine's capture of step 196 in that shape");
+ Check(run.Frames is StridedFrameSource && run.Frames.CopyLayer(98, FrameLayer.Field, shown.AsSpan()) && shown.AsSpan().SequenceEqual(stored)
+ && run.Frames.CopyLayer(99, FrameLayer.Field, shown.AsSpan()) && shown.AsSpan().SequenceEqual(stored),
+ "timeline frames 98 and 99 both show stored frame 49 (a stored frame stands in for the next one)");
+ Check(run.Traces.Length == 1 && run.Traces[0].Profiles.Count == 100,
+ $"the line probe's profiles are collected per timeline frame (100), not per stored one ({run.Traces.Length} traces, {(run.Traces.Length > 0 ? run.Traces[0].Profiles.Count : 0)} profiles)");
+ using (var scratch = new ScratchRunner(null))
+ using (var arrived = new ManualResetEventSlim())
+ {
+ ScratchResult? result = null;
+ scratch.Completed += (_, r) =>
+ {
+ result = r;
+ arrived.Set();
+ };
+ scratch.Request(spec, 98);
+ Check(arrived.Wait(30000) && result is { Snapshot: not null, Frame: 98 } && result.Snapshot.Shape == spec.Shape && result.Snapshot.FieldBytes.AsSpan().SequenceEqual(expected.FieldBytes),
+ "a scratch frame 98 in that quality has the spec's shape and the stored bytes (the scratch always computes the exact timeline frame)");
+ }
+ run.Dispose();
+ }
+ }
+
private static void CheckRenderer()
{
Console.WriteLine("--- renderer");
diff --git a/_tools/ui_check/PreviewQualityCheck.ps1 b/_tools/ui_check/PreviewQualityCheck.ps1
new file mode 100644
index 0000000..0023eda
--- /dev/null
+++ b/_tools/ui_check/PreviewQualityCheck.ps1
@@ -0,0 +1,125 @@
+# Drives View > Preview resolution / frames / samples by keyboard (F10 focuses the menu bar, Down opens a menu, Right moves
+# to View, Down walks its entries, Right opens a submenu, Enter picks) on tiny.wdproj (64 x 48, 200 steps, a frame every
+# 2 steps): a run is made, then each choice marks it stale and the automatic re-run follows in the reduced shape (the
+# status bar, the frame readout and the log file next to the exe are the witnesses: "50 of 100 frames stored as 32x24
+# (1/2 resolution, every 2. frame, 8-bit)"). The timeline never changes: with every second frame stored, frames 98 and
+# 99 show the same picture while 97 differs; the source marker stays at the source's canvas position on a half-size
+# picture; the settings survive a restart; everything is put back to Full at the end. Posted keys and UI Automation
+# properties only, as in the other harnesses.
+#
+# powershell -ExecutionPolicy Bypass -File _tools\ui_check\PreviewQualityCheck.ps1 [-Trace]
+param([switch]$Trace)
+. (Join-Path $PSScriptRoot "Common.ps1")
+$exe = Join-Path $PSScriptRoot "..\..\WaveDude.WPF\bin\Debug\net10.0-windows\WaveDude.WPF.exe"
+$log = Join-Path (Split-Path $exe) "WaveDude.WPF.log"
+$project = Join-Path $PSScriptRoot "tiny.wdproj"
+$by = [string][char]0xD7 # the multiplication sign of the log's "64x48", built from its code so the script stays ASCII
+$failures = 0
+function Check([string]$name, [bool]$ok, [string]$detail = "") {
+ if ($ok) { if ($Trace) { "PASS $name" } } else { "FAIL $name $detail"; $script:failures++ }
+}
+function Step([string]$what, [int]$vk, [int]$settle) {
+ Key $vk $settle
+ if ($Trace) { " {0,-12} focus {1} foreground {2}" -f $what, (FocusedId), (Foreground) }
+}
+# the log of this session (the app archives the previous one on start-up; the file stays open, so share the read)
+function LogText() {
+ $fs = New-Object IO.FileStream($log, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite)
+ try { $sr = New-Object IO.StreamReader($fs); return $sr.ReadToEnd() } finally { $fs.Dispose() }
+}
+function LogHas([string]$text) { return (LogText).Contains($text) }
+# View (2nd header) > entry $entry (0 Panes, 1 Theme, 2 Language, 3 Preview resolution, 4 Preview frames, 5 Preview samples) > item $item
+function ChooseView([int]$entry, [int]$item) {
+ Step "F10" 0x79 150 # the menu bar's first header (File)
+ Step "Down" 0x28 150 # opens File
+ Step "Right" $VK_RIGHT 150 # moves to View and opens it on its first entry
+ for ($i = 0; $i -lt $entry; $i++) { Step "Down" 0x28 100 }
+ Step "Right" $VK_RIGHT 150 # opens the submenu on its first item
+ for ($i = 0; $i -lt $item; $i++) { Step "Down" 0x28 100 }
+ Step "Enter" $VK_RETURN 300
+}
+# a choice stales the run and the automatic re-run completes
+function ChooseAndRerun([string]$what, [int]$entry, [int]$item) {
+ ChooseView $entry $item
+ Check "$what marks the run stale" (WaitFor { (RunStatus) -like "*edited since*" } 3000) (RunStatus)
+ Check "$what is followed by the automatic re-run" (WaitFor { (RunStatus) -like "Completed:*" -and (RunStatus) -notlike "*edited since*" } 20000 200) (RunStatus)
+ Start-Sleep -Milliseconds 300
+}
+function MarkerAtSource([string]$when) {
+ $expected = CanvasPoint "PreviewFieldImage" 64 48 20 24
+ $centre = CentreOf "Source:Source 1"
+ Check "the source marker sits at the source's canvas position $when" ([math]::Abs($centre[0] - $expected[0]) -lt 3 -and [math]::Abs($centre[1] - $expected[1]) -lt 3) ("marker {0:0},{1:0} expected {2:0},{3:0}" -f $centre[0], $centre[1], $expected[0], $expected[1])
+}
+# the pictures of the last three frames: with every frame stored all three differ, with every second one 99 repeats 98
+function LastFrames([string]$when, [bool]$repeated) {
+ FocusOn "PreviewPlay" # the frame-step keys are the pane's own bindings; the menu left the focus on the tree
+ Key $VK_END 500
+ Check "the last frame is 99 at step 198 $when" ((Frame) -eq "99 / 99" -and (StepText) -match "198$") ("{0}, {1}" -f (Frame), (StepText))
+ $at99 = FieldHash
+ Key $VK_COMMA 500
+ $at98 = FieldHash
+ Key $VK_COMMA 500
+ $at97 = FieldHash
+ Check "frame 97 differs from 98 $when" ((Frame) -eq "97 / 99" -and $at97 -ne $at98) (Frame)
+ if ($repeated) { Check "frame 99 shows the stored frame 98 again $when" ($at99 -eq $at98) }
+ else { Check "frame 99 differs from 98 $when" ($at99 -ne $at98) }
+}
+# a second start sometimes comes up active in spite of Start-App's parking (seen 2026-10-15): park it again, a little slower
+function Park() {
+ for ($i = 0; $i -lt 5 -and (Foreground) -eq "APP"; $i++) {
+ [Native]::ShowWindow($script:hwnd, 6) | Out-Null # SW_MINIMIZE
+ Start-Sleep -Milliseconds 300
+ $script:park.Activate(); [System.Windows.Forms.Application]::DoEvents()
+ Start-Sleep -Milliseconds 300
+ [Native]::ShowWindow($script:hwnd, 4) | Out-Null # SW_SHOWNOACTIVATE
+ Start-Sleep -Milliseconds 400
+ }
+}
+
+Start-App $exe $project
+try {
+ FocusOn "PreviewPlay" # a window never activated has no focused element, and F5 (a routed gesture) then goes nowhere
+ Key 0x74 300 # F5
+ Check "F5 run completes" (WaitFor { (RunStatus) -like "Completed:*" } 30000) (RunStatus)
+ Start-Sleep -Milliseconds 300
+ Check "the full run has 100 frames" ((Frame) -like "* / 99") (Frame)
+ Check "the log says all frames are stored" (LogHas "100 of 100 frames stored as 64${by}48 (full)")
+ MarkerAtSource "at full resolution"
+ LastFrames "at full quality" $false
+
+ ChooseAndRerun "View > Preview frames > Half" 4 1
+ Check "the timeline still has 100 frames" ((Frame) -like "* / 99") (Frame)
+ Check "the log says 50 of 100 frames are stored" (LogHas "50 of 100 frames stored as 64${by}48 (1/1 resolution, every 2. frame, 16-bit)")
+ LastFrames "with every second frame stored" $true
+
+ ChooseAndRerun "View > Preview resolution > Half" 3 1
+ Check "the log says the frames are 32x24" (LogHas "50 of 100 frames stored as 32${by}24 (1/2 resolution, every 2. frame, 16-bit)")
+ MarkerAtSource "on a half-size picture"
+
+ ChooseAndRerun "View > Preview samples > 8-bit" 5 1
+ Check "the log says 8-bit" (LogHas "50 of 100 frames stored as 32${by}24 (1/2 resolution, every 2. frame, 8-bit)")
+ Check "the app never took the foreground" ((Foreground) -ne "APP") (Foreground)
+}
+finally { Stop-App }
+
+# the choices are user settings: a fresh start runs reduced, and the menu puts everything back
+Start-Sleep -Milliseconds 800 # let the first instance's window go before the next one is parked
+Start-App $exe $project
+Park
+try {
+ FocusOn "PreviewPlay"
+ Key 0x74 300
+ Check "after a restart F5 runs in the kept quality" (WaitFor { (RunStatus) -like "Completed:*" } 30000) (RunStatus)
+ Start-Sleep -Milliseconds 300
+ Check "still 50 of 100 frames of 32x24, 8-bit (settings kept)" ((Frame) -like "* / 99" -and (LogHas "50 of 100 frames stored as 32${by}24 (1/2 resolution, every 2. frame, 8-bit)")) (Frame)
+ ChooseAndRerun "View > Preview samples > 16-bit" 5 0
+ ChooseAndRerun "View > Preview resolution > Full" 3 0
+ ChooseAndRerun "View > Preview frames > Full" 4 0
+ Check "back to all frames stored" ((Frame) -like "* / 99" -and (LogHas "100 of 100 frames stored as 64${by}48 (full)")) (Frame)
+ LastFrames "after the return to Full" $false
+ Check "the app never took the foreground" ((Foreground) -ne "APP") (Foreground)
+}
+finally { Stop-App }
+
+"$failures failure(s)"
+exit $failures