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#
OpenEXR export: the stored 16-bit floats as a sequence or a still
Alexander Graef0245e6139ba9
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8b6cb7d..13cb3dd 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -127,7 +127,10 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDA**Languages**: four string tables, live switch; converter output needs the language as an extra binding input.- **Export**: field, intensity or both, a still of the shown frame, from the current run when fresh and full,else a run is made first; PNG/JPEG sequences, MPEG-1, OpenDML AVI, H.264 MP4 via Media Foundation (the only- Windows-bound library piece besides WIC JPEG, which has an in-house fallback), QuickTime Animation MOV. Harness+ Windows-bound library piece besides WIC JPEG, which has an in-house fallback), QuickTime Animation MOV, and+ **OpenEXR sequences or stills** (2026-10-18, the user's choice for data export to NumPy, MATLAB, Octave add-ons+ and viewers such as DJV): the stored halves themselves, one uncompressed "Y" channel per file, no colours,+ brightness, outline or boxes; a sink that `WantsHalves` gets the plane from the job unrendered. Harnesshooks: `WAVEDUDE_EXPORT_PATH`, `WAVEDUDE_DISCARD_EDITS=1`.- File types `.wdproj` / `.wdscheme` are registered per user at start-up; unsaved edits ask on close.diff --git a/WaveDudeNext.WPF/MainWindow.Export.cs b/WaveDudeNext.WPF/MainWindow.Export.csindex ccf8c0f..bab1624 100644--- a/WaveDudeNext.WPF/MainWindow.Export.cs+++ b/WaveDudeNext.WPF/MainWindow.Export.cs@@ -105,7 +105,8 @@ public partial class MainWindowsuffix += "_" + (stillFrame * Math.Max(1, Project.Simulation.VisualizeEvery)).ToString(System.Globalization.CultureInfo.InvariantCulture);}string chosen;- int filterIndex = still ? Math.Clamp(Settings.Default.ExportFilterIndex + 1, 1, 2) : Math.Clamp(Settings.Default.ExportFilterIndex + 1, 1, ExportFormats.All.Length);+ // the still's filter lists the sequence formats, which lead the full list in the same order+ int filterIndex = still ? Math.Clamp(Settings.Default.ExportFilterIndex + 1, 1, ExportFormats.All.Count(ExportFormats.IsSequence)) : Math.Clamp(Settings.Default.ExportFilterIndex + 1, 1, ExportFormats.All.Length);string? scripted = Environment.GetEnvironmentVariable("WAVEDUDE_EXPORT_PATH");if (!string.IsNullOrEmpty(scripted)){@@ -242,8 +243,15 @@ public partial class MainWindow? () => ExportFormats.OpenStill(format, path, width, height, quality): () => ExportFormats.Open(format, path, width, height, fps, quality, frameCount);targets.Add(new ExportTarget(exportLayer, output, open));- Logger.Debug("Export target {Layer}: scheme '{Scheme}' (black level {Black}), brightness {Brightness}, outline {Outline}, probe boxes {Boxes}, markers {Markers}, to {Output}",- layer, settings.ColorScheme, settings.BlackLevel, settings.Brightness, settings.OverlayInExport && edges != null ? "gain " + settings.OverlayGain : "off", display.ProbeGraphsInExport ? "on" : "off", display.ProbeMarkersInExport ? "on" : "off", output);+ if (ExportFormats.IsData(format))+ {+ Logger.Debug("Export target {Layer}: the stored 16-bit values as OpenEXR (no colours, outline or boxes), to {Output}", layer, output);+ }+ else+ {+ Logger.Debug("Export target {Layer}: scheme '{Scheme}' (black level {Black}), brightness {Brightness}, outline {Outline}, probe boxes {Boxes}, markers {Markers}, to {Output}",+ layer, settings.ColorScheme, settings.BlackLevel, settings.Brightness, settings.OverlayInExport && edges != null ? "gain " + settings.OverlayGain : "off", display.ProbeGraphsInExport ? "on" : "off", display.ProbeMarkersInExport ? "on" : "off", output);+ }}if (!still && format == ExportFormat.Mpeg1){diff --git a/WaveDudeNext.WPF/Strings/Strings.DE.xaml b/WaveDudeNext.WPF/Strings/Strings.DE.xamlindex 2339100..4cb4823 100644--- a/WaveDudeNext.WPF/Strings/Strings.DE.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.DE.xaml@@ -187,11 +187,11 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="Ready">Bereit</s:String><!-- export: the Save dialog, the status bar line ({0} frames done, {1} frames) and the questions -->- <s:String x:Key="ExportDialogFilter">PNG-Bildfolge (*.png)|*.png|JPEG-Bildfolge (*.jpg)|*.jpg|MPEG-1-Video (*.mpg)|*.mpg|AVI-Video, unkomprimiert (*.avi)|*.avi|MP4-Video, H.264 (*.mp4)|*.mp4|QuickTime-Film, Animation-Codec, verlustfrei (*.mov)|*.mov</s:String>+ <s:String x:Key="ExportDialogFilter">PNG-Bildfolge (*.png)|*.png|JPEG-Bildfolge (*.jpg)|*.jpg|OpenEXR-Bildfolge, 16-Bit-Gleitkommadaten (*.exr)|*.exr|MPEG-1-Video (*.mpg)|*.mpg|AVI-Video, unkomprimiert (*.avi)|*.avi|MP4-Video, H.264 (*.mp4)|*.mp4|QuickTime-Film, Animation-Codec, verlustfrei (*.mov)|*.mov</s:String><s:String x:Key="ExportDialogTitleField">Feld exportieren</s:String><s:String x:Key="ExportDialogTitleIntensity">Intensität exportieren</s:String><s:String x:Key="ExportDialogTitleBoth">Feld und Intensität exportieren</s:String>- <s:String x:Key="ExportDialogFilterStill">PNG-Bild (*.png)|*.png|JPEG-Bild (*.jpg)|*.jpg</s:String>+ <s:String x:Key="ExportDialogFilterStill">PNG-Bild (*.png)|*.png|JPEG-Bild (*.jpg)|*.jpg|OpenEXR-Bild, 16-Bit-Gleitkommadaten (*.exr)|*.exr</s:String><s:String x:Key="ExportDialogTitleFrame">Bild exportieren</s:String><s:String x:Key="ExportFolderExistsFormat">Der Ordner {0} existiert und enthält Dateien. Ersetzen?</s:String><s:String x:Key="ExportError">Der Export ist fehlgeschlagen.</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.EN.xaml b/WaveDudeNext.WPF/Strings/Strings.EN.xamlindex 4d3d64f..0b5e85a 100644--- a/WaveDudeNext.WPF/Strings/Strings.EN.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.EN.xaml@@ -189,11 +189,11 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="Ready">Ready</s:String><!-- export: the Save dialog, the status bar line ({0} frames done, {1} frames) and the questions -->- <s:String x:Key="ExportDialogFilter">PNG image sequence (*.png)|*.png|JPEG image sequence (*.jpg)|*.jpg|MPEG-1 video (*.mpg)|*.mpg|AVI video, uncompressed (*.avi)|*.avi|MP4 video, H.264 (*.mp4)|*.mp4|QuickTime movie, Animation codec, lossless (*.mov)|*.mov</s:String>+ <s:String x:Key="ExportDialogFilter">PNG image sequence (*.png)|*.png|JPEG image sequence (*.jpg)|*.jpg|OpenEXR image sequence, 16-bit float data (*.exr)|*.exr|MPEG-1 video (*.mpg)|*.mpg|AVI video, uncompressed (*.avi)|*.avi|MP4 video, H.264 (*.mp4)|*.mp4|QuickTime movie, Animation codec, lossless (*.mov)|*.mov</s:String><s:String x:Key="ExportDialogTitleField">Export the field</s:String><s:String x:Key="ExportDialogTitleIntensity">Export the intensity</s:String><s:String x:Key="ExportDialogTitleBoth">Export the field and the intensity</s:String>- <s:String x:Key="ExportDialogFilterStill">PNG image (*.png)|*.png|JPEG image (*.jpg)|*.jpg</s:String>+ <s:String x:Key="ExportDialogFilterStill">PNG image (*.png)|*.png|JPEG image (*.jpg)|*.jpg|OpenEXR image, 16-bit float data (*.exr)|*.exr</s:String><s:String x:Key="ExportDialogTitleFrame">Export the frame</s:String><s:String x:Key="ExportFolderExistsFormat">The folder {0} exists and holds files. Replace them?</s:String><s:String x:Key="ExportError">The export failed.</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.FR.xaml b/WaveDudeNext.WPF/Strings/Strings.FR.xamlindex cd9c7d5..12e72c8 100644--- a/WaveDudeNext.WPF/Strings/Strings.FR.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.FR.xaml@@ -187,11 +187,11 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="Ready">Prêt</s:String><!-- export: the Save dialog, the status bar line ({0} frames done, {1} frames) and the questions -->- <s:String x:Key="ExportDialogFilter">Séquence d'images PNG (*.png)|*.png|Séquence d'images JPEG (*.jpg)|*.jpg|Vidéo MPEG-1 (*.mpg)|*.mpg|Vidéo AVI non compressée (*.avi)|*.avi|Vidéo MP4, H.264 (*.mp4)|*.mp4|Film QuickTime, codec Animation, sans perte (*.mov)|*.mov</s:String>+ <s:String x:Key="ExportDialogFilter">Séquence d'images PNG (*.png)|*.png|Séquence d'images JPEG (*.jpg)|*.jpg|Séquence d'images OpenEXR, données flottantes 16 bits (*.exr)|*.exr|Vidéo MPEG-1 (*.mpg)|*.mpg|Vidéo AVI non compressée (*.avi)|*.avi|Vidéo MP4, H.264 (*.mp4)|*.mp4|Film QuickTime, codec Animation, sans perte (*.mov)|*.mov</s:String><s:String x:Key="ExportDialogTitleField">Exporter le champ</s:String><s:String x:Key="ExportDialogTitleIntensity">Exporter l'intensité</s:String><s:String x:Key="ExportDialogTitleBoth">Exporter le champ et l'intensité</s:String>- <s:String x:Key="ExportDialogFilterStill">Image PNG (*.png)|*.png|Image JPEG (*.jpg)|*.jpg</s:String>+ <s:String x:Key="ExportDialogFilterStill">Image PNG (*.png)|*.png|Image JPEG (*.jpg)|*.jpg|Image OpenEXR, données flottantes 16 bits (*.exr)|*.exr</s:String><s:String x:Key="ExportDialogTitleFrame">Exporter l'image</s:String><s:String x:Key="ExportFolderExistsFormat">Le dossier {0} existe et contient des fichiers. Les remplacer ?</s:String><s:String x:Key="ExportError">L'export a échoué.</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.NL.xaml b/WaveDudeNext.WPF/Strings/Strings.NL.xamlindex 9ea52ca..b0194c0 100644--- a/WaveDudeNext.WPF/Strings/Strings.NL.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.NL.xaml@@ -187,11 +187,11 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="Ready">Gereed</s:String><!-- export: the Save dialog, the status bar line ({0} frames done, {1} frames) and the questions -->- <s:String x:Key="ExportDialogFilter">PNG-beeldreeks (*.png)|*.png|JPEG-beeldreeks (*.jpg)|*.jpg|MPEG-1-video (*.mpg)|*.mpg|AVI-video, ongecomprimeerd (*.avi)|*.avi|MP4-video, H.264 (*.mp4)|*.mp4|QuickTime-film, Animation-codec, verliesvrij (*.mov)|*.mov</s:String>+ <s:String x:Key="ExportDialogFilter">PNG-beeldreeks (*.png)|*.png|JPEG-beeldreeks (*.jpg)|*.jpg|OpenEXR-beeldreeks, 16-bits drijvendekommagegevens (*.exr)|*.exr|MPEG-1-video (*.mpg)|*.mpg|AVI-video, ongecomprimeerd (*.avi)|*.avi|MP4-video, H.264 (*.mp4)|*.mp4|QuickTime-film, Animation-codec, verliesvrij (*.mov)|*.mov</s:String><s:String x:Key="ExportDialogTitleField">Veld exporteren</s:String><s:String x:Key="ExportDialogTitleIntensity">Intensiteit exporteren</s:String><s:String x:Key="ExportDialogTitleBoth">Veld en intensiteit exporteren</s:String>- <s:String x:Key="ExportDialogFilterStill">PNG-beeld (*.png)|*.png|JPEG-beeld (*.jpg)|*.jpg</s:String>+ <s:String x:Key="ExportDialogFilterStill">PNG-beeld (*.png)|*.png|JPEG-beeld (*.jpg)|*.jpg|OpenEXR-beeld, 16-bits drijvendekommagegevens (*.exr)|*.exr</s:String><s:String x:Key="ExportDialogTitleFrame">Beeld exporteren</s:String><s:String x:Key="ExportFolderExistsFormat">De map {0} bestaat en bevat bestanden. Vervangen?</s:String><s:String x:Key="ExportError">De export is mislukt.</s:String>diff --git a/WaveDudeNext/Export/ExportFormat.cs b/WaveDudeNext/Export/ExportFormat.csindex a706bce..ef6fe8b 100644--- a/WaveDudeNext/Export/ExportFormat.cs+++ b/WaveDudeNext/Export/ExportFormat.cs@@ -24,6 +24,8 @@ public enum ExportFormatPng,/// <summary>A JPEG per frame in a folder of its own; the quality setting applies.</summary>Jpeg,+ /// <summary>An OpenEXR file per frame in a folder of its own: the stored 16-bit floats themselves, one channel, uncompressed; data, not a rendered picture (2026-10-18).</summary>+ Exr,/// <summary>An MPEG-1 program stream of I-pictures (<c>.mpg</c>); the quality setting and the nearest standard frame rate apply.</summary>Mpeg1,/// <summary>An uncompressed AVI with OpenDML indexes; lossless, large.</summary>@@ -102,13 +104,14 @@ public static class ExportFormats}/// <summary>The formats in filter order.</summary>- public static readonly ExportFormat[] All = [ExportFormat.Png, ExportFormat.Jpeg, ExportFormat.Mpeg1, ExportFormat.Avi, ExportFormat.Mp4, ExportFormat.Mov];+ public static readonly ExportFormat[] All = [ExportFormat.Png, ExportFormat.Jpeg, ExportFormat.Exr, ExportFormat.Mpeg1, ExportFormat.Avi, ExportFormat.Mp4, ExportFormat.Mov];/// <summary>The file extension with its dot.</summary>public static string Extension(ExportFormat format) => format switch{ExportFormat.Png => ".png",ExportFormat.Jpeg => ".jpg",+ ExportFormat.Exr => ".exr",ExportFormat.Mpeg1 => ".mpg",ExportFormat.Avi => ".avi",ExportFormat.Mp4 => ".mp4",@@ -121,6 +124,7 @@ public static class ExportFormats{".png" => ExportFormat.Png,".jpg" or ".jpeg" => ExportFormat.Jpeg,+ ".exr" => ExportFormat.Exr,".mpg" or ".mpeg" or ".m1v" => ExportFormat.Mpeg1,".avi" => ExportFormat.Avi,".mp4" or ".m4v" => ExportFormat.Mp4,@@ -128,8 +132,11 @@ public static class ExportFormats_ => null,};- /// <summary>Whether the format writes one file per frame.</summary>- public static bool IsSequence(ExportFormat format) => format is ExportFormat.Png or ExportFormat.Jpeg;+ /// <summary>Whether the format writes one file per frame (these are also the formats a still can take).</summary>+ public static bool IsSequence(ExportFormat format) => format is ExportFormat.Png or ExportFormat.Jpeg or ExportFormat.Exr;++ /// <summary>Whether the format holds the stored values rather than a rendered picture (OpenEXR): colours, brightness, outline and boxes do not apply.</summary>+ public static bool IsData(ExportFormat format) => format == ExportFormat.Exr;/// <summary>Whether the quality setting means anything to the format.</summary>public static bool UsesQuality(ExportFormat format) => format is ExportFormat.Jpeg or ExportFormat.Mpeg1 or ExportFormat.Mp4;@@ -144,8 +151,8 @@ public static class ExportFormatspublic static string SequenceFolder(string path) =>Path.Combine(Path.GetDirectoryName(path) ?? "", Path.GetFileNameWithoutExtension(path));- /// <summary>Opens a one-file sink for a still (PNG or JPEG only) at <paramref name="path"/>.</summary>- /// <param name="format">PNG or JPEG.</param>+ /// <summary>Opens a one-file sink for a still (PNG, JPEG or OpenEXR) at <paramref name="path"/>.</summary>+ /// <param name="format">PNG, JPEG or OpenEXR.</param>/// <param name="path">The file.</param>/// <param name="width">Frame width in pixels.</param>/// <param name="height">Frame height in pixels.</param>@@ -155,7 +162,8 @@ public static class ExportFormats{ExportFormat.Png => new ImageFileSink(path, width, height, (stream, frame) => PngEncoder.Write(stream, frame.Span, width, height)),ExportFormat.Jpeg => new ImageFileSink(path, width, height, JpegWriter(width, height, quality)),- _ => throw new NotSupportedException("A still is a PNG or a JPEG."),+ ExportFormat.Exr => ExrSink.Still(path, width, height),+ _ => throw new NotSupportedException("A still is a PNG, a JPEG or an OpenEXR file."),};/// <summary>@@ -179,6 +187,8 @@ public static class ExportFormatscase ExportFormat.Jpeg:return new ImageSequenceSink(SequenceFolder(path), Path.GetFileNameWithoutExtension(path), ".jpg", width, height,() => JpegWriter(width, height, quality), SequenceWorkers(encoderIsParallel: AlternativeJpeg == null), plannedFrames);+ case ExportFormat.Exr:+ return ExrSink.Sequence(SequenceFolder(path), Path.GetFileNameWithoutExtension(path), width, height, plannedFrames);case ExportFormat.Mpeg1:return new Mpeg1Writer(path, width, height, fps, quality);case ExportFormat.Avi:diff --git a/WaveDudeNext/Export/ExportJob.cs b/WaveDudeNext/Export/ExportJob.csindex 60a7bf8..f1b4aab 100644--- a/WaveDudeNext/Export/ExportJob.cs+++ b/WaveDudeNext/Export/ExportJob.cs@@ -107,11 +107,9 @@ 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));- }+ // an 8-bit store (palette indices with the brightness baked in) renders to the same pixels as the halves would+ // (2026-10-18; until then every export demanded a 16-bit run): the palette and black level still apply at+ // render time. Only a data sink (OpenEXR) needs the halves, which Render checks once the sinks are open.Store = store;FirstFrame = firstFrame;LastFrame = lastFrame;@@ -200,7 +198,18 @@ public sealed class ExportJob : INotifyPropertyChanged}/// <summary>A rendered frame on its way to a sink.</summary>- private sealed record Item(int Frame, int Target, int[] Pixels);+ /// <summary>A frame for one target: rendered pixels, or the store's halves for a sink that wants them (one of the two is set).</summary>+ private sealed record Item(int Frame, int Target, int[]? Pixels, Half[]? Values);++ /// <summary>The outline and the decoration over a rendered frame, the same for halves and for palette indices.</summary>+ private static void Finish(ExportLayer layer, int frame, int[] pixels, int width, int height)+ {+ if (layer.Edges != null && layer.EdgeGain > 0.0)+ {+ GlowingEdges.BlendAdditive(pixels, width, height, layer.Edges, layer.EdgeGain);+ }+ layer.Decorate?.Invoke(frame, pixels);+ }/// <summary>The render thread: starts the sink thread, renders every frame of the range into pooled buffers and queues them; waits for the sink thread at the end.</summary>private void Render()@@ -210,12 +219,11 @@ public sealed class ExportJob : INotifyPropertyChangedException? error = null;int width = Store.Width;int height = Store.Height;+ // the buffer pools: rendered pixels for the picture sinks, the store's halves for the data sinks (OpenEXR);+ // filled once the sinks are open and have said which they takeint buffers = Targets.Count * QueueDepth + 1;var free = new BlockingCollection<int[]>(buffers);- for (int i = 0; i < buffers; i++)- {- free.Add(new int[width * height]);- }+ var freeHalves = new BlockingCollection<Half[]>(buffers);var queue = new BlockingCollection<Item>(Targets.Count * QueueDepth);using var sinksReady = new ManualResetEventSlim();Exception? sinkError = null;@@ -234,8 +242,16 @@ public sealed class ExportJob : INotifyPropertyChangedsinksReady.Set();foreach (Item item in queue.GetConsumingEnumerable()){- Targets[item.Target].Sink!.Add(item.Pixels);- free.Add(item.Pixels);+ if (item.Values != null)+ {+ Targets[item.Target].Sink!.Add((ReadOnlySpan<Half>)item.Values);+ freeHalves.Add(item.Values);+ }+ else+ {+ Targets[item.Target].Sink!.Add(item.Pixels);+ free.Add(item.Pixels!);+ }if (item.Target == Targets.Count - 1){written++;@@ -256,7 +272,14 @@ public sealed class ExportJob : INotifyPropertyChanged// drain, so the render thread never blocks on a full queueforeach (Item item in queue.GetConsumingEnumerable()){- free.Add(item.Pixels);+ if (item.Values != null)+ {+ freeHalves.Add(item.Values);+ }+ else+ {+ free.Add(item.Pixels!);+ }}}finally@@ -283,7 +306,24 @@ public sealed class ExportJob : INotifyPropertyChangedtry{sinksReady.Wait();+ if (sinkError == null)+ {+ if (Store.Format != FrameFormat.Half && Targets.Any(target => target.Sink?.WantsHalves == true))+ {+ throw new InvalidOperationException("A data export (OpenEXR) needs a 16-bit run; this store holds palette indices.");+ }+ int pictureTargets = Targets.Count(target => target.Sink?.WantsHalves != true);+ for (int i = 0; i < pictureTargets * QueueDepth + 1; i++)+ {+ free.Add(new int[width * height]);+ }+ for (int i = 0; i < (Targets.Count - pictureTargets) * QueueDepth + 1; i++)+ {+ freeHalves.Add(new Half[width * height]);+ }+ }var values = new Half[width * height];+ byte[]? indices = Store.Format == FrameFormat.Index ? new byte[width * height] : null;for (int frame = FirstFrame; frame <= LastFrame && sinkError == null; frame++){if (_cancel.IsCancellationRequested)@@ -294,6 +334,30 @@ public sealed class ExportJob : INotifyPropertyChangedfor (int t = 0; t < Targets.Count; t++){ExportLayer layer = Targets[t].Layer;+ if (Targets[t].Sink!.WantsHalves)+ {+ // a data sink: the plane as stored, nothing rendered or drawn+ Half[] plane = freeHalves.Take();+ if (frame >= Store.Count || !Store.CopyLayer(frame, layer.Layer, plane))+ {+ throw new InvalidOperationException($"Frame {frame} is not in the store (it holds {Store.Count}).");+ }+ queue.Add(new Item(frame, t, null, plane));+ continue;+ }+ if (indices != null)+ {+ // the 8-bit store: the palette index as captured (brightness baked in), coloured through the LUT+ if (frame >= Store.Count || !Store.CopyLayer(frame, layer.Layer, indices.AsSpan()))+ {+ throw new InvalidOperationException($"Frame {frame} is not in the store (it holds {Store.Count}).");+ }+ int[] indexed = free.Take();+ FrameRenderer.RenderIndexed(indices, width, height, layer.Lut, indexed);+ Finish(layer, frame, indexed, width, height);+ queue.Add(new Item(frame, t, indexed, null));+ continue;+ }if (frame >= Store.Count || !Store.CopyLayer(frame, layer.Layer, values)){throw new InvalidOperationException($"Frame {frame} is not in the store (it holds {Store.Count}).");@@ -307,12 +371,8 @@ public sealed class ExportJob : INotifyPropertyChanged{FrameRenderer.RenderField(values, width, height, layer.Lut, layer.Brightness, pixels);}- if (layer.Edges != null && layer.EdgeGain > 0.0)- {- GlowingEdges.BlendAdditive(pixels, width, height, layer.Edges, layer.EdgeGain);- }- layer.Decorate?.Invoke(frame, pixels);- queue.Add(new Item(frame, t, pixels));+ Finish(layer, frame, pixels, width, height);+ queue.Add(new Item(frame, t, pixels, null));}}}diff --git a/WaveDudeNext/Export/ExrWriter.cs b/WaveDudeNext/Export/ExrWriter.csnew file mode 100644index 0000000..18cc208--- /dev/null+++ b/WaveDudeNext/Export/ExrWriter.cs@@ -0,0 +1,234 @@+// 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/>.++using System.Buffers.Binary;+using System.Globalization;+using System.Runtime.InteropServices;+using System.Text;++namespace WaveDudeNext.Export;++/// <summary>+/// Writes OpenEXR files (2026-10-18, the user's choice for a lossless export of the stored data: the one image format+/// made for 16-bit floats, which the compositing viewers, DJV among them, open as pictures and NumPy, MATLAB's+/// <c>exrread</c> and the like read as arrays). A single-part scanline file, version 2, no compression, one HALF+/// channel named <see cref="Channel"/> ("Y", luminance: every reader shows a one-channel file as grey), data and+/// display window the frame, increasing line order, pixel aspect 1, and a <c>comments</c> attribute naming the+/// program. The values are the store's halves as they are: field amplitudes in simulation units, negatives+/// included, intensity as accumulated; no palette, brightness, outline or boxes. Little-endian throughout, as the+/// format demands. Static and thread-free.+/// </summary>+public static class ExrWriter+{+ /// <summary>The channel every file holds.</summary>+ public const string Channel = "Y";++ private const int Magic = 20000630;+ private const int Version = 2;+ private const int PixelTypeHalf = 1;+ private const byte NoCompression = 0;+ private const byte IncreasingY = 0;++ /// <summary>Writes <paramref name="values"/> (row-major, at least width × height) as one file to <paramref name="stream"/>.</summary>+ /// <param name="stream">Takes the whole file in one write.</param>+ /// <param name="values">The plane's halves, row-major.</param>+ /// <param name="width">Frame width in pixels.</param>+ /// <param name="height">Frame height in pixels.</param>+ /// <param name="comment">Goes into the file's <c>comments</c> attribute; null for the program name alone.</param>+ public static void Write(Stream stream, ReadOnlySpan<Half> values, int width, int height, string? comment = null)+ {+ ArgumentOutOfRangeException.ThrowIfLessThan(width, 1);+ ArgumentOutOfRangeException.ThrowIfLessThan(height, 1);+ if (values.Length < width * height)+ {+ throw new ArgumentException("Fewer values than width × height.", nameof(values));+ }+ byte[] header = Header(width, height, comment ?? "WaveDude Next");+ int rowBytes = width * 2;+ int chunkBytes = 8 + rowBytes;+ long firstChunk = 8L + header.Length + 8L * height;+ var file = new byte[firstChunk + (long)chunkBytes * height];+ Span<byte> span = file;+ BinaryPrimitives.WriteInt32LittleEndian(span, Magic);+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], Version);+ header.CopyTo(span[8..]);+ int at = 8 + header.Length;+ for (int y = 0; y < height; y++)+ {+ BinaryPrimitives.WriteUInt64LittleEndian(span[at..], (ulong)(firstChunk + (long)chunkBytes * y));+ at += 8;+ }+ for (int y = 0; y < height; y++)+ {+ BinaryPrimitives.WriteInt32LittleEndian(span[at..], y);+ BinaryPrimitives.WriteInt32LittleEndian(span[(at + 4)..], rowBytes);+ Span<byte> row = span.Slice(at + 8, rowBytes);+ ReadOnlySpan<Half> source = values.Slice(y * width, width);+ if (BitConverter.IsLittleEndian)+ {+ MemoryMarshal.AsBytes(source).CopyTo(row);+ }+ else+ {+ for (int x = 0; x < width; x++)+ {+ BinaryPrimitives.WriteHalfLittleEndian(row[(x * 2)..], source[x]);+ }+ }+ at += chunkBytes;+ }+ stream.Write(file, 0, file.Length);+ }++ /// <summary>The header: the required attributes in the order the reference implementation writes them, then the comment, then the terminating null.</summary>+ private static byte[] Header(int width, int height, string comment)+ {+ using var header = new MemoryStream();+ // chlist: name, pixel type, pLinear, three reserved bytes, x and y sampling; the list ends with a null+ using (var channels = new MemoryStream())+ {+ channels.Write(Encoding.ASCII.GetBytes(Channel));+ channels.WriteByte(0);+ WriteInt(channels, PixelTypeHalf);+ channels.WriteByte(0);+ channels.Write(new byte[3]);+ WriteInt(channels, 1);+ WriteInt(channels, 1);+ channels.WriteByte(0);+ Attribute(header, "channels", "chlist", channels.ToArray());+ }+ Attribute(header, "compression", "compression", [NoCompression]);+ byte[] window = new byte[16];+ BinaryPrimitives.WriteInt32LittleEndian(window.AsSpan(8), width - 1);+ BinaryPrimitives.WriteInt32LittleEndian(window.AsSpan(12), height - 1);+ Attribute(header, "dataWindow", "box2i", window);+ Attribute(header, "displayWindow", "box2i", window);+ Attribute(header, "lineOrder", "lineOrder", [IncreasingY]);+ Attribute(header, "pixelAspectRatio", "float", Float(1f));+ Attribute(header, "screenWindowCenter", "v2f", new byte[8]);+ Attribute(header, "screenWindowWidth", "float", Float(1f));+ Attribute(header, "comments", "string", Encoding.UTF8.GetBytes(comment));+ header.WriteByte(0);+ return header.ToArray();+ }++ private static void Attribute(Stream stream, string name, string type, byte[] value)+ {+ stream.Write(Encoding.ASCII.GetBytes(name));+ stream.WriteByte(0);+ stream.Write(Encoding.ASCII.GetBytes(type));+ stream.WriteByte(0);+ WriteInt(stream, value.Length);+ stream.Write(value);+ }++ private static void WriteInt(Stream stream, int value)+ {+ Span<byte> bytes = stackalloc byte[4];+ BinaryPrimitives.WriteInt32LittleEndian(bytes, value);+ stream.Write(bytes);+ }++ private static byte[] Float(float value)+ {+ byte[] bytes = new byte[4];+ BinaryPrimitives.WriteSingleLittleEndian(bytes, value);+ return bytes;+ }+}++/// <summary>+/// A sink of OpenEXR files, one per frame (<see cref="Sequence"/>: <c>name_0000.exr</c> and on in a folder, the frame+/// number at least four digits wide and as many as the planned frames need) or exactly one (<see cref="Still"/>).+/// Takes the store's halves (<see cref="WantsHalves"/>), never rendered pixels. Each file is written and closed in+/// <see cref="Add(ReadOnlySpan{Half})"/>; a frame of 1920 × 1080 is 4 MB, so no worker pool is needed. One thread at a time.+/// </summary>+public sealed class ExrSink : IFrameSink+{+ private readonly string? _stillPath;+ private readonly string _folder;+ private readonly string _baseName;+ private readonly int _digits;+ private bool _closed;++ private ExrSink(string? stillPath, string folder, string baseName, int width, int height, int plannedFrames)+ {+ ArgumentOutOfRangeException.ThrowIfLessThan(width, 1);+ ArgumentOutOfRangeException.ThrowIfLessThan(height, 1);+ _stillPath = stillPath;+ _folder = folder;+ _baseName = baseName;+ _digits = Math.Max(4, Math.Max(0, plannedFrames - 1).ToString(CultureInfo.InvariantCulture).Length);+ Width = width;+ Height = height;+ Directory.CreateDirectory(folder);+ }++ /// <summary>A sequence in <paramref name="folder"/> (created when missing) named <paramref name="baseName"/><c>_0000.exr</c> and on.</summary>+ public static ExrSink Sequence(string folder, string baseName, int width, int height, int plannedFrames) =>+ new(null, folder, baseName, width, height, plannedFrames);++ /// <summary>One file at <paramref name="path"/>; a second frame is refused.</summary>+ public static ExrSink Still(string path, int width, int height) =>+ new(path, Path.GetDirectoryName(Path.GetFullPath(path)) ?? "", Path.GetFileNameWithoutExtension(path), width, height, 1);++ /// <inheritdoc/>+ public int Width { get; }++ /// <inheritdoc/>+ public int Height { get; }++ /// <inheritdoc/>+ public int FrameCount { get; private set; }++ /// <inheritdoc/>+ public string Output => _stillPath ?? _folder;++ /// <inheritdoc/>+ public bool WantsHalves => true;++ /// <summary>The file of frame <paramref name="index"/> of a sequence.</summary>+ public string PathOf(int index) => Path.Combine(_folder, _baseName + "_" + index.ToString("D" + _digits, CultureInfo.InvariantCulture) + ".exr");++ /// <inheritdoc/>+ public void Add(ReadOnlySpan<int> pixels) => throw new NotSupportedException("An OpenEXR file holds the store's halves, not rendered pixels.");++ /// <inheritdoc/>+ public void Add(ReadOnlySpan<Half> values)+ {+ if (_closed)+ {+ throw new InvalidOperationException("The sink is closed.");+ }+ if (_stillPath != null && FrameCount > 0)+ {+ throw new InvalidOperationException("A still takes one frame.");+ }+ string path = _stillPath ?? PathOf(FrameCount);+ using (var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16))+ {+ ExrWriter.Write(stream, values, Width, Height, "WaveDude Next, frame " + FrameCount.ToString(CultureInfo.InvariantCulture));+ }+ FrameCount++;+ }++ /// <inheritdoc/>+ public void Close() => _closed = true;++ /// <inheritdoc/>+ public void Dispose() => Close();+}diff --git a/WaveDudeNext/Export/IFrameSink.cs b/WaveDudeNext/Export/IFrameSink.csindex cb8e067..4480111 100644--- a/WaveDudeNext/Export/IFrameSink.cs+++ b/WaveDudeNext/Export/IFrameSink.cs@@ -45,6 +45,17 @@ public interface IFrameSink : IDisposable/// <exception cref="IOException">The file could not be written.</exception>void Add(ReadOnlySpan<int> pixels);+ /// <summary>+ /// Whether the sink takes the store's halves through <see cref="Add(ReadOnlySpan{Half})"/> instead of rendered+ /// pixels: a data format such as OpenEXR (2026-10-18). The job then neither colours nor decorates its frames.+ /// </summary>+ bool WantsHalves => false;++ /// <summary>Appends one frame as the plane's halves, row-major, at least width × height values; only for a sink with <see cref="WantsHalves"/>.</summary>+ /// <param name="values">The plane as stored.</param>+ /// <exception cref="NotSupportedException">The sink takes rendered pixels.</exception>+ void Add(ReadOnlySpan<Half> values) => throw new NotSupportedException("This sink takes rendered pixels.");+/// <summary>Finishes the output (indexes, trailers, open handles). Idempotent.</summary>void Close();}diff --git a/_tools/library_check/ExportChecks.cs b/_tools/library_check/ExportChecks.csindex 6cd6d62..019d226 100644--- a/_tools/library_check/ExportChecks.cs+++ b/_tools/library_check/ExportChecks.cs@@ -19,6 +19,7 @@ using System.Buffers.Binary;using System.Diagnostics;using System.Globalization;using System.IO.Compression;+using System.Runtime.InteropServices;using System.Text;using WaveDudeNext.Export;using WaveDudeNext.Model;@@ -250,6 +251,52 @@ internal static class ExportCheckscheck(still.FrameCount == 1 && refused, "formats: a still takes one frame and refuses a second");}check(DecodePng(File.ReadAllBytes(stillPath), w, h)!.SequenceEqual(frames[4]), "formats: the still is the frame");+ // OpenEXR (2026-10-18): the stored halves as a one-channel scanline file, parsed in-house and decoded by ffmpeg+ var halves = new Half[w * h];+ for (int i = 0; i < halves.Length; i++)+ {+ halves[i] = (Half)(Math.Sin(i * 0.013) * (i % 7 == 0 ? -1.5 : 0.8)); // negatives and a value beyond 1 included+ }+ using (IFrameSink exr = ExportFormats.Open(ExportFormat.Exr, Path.Combine(folder, "exr.exr"), w, h, 30, 70, 3))+ {+ bool pixelsRefused = false;+ try+ {+ exr.Add(frames[0]);+ }+ catch (NotSupportedException)+ {+ pixelsRefused = true;+ }+ exr.Add(new Half[w * h]);+ exr.Add(halves);+ check(exr.WantsHalves && pixelsRefused && exr.FrameCount == 2 && !ExportFormats.Open(ExportFormat.Png, Path.Combine(folder, "p.png"), w, h, 30, 70, 1).WantsHalves,+ "formats: the OpenEXR sink wants halves and refuses pixels; the PNG sink does not");+ }+ string exrFile = Path.Combine(folder, "exr", "exr_0001.exr");+ string exrNote = "";+ Half[]? back = File.Exists(exrFile) ? ReadExr(File.ReadAllBytes(exrFile), w, h, out exrNote) : null;+ check(back != null && MemoryMarshal.AsBytes(back.AsSpan()).SequenceEqual(MemoryMarshal.AsBytes(halves.AsSpan())),+ "formats: exr_0001.exr is a version 2 scanline file, channel Y half, uncompressed, with the halves bit for bit" + (back == null ? " (" + (File.Exists(exrFile) ? exrNote : "no file") + ")" : ""));+ if (Ffmpeg != null)+ {+ // decoded to 16-bit grey, the one form every ffmpeg since 2018 gives for a one-channel EXR: value × 65536,+ // clipped to 0..65535 (the negatives and the 1.5 land on the limits); so the values and their places are checked+ ushort[]? decodedExr = DecodeGray16(exrFile, w, h);+ bool same = decodedExr != null;+ for (int i = 0; same && i < halves.Length; i++)+ {+ int expected = (int)Math.Clamp(Math.Round((float)halves[i] * 65536f), 0, 65535);+ same = Math.Abs(decodedExr![i] - expected) <= 2;+ }+ check(same, "formats: ffmpeg decodes the OpenEXR file to the same values (16-bit grey, value × 65536, clipped)");+ }+ string exrStill = Path.Combine(folder, "still.exr");+ using (IFrameSink still = ExportFormats.OpenStill(ExportFormat.Exr, exrStill, w, h, 70))+ {+ still.Add(halves);+ }+ check(ReadExr(File.ReadAllBytes(exrStill), w, h, out _) is { } stillBack && MemoryMarshal.AsBytes(stillBack.AsSpan()).SequenceEqual(MemoryMarshal.AsBytes(halves.AsSpan())), "formats: an OpenEXR still holds the frame");bool videoRefused = false;try{@@ -353,10 +400,14 @@ internal static class ExportChecksvar intensityLayer = new ExportLayer(FrameLayer.Intensity, null, 30f, null, 0, null);string seqPath = Path.Combine(folder, "field.png");string aviPath = Path.Combine(folder, "intensity.avi");+ string exrPath = Path.Combine(folder, "data.exr");var targets = new List<ExportTarget>{new(fieldLayer, ExportFormats.SequenceFolder(seqPath), () => ExportFormats.Open(ExportFormat.Png, seqPath, 64, 48, 30, 70, 6)),new(intensityLayer, aviPath, () => ExportFormats.Open(ExportFormat.Avi, aviPath, 64, 48, 30, 70, 6)),+ // a data target beside the pictures: the job hands it the stored halves, nothing rendered or decorated+ new(new ExportLayer(FrameLayer.Field, lut, 30f, null, 0, (_, _) => throw new InvalidOperationException("a data target is never decorated")),+ ExportFormats.SequenceFolder(exrPath), () => ExportFormats.Open(ExportFormat.Exr, exrPath, 64, 48, 30, 70, 6)),};var job = new ExportJob(store, 2, 7, targets, null);var states = new List<ExportState>();@@ -386,6 +437,10 @@ internal static class ExportCheckscheck(first != null && first.SequenceEqual(expected), "job: field_0000.png is frame 2 as the renderer colours it, with the decoration");AviWalk walk = WalkAvi(File.ReadAllBytes(aviPath));check(walk.Frames == 6 && walk.TotalInDmlh == 6 && walk.EndsAtFileEnd, "job: the intensity AVI holds 6 frames");+ string exrFirst = Path.Combine(folder, "data", "data_0000.exr");+ Half[]? exrValues = File.Exists(exrFirst) ? ReadExr(File.ReadAllBytes(exrFirst), 64, 48, out _) : null;+ check(Directory.GetFiles(Path.Combine(folder, "data")).Length == 6 && exrValues != null && MemoryMarshal.AsBytes(exrValues.AsSpan()).SequenceEqual(MemoryMarshal.AsBytes(values.AsSpan())),+ "job: data_0000.exr holds frame 2's stored halves bit for bit, undecorated, beside the pictures");// cancelled: a slow decoration lets the cancel land after the first frameusing var started = new ManualResetEventSlim();@@ -741,6 +796,114 @@ internal static class ExportChecksreturn bytes;}+ /// <summary>Decodes a one-channel file with ffmpeg to 16-bit grey samples of w × h; null when ffmpeg failed or the size is off.</summary>+ private static ushort[]? DecodeGray16(string path, int w, int h)+ {+ var info = new ProcessStartInfo(Ffmpeg!)+ {+ RedirectStandardOutput = true,+ RedirectStandardError = true,+ UseShellExecute = false,+ CreateNoWindow = true,+ };+ foreach (string arg in new[] { "-v", "error", "-i", path, "-f", "rawvideo", "-pix_fmt", "gray16le", "-" })+ {+ info.ArgumentList.Add(arg);+ }+ using Process process = Process.Start(info)!;+ using var output = new MemoryStream();+ Task<string> errors = process.StandardError.ReadToEndAsync();+ process.StandardOutput.BaseStream.CopyTo(output);+ process.WaitForExit();+ string error = errors.Result;+ if (process.ExitCode != 0 || output.Length != (long)w * h * 2)+ {+ Console.WriteLine(" ffmpeg: exit " + process.ExitCode + ", " + output.Length + " bytes " + error.Trim());+ return null;+ }+ byte[] bytes = output.ToArray();+ var samples = new ushort[w * h];+ for (int i = 0; i < samples.Length; i++)+ {+ samples[i] = BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(i * 2));+ }+ return samples;+ }++ /// <summary>+ /// Reads the OpenEXR files <see cref="ExrWriter"/> writes: magic, version 2 without flags, the attributes (channel+ /// "Y" as HALF, no compression, the windows the frame), the offset table and one chunk per scanline. Null with a+ /// note when anything is off.+ /// </summary>+ private static Half[]? ReadExr(byte[] file, int w, int h, out string note)+ {+ note = "";+ if (file.Length < 8 || BinaryPrimitives.ReadInt32LittleEndian(file) != 20000630 || BinaryPrimitives.ReadInt32LittleEndian(file.AsSpan(4)) != 2)+ {+ note = "magic or version";+ return null;+ }+ int at = 8;+ bool channelOk = false, compressionOk = false, windowOk = false;+ while (true)+ {+ int end = Array.IndexOf(file, (byte)0, at);+ if (end == at)+ {+ at++;+ break; // the header's terminating null+ }+ string name = Encoding.ASCII.GetString(file, at, end - at);+ at = end + 1;+ end = Array.IndexOf(file, (byte)0, at);+ string type = Encoding.ASCII.GetString(file, at, end - at);+ at = end + 1;+ int size = BinaryPrimitives.ReadInt32LittleEndian(file.AsSpan(at));+ at += 4;+ ReadOnlySpan<byte> value = file.AsSpan(at, size);+ at += size;+ switch (name)+ {+ case "channels":+ channelOk = type == "chlist" && value[0] == (byte)'Y' && value[1] == 0 && BinaryPrimitives.ReadInt32LittleEndian(value[2..]) == 1 && value[^1] == 0;+ break;+ case "compression":+ compressionOk = type == "compression" && value[0] == 0;+ break;+ case "dataWindow":+ windowOk = type == "box2i" && BinaryPrimitives.ReadInt32LittleEndian(value) == 0 && BinaryPrimitives.ReadInt32LittleEndian(value[4..]) == 0+ && BinaryPrimitives.ReadInt32LittleEndian(value[8..]) == w - 1 && BinaryPrimitives.ReadInt32LittleEndian(value[12..]) == h - 1;+ break;+ }+ }+ if (!channelOk || !compressionOk || !windowOk)+ {+ note = "header: channel " + channelOk + ", compression " + compressionOk + ", window " + windowOk;+ return null;+ }+ var offsets = new long[h];+ for (int y = 0; y < h; y++)+ {+ offsets[y] = (long)BinaryPrimitives.ReadUInt64LittleEndian(file.AsSpan(at));+ at += 8;+ }+ var values = new Half[w * h];+ for (int y = 0; y < h; y++)+ {+ int chunk = (int)offsets[y];+ if (chunk + 8 + w * 2 > file.Length || BinaryPrimitives.ReadInt32LittleEndian(file.AsSpan(chunk)) != y || BinaryPrimitives.ReadInt32LittleEndian(file.AsSpan(chunk + 4)) != w * 2)+ {+ note = "chunk " + y;+ return null;+ }+ for (int x = 0; x < w; x++)+ {+ values[y * w + x] = BinaryPrimitives.ReadHalfLittleEndian(file.AsSpan(chunk + 8 + x * 2));+ }+ }+ return values;+ }+/// <summary>For a failure message: the first pixel where RGB24 bytes differ from the frame, with both values.</summary>private static string Mismatch(byte[]? rgb, int[] frame, int w, int h){