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#

Import of the author's JSON projects

Alexander Graefcd61c5d7e852
diff --git a/CLAUDE.md b/CLAUDE.md
index 22ce75b..8dd6ab8 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -128,6 +128,22 @@ WPF shell as it stands:
`PreviewPane.OverlayImage` on the picture cells). WPF composites source-over, not additively:
the layer's alpha is the edge strength × gain and its colour the edge colour at full brightness,
so the preview and a baked export differ slightly at strong edges.
+- **Import of the author's projects** (2026-10-14, promised to the author): `Model/LegacyProject.Import`
+ reads a `configuration.json` with `System.Text.Json`, key for key as the legacy `FromConfig` readers did
+ and with their fallbacks (a file without `use_4th_order_laplacian` means off, without `wave_speed_c`
+ 0.563), into a new `Project` with a fresh seed: the scene image is embedded when the relative path
+ resolves beside the file (else the path is kept and noted), damping enabled + size become
+ `DampingEdge`, the preview/export/scheme/brightness/video keys of the author's "simulation" section go
+ to `Display`, `use_gpu` is ignored, a composite source becomes a `SourceArray` whose random amounts count
+ only with `composite_mode` "randomize" and the flag on (the stored elements are not read: they are
+ regenerated from the seed, so a randomised array differs from the original, noted), a source without a
+ position or switched off comes in disabled, probes are named "Probe n", "start after step" counts only
+ with its flag, and a scene-level `use_probes` of false deactivates them. Notes are logged as warnings.
+ `MainWindow.OpenFile` routes any `.json` there (Open dialog, drag and drop, command line; the filter lists
+ "Wave Dude 2D projects (configuration.json)"); the result is unsaved and Save As proposes
+ `<project_name>.wdproj` beside the original (`_suggestedFileName`). Checked in `library_check` on
+ Examples 12, 5 and 3 and the `Project/Test` file (skipped when `Wave_Dude_Examples` is not found above
+ the harness binary), including an XML round trip and the refusal of a newer `format_version`.
- **Array rotation** (2026-10-14, the user's request): `SourceArray.Angle` in degrees, counter-clockwise on
the screen (y points down, so x' = x cos + y sin, y' = y cos − x sin about the source position),
normalised into (−180, 180]; applied in `Source.GenerateElements` before the random offsets, edited in the
@@ -327,6 +343,11 @@ The two legacy harnesses are console programs compiled with `csc` against the `W
switches back to System. A window Windows never activated has no focused element and loses posted
keys; `Start-App` posts `WM_SETFOCUS` then (`FocusedId` "(none)"). Settles are 60 ms per key
(`Key`'s default), 100–300 ms where layout follows, `WaitFor` for anything the app computes.
+ `_tools/ui_check/ImportCheck.ps1` (2026-10-14, 10 checks, about 10 s) starts the app with Example 12's
+ `configuration.json` on the command line and checks the import landed: an unsaved project (bare title),
+ four sources and two probes in the tree with their enabled/active state, 7500 frames on the timeline, the
+ embedded image's 16:9 canvas, Source 1's marker at (150, 140), and the status bar's import message
+ (the message text block carries the id `StatusMessage`).
`FocusedId` is **one** UI Automation query for the element with keyboard focus (a template part's
id such as `PART_EditableTextBox` is mapped to its owner); asking 17 ids one by one cost half a
second per Tab and made `FocusOn` crawl. Timings after the 2026-10-14 clean-up: RunCheck 67 s
@@ -659,9 +680,7 @@ PreviewCheck 12 s, LanguageCheck 17 s, `library_check` about 20 s). The next ses
and a decision whether export needs a finished run (simplest: export the frames that exist).
Author's point 10.
-**Also open, smaller.** Import of the author's JSON projects (`Wave_Dude_Examples/*/configuration.json`;
-the legacy `ProjectConfig`/`ProjectStore` read them; the user promised the author an importer);
-a colour picker dialog for stops (hex only now; WinForms `ColorDialog` needs `UseWindowsForms`);
+**Also open, smaller.** A colour picker dialog for stops (hex only now; WinForms `ColorDialog` needs `UseWindowsForms`);
offer `ColorScheme.Simplify` in the editor; renaming a project scheme does not update the layers that
refer to it; base64 vs BaseXML for the embedded image; the RAM-first frame store (numbers above);
dropping the 9-point Laplacian (author's suggestion, user undecided); timeline event tracks, zoom and
diff --git a/WaveDude.WPF/MainWindow.xaml b/WaveDude.WPF/MainWindow.xaml
index 2097ada..d38e0f9 100644
--- a/WaveDude.WPF/MainWindow.xaml
+++ b/WaveDude.WPF/MainWindow.xaml
@@ -206,7 +206,7 @@
</TextBlock>
</StatusBarItem>
<StatusBarItem>
- <TextBlock x:Name="txtStatus" Text="{DynamicResource Ready}" />
+ <TextBlock x:Name="txtStatus" Text="{DynamicResource Ready}" AutomationProperties.AutomationId="StatusMessage" />
</StatusBarItem>
</StatusBar>
diff --git a/WaveDude.WPF/MainWindow.xaml.cs b/WaveDude.WPF/MainWindow.xaml.cs
index c78b57d..e5b3695 100644
--- a/WaveDude.WPF/MainWindow.xaml.cs
+++ b/WaveDude.WPF/MainWindow.xaml.cs
@@ -126,6 +126,11 @@ public partial class MainWindow : Window
ImportScheme(fileName);
return;
}
+ if (LegacyProject.IsLegacyFile(fileName))
+ {
+ ImportLegacy(fileName);
+ return;
+ }
try
{
fileName = Path.GetFullPath(fileName);
@@ -133,6 +138,7 @@ public partial class MainWindow : Window
DiscardRun();
Project = loaded;
Filename = fileName;
+ _suggestedFileName = null;
Logger.Info("Opened '{Path}'", fileName);
RememberRecent(fileName);
projectTree.SelectRoot();
@@ -144,6 +150,38 @@ public partial class MainWindow : Window
}
}
+ /// <summary>
+ /// A project of the author's program (its <c>configuration.json</c>) becomes a new, unsaved project
+ /// (2026-10-14): the scene image is embedded, what could not be carried over exactly is logged as a
+ /// warning, and Save As proposes a <c>.wdproj</c> named after the project beside the original.
+ /// </summary>
+ private void ImportLegacy(string fileName)
+ {
+ try
+ {
+ var notes = new List<string>();
+ Project imported = LegacyProject.Import(fileName, notes, out string projectName);
+ DiscardRun();
+ Project = imported;
+ Filename = null;
+ _suggestedFileName = LegacyProject.SuggestedFileName(fileName, projectName);
+ foreach (string note in notes)
+ {
+ Logger.Warn(note);
+ }
+ Logger.Info("Imported the legacy project '{Name}'; save it as a Wave Dude project (File > Save As)", projectName.Length > 0 ? projectName : Path.GetFileName(fileName));
+ projectTree.SelectRoot();
+ }
+ catch (Exception ex)
+ {
+ Logger.Error(ex, "Error while importing '{Path}'", fileName);
+ ShowError(string.Format((string)FindResource("OpenError"), fileName), ex);
+ }
+ }
+
+ /// <summary>The file name Save As proposes for an unsaved imported project; null otherwise.</summary>
+ private string? _suggestedFileName;
+
/// <summary>A scheme file (double-clicked, or given on the command line) is added to the open project's own schemes and selected.</summary>
private void ImportScheme(string fileName)
{
@@ -208,6 +246,7 @@ public partial class MainWindow : Window
DiscardRun();
Project = new Project();
Filename = null;
+ _suggestedFileName = null;
projectTree.SelectRoot();
}
@@ -248,7 +287,7 @@ public partial class MainWindow : Window
Filter = (string)FindResource("SaveFileDialogFilter"),
DefaultExt = ProjectExtension,
AddExtension = true,
- FileName = Filename ?? "",
+ FileName = Filename ?? _suggestedFileName ?? "",
};
if (dialog.ShowDialog(this) == true)
{
@@ -263,6 +302,7 @@ public partial class MainWindow : Window
DiscardRun();
Project = new Project();
Filename = null;
+ _suggestedFileName = null;
projectTree.SelectRoot();
}
diff --git a/WaveDude.WPF/Strings/Strings.DE.xaml b/WaveDude.WPF/Strings/Strings.DE.xaml
index f3b9c3b..18f6e4f 100644
--- a/WaveDude.WPF/Strings/Strings.DE.xaml
+++ b/WaveDude.WPF/Strings/Strings.DE.xaml
@@ -157,7 +157,7 @@
<s:String x:Key="TipRemoveStop">Diesen Stützpunkt entfernen</s:String>
<s:String x:Key="TipStopPosition">Position im Verlauf: 0 beim kleinsten Wert, 1 beim größten</s:String>
<s:String x:Key="TipStopColor">Farbe als #RRGGBB; Eingabe übernimmt sie</s:String>
- <s:String x:Key="OpenFileDialogFilter">Wave-Dude-Projekte (*.wdproj)|*.wdproj|XML-Dateien (*.xml)|*.xml|Alle Dateien (*.*)|*.*</s:String>
+ <s:String x:Key="OpenFileDialogFilter">Wave-Dude-Projekte (*.wdproj)|*.wdproj|Wave-Dude-2D-Projekte (configuration.json)|configuration.json;*.json|XML-Dateien (*.xml)|*.xml|Alle Dateien (*.*)|*.*</s:String>
<s:String x:Key="SaveFileDialogFilter">Wave-Dude-Projekte (*.wdproj)|*.wdproj|XML-Dateien (*.xml)|*.xml</s:String>
<s:String x:Key="OpenError">'{0}' konnte nicht geöffnet werden.</s:String>
<s:String x:Key="SaveError">'{0}' konnte nicht gespeichert werden.</s:String>
diff --git a/WaveDude.WPF/Strings/Strings.EN.xaml b/WaveDude.WPF/Strings/Strings.EN.xaml
index c3036d5..9eb3e10 100644
--- a/WaveDude.WPF/Strings/Strings.EN.xaml
+++ b/WaveDude.WPF/Strings/Strings.EN.xaml
@@ -157,7 +157,7 @@
<s:String x:Key="TipRemoveStop">Remove this stop</s:String>
<s:String x:Key="TipStopPosition">Position along the gradient: 0 at the lowest value, 1 at the highest</s:String>
<s:String x:Key="TipStopColor">Colour as #RRGGBB; Enter applies it</s:String>
- <s:String x:Key="OpenFileDialogFilter">Wave Dude projects (*.wdproj)|*.wdproj|XML files (*.xml)|*.xml|All files (*.*)|*.*</s:String>
+ <s:String x:Key="OpenFileDialogFilter">Wave Dude projects (*.wdproj)|*.wdproj|Wave Dude 2D projects (configuration.json)|configuration.json;*.json|XML files (*.xml)|*.xml|All files (*.*)|*.*</s:String>
<s:String x:Key="SaveFileDialogFilter">Wave Dude projects (*.wdproj)|*.wdproj|XML files (*.xml)|*.xml</s:String>
<s:String x:Key="OpenError">Could not open '{0}'.</s:String>
<s:String x:Key="SaveError">Could not save '{0}'.</s:String>
diff --git a/WaveDude.WPF/Strings/Strings.FR.xaml b/WaveDude.WPF/Strings/Strings.FR.xaml
index 25f6d35..cee2f74 100644
--- a/WaveDude.WPF/Strings/Strings.FR.xaml
+++ b/WaveDude.WPF/Strings/Strings.FR.xaml
@@ -157,7 +157,7 @@
<s:String x:Key="TipRemoveStop">Supprimer ce point</s:String>
<s:String x:Key="TipStopPosition">Position dans le dégradé : 0 à la valeur la plus basse, 1 à la plus haute</s:String>
<s:String x:Key="TipStopColor">Couleur en #RRGGBB ; Entrée l'applique</s:String>
- <s:String x:Key="OpenFileDialogFilter">Projets Wave Dude (*.wdproj)|*.wdproj|Fichiers XML (*.xml)|*.xml|Tous les fichiers (*.*)|*.*</s:String>
+ <s:String x:Key="OpenFileDialogFilter">Projets Wave Dude (*.wdproj)|*.wdproj|Projets Wave Dude 2D (configuration.json)|configuration.json;*.json|Fichiers XML (*.xml)|*.xml|Tous les fichiers (*.*)|*.*</s:String>
<s:String x:Key="SaveFileDialogFilter">Projets Wave Dude (*.wdproj)|*.wdproj|Fichiers XML (*.xml)|*.xml</s:String>
<s:String x:Key="OpenError">Impossible d'ouvrir '{0}'.</s:String>
<s:String x:Key="SaveError">Impossible d'enregistrer '{0}'.</s:String>
diff --git a/WaveDude.WPF/Strings/Strings.NL.xaml b/WaveDude.WPF/Strings/Strings.NL.xaml
index 872e752..1f82c36 100644
--- a/WaveDude.WPF/Strings/Strings.NL.xaml
+++ b/WaveDude.WPF/Strings/Strings.NL.xaml
@@ -157,7 +157,7 @@
<s:String x:Key="TipRemoveStop">Dit punt verwijderen</s:String>
<s:String x:Key="TipStopPosition">Positie in het verloop: 0 bij de laagste waarde, 1 bij de hoogste</s:String>
<s:String x:Key="TipStopColor">Kleur als #RRGGBB; Enter past hem toe</s:String>
- <s:String x:Key="OpenFileDialogFilter">Wave Dude-projecten (*.wdproj)|*.wdproj|XML-bestanden (*.xml)|*.xml|Alle bestanden (*.*)|*.*</s:String>
+ <s:String x:Key="OpenFileDialogFilter">Wave Dude-projecten (*.wdproj)|*.wdproj|Wave Dude 2D-projecten (configuration.json)|configuration.json;*.json|XML-bestanden (*.xml)|*.xml|Alle bestanden (*.*)|*.*</s:String>
<s:String x:Key="SaveFileDialogFilter">Wave Dude-projecten (*.wdproj)|*.wdproj|XML-bestanden (*.xml)|*.xml</s:String>
<s:String x:Key="OpenError">Kan '{0}' niet openen.</s:String>
<s:String x:Key="SaveError">Kan '{0}' niet opslaan.</s:String>
diff --git a/WaveDude/Model/LegacyProject.cs b/WaveDude/Model/LegacyProject.cs
new file mode 100644
index 0000000..31931f5
--- /dev/null
+++ b/WaveDude/Model/LegacyProject.cs
@@ -0,0 +1,333 @@
+using System.Globalization;
+using System.Text.Json;
+using NLog;
+
+namespace WaveDude.Model;
+
+/// <summary>
+/// Reads a project of the author's program (a <c>configuration.json</c> in a project folder, see
+/// <c>Wave_Dude_2D/ProjectConfig.cs</c> and the per-class <c>FromConfig</c> readers) into a <see cref="Project"/>
+/// (2026-10-14; the user promised the author an importer). The mapping follows the legacy readers key for key,
+/// including their fallbacks for keys a file may lack, so an old project keeps its exact behaviour:
+/// <list type="bullet">
+/// <item><description>scene: mode, size, damping (enabled + size → <see cref="Scene.DampingEdge"/>, 0 when off), image sources, object sources, refractive index. A scene image given by a path relative to the folder is embedded when the file exists (<see cref="Scene.ImageData"/>), else the path is kept and noted.</description></item>
+/// <item><description>simulation: steps, interval, solver (4th-order Laplacian, wave speed, time decay, frequency scale, intensity scale); the preview/export flags, schemes, brightness and black levels go to <see cref="Display"/>, the video settings to <see cref="Video"/>. The GPU flag is ignored (an application setting here).</description></item>
+/// <item><description>object sources: one <see cref="Source"/> each; a composite one gets a <see cref="SourceArray"/>, with the random amounts only when the composite mode is "randomize" and the flag is on. The stored emitter elements are not read: they are regenerated from the project seed, so a randomised array differs from the original (noted). A source without a position, or switched off, is imported disabled.</description></item>
+/// <item><description>probes: one <see cref="Probe"/> each, named "Probe n"; "start after step" is 0 unless its flag is on; a scene-level <c>use_probes</c> of false deactivates them all.</description></item>
+/// </list>
+/// The project gets a fresh seed and the file's description. Thread-free; the caller owns the result.
+/// </summary>
+public static class LegacyProject
+{
+ private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
+
+ /// <summary>File name of a legacy project's configuration inside its folder.</summary>
+ public const string FileName = "configuration.json";
+
+ /// <summary>Extension of the files this importer reads.</summary>
+ public const string Extension = ".json";
+
+ /// <summary>Newest <c>format_version</c> this importer understands.</summary>
+ public const int SupportedFormatVersion = 1;
+
+ /// <summary>Whether <paramref name="path"/> names a legacy project (by its extension; the author's file is always <see cref="FileName"/>).</summary>
+ public static bool IsLegacyFile(string path) => string.Equals(Path.GetExtension(path), Extension, StringComparison.OrdinalIgnoreCase);
+
+ /// <summary>The <c>.wdproj</c> name proposed for an imported project: the legacy project's name (or its folder's) beside the configuration file.</summary>
+ public static string SuggestedFileName(string path, string projectName)
+ {
+ string folder = Path.GetDirectoryName(Path.GetFullPath(path)) ?? "";
+ string name = projectName.Length > 0 ? projectName : Path.GetFileName(folder);
+ foreach (char invalid in Path.GetInvalidFileNameChars())
+ {
+ name = name.Replace(invalid, '_');
+ }
+ return Path.Combine(folder, (name.Length > 0 ? name : "project") + ".wdproj");
+ }
+
+ /// <summary>
+ /// Imports the legacy project at <paramref name="path"/>.
+ /// </summary>
+ /// <param name="path">The <c>configuration.json</c>; a scene image path is resolved against its folder.</param>
+ /// <param name="notes">Receives what could not be carried over exactly (a missing image, a regenerated random array, a disabled source); may be null.</param>
+ /// <param name="projectName">Receives the file's project name, "" when it has none.</param>
+ /// <exception cref="InvalidDataException">The file is not a legacy project, or of a newer format.</exception>
+ public static Project Import(string path, IList<string>? notes, out string projectName)
+ {
+ path = Path.GetFullPath(path);
+ string folder = Path.GetDirectoryName(path) ?? "";
+ JsonElement root;
+ using JsonDocument document = Parse(path);
+ root = document.RootElement;
+ if (root.ValueKind != JsonValueKind.Object)
+ {
+ throw new InvalidDataException($"The file {Path.GetFileName(path)} is not a project configuration (a JSON object was expected).");
+ }
+ int version = Int(root, "format_version", SupportedFormatVersion);
+ if (version > SupportedFormatVersion)
+ {
+ throw new InvalidDataException($"The file {Path.GetFileName(path)} was made by a newer version of the program (format {version}).");
+ }
+ projectName = Text(root, "project_name", "");
+ var project = new Project { Description = Text(root, "description", "") };
+ JsonElement? scene = Section(root, "scene");
+ ImportScene(scene, project.Scene, folder, notes);
+ ImportSimulation(Section(root, "simulation"), project);
+ ImportSources(Section(root, "object_sources"), project, notes);
+ ImportProbes(Section(root, "probes"), project, scene, notes);
+ project.Normalize();
+ Logger.Info("Imported legacy project '{Name}' from '{Path}': {Sources} sources, {Probes} probes", projectName, path, project.Sources.Count, project.Probes.Count);
+ return project;
+ }
+
+ private static JsonDocument Parse(string path)
+ {
+ try
+ {
+ return JsonDocument.Parse(File.ReadAllBytes(path), new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
+ }
+ catch (JsonException ex)
+ {
+ throw new InvalidDataException($"The file {Path.GetFileName(path)} is not valid JSON: {ex.Message}", ex);
+ }
+ }
+
+ private static void ImportScene(JsonElement? section, Scene scene, string folder, IList<string>? notes)
+ {
+ // the legacy fallbacks: a project saved before a key existed keeps its previous behaviour
+ scene.Mode = Text(section, "mode", "user_defined") == "image" ? SceneMode.Image : SceneMode.Canvas;
+ scene.Width = Int(section, "user_width", Scene.DefaultWidth);
+ scene.Height = Int(section, "user_height", Scene.DefaultHeight);
+ scene.DampingEdge = Bool(section, "damping_edge_enabled", false) ? Int(section, "damping_edge_size_px", Scene.DefaultDampingEdge) : 0;
+ scene.ImageSources = Bool(section, "use_sources", false);
+ scene.ImageSourceScale = Double(section, "image_source_scale", Scene.DefaultImageSourceScale);
+ scene.ObjectSources = Bool(section, "use_object_sources", false);
+ scene.RefractiveIndex = Double(section, "background_refractive_index", Scene.DefaultRefractiveIndex);
+ string imageFile = Text(section, "image_file", "");
+ if (imageFile.Length == 0)
+ {
+ return;
+ }
+ // the author stores the image relative to the project folder (forward slashes); here it is embedded
+ string imagePath = Path.Combine(folder, imageFile.Replace('/', Path.DirectorySeparatorChar));
+ if (File.Exists(imagePath))
+ {
+ scene.ImageData = File.ReadAllBytes(imagePath);
+ scene.Image = Path.GetFileName(imagePath);
+ }
+ else
+ {
+ scene.Image = imageFile;
+ notes?.Add($"The scene image '{imageFile}' was not found next to the project; its path is kept, but the scene has no image until one is chosen.");
+ }
+ }
+
+ private static void ImportSimulation(JsonElement? section, Project project)
+ {
+ Simulation simulation = project.Simulation;
+ simulation.Steps = Int(section, "steps", Simulation.DefaultSteps);
+ simulation.VisualizeEvery = Int(section, "visualize_every", 2);
+ simulation.FourthOrderLaplacian = Bool(section, "use_4th_order_laplacian", false);
+ simulation.WaveSpeed = Double(section, "wave_speed_c", 0.563);
+ simulation.TimeDecay = Double(section, "time_decay_factor", 10.0);
+ simulation.SourceFrequencyScale = Double(section, "source_frequency_scale", 2.0);
+ simulation.IntensityScale = Double(section, "intensity_scale", 1.0);
+ Display display = project.Display;
+ display.Field.Preview = Bool(section, "preview_field", true);
+ display.Intensity.Preview = Bool(section, "preview_intensity", true);
+ display.Field.Export = Bool(section, "export_field", false);
+ display.Intensity.Export = Bool(section, "export_intensity", false);
+ display.Field.ColorScheme = Text(section, "field_color_scheme", Display.DefaultFieldColorScheme);
+ display.Intensity.ColorScheme = Text(section, "intensity_color_scheme", Display.DefaultIntensityColorScheme);
+ display.Field.Brightness = Double(section, "field_brightness", DisplayLayer.DefaultBrightness);
+ display.Intensity.Brightness = Double(section, "intensity_brightness", DisplayLayer.DefaultBrightness);
+ display.Field.BlackLevel = Double(section, "field_black_level", Display.DefaultFieldBlackLevel);
+ display.Intensity.BlackLevel = Double(section, "intensity_black_level", 0.0);
+ display.Video.Fps = Int(section, "video_fps", Video.DefaultFps);
+ display.Video.Quality = Int(section, "video_quality", Video.DefaultQuality);
+ }
+
+ private static void ImportSources(JsonElement? section, Project project, IList<string>? notes)
+ {
+ foreach (JsonElement item in Items(section))
+ {
+ var source = new Source { Name = Text(item, "name", "") };
+ if (source.Name.Length == 0)
+ {
+ source.Name = "Source " + (project.Sources.Count + 1).ToString(CultureInfo.InvariantCulture);
+ }
+ source.X = Int(item, "x", 0);
+ source.Y = Int(item, "y", 0);
+ // a source the author never placed has no position to simulate at; it comes in switched off
+ bool hasPosition = Bool(item, "has_position", true);
+ source.Enabled = Bool(item, "source_on", true) && hasPosition;
+ if (!hasPosition)
+ {
+ notes?.Add($"Source '{source.Name}' had no position in the original project and is imported disabled.");
+ }
+ source.DetachAfter = Bool(item, "detach_source", false) ? Int(item, "detach_after_steps", 1000) : Source.NeverDetach;
+ source.Frequency = Int(item, "frequency", Source.DefaultLevel);
+ source.Amplitude = Int(item, "amplitude", Source.DefaultAmplitude);
+ source.Phase = Int(item, "phase_deg", 0);
+ source.Mode = Text(item, "mode", "continuous") == "pulsed" ? SourceMode.Pulsed : SourceMode.Continuous;
+ source.PulseShape = Text(item, "pulse_shape", "gaussian") == "smoothed_square" ? PulseShape.SmoothedSquare : PulseShape.Gaussian;
+ source.PulseWidth = Int(item, "pulse_width_cycles", Source.DefaultWidth);
+ source.OffWidth = Int(item, "off_state_cycles", Source.DefaultWidth);
+ if (Text(item, "main_type", "single") == "composite")
+ {
+ // the random amounts count only when the composite mode randomises and the flag is on
+ bool randomize = Text(item, "composite_mode", "inherit") == "randomize";
+ source.Array = new SourceArray
+ {
+ SizeX = Int(item, "array_size_x", 1),
+ SizeY = Int(item, "array_size_y", 1),
+ SpacingX = Int(item, "spacing_x", SourceArray.DefaultSpacing),
+ SpacingY = Int(item, "spacing_y", SourceArray.DefaultSpacing),
+ RandomFrequency = Amount(item, randomize, "randomize_frequency"),
+ RandomPhase = Amount(item, randomize, "randomize_phase"),
+ RandomOffWidth = Amount(item, randomize, "randomize_off_width"),
+ RandomPosition = Amount(item, randomize, "randomize_position"),
+ };
+ if (source.Array.IsRandomized)
+ {
+ notes?.Add($"Source '{source.Name}' uses random offsets; its emitters are regenerated from this project's seed and differ from the original's.");
+ }
+ }
+ project.Sources.Add(source);
+ }
+ }
+
+ /// <summary>A random amount of an array: the <c>*_amount</c> value when the array randomises and the <c>randomize_*</c> flag is on, else 0.</summary>
+ private static int Amount(JsonElement item, bool randomize, string flag) =>
+ randomize && Bool(item, flag, false) ? Int(item, flag + "_amount", 0) : 0;
+
+ private static void ImportProbes(JsonElement? section, Project project, JsonElement? scene, IList<string>? notes)
+ {
+ // a later version of the author's program has a scene-level switch for all probes
+ bool useProbes = Bool(scene, "use_probes", true);
+ foreach (JsonElement item in Items(section))
+ {
+ var probe = new Probe
+ {
+ Name = "Probe " + (project.Probes.Count + 1).ToString(CultureInfo.InvariantCulture),
+ Active = Bool(item, "active", true) && useProbes,
+ Layer = Text(item, "place_on", "field") == "intensity" ? ProbeLayer.Intensity : ProbeLayer.Field,
+ Kind = Text(item, "probe_type", "point") == "line" ? ProbeKind.Line : ProbeKind.Point,
+ AX = Int(item, "ax", 100),
+ AY = Int(item, "ay", 100),
+ BX = Int(item, "bx", 300),
+ BY = Int(item, "by", 100),
+ BoxSize = Text(item, "box_size", "medium") switch
+ {
+ "tiny" => ProbeBoxSize.Tiny,
+ "small" => ProbeBoxSize.Small,
+ "large" => ProbeBoxSize.Large,
+ "extra_large" => ProbeBoxSize.ExtraLarge,
+ _ => ProbeBoxSize.Medium,
+ },
+ ScaleMode = Text(item, "scale_mode", "running") == "full" ? ProbeScaleMode.Full : ProbeScaleMode.Running,
+ AutoScaleX = Bool(item, "auto_scale_x", true),
+ AutoScaleY = Bool(item, "auto_scale_y", true),
+ YMin = Double(item, "y_min", -1.0),
+ YMax = Double(item, "y_max", 1.0),
+ Window = Int(item, "running_window", Probe.DefaultWindow),
+ StartAfter = Bool(item, "use_start_after_step", false) ? Int(item, "start_after_step", 0) : 0,
+ };
+ // the measurement after the layer, which coerces it
+ probe.Measurement = Text(item, "measurement", "amplitude") switch
+ {
+ "intensity" => ProbeMeasurement.Intensity,
+ "integrated_intensity" => ProbeMeasurement.IntegratedIntensity,
+ _ => ProbeMeasurement.Amplitude,
+ };
+ // the box position last: setting A first would drag a box that happens to share its position along
+ probe.BoxX = Int(item, "box_x", 450);
+ probe.BoxY = Int(item, "box_y", 20);
+ project.Probes.Add(probe);
+ }
+ if (!useProbes && project.Probes.Count > 0)
+ {
+ notes?.Add("The original project had its probes switched off; they are imported inactive.");
+ }
+ }
+
+ // ---------------------------------------------------------------- tolerant readers (the legacy readers' rules)
+
+ /// <summary>The named object below <paramref name="parent"/>, or null when missing or not an object.</summary>
+ private static JsonElement? Section(JsonElement parent, string name) =>
+ parent.TryGetProperty(name, out JsonElement value) && value.ValueKind == JsonValueKind.Object ? value : null;
+
+ /// <summary>The objects of a section's <c>items</c> array (a "count" entry is ignored, the array rules); none when absent.</summary>
+ private static IEnumerable<JsonElement> Items(JsonElement? section)
+ {
+ if (section is { } s && s.TryGetProperty("items", out JsonElement items) && items.ValueKind == JsonValueKind.Array)
+ {
+ foreach (JsonElement item in items.EnumerateArray())
+ {
+ if (item.ValueKind == JsonValueKind.Object)
+ {
+ yield return item;
+ }
+ }
+ }
+ }
+
+ private static bool TryGet(JsonElement? parent, string key, out JsonElement value)
+ {
+ if (parent is { } p && p.TryGetProperty(key, out value) && value.ValueKind != JsonValueKind.Null)
+ {
+ return true;
+ }
+ value = default;
+ return false;
+ }
+
+ /// <summary>A string value, or any scalar as text (invariant culture); the fallback when missing or null.</summary>
+ private static string Text(JsonElement? parent, string key, string fallback)
+ {
+ if (!TryGet(parent, key, out JsonElement value))
+ {
+ return fallback;
+ }
+ return value.ValueKind switch
+ {
+ JsonValueKind.String => value.GetString() ?? fallback,
+ JsonValueKind.True => "true",
+ JsonValueKind.False => "false",
+ JsonValueKind.Number => value.GetRawText(),
+ _ => fallback,
+ };
+ }
+
+ /// <summary>A boolean; the fallback unless the value is an actual JSON boolean (the legacy readers did not parse strings here either).</summary>
+ private static bool Bool(JsonElement? parent, string key, bool fallback) =>
+ TryGet(parent, key, out JsonElement value) && value.ValueKind is JsonValueKind.True or JsonValueKind.False ? value.GetBoolean() : fallback;
+
+ /// <summary>An integer (a whole number, or numeric text); the fallback when missing or not convertible. The model clamps the range.</summary>
+ private static int Int(JsonElement? parent, string key, int fallback)
+ {
+ if (!TryGet(parent, key, out JsonElement value))
+ {
+ return fallback;
+ }
+ if (value.ValueKind == JsonValueKind.Number)
+ {
+ return value.TryGetInt32(out int whole) ? whole : value.TryGetDouble(out double number) && Math.Abs(number) < int.MaxValue ? (int)Math.Round(number) : fallback;
+ }
+ return value.ValueKind == JsonValueKind.String && int.TryParse(value.GetString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed) ? parsed : fallback;
+ }
+
+ /// <summary>A double (a number, or numeric text); the fallback when missing or not convertible. The model clamps the range.</summary>
+ private static double Double(JsonElement? parent, string key, double fallback)
+ {
+ if (!TryGet(parent, key, out JsonElement value))
+ {
+ return fallback;
+ }
+ if (value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out double number))
+ {
+ return number;
+ }
+ return value.ValueKind == JsonValueKind.String && double.TryParse(value.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out double parsed) ? parsed : fallback;
+ }
+}
diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.cs
index 603eba3..d9fadf8 100644
--- a/_tools/library_check/Program.cs
+++ b/_tools/library_check/Program.cs
@@ -168,6 +168,7 @@ internal static class Program
CheckFrameStore(scene);
CheckRenderer();
CheckColorSchemes();
+ CheckImport();
CheckRun();
Console.WriteLine(_failures == 0 ? "LIBRARY OK" : _failures + " check(s) failed");
@@ -684,6 +685,86 @@ internal static class Program
Check(frame[2 * 5 + 2] == unchecked((int)0xFFBFBFBF) && frame[2 * 5 + 3] == unchecked((int)0xFF404040), "additive blend adds edge x gain per channel and leaves flat pixels alone");
}
+ /// <summary>The repository root (the folder holding the author's examples), found by walking up from the harness binary; null when not found.</summary>
+ private static string? FindRepoRoot()
+ {
+ for (DirectoryInfo? dir = new(AppContext.BaseDirectory); dir != null; dir = dir.Parent)
+ {
+ if (Directory.Exists(Path.Combine(dir.FullName, "Wave_Dude_Examples")))
+ {
+ return dir.FullName;
+ }
+ }
+ return null;
+ }
+
+ private static void CheckImport()
+ {
+ Console.WriteLine("--- legacy project import");
+ string? root = FindRepoRoot();
+ if (root == null)
+ {
+ Console.WriteLine(" skip import: the Wave_Dude_Examples folder was not found above the harness");
+ return;
+ }
+ var notes = new List<string>();
+ Project p = LegacyProject.Import(Path.Combine(root, "Wave_Dude_Examples", "Example12_Dispersion", "configuration.json"), notes, out string name);
+ Check(name == "Example12_Dispersion" && p.Description.StartsWith("This example shows the difference", StringComparison.Ordinal) && notes.Count == 0, "Example 12: name and description, no notes");
+ Check(p.Scene.Mode == SceneMode.Image && p.Scene.Image == "frequency_race_track (2).png" && p.Scene.ImageData is { Length: 58074 } && p.Scene.Width == 1920 && p.Scene.Height == 1080, "scene: image mode, the image embedded (58074 bytes) under its file name, 1920 x 1080");
+ Check(p.Scene.DampingEdge == 64 && !p.Scene.ImageSources && p.Scene.ObjectSources && p.Scene.RefractiveIndex == 1.0 && p.Scene.ImageSourceScale == 1.0, "scene: damping 64, object sources on, image sources off");
+ Check(p.Simulation.Steps == 15000 && p.Simulation.VisualizeEvery == 2 && !p.Simulation.FourthOrderLaplacian && p.Simulation.WaveSpeed == 1.0 && p.Simulation.TimeDecay == 10.0 && p.Simulation.SourceFrequencyScale == 2.0 && p.Simulation.IntensityScale == 1.0, "simulation: 15000 steps every 2, 9-point stencil, c 1, decay 10");
+ Check(p.Display.Field.Brightness == 80 && p.Display.Intensity.Brightness == 30 && p.Display.Field.BlackLevel == -0.05 && p.Display.Intensity.BlackLevel == 0 && p.Display.Field.ColorScheme == "Default_Field" && p.Display.Intensity.ColorScheme == "Default_intensity", "display: brightness 80 / 30, black levels, schemes");
+ Check(p.Display.Field.Preview && p.Display.Intensity.Preview && !p.Display.Field.Export && !p.Display.Intensity.Export && p.Display.Video.Fps == 60 && p.Display.Video.Quality == 70, "display: previews on, exports off, 60 fps at quality 70");
+ Check(p.Sources.Count == 4 && p.Sources.Select(s => s.Name).SequenceEqual(["Source 1", "Source 2", "Source 3", "Source 4"]) && p.Sources.Select(s => s.Frequency).SequenceEqual([40, 100, 150, 240]) && p.Sources.Select(s => s.Amplitude).SequenceEqual([70, 80, 90, 100]), "4 single sources with their names, levels and amplitudes");
+ Check(p.Sources.All(s => s.Enabled && s.Array == null && s.DetachAfter == Source.NeverDetach && s.Mode == SourceMode.Continuous && s.Elements.Count == 1) && p.Sources[0].X == 150 && p.Sources[0].Y == 140 && p.Sources[3].Y == 924, "sources enabled, single, never detaching, placed, with one emitter each");
+ Check(p.Probes.Count == 2 && p.Probes.All(pr => !pr.Active && pr.Layer == ProbeLayer.Field && pr.Measurement == ProbeMeasurement.Amplitude && pr.BoxSize == ProbeBoxSize.Medium && pr.Window == 500 && pr.StartAfter == 0), "2 inactive field probes, medium boxes, window 500, no start step");
+ Check(p.Probes[0].Kind == ProbeKind.Line && p.Probes[0].AX == 1713 && p.Probes[0].AY == 2 && p.Probes[0].BX == 1719 && p.Probes[0].BY == 1073 && p.Probes[0].BoxX == 1 && p.Probes[0].BoxY == 426 && p.Probes[0].Name == "Probe 1", "probe 1: a line from (1713, 2) to (1719, 1073), box at (1, 426)");
+ Check(p.Probes[1].Kind == ProbeKind.Point && p.Probes[1].AX == 100 && p.Probes[1].BoxX == 450 && p.Probes[1].BoxY == 20 && p.Probes[1].Name == "Probe 2", "probe 2: the author's default point probe");
+ using (var stream = new MemoryStream())
+ {
+ p.Save(stream);
+ stream.Position = 0;
+ Project back = Project.Load(stream);
+ Check(back.Sources.Count == 4 && back.Probes.Count == 2 && back.Scene.ImageData!.SequenceEqual(p.Scene.ImageData!) && back.Simulation.Steps == 15000 && !back.Simulation.FourthOrderLaplacian, "the imported project round-trips through the XML format");
+ }
+ Check(LegacyProject.SuggestedFileName(Path.Combine(root, "Wave_Dude_Examples", "Example12_Dispersion", "configuration.json"), name) == Path.Combine(root, "Wave_Dude_Examples", "Example12_Dispersion", "Example12_Dispersion.wdproj"), "Save As proposes <name>.wdproj beside the original");
+
+ // a composite, randomised, detaching, pulsed source; a missing image in canvas mode; a global probe switch
+ notes.Clear();
+ p = LegacyProject.Import(Path.Combine(root, "Wave_Dude_Examples", "Example5_Small_incoherent_source", "configuration.json"), notes, out _);
+ Check(p.Scene.Mode == SceneMode.Canvas && p.Scene.ImageData == null && p.Scene.Image == "scene_images/spherrical_mirror_small_central_aperture.png" && notes.Any(n => n.Contains("not found")), "Example 5: canvas mode, the missing image's path kept and noted");
+ Source composite = p.Sources[0];
+ Check(composite.Array is { SizeX: 5, SizeY: 5, SpacingX: 3, SpacingY: 3, RandomFrequency: 50, RandomPhase: 90, RandomOffWidth: 19, RandomPosition: 1 } && composite.Elements.Count == 25, "a 5 x 5 array with its random amounts, 25 emitters regenerated");
+ Check(composite.Mode == SourceMode.Pulsed && composite.PulseWidth == 5 && composite.OffWidth == 20 && composite.DetachAfter == 2000 && composite.Enabled && notes.Any(n => n.Contains("random offsets")), "pulsed 5 / 20 cycles, detaching after step 2000, the regeneration noted");
+ Check(p.Simulation.WaveSpeed == 0.563 && p.Display.Field.ColorScheme == "Orange_symmetry" && p.Display.Intensity.ColorScheme == "Purple_rain" && p.Display.Field.Brightness == 50, "c 0.563 and the chosen schemes");
+ Check(p.Probes[0] is { Active: true, Kind: ProbeKind.Point, AutoScaleY: false, YMin: -0.02, YMax: 0.02, BoxSize: ProbeBoxSize.ExtraLarge, BoxX: 14, BoxY: 14 } && p.Probes[1] is { Layer: ProbeLayer.Intensity, Measurement: ProbeMeasurement.Intensity, Kind: ProbeKind.Line, StartAfter: 0, YMax: 0.0001 }, "probes: fixed value ranges, the unused start step dropped, use_probes honoured");
+
+ // start-after steps in use, an intensity probe, a detaching single source, the fallback decay
+ notes.Clear();
+ p = LegacyProject.Import(Path.Combine(root, "Wave_Dude_Examples", "Example3_Spherical_mirror", "configuration.json"), notes, out _);
+ Check(p.Probes[0] is { StartAfter: 600, Window: 3000, Layer: ProbeLayer.Intensity, Measurement: ProbeMeasurement.Intensity } && p.Probes[1] is { StartAfter: 600, Measurement: ProbeMeasurement.IntegratedIntensity, Kind: ProbeKind.Line }, "Example 3: start-after steps kept when their flag is on, intensity measurements");
+ Check(p.Sources[0] is { Array: null, DetachAfter: 670, PulseWidth: 70, OffWidth: 100, Frequency: 200 } && p.Simulation.TimeDecay == 8 && p.Display.Intensity.ColorScheme == "Copper", "a single detaching source (its unused array settings ignored), decay 8, Copper");
+ Check(p.Scene.Mode == SceneMode.Image && p.Scene.ImageData == null && notes.Count == 1, "image mode with the image missing: one note");
+
+ // a source the author never placed
+ notes.Clear();
+ p = LegacyProject.Import(Path.Combine(root, "Project", "Test", "configuration.json"), notes, out _);
+ Check(p.Sources.Count == 1 && !p.Sources[0].Enabled && notes.Any(n => n.Contains("no position")) && p.Simulation.TimeDecay == 5, "Test: a source without a position comes in disabled and noted");
+ bool refused = false;
+ string newer = Path.Combine(Path.GetTempPath(), "library_check-newer.json");
+ File.WriteAllText(newer, "{ \"format_version\": 2 }");
+ try
+ {
+ LegacyProject.Import(newer, null, out _);
+ }
+ catch (InvalidDataException)
+ {
+ refused = true;
+ }
+ File.Delete(newer);
+ Check(refused, "a newer format version is refused");
+ }
+
private static void CheckRun()
{
Console.WriteLine("--- run");
diff --git a/_tools/ui_check/ImportCheck.ps1 b/_tools/ui_check/ImportCheck.ps1
new file mode 100644
index 0000000..09cdedf
--- /dev/null
+++ b/_tools/ui_check/ImportCheck.ps1
@@ -0,0 +1,42 @@
+# Opens one of the author's projects (Wave_Dude_Examples/Example12_Dispersion/configuration.json) through the
+# command line and checks the import landed in the app (2026-10-14): the title shows no file (the project is
+# unsaved), the tree lists the four sources and two probes, the preview's canvas is the embedded image's
+# 1920 x 1080, and the status bar carries the import message. See Common.ps1 for the rules (no mouse, no
+# activation, no UIA patterns). Prints PASS/FAIL per check and exits with the failure count.
+#
+# powershell -ExecutionPolicy Bypass -File _tools\ui_check\ImportCheck.ps1 [-Exe <path>] [-Trace]
+
+param(
+ [string]$Exe = (Join-Path $PSScriptRoot "..\..\WaveDude.WPF\bin\Debug\net10.0-windows\WaveDude.WPF.exe"),
+ [switch]$Trace
+)
+
+. (Join-Path $PSScriptRoot "Common.ps1")
+
+Start-App $Exe (Join-Path $PSScriptRoot "..\..\Wave_Dude_Examples\Example12_Dispersion\configuration.json")
+try {
+ Check "the imported project is unsaved: the title is the bare application name" ($win.Current.Name -eq "Wave Dude") $win.Current.Name
+ $sources = @("Source 1", "Source 2", "Source 3", "Source 4") | Where-Object { try { (Find ("Tree:" + $_)) -ne $null } catch { $false } }
+ Check "the tree lists the four sources" ($sources.Count -eq 4) ("found " + $sources.Count)
+ $probes = @("Probe 1", "Probe 2") | Where-Object { try { (Find ("Tree:" + $_)) -ne $null } catch { $false } }
+ Check "and the two probes" ($probes.Count -eq 2) ("found " + $probes.Count)
+ Check "the probes came in inactive" (-not (ToggleOn "Enabled:Probe 1") -and -not (ToggleOn "Enabled:Probe 2"))
+ Check "the sources came in enabled" ((ToggleOn "Enabled:Source 1") -and (ToggleOn "Enabled:Source 4"))
+ # 15000 steps every 2: 7500 frames
+ Check "the timeline spans the imported run length (7500 frames)" ((Frame) -eq "0 / 7499") (Frame)
+ # the canvas is the embedded 1920 x 1080 image: the field picture keeps a 16:9 aspect
+ $r = (Find "PreviewFieldImage").Current.BoundingRectangle
+ Check "the preview shows the embedded image's 16:9 canvas" ([math]::Abs($r.Width / $r.Height - 16 / 9) -lt 0.02) ("{0:0}x{1:0}" -f $r.Width, $r.Height)
+ # the source marker sits where the file says: Source 1 at (150, 140) of 1920 x 1080
+ $expected = CanvasPoint "PreviewFieldImage" 1920 1080 150 140
+ $centre = CentreOf "Source:Source 1"
+ Check "Source 1's marker sits at (150, 140) of the canvas" ([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])
+ $status = (Find "StatusMessage").Current.Name
+ Check "the status bar reports the import" ($status -like "*Imported the legacy project 'Example12_Dispersion'*") $status
+ Check "app never became the foreground window" ((Foreground) -ne "APP") (Foreground)
+}
+finally {
+ Stop-App
+}
+Write-Output ("{0} failure(s)" -f $script:failures)
+exit $script:failures