Skip to content

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

C#

The renderer is vectorised and measured; the run's loops on dedicated threads

Alexander Graef1cfe08f79162
diff --git a/CLAUDE.md b/CLAUDE.md
index 7cddc41..e857d8b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -125,8 +125,29 @@ WPF shell as it stands:
and curve pens (2.3 ms to 1.1 per draw); and **the shown position advances only while the presenter is free**
(`FramePresenter.IsBusy`, in the playback tick and the live follow): the clock keeps counting, so time stays right,
and the overlays and the bar are redrawn once per picture that can be shown instead of sixty times a second for
- pictures that never appear (this canvas presents 11 to 14 a second, colouring 61 ms of a 2880 x 1080 frame on the
- pool, which is the next thing worth speeding up). Tried and reverted: the playback timer and the pixel copy at
+ pictures that never appear (this canvas presented 11 to 14 a second under the harness).
+ **The colouring, measured properly** (2026-10-16, later): `library_check -- bench-render [w h]` times the
+ renderer alone, parallel and on one thread, scalar against vector, with the warm-up the "Bench numbers need
+ the JIT warm" rule above demands (60 calls and a 300 ms pause; a first version with 20 calls reported 4.6 to
+ 6.3 ms a layer for what is 2 ms warm, and a day's conclusions were drawn from it before the rule was reread).
+ Warm, the committed renderer coloured a 2880 x 1080 layer in 1.9 to 2.4 ms on ten cores; the "61 ms" the
+ presenter logged during a run was the harness's UI Automation traffic (a quiet run: 20 ms both layers during the
+ run, 7 after). What stayed: the run's stepping loop and writer on dedicated threads (`LongRunning`); the
+ presenter's Debug line splitting the copy out of the store, the colouring and the copy into the bitmap;
+ `bench-render ... load` timing the renderer beside a real GPU run with its store in the same process (no
+ slowdown: the run is not what slows it). Tried and reverted: below-normal priority for the run's threads (the run
+ a quarter slower, the renderer unchanged). **The renderer is vectorised** (`FrameRenderer.FieldRow`/`IntensityRow`,
+ four pixels per 128-bit register, NaN and non-positive lanes through masks, the scalar helpers for the tail; bit
+ for bit equal to `ColorLut.FieldIndex`/`IntensityIndex`, checked over NaN, infinities, zeros, the clamp edges, odd
+ widths, grey and palette; `IntensityIndex` in single precision, what the GPU's `capture_index` kernel computes) and
+ **the rows go to the workers in blocks of 32** (`Partitioner.Create`), not one at a time. Warm numbers: a palette
+ layer 1.9 to 2.4 ms before, 1.4 to 1.7 after; grey 2.3 to 1.1; on one core, the user's question about weak CPUs,
+ the field 5.9 to 2.9 ns a pixel and the intensity 4.8 to 3.0, so a laptop's few cores gain about two times, which
+ is why the rows stay. The palette lookup, four scalar table reads per register, is the floor; past it lies only
+ colouring on the GPU, where the halves already are when captured, not built. The start-up stall of about 350 ms
+ at window creation (the watchdog's Debug line, "run none") is unmeasured: it coincides with the scratch runner's
+ OpenCL compile on another thread, which proves nothing; log the UI thread's start-up milestones against the
+ episode before touching anything. Tried and reverted: the playback timer and the pixel copy at
background priority (a mouse scrub then lagged behind every move), a fixed ten-frames-a-second cap on the presenter
while the engine runs (the live follow stuttered), a yield to input priority after each presented frame (no
effect). The watchdog stays (the user: a user would never know about a stall otherwise): two 100 ms timers at
diff --git a/WaveDudeNext.WPF/Rendering/FramePresenter.cs b/WaveDudeNext.WPF/Rendering/FramePresenter.cs
index c9485d4..454fe74 100644
--- a/WaveDudeNext.WPF/Rendering/FramePresenter.cs
+++ b/WaveDudeNext.WPF/Rendering/FramePresenter.cs
@@ -52,7 +52,7 @@ public sealed class FramePresenter
private int _renderedFrame = -1;
private Job? _renderedJob;
private readonly Stopwatch _renderClock = new();
- private readonly Stopwatch _colourClock = new(), _writeClock = new();
+ private readonly Stopwatch _copyClock = new(), _colourClock = new(), _writeClock = new();
private int _renderCount;
/// <param name="dispatcher">The UI thread's dispatcher, where the bitmaps live.</param>
@@ -214,13 +214,14 @@ public sealed class FramePresenter
{
continue;
}
- _colourClock.Start();
+ _copyClock.Start();
bool copied = job.Indices != null ? job.Source.CopyLayer(frame, layer, job.Indices.AsSpan()) : job.Source.CopyLayer(frame, layer, job.Halves.AsSpan());
+ _copyClock.Stop();
if (!copied)
{
- _colourClock.Stop();
continue;
}
+ _colourClock.Start();
if (job.Indices != null)
{
// palette indices: the brightness was applied when the frame was captured, only the palette is looked up
@@ -282,10 +283,11 @@ public sealed class FramePresenter
if (++_renderCount % RenderLogInterval == 0)
{
// the cost of one presented frame (copy, colouring, bitmap write), averaged; for judging the pipeline at full resolution
- Logger.Debug("Preview: {Width}x{Height}, {Average:0.0} ms per frame over the last {Count} (colouring {Colour:0.0}, copy into the bitmap {Write:0.0}, both on the pool)",
+ Logger.Debug("Preview: {Width}x{Height}, {Average:0.0} ms per frame over the last {Count} (copy out of the store {Copy:0.0}, colouring {Colour:0.0}, copy into the bitmap {Write:0.0}, all on the pool)",
width, height, _renderClock.Elapsed.TotalMilliseconds / RenderLogInterval, RenderLogInterval,
- _colourClock.Elapsed.TotalMilliseconds / RenderLogInterval, _writeClock.Elapsed.TotalMilliseconds / RenderLogInterval);
+ _copyClock.Elapsed.TotalMilliseconds / RenderLogInterval, _colourClock.Elapsed.TotalMilliseconds / RenderLogInterval, _writeClock.Elapsed.TotalMilliseconds / RenderLogInterval);
_renderClock.Reset();
+ _copyClock.Reset();
_colourClock.Reset();
_writeClock.Reset();
}
diff --git a/WaveDudeNext/Rendering/ColorLut.cs b/WaveDudeNext/Rendering/ColorLut.cs
index 6a1a482..1b6ae3b 100644
--- a/WaveDudeNext/Rendering/ColorLut.cs
+++ b/WaveDudeNext/Rendering/ColorLut.cs
@@ -128,7 +128,9 @@ public sealed class ColorLut
{
return 0;
}
- return (int)(Math.Min(Math.Sqrt(intensity) * brightness, 1.0) * 254.0);
+ // single precision throughout (2026-10-16): what the GPU's capture_index kernel computes and what the
+ // vectorised renderer reproduces bit for bit; the double arithmetic before differed in the last bit at most
+ return (int)(MathF.Min(MathF.Sqrt(intensity) * brightness, 1f) * 254f);
}
/// <summary>
diff --git a/WaveDudeNext/Rendering/FrameRenderer.cs b/WaveDudeNext/Rendering/FrameRenderer.cs
index f940449..7d40ea8 100644
--- a/WaveDudeNext/Rendering/FrameRenderer.cs
+++ b/WaveDudeNext/Rendering/FrameRenderer.cs
@@ -15,7 +15,9 @@
// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
// <https://www.gnu.org/licenses/>.
+using System.Collections.Concurrent;
using System.Numerics.Tensors;
+using System.Runtime.Intrinsics;
namespace WaveDudeNext.Rendering;
@@ -25,12 +27,20 @@ namespace WaveDudeNext.Rendering;
/// <c>render_intensity</c> in the Python code: the value is converted to a table index (see
/// <see cref="ColorLut"/>) and the index to a colour. Without a colour table (null) the index itself is used
/// as grey level. Row loops run in parallel (each worker converts its row to floats with the vectorised
-/// <see cref="TensorPrimitives.ConvertToSingle"/> first), so the methods are CPU-bound but not thread-affine;
+/// <see cref="TensorPrimitives.ConvertToSingle"/> first and colours four pixels at a time on 128-bit registers),
+/// so the methods are CPU-bound but not thread-affine;
/// the caller owns the buffers and must not touch them while a call is in progress.
/// </summary>
public static class FrameRenderer
{
/// <summary>
+ /// The rows in one contiguous block per core (2026-10-16): row by row, the parallel loop reached a speed-up of
+ /// 1.4 on ten cores (per-row scheduling and pool threads parking between 6 ms bursts); in blocks each worker
+ /// takes one range and the loop runs close to the core count.
+ /// </summary>
+ private static OrderablePartitioner<Tuple<int, int>> Blocks(int height) =>
+ Partitioner.Create(0, height, 32);
+ /// <summary>
/// Renders the wave field: every value is mapped by <see cref="ColorLut.FieldIndex"/>
/// (<c>clip(value · brightness, -1, 1) · 127 + 127</c>) and coloured.
/// </summary>
@@ -42,13 +52,12 @@ public static class FrameRenderer
/// <param name="pixels">Destination, at least <paramref name="width"/> × <paramref name="height"/> packed BGRA32 pixels, row-major.</param>
public static void RenderField(ReadOnlyMemory<Half> values, int width, int height, int[]? lut, float brightness, Memory<int> pixels)
{
- Parallel.For(0, height, () => new float[width], (y, _, row) =>
+ Parallel.ForEach(Blocks(height), () => new float[width], (block, _, row) =>
{
- TensorPrimitives.ConvertToSingle(values.Span.Slice(y * width, width), row);
- Span<int> target = pixels.Span.Slice(y * width, width);
- for (int x = 0; x < width; x++)
+ for (int y = block.Item1; y < block.Item2; y++)
{
- target[x] = Colorize(ColorLut.FieldIndex(row[x], brightness), lut);
+ TensorPrimitives.ConvertToSingle(values.Span.Slice(y * width, width), row);
+ FieldRow(row, lut, brightness, pixels.Span.Slice(y * width, width));
}
return row;
}, _ => { });
@@ -66,18 +75,93 @@ public static class FrameRenderer
/// <param name="pixels">Destination, at least <paramref name="width"/> × <paramref name="height"/> packed BGRA32 pixels, row-major.</param>
public static void RenderIntensity(ReadOnlyMemory<Half> values, int width, int height, int[]? lut, float brightness, Memory<int> pixels)
{
- Parallel.For(0, height, () => new float[width], (y, _, row) =>
+ Parallel.ForEach(Blocks(height), () => new float[width], (block, _, row) =>
{
- TensorPrimitives.ConvertToSingle(values.Span.Slice(y * width, width), row);
- Span<int> target = pixels.Span.Slice(y * width, width);
- for (int x = 0; x < width; x++)
+ for (int y = block.Item1; y < block.Item2; y++)
{
- target[x] = Colorize(ColorLut.IntensityIndex(row[x], brightness), lut);
+ TensorPrimitives.ConvertToSingle(values.Span.Slice(y * width, width), row);
+ IntensityRow(row, lut, brightness, pixels.Span.Slice(y * width, width));
}
return row;
}, _ => { });
}
+ /// <summary>
+ /// One row of the field, four pixels at a time on 128-bit registers (2026-10-16, the width every x64 and ARM64
+ /// machine accelerates): the same operations in the same order as <see cref="ColorLut.FieldIndex"/>, so the
+ /// indices are identical bit for bit (the library harness checks it over awkward values); NaN lanes take 127
+ /// through a mask, so the min/max semantics for NaN never matter. The tail and a machine without acceleration
+ /// go through the scalar helper.
+ /// </summary>
+ internal static void FieldRow(ReadOnlySpan<float> row, int[]? lut, float brightness, Span<int> target)
+ {
+ int x = 0;
+ if (Vector128.IsHardwareAccelerated)
+ {
+ Vector128<float> gain = Vector128.Create(brightness);
+ Vector128<float> one = Vector128.Create(1f);
+ Vector128<float> minusOne = Vector128.Create(-1f);
+ Vector128<float> scale = Vector128.Create(127f);
+ Vector128<int> nanIndex = Vector128.Create(127);
+ for (; x <= row.Length - 4; x += 4)
+ {
+ Vector128<float> scaled = Vector128.Create(row.Slice(x, 4)) * gain;
+ Vector128<int> isNumber = Vector128.Equals(scaled, scaled).AsInt32();
+ Vector128<float> clamped = Vector128.Min(Vector128.Max(scaled, minusOne), one);
+ Vector128<int> index = Vector128.ConvertToInt32(clamped * scale + scale);
+ Store(Vector128.ConditionalSelect(isNumber, index, nanIndex), lut, target.Slice(x, 4));
+ }
+ }
+ for (; x < row.Length; x++)
+ {
+ target[x] = Colorize(ColorLut.FieldIndex(row[x], brightness), lut);
+ }
+ }
+
+ /// <summary>
+ /// One row of the intensity, four pixels at a time: the operations of <see cref="ColorLut.IntensityIndex(float, float)"/>
+ /// in the same single precision; lanes that are not positive (zero, negative, NaN) take 0 through a mask.
+ /// </summary>
+ internal static void IntensityRow(ReadOnlySpan<float> row, int[]? lut, float brightness, Span<int> target)
+ {
+ int x = 0;
+ if (Vector128.IsHardwareAccelerated)
+ {
+ Vector128<float> gain = Vector128.Create(brightness);
+ Vector128<float> one = Vector128.Create(1f);
+ Vector128<float> scale = Vector128.Create(254f);
+ Vector128<float> zero = Vector128<float>.Zero;
+ for (; x <= row.Length - 4; x += 4)
+ {
+ Vector128<float> value = Vector128.Create(row.Slice(x, 4));
+ Vector128<int> positive = Vector128.GreaterThan(value, zero).AsInt32();
+ Vector128<float> scaled = Vector128.Sqrt(value) * gain;
+ Vector128<int> index = Vector128.ConvertToInt32(Vector128.Min(scaled, one) * scale);
+ Store(Vector128.ConditionalSelect(positive, index, Vector128<int>.Zero), lut, target.Slice(x, 4));
+ }
+ }
+ for (; x < row.Length; x++)
+ {
+ target[x] = Colorize(ColorLut.IntensityIndex(row[x], brightness), lut);
+ }
+ }
+
+ /// <summary>Four palette indices to four pixels: a lookup each with a palette, else the grey arithmetic on the register.</summary>
+ private static void Store(Vector128<int> index, int[]? lut, Span<int> target)
+ {
+ if (lut != null)
+ {
+ target[0] = lut[index[0]];
+ target[1] = lut[index[1]];
+ target[2] = lut[index[2]];
+ target[3] = lut[index[3]];
+ }
+ else
+ {
+ (index * Vector128.Create(0x010101) | Vector128.Create(unchecked((int)0xFF000000))).CopyTo(target);
+ }
+ }
+
/// <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
diff --git a/WaveDudeNext/Runs/SimulationRun.cs b/WaveDudeNext/Runs/SimulationRun.cs
index 8bf5a04..77d76b1 100644
--- a/WaveDudeNext/Runs/SimulationRun.cs
+++ b/WaveDudeNext/Runs/SimulationRun.cs
@@ -193,7 +193,10 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposable
throw new InvalidOperationException("The run has already been started.");
}
State = RunState.Starting;
- Task.Run(RunLoop);
+ // a thread of its own, not a pool thread (2026-10-16): the loop lives for the whole run and mostly waits on the
+ // GPU, which is not what pool threads are for; the writer below is the same. (A below-normal priority for the
+ // two was tried, to keep their busy-waits off the renderer's cores, and slowed the run by a quarter.)
+ Task.Factory.StartNew(RunLoop, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
/// <summary>Parks the worker before its next step; <see cref="State"/> becomes Paused when it gets there.</summary>
@@ -290,7 +293,7 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposable
}
writer?.Wait();
};
- writer = Task.Run(() =>
+ writer = Task.Factory.StartNew(() =>
{
foreach (FrameSnapshot snapshot in pending.GetConsumingEnumerable())
{
@@ -303,7 +306,7 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposable
Interlocked.Add(ref storeTicks, Stopwatch.GetTimestamp() - w1);
pool.Add(snapshot);
}
- });
+ }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
for (int i = 0; i < Spec.Steps; i++)
{
if (!_gate.IsSet)
diff --git a/WaveDudeNext/WaveDudeNext.csproj b/WaveDudeNext/WaveDudeNext.csproj
index c6fbab2..93d7209 100644
--- a/WaveDudeNext/WaveDudeNext.csproj
+++ b/WaveDudeNext/WaveDudeNext.csproj
@@ -24,6 +24,10 @@
<EmbeddedResource Include="ColorSchemes\*.wdscheme" LogicalName="ColorSchemes/%(Filename)%(Extension)" />
</ItemGroup>
+ <ItemGroup>
+ <InternalsVisibleTo Include="LibraryCheck" />
+ </ItemGroup>
+
<ItemGroup>
<PackageReference Include="NLog" Version="6.2.1" />
<PackageReference Include="System.Numerics.Tensors" Version="10.0.12" />
diff --git a/_tools/library_check/LibraryCheck.csproj b/_tools/library_check/LibraryCheck.csproj
index 945cb87..4237d73 100644
--- a/_tools/library_check/LibraryCheck.csproj
+++ b/_tools/library_check/LibraryCheck.csproj
@@ -12,6 +12,7 @@
<RootNamespace>LibraryCheck</RootNamespace>
<!-- the .editorconfig code-style rules are build warnings too: a file without the license header (IDE0073) -->
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<!-- UseWPF drops System.IO from the implicit usings -->
diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.cs
index 7816aea..fec64f2 100644
--- a/_tools/library_check/Program.cs
+++ b/_tools/library_check/Program.cs
@@ -184,6 +184,11 @@ internal static class Program
}
return 0;
}
+ if (args.Length > 0 && args[0] == "bench-render")
+ {
+ BenchRender(args.Length > 1 ? int.Parse(args[1]) : 1920, args.Length > 2 ? int.Parse(args[2]) : 1080, args.Length > 3 && args[3] == "load");
+ return 0;
+ }
if (args.Length > 0 && args[0] == "bench-export")
{
ExportChecks.Bench(args.Length > 1 ? int.Parse(args[1]) : 1920, args.Length > 2 ? int.Parse(args[2]) : 1080);
@@ -220,6 +225,99 @@ internal static class Program
return _failures == 0 ? 0 : 1;
}
+ /// <summary>"bench-render [w h]": what colouring a stored frame costs, per layer, at that size (the presenter's cost per picture).</summary>
+ private static void BenchRender(int w, int h, bool load = false)
+ {
+ Console.WriteLine($"--- bench-render {w}x{h} (Vector128 accelerated: {System.Runtime.Intrinsics.Vector128.IsHardwareAccelerated}){(load ? ", under a frame store's load" : "")}");
+ using var stop = new CancellationTokenSource();
+ SimulationRun? run = null;
+ FrameStore? runStore = null;
+ if (load)
+ {
+ // the real thing: a GPU run of this size with its store, in this process, while the renderer is timed
+ var project = new Project();
+ project.Scene.Width = w;
+ project.Scene.Height = h;
+ project.Simulation.Steps = 4000;
+ project.Simulation.VisualizeEvery = 2;
+ Source source = project.AddSource();
+ source.X = w / 3;
+ source.Y = h / 2;
+ source.Frequency = 120;
+ RunSpec spec = RunSpec.Create(project, null, preferGpu: true);
+ string path = Path.Combine(Path.GetTempPath(), "library_check-bench-run-" + Guid.NewGuid().ToString("N") + FrameCache.Extension);
+ runStore = FrameStore.Create(path, spec.Shape, spec.Layers, spec.StoredFrameCount, spec.CaptureEvery);
+ run = new SimulationRun(spec, runStore, null);
+ run.Start();
+ Thread.Sleep(1500);
+ Console.WriteLine($" run: {run.State}, {run.EngineDescription}");
+ }
+ var random = new Random(7);
+ var field = new Half[w * h];
+ var intensity = new Half[w * h];
+ for (int i = 0; i < field.Length; i++)
+ {
+ field[i] = (Half)(random.NextDouble() * 2 - 1);
+ intensity[i] = (Half)(random.NextDouble() * 1.5);
+ }
+ int[] lut = ColorLut.Build(ColorSchemeStore.LoadBuiltIn(null).First(s => s.Name == Display.DefaultFieldColorScheme)).Argb;
+ var pixels = new int[w * h];
+ foreach ((string name, Action render) in new (string, Action)[]
+ {
+ ("intensity", () => FrameRenderer.RenderIntensity(intensity, w, h, lut, 1f, pixels)),
+ ("field", () => FrameRenderer.RenderField(field, w, h, lut, 1f, pixels)),
+ ("field, grey", () => FrameRenderer.RenderField(field, w, h, null, 1f, pixels)),
+ ("intensity again", () => FrameRenderer.RenderIntensity(intensity, w, h, lut, 1f, pixels)),
+ })
+ {
+ for (int i = 0; i < 60; i++)
+ {
+ render();
+ }
+ Thread.Sleep(300); // the tiered JIT's background recompilation
+ var clock = Stopwatch.StartNew();
+ const int Runs = 100;
+ for (int i = 0; i < Runs; i++)
+ {
+ render();
+ }
+ double ms = clock.Elapsed.TotalMilliseconds / Runs;
+ Console.WriteLine($" {name,-12} {ms,6:0.00} ms per layer ({ms * 1e6 / (w * (double)h):0.00} ns per pixel)");
+ }
+ // one core's view: a single row, scalar helpers against the vector rows, no parallel loop and no memory traffic
+ {
+ var row = new float[w];
+ var got = new int[w];
+ var rng2 = new Random(3);
+ for (int i = 0; i < w; i++) { row[i] = (float)(rng2.NextDouble() * 2 - 1); }
+ foreach ((string name, Action render) in new (string, Action)[]
+ {
+ ("field scalar", () => { for (int x = 0; x < w; x++) { got[x] = FrameRenderer.Colorize(ColorLut.FieldIndex(row[x], 1f), lut); } }),
+ ("field vector", () => FrameRenderer.FieldRow(row, lut, 1f, got)),
+ ("intensity scalar", () => { for (int x = 0; x < w; x++) { got[x] = FrameRenderer.Colorize(ColorLut.IntensityIndex(row[x], 1f), lut); } }),
+ ("intensity vector", () => FrameRenderer.IntensityRow(row, lut, 1f, got)),
+ ("grey scalar", () => { for (int x = 0; x < w; x++) { got[x] = FrameRenderer.Colorize(ColorLut.FieldIndex(row[x], 1f), null); } }),
+ ("grey vector", () => FrameRenderer.FieldRow(row, null, 1f, got)),
+ })
+ {
+ for (int i = 0; i < 2000; i++) { render(); }
+ var clock = Stopwatch.StartNew();
+ const int Rows = 20000;
+ for (int i = 0; i < Rows; i++) { render(); }
+ double ns = clock.Elapsed.TotalMilliseconds * 1e6 / Rows / w;
+ Console.WriteLine($" one thread, {name,-18} {ns:0.00} ns per pixel");
+ }
+ }
+ stop.Cancel();
+ if (run != null)
+ {
+ Console.WriteLine($" run while measuring: {run.State}, {run.StepsDone} steps done");
+ run.Stop();
+ run.Completion.Wait(10000);
+ runStore?.Dispose();
+ }
+ }
+
/// <summary>"bench [w h]": what a step costs on each engine at that size, pure stepping and with a frame readback every 2 steps.</summary>
private static void Bench(int w, int h)
{
@@ -944,6 +1042,41 @@ internal static class Program
Check(pixels[1] == ColorLut.FieldIndex(0.5f, 1f) && pixels[1] == 190, "field with LUT uses FieldIndex (0.5 -> 190)");
var intensities = new Half[4] { (Half)0f, (Half)(-1f), (Half)0.25f, (Half)9f };
FrameRenderer.RenderIntensity(intensities, 2, 2, lut, 1f, pixels);
+ // the vectorised rows (2026-10-16) equal the scalar helpers bit for bit: awkward values, every brightness, odd widths, with and without a palette
+ {
+ float[] awkward = [0f, -0f, 1f, -1f, 0.5f, -0.5f, 1.0001f, -1.0001f, 127f, 1e-7f, -1e-7f, float.NaN, float.PositiveInfinity, float.NegativeInfinity, 6.1e-5f, 65504f, 0.0078125f, 0.99999f];
+ var rng = new Random(11);
+ bool vectorEqual = true;
+ foreach (int width in new[] { 1, 3, 4, 5, 37 })
+ {
+ var row = new float[width];
+ var got = new int[width];
+ foreach (float brightness in new[] { 0f, 0.37f, 1f, 3.5f })
+ {
+ for (int trial = 0; trial < 200 && vectorEqual; trial++)
+ {
+ for (int x = 0; x < width; x++)
+ {
+ row[x] = trial % 3 == 0 ? awkward[rng.Next(awkward.Length)] : (float)(rng.NextDouble() * 4 - 2);
+ }
+ foreach (int[]? palette in new[] { lut, null })
+ {
+ FrameRenderer.FieldRow(row, palette, brightness, got);
+ for (int x = 0; x < width; x++)
+ {
+ vectorEqual &= got[x] == FrameRenderer.Colorize(ColorLut.FieldIndex(row[x], brightness), palette);
+ }
+ FrameRenderer.IntensityRow(row, palette, brightness, got);
+ for (int x = 0; x < width; x++)
+ {
+ vectorEqual &= got[x] == FrameRenderer.Colorize(ColorLut.IntensityIndex(row[x], brightness), palette);
+ }
+ }
+ }
+ }
+ }
+ Check(vectorEqual, "the vectorised field and intensity rows equal the scalar helpers bit for bit (NaN, infinities, zeros, the clamp edges, odd widths, grey and palette)");
+ }
Check(pixels[0] == 0 && pixels[1] == 0 && pixels[2] == 127 && pixels[3] == 254, "intensity: <= 0 -> 0, sqrt(0.25) -> 127, clamp -> 254");
var stops = new Rgb[ColorScheme.StopCount];
for (int i = 0; i < stops.Length; i++)