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#

Scene image follows its file: the source path is kept, watched while open, compared on opening

Alexander Graef3edd191143b6
diff --git a/CLAUDE.md b/CLAUDE.md
index 3fabd1d..cabd53a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -142,7 +142,16 @@ WPF shell as it stands:
`PreviewPane.RefreshColors`). The scene image is picked with Scene > Browse… and **embedded**:
`Scene.ImageData` holds the file's bytes (base64 element, `XmlSerializer`'s own encoding),
`Scene.Image` just its name, the view shows "w × h, KB"; `LoadSceneImage` decodes the bytes once
- per array, a path is still honoured for old files. Open decisions: base64 vs BaseXML for the
+ per array, a path is still honoured for old files. **The embedded image follows its file** (2026-10-15, the
+ user's rule): `Scene.ImagePath` remembers where the bytes came from (relative to the project file when inside
+ its folder, made relative on save, absolute otherwise; set by Browse and the importer; shown read-only in the
+ scene view, id `SceneImagePath`; a project from before the path existed finds its image by name beside the
+ project file or in a `scene_images` folder next to it, `LocateSceneImageFile`); `MainWindow.SceneImageWatch.cs` watches that file while the project is open
+ (`FileSystemWatcher`, 400 ms debounce, reads retried while the editor holds the file) and re-embeds it when
+ its bytes differ, and compares it once when a project is opened or imported, taking the file when it differs.
+ Both go through the model, so the project turns dirty (asterisk, save prompt), the run goes stale and the
+ frame is recomputed; a path change alone is not a simulation change. No hash: the embedded bytes are the
+ baseline and the file has to be read to re-embed it anyway. Open decisions: base64 vs BaseXML for the
bytes (base64 is what `XmlSerializer` does natively; BaseXML would need an in-house codec); a colour
picker dialog for the stops (hex text only today; the WinForms `ColorDialog` would need
`UseWindowsForms`); renaming a project scheme does not update the layers that refer to it.
@@ -584,6 +593,12 @@ The two legacy harnesses are console programs compiled with `csc` against the `W
**harness hooks** in the app, read from the environment: `WAVEDUDE_EXPORT_PATH` replaces the Save dialog
(`{name}` = the suggested name) and `WAVEDUDE_DISCARD_EDITS=1` skips the save question on closing
(`Start-App` sets it), because posted keys cannot drive a common dialog or a message box.
+ `_tools/ui_check/SceneImageCheck.ps1` (2026-10-15, 6 checks, about 25 s: the app ends dirty, so the close
+ runs into the save prompt and `Stop-App` kills it after 8 s) builds a project in a temporary folder whose
+ embedded image (the ball lens) differs from the file its path names (the race track): opening it takes the
+ file and turns the project dirty, the status bar says so, the scene view shows the path; then the file is
+ overwritten on disk and the picture follows within a moment; a second project without a path finds its
+ image by name in `scene_images` and stores the relative path (8 checks, about 40 s).
`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
diff --git a/WaveDude.WPF/MainWindow.Live.cs b/WaveDude.WPF/MainWindow.Live.cs
index 016bbc1..384d3a9 100644
--- a/WaveDude.WPF/MainWindow.Live.cs
+++ b/WaveDude.WPF/MainWindow.Live.cs
@@ -132,6 +132,11 @@ public partial class MainWindow
private void OnProjectChanged(object? sender, ProjectChange change)
{
IsDirty = true;
+ if (change.Item is Scene && change.Property is nameof(Scene.ImagePath) or nameof(Scene.ImageData))
+ {
+ // a new image file to watch (Browse, a reload, a path made relative)
+ ArmSceneImageWatch();
+ }
if (change.Item is ColorScheme or ObservableCollection<ColorScheme>)
{
// a project scheme edited, added or removed: recolour the frame shown
@@ -377,6 +382,7 @@ public partial class MainWindow
private void ShutdownScratch()
{
+ DisarmSceneImageWatch();
_scratchRequested = null;
_scratchTimer?.Stop();
_rerunTimer?.Stop();
diff --git a/WaveDude.WPF/MainWindow.Project.cs b/WaveDude.WPF/MainWindow.Project.cs
index aa36a48..fd17591 100644
--- a/WaveDude.WPF/MainWindow.Project.cs
+++ b/WaveDude.WPF/MainWindow.Project.cs
@@ -188,6 +188,7 @@ public partial class MainWindow
ScenePixels pixels = SceneImageLoader.Load(bytes);
Project.Scene.ImageData = bytes;
Project.Scene.Image = Path.GetFileName(dialog.FileName);
+ Project.Scene.ImagePath = Scene.StoredImagePath(ProjectFolder, dialog.FileName);
Project.Scene.Mode = SceneMode.Image;
Logger.Info("Scene image '{Name}' embedded: {Width}×{Height}, {Size} KB", Project.Scene.Image, pixels.Width, pixels.Height, Math.Max(1, bytes.Length / 1024));
}
diff --git a/WaveDude.WPF/MainWindow.SceneImageWatch.cs b/WaveDude.WPF/MainWindow.SceneImageWatch.cs
new file mode 100644
index 0000000..03b9afd
--- /dev/null
+++ b/WaveDude.WPF/MainWindow.SceneImageWatch.cs
@@ -0,0 +1,167 @@
+using System.IO;
+using System.Windows.Threading;
+using WaveDude.Model;
+using WaveDude.Runs;
+using WaveDude.WPF.Rendering;
+
+namespace WaveDude.WPF;
+
+/// <summary>
+/// Keeps the embedded scene image in step with the file it came from (the user's rule, 2026-10-15): the file
+/// named by <see cref="Scene.ImagePath"/> is watched while the project is open and re-embedded when it changes
+/// on disk (debounced, read again while the editor still holds it), and when a project is opened the file is
+/// compared with the embedded bytes once and taken instead when it differs. Either way the change goes
+/// through the model, so it marks the project dirty, makes the run stale and asks the scratch runner for the
+/// frame, like a scene edit. The embedded bytes are the baseline, so "changed" is a byte comparison; no hash.
+/// UI thread; the watcher's events are marshalled to it.
+/// </summary>
+public partial class MainWindow
+{
+ /// <summary>How long after the last file event the image is read: editors write in several steps.</summary>
+ private static readonly TimeSpan SceneImageDebounce = TimeSpan.FromMilliseconds(400);
+
+ private FileSystemWatcher? _sceneImageWatcher;
+ private DispatcherTimer? _sceneImageTimer;
+
+ /// <summary>Folders beside the project file where a project without a path may find its image by name: the folder itself and the author's layout.</summary>
+ private static readonly string[] SceneImageFolders = ["", "scene_images"];
+
+ /// <summary>Arms the watch on the current scene image file (after a project, path or file name change) and takes the file at once when it differs from the embedded image.</summary>
+ private void SyncSceneImage(string reason)
+ {
+ LocateSceneImageFile();
+ ArmSceneImageWatch();
+ ReloadSceneImageIfChanged(reason);
+ }
+
+ /// <summary>
+ /// A project saved before the path existed knows its image only by name: looks for that name beside the
+ /// project file and in a <c>scene_images</c> folder next to it (the author's layout, where an imported
+ /// project is usually saved) and adopts the first match as the path, so the file is watched and compared
+ /// from now on. Nothing happens without an embedded image, a name, or a project folder.
+ /// </summary>
+ private void LocateSceneImageFile()
+ {
+ Scene scene = Project.Scene;
+ if (scene.ImagePath.Length > 0 || scene.Image.Length == 0 || scene.ImageData == null || ProjectFolder is not { } folder)
+ {
+ return;
+ }
+ foreach (string sub in SceneImageFolders)
+ {
+ string candidate = Path.Combine(folder, sub, scene.Image);
+ if (File.Exists(candidate))
+ {
+ scene.ImagePath = Scene.StoredImagePath(folder, candidate);
+ Logger.Info("Scene image file found for '{Name}': '{Path}' (the project had no path; it is watched from now on)", scene.Image, scene.ImagePath);
+ return;
+ }
+ }
+ }
+
+ /// <summary>Watches the scene image's source file; nothing when the project has no embedded image or the path does not resolve.</summary>
+ private void ArmSceneImageWatch()
+ {
+ DisarmSceneImageWatch();
+ Scene scene = Project.Scene;
+ string path = scene.ResolveImagePath(ProjectFolder);
+ if (path.Length == 0 || scene.ImageData == null)
+ {
+ return;
+ }
+ string? folder = Path.GetDirectoryName(path);
+ if (folder == null || !Directory.Exists(folder))
+ {
+ return;
+ }
+ try
+ {
+ _sceneImageWatcher = new FileSystemWatcher(folder, Path.GetFileName(path))
+ {
+ NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.FileName | NotifyFilters.CreationTime,
+ };
+ _sceneImageWatcher.Changed += OnSceneImageFileEvent;
+ _sceneImageWatcher.Created += OnSceneImageFileEvent;
+ _sceneImageWatcher.Renamed += OnSceneImageFileEvent;
+ _sceneImageWatcher.EnableRaisingEvents = true;
+ Logger.Debug("Watching the scene image file '{Path}'", path);
+ }
+ catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException)
+ {
+ Logger.Debug("The scene image file '{Path}' cannot be watched: {Message}", path, ex.Message);
+ _sceneImageWatcher = null;
+ }
+ }
+
+ private void DisarmSceneImageWatch()
+ {
+ _sceneImageTimer?.Stop();
+ if (_sceneImageWatcher != null)
+ {
+ _sceneImageWatcher.EnableRaisingEvents = false;
+ _sceneImageWatcher.Dispose();
+ _sceneImageWatcher = null;
+ }
+ }
+
+ /// <summary>A file event (on the watcher's thread): restarts the debounce on the UI thread.</summary>
+ private void OnSceneImageFileEvent(object sender, FileSystemEventArgs e) => Dispatcher.BeginInvoke(() =>
+ {
+ _sceneImageTimer ??= MakeTimer(SceneImageDebounce, () =>
+ {
+ _sceneImageTimer!.Stop();
+ ReloadSceneImageIfChanged("changed on disk");
+ });
+ _sceneImageTimer.Stop();
+ _sceneImageTimer.Start();
+ });
+
+ /// <summary>
+ /// Reads the scene image's source file and embeds it when its bytes differ from the embedded ones; a file
+ /// that is not an image is reported and left alone. True when the image was replaced.
+ /// </summary>
+ private bool ReloadSceneImageIfChanged(string reason)
+ {
+ Scene scene = Project.Scene;
+ string path = scene.ResolveImagePath(ProjectFolder);
+ if (path.Length == 0 || scene.ImageData == null || !File.Exists(path))
+ {
+ return false;
+ }
+ byte[]? bytes = TryReadAll(path);
+ if (bytes == null || bytes.AsSpan().SequenceEqual(scene.ImageData))
+ {
+ return false;
+ }
+ try
+ {
+ ScenePixels pixels = SceneImageLoader.Load(bytes);
+ scene.ImageData = bytes;
+ scene.Image = Path.GetFileName(path);
+ Logger.Info("Scene image '{Name}' re-embedded from '{Path}' ({Reason}): {Width}×{Height}, {Size} KB", scene.Image, path, reason, pixels.Width, pixels.Height, Math.Max(1, bytes.Length / 1024));
+ return true;
+ }
+ catch (Exception ex) when (ex is NotSupportedException or FileFormatException or IOException)
+ {
+ Logger.Warn(ex, "The scene image file '{Path}' changed but cannot be read as an image: {Message}", path, ex.Message);
+ return false;
+ }
+ }
+
+ /// <summary>Reads the whole file, trying again for a moment while the program writing it still holds it.</summary>
+ private static byte[]? TryReadAll(string path)
+ {
+ for (int attempt = 0; attempt < 8; attempt++)
+ {
+ try
+ {
+ return File.ReadAllBytes(path);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Thread.Sleep(100);
+ }
+ }
+ return null;
+ }
+}
diff --git a/WaveDude.WPF/MainWindow.xaml.cs b/WaveDude.WPF/MainWindow.xaml.cs
index e64d0a5..54eeba5 100644
--- a/WaveDude.WPF/MainWindow.xaml.cs
+++ b/WaveDude.WPF/MainWindow.xaml.cs
@@ -178,6 +178,8 @@ public partial class MainWindow : Window
Logger.Info("Opened '{Path}'", fileName);
RememberRecent(fileName);
projectTree.SelectRoot();
+ // the embedded image against its file: a changed file is taken (the project is then dirty) and watched from here on
+ SyncSceneImage("changed since the project was saved");
}
catch (Exception ex)
{
@@ -200,6 +202,7 @@ public partial class MainWindow : Window
DiscardRun();
Project = imported;
Filename = null;
+ SyncSceneImage("imported");
_suggestedFileName = LegacyProject.SuggestedFileName(fileName, projectName);
foreach (string note in notes)
{
@@ -242,9 +245,12 @@ public partial class MainWindow : Window
try
{
fileName = Path.GetFullPath(fileName);
+ // an image file inside the project's folder is stored relative to it, so the project moves with its image
+ Project.Scene.RelativizeImagePath(Path.GetDirectoryName(fileName));
Project.Save(fileName);
Filename = fileName;
IsDirty = false;
+ ArmSceneImageWatch();
Logger.Info("Saved '{Path}'", fileName);
RememberRecent(fileName);
return true;
diff --git a/WaveDude.WPF/Strings/Strings.DE.xaml b/WaveDude.WPF/Strings/Strings.DE.xaml
index 4a38590..8fe8097 100644
--- a/WaveDude.WPF/Strings/Strings.DE.xaml
+++ b/WaveDude.WPF/Strings/Strings.DE.xaml
@@ -283,6 +283,8 @@
<s:String x:Key="Hint.Scene.Mode">Leere Leinwand der angegebenen Größe oder eine aus dem Szenenbild gebaute Leinwand.</s:String>
<s:String x:Key="Label.Scene.Image">Szenenbild</s:String>
<s:String x:Key="Hint.Scene.Image">Bild, aus dem die Leinwand gebaut wird: Rot = Brechungsindex, Grün = Quellen, Blau = Dämpfung. Der Name des eingebetteten Bilds oder ein Pfad relativ zum Projektordner.</s:String>
+ <s:String x:Key="Label.Scene.ImagePath">Bilddatei</s:String>
+ <s:String x:Key="Hint.Scene.ImagePath">Herkunft des eingebetteten Bilds. Die Datei wird beobachtet, solange das Projekt offen ist, und bei Änderung neu eingebettet; beim Öffnen des Projekts ersetzt eine geänderte Datei das eingebettete Bild ebenfalls.</s:String>
<s:String x:Key="Label.Scene.Width">Breite</s:String>
<s:String x:Key="Hint.Scene.Width">Breite einer leeren Leinwand in Pixeln.</s:String>
<s:String x:Key="Label.Scene.Height">Höhe</s:String>
diff --git a/WaveDude.WPF/Strings/Strings.EN.xaml b/WaveDude.WPF/Strings/Strings.EN.xaml
index 1b85fe4..f250cc4 100644
--- a/WaveDude.WPF/Strings/Strings.EN.xaml
+++ b/WaveDude.WPF/Strings/Strings.EN.xaml
@@ -283,6 +283,8 @@
<s:String x:Key="Hint.Scene.Mode">Blank canvas of the given size, or a canvas built from the scene image.</s:String>
<s:String x:Key="Label.Scene.Image">Scene image</s:String>
<s:String x:Key="Hint.Scene.Image">Image the canvas is built from: red = refractive index, green = sources, blue = damping. The name of the embedded image, or a path relative to the project folder.</s:String>
+ <s:String x:Key="Label.Scene.ImagePath">Image file</s:String>
+ <s:String x:Key="Hint.Scene.ImagePath">Where the embedded image came from. It is watched while the project is open and re-embedded when it changes; on opening the project a changed file replaces the embedded image too.</s:String>
<s:String x:Key="Label.Scene.Width">Width</s:String>
<s:String x:Key="Hint.Scene.Width">Width of a blank canvas in pixels.</s:String>
<s:String x:Key="Label.Scene.Height">Height</s:String>
diff --git a/WaveDude.WPF/Strings/Strings.FR.xaml b/WaveDude.WPF/Strings/Strings.FR.xaml
index 27f5ed1..06e926a 100644
--- a/WaveDude.WPF/Strings/Strings.FR.xaml
+++ b/WaveDude.WPF/Strings/Strings.FR.xaml
@@ -283,6 +283,8 @@
<s:String x:Key="Hint.Scene.Mode">Toile vierge de la taille donnée, ou toile construite à partir de l'image de scène.</s:String>
<s:String x:Key="Label.Scene.Image">Image de scène</s:String>
<s:String x:Key="Hint.Scene.Image">Image dont la toile est construite : rouge = indice de réfraction, vert = sources, bleu = amortissement. Le nom de l'image intégrée, ou un chemin relatif au dossier du projet.</s:String>
+ <s:String x:Key="Label.Scene.ImagePath">Fichier image</s:String>
+ <s:String x:Key="Hint.Scene.ImagePath">Origine de l'image intégrée. Le fichier est surveillé tant que le projet est ouvert et réintégré quand il change ; à l'ouverture du projet, un fichier modifié remplace aussi l'image intégrée.</s:String>
<s:String x:Key="Label.Scene.Width">Largeur</s:String>
<s:String x:Key="Hint.Scene.Width">Largeur d'une toile vierge en pixels.</s:String>
<s:String x:Key="Label.Scene.Height">Hauteur</s:String>
diff --git a/WaveDude.WPF/Strings/Strings.NL.xaml b/WaveDude.WPF/Strings/Strings.NL.xaml
index 2915fd1..9b1e999 100644
--- a/WaveDude.WPF/Strings/Strings.NL.xaml
+++ b/WaveDude.WPF/Strings/Strings.NL.xaml
@@ -283,6 +283,8 @@
<s:String x:Key="Hint.Scene.Mode">Leeg canvas van de opgegeven grootte, of een canvas opgebouwd uit de scèneafbeelding.</s:String>
<s:String x:Key="Label.Scene.Image">Scèneafbeelding</s:String>
<s:String x:Key="Hint.Scene.Image">Afbeelding waaruit het canvas wordt opgebouwd: rood = brekingsindex, groen = bronnen, blauw = demping. De naam van de ingebedde afbeelding, of een pad relatief aan de projectmap.</s:String>
+ <s:String x:Key="Label.Scene.ImagePath">Afbeeldingsbestand</s:String>
+ <s:String x:Key="Hint.Scene.ImagePath">Herkomst van de ingebedde afbeelding. Het bestand wordt bewaakt zolang het project open is en opnieuw ingebed als het verandert; bij het openen van het project vervangt een gewijzigd bestand de ingebedde afbeelding ook.</s:String>
<s:String x:Key="Label.Scene.Width">Breedte</s:String>
<s:String x:Key="Hint.Scene.Width">Breedte van een leeg canvas in pixels.</s:String>
<s:String x:Key="Label.Scene.Height">Hoogte</s:String>
diff --git a/WaveDude.WPF/Views/SceneView.xaml b/WaveDude.WPF/Views/SceneView.xaml
index 262bfad..e8ea99e 100644
--- a/WaveDude.WPF/Views/SceneView.xaml
+++ b/WaveDude.WPF/Views/SceneView.xaml
@@ -43,6 +43,10 @@
<TextBox Style="{StaticResource ImageOnly}" Text="{Binding Image, UpdateSourceTrigger=PropertyChanged}" ToolTip="{meta:Hint model:Scene.Image}" />
</DockPanel>
+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Scene.ImagePath}" />
+ <TextBlock VerticalAlignment="Center" Text="{Binding ImagePath}" TextTrimming="CharacterEllipsis" ToolTip="{meta:Hint model:Scene.ImagePath}"
+ AutomationProperties.AutomationId="SceneImagePath" />
+
<TextBlock Style="{StaticResource FormLabel}" Text="{DynamicResource LabelEmbeddedImage}" />
<TextBlock VerticalAlignment="Center" Text="{Binding ImageData, Converter={StaticResource ImageInfo}}"
ToolTip="{DynamicResource TipEmbeddedImage}" AutomationProperties.AutomationId="SceneImageInfo" />
diff --git a/WaveDude/Model/LegacyProject.cs b/WaveDude/Model/LegacyProject.cs
index e4db563..7ba1f1a 100644
--- a/WaveDude/Model/LegacyProject.cs
+++ b/WaveDude/Model/LegacyProject.cs
@@ -114,6 +114,8 @@ public static class LegacyProject
{
scene.ImageData = File.ReadAllBytes(imagePath);
scene.Image = Path.GetFileName(imagePath);
+ // the source stays known (absolute: the imported project has no file yet), so the file is watched
+ scene.ImagePath = Path.GetFullPath(imagePath);
}
else
{
diff --git a/WaveDude/Model/ProjectWatcher.cs b/WaveDude/Model/ProjectWatcher.cs
index 9408278..850a862 100644
--- a/WaveDude/Model/ProjectWatcher.cs
+++ b/WaveDude/Model/ProjectWatcher.cs
@@ -16,6 +16,7 @@ public sealed record ProjectChange(object Item, string? Property)
/// </summary>
public bool AffectsSimulation => Item switch
{
+ Scene when Property == nameof(Scene.ImagePath) => false,
Scene or Simulation or Source or SourceArray => true,
Project => Property is nameof(Project.Seed) or nameof(Project.Scene) or nameof(Project.Simulation) or nameof(Project.Sources),
ObservableCollection<ColorScheme> or ObservableCollection<Probe> => false,
diff --git a/WaveDude/Model/Scene.cs b/WaveDude/Model/Scene.cs
index 2895cde..8f0ce66 100644
--- a/WaveDude/Model/Scene.cs
+++ b/WaveDude/Model/Scene.cs
@@ -45,6 +45,7 @@ public sealed class Scene : ObservableObject
private SceneMode _mode = SceneMode.Canvas;
private string _image = "";
+ private string _imagePath = "";
private int _width = DefaultWidth;
private int _height = DefaultHeight;
private int _dampingEdge;
@@ -96,6 +97,59 @@ public sealed class Scene : ObservableObject
/// <summary>Only an embedded image is written.</summary>
public bool ShouldSerializeImageData() => _imageData != null;
+ /// <summary>
+ /// Where the embedded image came from (2026-10-15): the file's path, relative to the project file when it lies
+ /// in that folder (<see cref="StoredImagePath"/>), absolute otherwise, "" when unknown. The application
+ /// watches it while the project is open and re-embeds the file when it changes, and compares it with the
+ /// embedded bytes when the project is opened. Changing the path changes nothing in the simulation.
+ /// </summary>
+ [XmlAttribute]
+ [DefaultValue("")]
+ [Category("Canvas")]
+ [DisplayName("Image file")]
+ [Description("Where the embedded image came from. It is watched while the project is open and re-embedded when it changes; on opening the project a changed file replaces the embedded image too.")]
+ public string ImagePath
+ {
+ get => _imagePath;
+ set => SetProperty(ref _imagePath, value ?? "");
+ }
+
+ /// <summary>The form of <paramref name="fullPath"/> stored in a project: relative to <paramref name="projectFolder"/> when it lies inside it (case-insensitive), else as given.</summary>
+ /// <param name="projectFolder">The project file's folder; null or empty for an unsaved project.</param>
+ /// <param name="fullPath">The image file's absolute path.</param>
+ public static string StoredImagePath(string? projectFolder, string fullPath)
+ {
+ if (string.IsNullOrEmpty(projectFolder) || !Path.IsPathRooted(fullPath))
+ {
+ return fullPath;
+ }
+ string relative = Path.GetRelativePath(projectFolder, fullPath);
+ return relative.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(relative) ? fullPath : relative;
+ }
+
+ /// <summary>The image file's full path: <see cref="ImagePath"/> as given when rooted, resolved against <paramref name="projectFolder"/> when relative; "" when there is no path or no folder to resolve against.</summary>
+ public string ResolveImagePath(string? projectFolder)
+ {
+ if (ImagePath.Length == 0)
+ {
+ return "";
+ }
+ if (Path.IsPathRooted(ImagePath))
+ {
+ return ImagePath;
+ }
+ return string.IsNullOrEmpty(projectFolder) ? "" : Path.GetFullPath(ImagePath, projectFolder);
+ }
+
+ /// <summary>Turns an absolute <see cref="ImagePath"/> inside <paramref name="projectFolder"/> into a relative one (called when the project is saved).</summary>
+ public void RelativizeImagePath(string? projectFolder)
+ {
+ if (Path.IsPathRooted(ImagePath))
+ {
+ ImagePath = StoredImagePath(projectFolder, ImagePath);
+ }
+ }
+
/// <summary>Width of a blank canvas in pixels.</summary>
[XmlAttribute]
[DefaultValue(DefaultWidth)]
@@ -182,7 +236,7 @@ public sealed class Scene : ObservableObject
[XmlIgnore]
[Browsable(false)]
public bool IsDefault =>
- Mode == SceneMode.Canvas && Image.Length == 0 && ImageData == null && Width == DefaultWidth && Height == DefaultHeight
+ Mode == SceneMode.Canvas && Image.Length == 0 && ImagePath.Length == 0 && ImageData == null && Width == DefaultWidth && Height == DefaultHeight
&& DampingEdge == 0 && RefractiveIndex == DefaultRefractiveIndex && !ImageSources
&& ImageSourceScale == DefaultImageSourceScale && ObjectSources;
@@ -190,6 +244,7 @@ public sealed class Scene : ObservableObject
public void Normalize()
{
Image ??= "";
+ ImagePath ??= "";
Width = Math.Clamp(Width, MinSize, MaxSize);
Height = Math.Clamp(Height, MinSize, MaxSize);
DampingEdge = Math.Clamp(DampingEdge, 0, MaxDampingEdge);
diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.cs
index b4b06b6..0306d6f 100644
--- a/_tools/library_check/Program.cs
+++ b/_tools/library_check/Program.cs
@@ -725,6 +725,21 @@ internal static class Program
Project loaded = Project.Load(stream);
Check(loaded.ColorSchemes.Count == 1 && loaded.ColorSchemes[0].Name == "Mine" && loaded.ColorSchemes[0].Colors.SequenceEqual(field.Colors), "a project file embeds its own schemes");
Check(loaded.Scene.ImageData != null && loaded.Scene.ImageData.SequenceEqual(project.Scene.ImageData) && loaded.Scene.Image == "scene.png", "a project file embeds the scene image bytes (base64)");
+ // the image's source path (2026-10-15): relative inside the project folder, absolute elsewhere, resolved back, not a simulation change
+ string projectFolder = Path.Combine(Path.GetTempPath(), "wd-project");
+ Check(Scene.StoredImagePath(projectFolder, Path.Combine(projectFolder, "scenes", "a.png")) == Path.Combine("scenes", "a.png") && Scene.StoredImagePath(projectFolder, Path.Combine(Path.GetTempPath(), "b.png")) == Path.Combine(Path.GetTempPath(), "b.png") && Scene.StoredImagePath(null, Path.Combine(projectFolder, "a.png")) == Path.Combine(projectFolder, "a.png"),
+ "StoredImagePath: relative inside the project folder, absolute outside or without a folder");
+ project.Scene.ImagePath = Path.Combine("scenes", "a.png");
+ Check(project.Scene.ResolveImagePath(projectFolder) == Path.Combine(projectFolder, "scenes", "a.png") && project.Scene.ResolveImagePath(null) == "" && new Scene { ImagePath = Path.Combine(projectFolder, "a.png") }.ResolveImagePath(null) == Path.Combine(projectFolder, "a.png"),
+ "ResolveImagePath: relative needs the folder, absolute does not");
+ using var stream2 = new MemoryStream();
+ project.Save(stream2);
+ stream2.Position = 0;
+ Check(Project.Load(stream2).Scene.ImagePath == Path.Combine("scenes", "a.png"), "the image path round-trips through the file");
+ Check(!new ProjectChange(project.Scene, nameof(Scene.ImagePath)).AffectsSimulation && new ProjectChange(project.Scene, nameof(Scene.ImageData)).AffectsSimulation, "the path is no simulation change, the bytes are");
+ var abs = new Scene { ImagePath = Path.Combine(projectFolder, "a.png") };
+ abs.RelativizeImagePath(projectFolder);
+ Check(abs.ImagePath == "a.png", "RelativizeImagePath on save");
var edited = loaded.ColorSchemes[0];
int changes = 0;
edited.PropertyChanged += (_, args) => changes += args.PropertyName == nameof(ColorScheme.Stops) ? 1 : 0;
@@ -905,6 +920,7 @@ internal static class Program
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(Path.IsPathRooted(p.Scene.ImagePath) && p.Scene.ImagePath.EndsWith(Path.Combine("scene_images", "frequency_race_track (2).png"), StringComparison.OrdinalIgnoreCase), "the import keeps the image's source path (absolute) for the watch");
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");
diff --git a/_tools/ui_check/SceneImageCheck.ps1 b/_tools/ui_check/SceneImageCheck.ps1
new file mode 100644
index 0000000..65f4fc2
--- /dev/null
+++ b/_tools/ui_check/SceneImageCheck.ps1
@@ -0,0 +1,85 @@
+# The embedded scene image follows its file (2026-10-15): a project whose embedded image differs from the file its
+# path names takes the file when opened (the project turns dirty: asterisk in the title), and while the project is
+# open a change of that file on disk is re-embedded within a second (the picture changes, the status bar says so).
+# The project and its image live in a temporary folder; the embedded image is the ball lens, the file the race
+# track, then the file becomes the ball lens again. A second project without a path but with the image by name in
+# a scene_images folder beside it (a project saved before the path existed) must find it there. See Common.ps1
+# for the rules (no mouse, no activation, no UIA patterns). The app is dirty at the end of each phase, so
+# Stop-App's close runs into the save prompt and kills it after 8 s.
+#
+# powershell -ExecutionPolicy Bypass -File _tools\ui_check\SceneImageCheck.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")
+
+$examples = Join-Path $PSScriptRoot "..\..\Wave_Dude_Examples"
+$raceTrack = Join-Path $examples "Example12_Dispersion\scene_images\frequency_race_track (2).png"
+$ballLens = Join-Path $examples "Example4_Ball_lens\scene_images\Ball_lens_high_RI_AR.png"
+$folder = Join-Path $env:TEMP ("wd-scene-" + [Guid]::NewGuid().ToString("N"))
+$null = New-Item -ItemType Directory -Path $folder
+Copy-Item $raceTrack (Join-Path $folder "scene.png")
+$embedded = [Convert]::ToBase64String([IO.File]::ReadAllBytes($ballLens))
+$project = Join-Path $folder "watch.wdproj"
+@"
+<?xml version="1.0" encoding="utf-8"?>
+<Project Version="1" Seed="7">
+ <Scene Mode="Image" Image="scene.png" ImagePath="scene.png" DampingEdge="64">
+ <ImageData>$embedded</ImageData>
+ </Scene>
+ <Simulation Steps="100" VisualizeEvery="2" />
+ <Source Name="Source 1" X="150" Y="140" Frequency="100" />
+</Project>
+"@ | Set-Content -Path $project -Encoding UTF8
+
+Start-App $Exe $project
+try {
+ Check "opening a project whose image file differs from the embedded image takes the file: the project is dirty" (WaitFor { $win.Current.Name -like "*`*" } 5000 100) $win.Current.Name
+ $status = (Find "StatusMessage").Current.Name
+ Check "the status bar says the image was re-embedded on opening" ($status -like "*re-embedded*changed since the project was saved*") $status
+ FocusOn "Tree:Project"
+ Key $VK_DOWN 400 # the Scene node: the Properties pane shows the scene view
+ Check "the scene view shows the image file's path" ((Find "SceneImagePath").Current.Name -eq "scene.png") (Find "SceneImagePath").Current.Name
+ $null = WaitFor { (Find "StatusExport").Current.Name -eq "" } 20000 200
+ Start-Sleep -Milliseconds 500
+ $before = FieldHash
+ # the file changes on disk while the project is open: back to the ball lens
+ Copy-Item $ballLens (Join-Path $folder "scene.png") -Force
+ Check "a change of the file on disk is re-embedded within a moment" (WaitFor { (Find "StatusMessage").Current.Name -like "*re-embedded*changed on disk*" } 6000 100) (Find "StatusMessage").Current.Name
+ Check "and the field picture changes with it" (WaitFor { (FieldHash) -ne $before } 10000 200)
+ Check "app never became the foreground window" ((Foreground) -ne "APP") (Foreground)
+}
+finally {
+ Stop-App
+}
+# a project from before the path existed: the image only by name, the file in scene_images beside the project
+$null = New-Item -ItemType Directory -Path (Join-Path $folder "scene_images")
+Copy-Item $raceTrack (Join-Path $folder "scene_images\old.png")
+$old = Join-Path $folder "old.wdproj"
+@"
+<?xml version="1.0" encoding="utf-8"?>
+<Project Version="1" Seed="7">
+ <Scene Mode="Image" Image="old.png" DampingEdge="64">
+ <ImageData>$embedded</ImageData>
+ </Scene>
+ <Simulation Steps="100" VisualizeEvery="2" />
+ <Source Name="Source 1" X="150" Y="140" Frequency="100" />
+</Project>
+"@ | Set-Content -Path $old -Encoding UTF8
+Start-App $Exe $old
+try {
+ Check "a project without a path finds its image by name in scene_images and takes the changed file" (WaitFor { (Find "StatusMessage").Current.Name -like "*re-embedded*" } 5000 100) (Find "StatusMessage").Current.Name
+ FocusOn "Tree:Project"
+ Key $VK_DOWN 400
+ Check "the found path is stored relative to the project" ((Find "SceneImagePath").Current.Name -eq "scene_images\old.png") (Find "SceneImagePath").Current.Name
+ Check "app never became the foreground window" ((Foreground) -ne "APP") (Foreground)
+}
+finally {
+ Stop-App
+ Remove-Item -Recurse -Force $folder -ErrorAction SilentlyContinue
+}
+Write-Output ("{0} failure(s)" -f $script:failures)
+exit $script:failures