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#
Brightness in each picture's header, with an Auto button that fits it once to the frame shown
Alexander Graef19f1621a15f8
diff --git a/CLAUDE.md b/CLAUDE.mdindex 59e5906..aaf393a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -133,6 +133,10 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDAis paused while a scratch frame computes. Every scratch request is computed, however long.- **A picture changes only when a frame for its position arrives**; otherwise the last picture stays. A long waitdims the pictures under a spinner, mirrored on the taskbar.+- **Brightness** (2026-10-20, Jeroen's point 9) sits in each picture's header strip (`HeaderStrip`: title, a caption that+ gives way first, the box and **Auto** at the far end; turned on its side with the title); Auto fits once to the frame+ shown (the 99.5th percentile of |field| or √intensity at the palette's top, the user's choice of the variants), an+ 8-bit preview computing that frame in 16-bit first; the context menu has Brightness and Auto brightness.- **Play means "show me the simulation"**: it starts an automatic run when needed and holds at the newest frameuntil the run catches up. Live follows a running run until the user scrubs; it ends with a last follow to thefinal frame. A replaced project goes to frame 0; a discarded run keeps the position. In/out points are steps.diff --git a/WaveDudeNext.WPF/Commands/DisplayCommands.cs b/WaveDudeNext.WPF/Commands/DisplayCommands.csnew file mode 100644index 0000000..f352e45--- /dev/null+++ b/WaveDudeNext.WPF/Commands/DisplayCommands.cs@@ -0,0 +1,34 @@+// 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+// Jeroen Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026+// <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>+// 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.Windows.Input;++namespace WaveDudeNext.WPF.Commands;++/// <summary>+/// The pictures' brightness (2026-10-20, Jeroen's point 9: it sat with his previews, here it took a search through+/// the project tree): from the box in each picture's header and the picture's context menu. The parameter is the+/// picture's <see cref="Model.ProbeLayer"/> (the cell's <c>PreviewPane.Layer</c>).+/// </summary>+public static class DisplayCommands+{+ /// <summary>Fits the layer's brightness once to the frame shown (handled by the main window, <c>MainWindow.Display.cs</c>).</summary>+ public static readonly RoutedUICommand AutoBrightness = new("Auto brightness", nameof(AutoBrightness), typeof(DisplayCommands));++ /// <summary>Moves the keyboard focus to the brightness box in the picture's header (handled by the preview pane).</summary>+ public static readonly RoutedUICommand EditBrightness = new("Brightness", nameof(EditBrightness), typeof(DisplayCommands));+}diff --git a/WaveDudeNext.WPF/Controls/HeaderStrip.cs b/WaveDudeNext.WPF/Controls/HeaderStrip.csnew file mode 100644index 0000000..fd4655f--- /dev/null+++ b/WaveDudeNext.WPF/Controls/HeaderStrip.cs@@ -0,0 +1,106 @@+// 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+// Jeroen Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026+// <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>+// 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.Windows;+using System.Windows.Controls;++namespace WaveDudeNext.WPF.Controls;++/// <summary>+/// A picture's header strip (2026-10-20): the title at the start, the tools (the brightness box and its Auto button)+/// at the far end, and a caption just before the tools that is left out when the three do not fit, so the title+/// stays whole on a small picture (a stacked picture turned the strip on its side and cut "Intensity" to "Inter").+/// Children in that order: title, caption, tools; each is centred across the strip. When even the title and the+/// tools do not fit, the title gets what the tools leave. UI thread, like every element.+/// </summary>+public sealed class HeaderStrip : Panel+{+ /// <summary>Identifies the <see cref="Spacing"/> property.</summary>+ public static readonly DependencyProperty SpacingProperty = DependencyProperty.Register(+ nameof(Spacing), typeof(double), typeof(HeaderStrip),+ new FrameworkPropertyMetadata(12.0, FrameworkPropertyMetadataOptions.AffectsMeasure));++ private bool _captionShown = true;++ /// <summary>Least space between the title and what follows it, in pixels.</summary>+ public double Spacing+ {+ get => (double)GetValue(SpacingProperty);+ set => SetValue(SpacingProperty, value);+ }++ /// <inheritdoc/>+ protected override Size MeasureOverride(Size availableSize)+ {+ var unbounded = new Size(double.PositiveInfinity, availableSize.Height);+ double width = 0.0;+ double height = 0.0;+ foreach (UIElement child in InternalChildren)+ {+ child.Measure(unbounded);+ width += child.DesiredSize.Width;+ height = Math.Max(height, child.DesiredSize.Height);+ }+ if (InternalChildren.Count < 3)+ {+ return new Size(Math.Min(width, availableSize.Width), height);+ }+ UIElement title = InternalChildren[0];+ UIElement caption = InternalChildren[1];+ UIElement tools = InternalChildren[2];+ double spacing = Spacing;+ double full = title.DesiredSize.Width + spacing + caption.DesiredSize.Width + tools.DesiredSize.Width;+ _captionShown = full <= availableSize.Width;+ double needed = _captionShown ? full : title.DesiredSize.Width + spacing + tools.DesiredSize.Width;+ if (needed > availableSize.Width)+ {+ // the title takes what the tools leave, trimmed by its own TextTrimming+ title.Measure(new Size(Math.Max(0.0, availableSize.Width - spacing - tools.DesiredSize.Width), availableSize.Height));+ needed = availableSize.Width;+ }+ return new Size(needed, height);+ }++ /// <inheritdoc/>+ protected override Size ArrangeOverride(Size finalSize)+ {+ if (InternalChildren.Count < 3)+ {+ double x = 0.0;+ foreach (UIElement child in InternalChildren)+ {+ child.Arrange(Centred(x, child, finalSize.Height));+ x += child.DesiredSize.Width;+ }+ return finalSize;+ }+ UIElement title = InternalChildren[0];+ UIElement caption = InternalChildren[1];+ UIElement tools = InternalChildren[2];+ double toolsX = Math.Max(0.0, finalSize.Width - tools.DesiredSize.Width);+ tools.Arrange(Centred(toolsX, tools, finalSize.Height));+ double captionX = toolsX - caption.DesiredSize.Width;+ caption.Arrange(_captionShown ? Centred(captionX, caption, finalSize.Height) : new Rect(toolsX, 0.0, 0.0, 0.0));+ double titleWidth = Math.Min(title.DesiredSize.Width, Math.Max(0.0, (_captionShown ? captionX : toolsX) - Spacing));+ title.Arrange(new Rect(0.0, (finalSize.Height - title.DesiredSize.Height) / 2.0, titleWidth, title.DesiredSize.Height));+ return finalSize;+ }++ /// <summary>The child's rectangle at <paramref name="x"/>, at its desired size, centred across the strip.</summary>+ private static Rect Centred(double x, UIElement child, double height) =>+ new(x, (height - child.DesiredSize.Height) / 2.0, child.DesiredSize.Width, child.DesiredSize.Height);+}diff --git a/WaveDudeNext.WPF/MainWindow.Display.cs b/WaveDudeNext.WPF/MainWindow.Display.csnew file mode 100644index 0000000..65ed6c3--- /dev/null+++ b/WaveDudeNext.WPF/MainWindow.Display.cs@@ -0,0 +1,130 @@+// 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+// Jeroen Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026+// <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>+// 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.IO;+using System.Windows;+using System.Windows.Input;+using WaveDudeNext.Engine;+using WaveDudeNext.Model;+using WaveDudeNext.Rendering;+using WaveDudeNext.Runs;+using WaveDudeNext.WPF.Properties;++namespace WaveDudeNext.WPF;++/// <summary>+/// The pictures' Auto brightness (2026-10-20, Jeroen's point 9; the user's choice of the variants: a one-shot fit to+/// the frame shown, the brightness then staying put, so a decaying wave still looks like one). A frame of halves+/// (a 16-bit run, or a scratch frame in 16-bit) is fitted at once; palette indices are clipped at the brightness+/// they were captured with, so for an 8-bit preview the frame is computed once more in 16-bit, on an engine of its+/// own, and fitted when it arrives. The fit is an ordinary brightness edit: in 8-bit it is a simulation edit as+/// any other. UI thread.+/// </summary>+public partial class MainWindow+{+ /// <summary>Computes the 16-bit frame of an 8-bit preview for a fit; null between fits (its engine is released).</summary>+ private ScratchRunner? _fitRunner;++ /// <summary>The layer and frame the pending fit is for.</summary>+ private (ProbeLayer Layer, int Frame) _fitRequest;++ /// <summary>The run paused while the fit's frame computes (the user's frame comes first, as for scratch frames).</summary>+ private SimulationRun? _pausedForFit;++ private void CanAutoBrightness(object sender, CanExecuteRoutedEventArgs e) =>+ e.CanExecute = _fitRunner == null && !IsExporting && Project.Simulation.Steps > 0;++ private void OnAutoBrightness(object sender, ExecutedRoutedEventArgs e)+ {+ ProbeLayer layer = e.Parameter is ProbeLayer.Intensity ? ProbeLayer.Intensity : ProbeLayer.Field;+ FrameLayer plane = PlaneOf(layer);+ if (previewPane.ShownFrame is { Source: { Format: FrameFormat.Half } source, Frame: int shown } && source.Has(plane) && source.Count > 0)+ {+ var halves = new Half[source.Width * source.Height];+ if (source.CopyLayer(Math.Clamp(shown, 0, source.Count - 1), plane, halves))+ {+ ApplyFit(layer, BrightnessFit.For(halves, plane), PreviewPosition);+ return;+ }+ }+ RunSpec spec;+ try+ {+ spec = RunSpec.Create(Project, LoadSceneImage(), Settings.Default.UseGpu, trackIntensity: plane == FrameLayer.Intensity,+ quality: PreviewQualitySetting with { Format = FrameFormat.Half });+ }+ catch (Exception ex) when (ex is RunSpecException or IOException or UnauthorizedAccessException or NotSupportedException)+ {+ Logger.Warn("No brightness fit: {Message}", ex.Message);+ return;+ }+ int frame = Math.Clamp(PreviewPosition, 0, Math.Max(0, spec.FrameCount - 1));+ Logger.Info("Fitting the {Layer} brightness: frame {Frame} is computed in 16-bit", layer == ProbeLayer.Field ? "field" : "intensity", frame);+ if (Run is { IsActive: true } run && !run.IsPauseRequested)+ {+ run.Pause();+ _pausedForFit = run;+ }+ _fitRequest = (layer, frame);+ _fitRunner = new ScratchRunner(SynchronizationContext.Current);+ _fitRunner.Completed += OnFitFrameCompleted;+ _fitRunner.Request(spec, frame);+ CommandManager.InvalidateRequerySuggested();+ }++ private void OnFitFrameCompleted(object? sender, ScratchResult result)+ {+ ScratchRunner? runner = _fitRunner;+ _fitRunner = null;+ if (runner != null)+ {+ runner.Completed -= OnFitFrameCompleted;+ }+ if (_pausedForFit is { } paused)+ {+ _pausedForFit = null;+ if (ReferenceEquals(paused, Run) && paused.IsActive)+ {+ paused.Resume();+ }+ }+ FrameLayer plane = PlaneOf(_fitRequest.Layer);+ var source = new SnapshotFrameSource(result.Snapshot);+ var halves = new Half[source.Width * source.Height];+ double? fit = source.Has(plane) && source.CopyLayer(0, plane, halves) ? BrightnessFit.For(halves, plane) : null;+ // the runner's engine is released once its result is read (the snapshot belongs to the runner)+ runner?.Dispose();+ ApplyFit(_fitRequest.Layer, fit, result.Frame);+ CommandManager.InvalidateRequerySuggested();+ }++ /// <summary>Sets the fitted brightness on the layer, or says there was nothing to fit.</summary>+ private void ApplyFit(ProbeLayer layer, double? fit, int frame)+ {+ string name = layer == ProbeLayer.Field ? "field" : "intensity";+ DisplayLayer settings = layer == ProbeLayer.Field ? Project.Display.Field : Project.Display.Intensity;+ if (fit is not { } brightness)+ {+ Logger.Info("No {Layer} brightness fitted: frame {Frame} is empty", name, frame);+ return;+ }+ Logger.Info("The {Layer} brightness is fitted to frame {Frame}: {Old:G4} becomes {New:G4}", name, frame, settings.Brightness, brightness);+ settings.Brightness = brightness;+ }++ private static FrameLayer PlaneOf(ProbeLayer layer) => layer == ProbeLayer.Intensity ? FrameLayer.Intensity : FrameLayer.Field;+}diff --git a/WaveDudeNext.WPF/MainWindow.xaml b/WaveDudeNext.WPF/MainWindow.xamlindex d146d20..3b32f1f 100644--- a/WaveDudeNext.WPF/MainWindow.xaml+++ b/WaveDudeNext.WPF/MainWindow.xaml@@ -173,6 +173,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<CommandBinding Command="{x:Static commands:ViewCommands.SetPreviewResolution}" Executed="OnSetPreviewResolution" /><CommandBinding Command="{x:Static commands:ViewCommands.SetPreviewFrames}" Executed="OnSetPreviewFrames" /><CommandBinding Command="{x:Static commands:ViewCommands.SetPreviewSamples}" Executed="OnSetPreviewSamples" />+ <!-- the pictures' Auto brightness; handler in MainWindow.Display.cs -->+ <CommandBinding Command="{x:Static commands:DisplayCommands.AutoBrightness}" CanExecute="CanAutoBrightness" Executed="OnAutoBrightness" /><!-- project structure; handlers in MainWindow.Project.cs --><CommandBinding Command="{x:Static commands:ProjectCommands.AddSource}" Executed="OnAddSource" />diff --git a/WaveDudeNext.WPF/Panes/PreviewPane.xaml b/WaveDudeNext.WPF/Panes/PreviewPane.xamlindex 63d7d83..965e207 100644--- a/WaveDudeNext.WPF/Panes/PreviewPane.xaml+++ b/WaveDudeNext.WPF/Panes/PreviewPane.xaml@@ -24,6 +24,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file orxmlns:converters="clr-namespace:WaveDudeNext.WPF.Converters"xmlns:controls="clr-namespace:WaveDudeNext.WPF.Controls"xmlns:commands="clr-namespace:WaveDudeNext.WPF.Commands"+ xmlns:model="clr-namespace:WaveDudeNext.Model;assembly=WaveDudeNext"Background="{DynamicResource DocumentBackground}" Focusable="True" IsTabStop="False"><UserControl.Resources>@@ -360,6 +361,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<CommandBinding Command="{x:Static commands:PreviewCommands.ClearRange}" CanExecute="CanClearRange" Executed="OnClearRange" /><CommandBinding Command="{x:Static commands:PreviewCommands.ToggleLoop}" CanExecute="CanTransport" Executed="OnToggleLoop" /><CommandBinding Command="{x:Static commands:PreviewCommands.ToggleLive}" CanExecute="CanToggleLive" Executed="OnToggleLive" />+ <CommandBinding Command="{x:Static commands:DisplayCommands.EditBrightness}" Executed="OnEditBrightness" /></UserControl.CommandBindings><!-- plain letters are not valid KeyGestures on a command, so these live here; CanTransport keeps them out of text boxes --><UserControl.InputBindings>@@ -522,9 +524,26 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type HeaderedContentControl}">- <!-- the label goes above the picture, or rotated to its left when the cell is wider than the picture -->+ <!-- the label goes above the picture, or rotated to its left when the cell is wider than the picture; it is a+ strip of the title and, at its far end, the layer's brightness with its Auto button (2026-10-20, Jeroen's+ point 9: his previews had the scale factor beside them), so turned on the side the box and button turn+ with it and end at the picture's bottom edge; the caption gives way first when the strip is short --><controls:PictureFrame>- <TextBlock Style="{StaticResource PictureLabel}" Text="{TemplateBinding Header}" />+ <controls:HeaderStrip Margin="0,10,0,4">+ <TextBlock Style="{StaticResource PictureLabel}" Margin="0" TextTrimming="CharacterEllipsis" Text="{TemplateBinding Header}" />+ <TextBlock Text="{DynamicResource Label.DisplayLayer.Brightness}" Foreground="{DynamicResource WindowForeground}" Margin="0,0,4,0" />+ <StackPanel Orientation="Horizontal">+ <controls:NumberBox x:Name="brightnessBox" Width="64" Minimum="0.0001" Maximum="100000"+ Text="{Binding Path=(local:PreviewPane.Settings).Brightness, RelativeSource={RelativeSource TemplatedParent}}"+ ToolTip="{DynamicResource Hint.DisplayLayer.Brightness}"+ AutomationProperties.Name="{DynamicResource Label.DisplayLayer.Brightness}"+ AutomationProperties.AutomationId="{Binding Tag, RelativeSource={RelativeSource TemplatedParent}, StringFormat={}{0}Brightness}" />+ <Button Margin="4,0,0,0" Padding="6,0" Content="{DynamicResource ButtonAutoBrightness}" ToolTip="{DynamicResource TipAutoBrightness}"+ Command="{x:Static commands:DisplayCommands.AutoBrightness}"+ CommandParameter="{Binding Path=(local:PreviewPane.Layer), RelativeSource={RelativeSource TemplatedParent}}"+ AutomationProperties.AutomationId="{Binding Tag, RelativeSource={RelativeSource TemplatedParent}, StringFormat={}{0}AutoBrightness}" />+ </StackPanel>+ </controls:HeaderStrip><!-- the picture with the source/probe handles over it; both fill the same rectangle --><Grid><Image Source="{TemplateBinding Content}" Stretch="Uniform" AutomationProperties.AutomationId="{TemplateBinding Tag}" />@@ -627,17 +646,20 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<RowDefinition Height="*" /></Grid.RowDefinitions><HeaderedContentControl x:Name="fieldCell" Style="{StaticResource PictureCell}" Header="{DynamicResource SectionField}"- Content="{Binding FieldImage, ElementName=pane}" Tag="PreviewFieldImage" local:PreviewPane.Layer="Field"+ Content="{Binding FieldImage, ElementName=pane}" Tag="PreviewFieldImage" local:PreviewPane.Layer="Field" local:PreviewPane.Settings="{Binding FieldSettings, ElementName=pane}"local:PreviewPane.OverlayImage="{Binding FieldOverlay, ElementName=pane}"Visibility="{Binding FieldSettings.Preview, ElementName=pane, Converter={StaticResource BoolToVisibility}, FallbackValue=Visible}"><HeaderedContentControl.ContextMenu>- <!-- a still of this picture first, then the exports in the File menu's order; the commands route from the cell (CommandTarget) up to the window -->+ <!-- the brightness first, then a still of this picture, then the exports in the File menu's order; the commands route from the cell (CommandTarget) up to the pane and the window --><ContextMenu><ContextMenu.Resources><Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}"><Setter Property="CommandTarget" Value="{Binding PlacementTarget, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" /></Style></ContextMenu.Resources>+ <MenuItem Header="{DynamicResource MenuBrightness}" Command="{x:Static commands:DisplayCommands.EditBrightness}" CommandParameter="{x:Static model:ProbeLayer.Field}" AutomationProperties.AutomationId="ContextBrightness" />+ <MenuItem Header="{DynamicResource MenuAutoBrightness}" Command="{x:Static commands:DisplayCommands.AutoBrightness}" CommandParameter="{x:Static model:ProbeLayer.Field}" AutomationProperties.AutomationId="ContextAutoBrightness" />+ <Separator /><MenuItem Header="{DynamicResource MenuExportThisFrame}" Command="{x:Static commands:ExportCommands.FieldFrame}" AutomationProperties.AutomationId="ContextExportFrame" /><Separator /><MenuItem Header="{DynamicResource MenuFileExportField}" Command="{x:Static commands:ExportCommands.Field}" AutomationProperties.AutomationId="ContextExportField" />@@ -650,17 +672,20 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file orAutomationProperties.Name="{DynamicResource TipPreviewSplitter}" AutomationProperties.AutomationId="PreviewSplitter"MouseDoubleClick="OnSplitterMouseDoubleClick" KeyDown="OnSplitterKeyDown" /><HeaderedContentControl x:Name="intensityCell" Style="{StaticResource SecondPictureCell}" Header="{DynamicResource SectionIntensity}"- Content="{Binding IntensityImage, ElementName=pane}" Tag="PreviewIntensityImage" local:PreviewPane.Layer="Intensity"+ Content="{Binding IntensityImage, ElementName=pane}" Tag="PreviewIntensityImage" local:PreviewPane.Layer="Intensity" local:PreviewPane.Settings="{Binding IntensitySettings, ElementName=pane}"local:PreviewPane.OverlayImage="{Binding IntensityOverlay, ElementName=pane}"Visibility="{Binding IntensitySettings.Preview, ElementName=pane, Converter={StaticResource BoolToVisibility}, FallbackValue=Visible}"><HeaderedContentControl.ContextMenu>- <!-- a still of this picture first, then the exports in the File menu's order; the commands route from the cell (CommandTarget) up to the window -->+ <!-- the brightness first, then a still of this picture, then the exports in the File menu's order; the commands route from the cell (CommandTarget) up to the pane and the window --><ContextMenu><ContextMenu.Resources><Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}"><Setter Property="CommandTarget" Value="{Binding PlacementTarget, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" /></Style></ContextMenu.Resources>+ <MenuItem Header="{DynamicResource MenuBrightness}" Command="{x:Static commands:DisplayCommands.EditBrightness}" CommandParameter="{x:Static model:ProbeLayer.Intensity}" AutomationProperties.AutomationId="ContextBrightness" />+ <MenuItem Header="{DynamicResource MenuAutoBrightness}" Command="{x:Static commands:DisplayCommands.AutoBrightness}" CommandParameter="{x:Static model:ProbeLayer.Intensity}" AutomationProperties.AutomationId="ContextAutoBrightness" />+ <Separator /><MenuItem Header="{DynamicResource MenuExportThisFrame}" Command="{x:Static commands:ExportCommands.IntensityFrame}" AutomationProperties.AutomationId="ContextExportFrame" /><Separator /><MenuItem Header="{DynamicResource MenuFileExportField}" Command="{x:Static commands:ExportCommands.Field}" AutomationProperties.AutomationId="ContextExportField" />diff --git a/WaveDudeNext.WPF/Panes/PreviewPane.xaml.cs b/WaveDudeNext.WPF/Panes/PreviewPane.xaml.csindex b6a0bfe..348a16a 100644--- a/WaveDudeNext.WPF/Panes/PreviewPane.xaml.cs+++ b/WaveDudeNext.WPF/Panes/PreviewPane.xaml.cs@@ -185,6 +185,23 @@ public partial class PreviewPane : UserControlpublic static void SetLayer(DependencyObject element, ProbeLayer value) => element.SetValue(LayerProperty, value);+ /// <summary>Attached to each picture cell: the display settings of its layer, which the brightness box in its header edits.</summary>+ public static readonly DependencyProperty SettingsProperty = DependencyProperty.RegisterAttached(+ "Settings", typeof(DisplayLayer), typeof(PreviewPane));++ public static DisplayLayer? GetSettings(DependencyObject element) => (DisplayLayer?)element.GetValue(SettingsProperty);++ public static void SetSettings(DependencyObject element, DisplayLayer? value) => element.SetValue(SettingsProperty, value);++ /// <summary>+ /// The frames the pictures show and the index of the one shown (the scratch frame, index 0, or the run's frame at the+ /// position), or null when nothing is shown; for the brightness fit. UI thread.+ /// </summary>+ public (IFrameSource Source, int Frame)? ShownFrame => _presenter.Source is { } source ? (source, _shownFrame) : null;++ /// <summary>Index of the frame last asked of the presenter in its source (see <see cref="ShownFrame"/>).</summary>+ private int _shownFrame;+/// <summary>Identifies the <see cref="IntensityImage"/> property.</summary>public static readonly DependencyProperty IntensityImageProperty = DependencyProperty.Register(nameof(IntensityImage), typeof(ImageSource), typeof(PreviewPane));@@ -662,6 +679,7 @@ public partial class PreviewPane : UserControl_presenter.Source = _scratchSource;GraphScratch = scratch;UpdateCanvas(_scratchSource);+ _shownFrame = 0;_presenter.Show(0);}else if (run != null && run.FrameCount > Position)@@ -671,6 +689,7 @@ public partial class PreviewPane : UserControl// the stored frame is right even with the probes stale; the graphs then take the scratch recording for this position once it is thereGraphScratch = IsProbesStale && scratch is { Snapshot: not null } && scratch.Frame == Position ? scratch : null;UpdateCanvas(run.Frames);+ _shownFrame = Position;_presenter.Show(Position);}else if (run == null && scratch == null && _presenter.Source != null)@@ -1164,4 +1183,15 @@ public partial class PreviewPane : UserControlnext.Focus();e.Handled = true;}++ /// <summary>The context menu's "Brightness": the keyboard focus goes to the brightness box in that picture's header.</summary>+ private void OnEditBrightness(object sender, ExecutedRoutedEventArgs e)+ {+ HeaderedContentControl cell = e.Parameter is ProbeLayer.Intensity ? intensityCell : fieldCell;+ if (cell.Template?.FindName("brightnessBox", cell) is UIElement box)+ {+ box.Focus();+ Keyboard.Focus(box);+ }+ }}diff --git a/WaveDudeNext.WPF/Strings/Strings.DE.xaml b/WaveDudeNext.WPF/Strings/Strings.DE.xamlindex 1fe572c..927de06 100644--- a/WaveDudeNext.WPF/Strings/Strings.DE.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.DE.xaml@@ -39,6 +39,10 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="MenuFileExportFieldFrame">Feld-Ein_zelbild exportieren...</s:String><s:String x:Key="MenuFileExportIntensityFrame">Intensitäts-Einzelbild e_xportieren...</s:String><s:String x:Key="MenuExportThisFrame">_Dieses Bild exportieren...</s:String>+ <s:String x:Key="MenuBrightness">_Helligkeit</s:String>+ <s:String x:Key="MenuAutoBrightness">_Automatische Helligkeit</s:String>+ <s:String x:Key="ButtonAutoBrightness">Auto</s:String>+ <s:String x:Key="TipAutoBrightness">Die Helligkeit einmal an das gezeigte Bild anpassen: das hellste halbe Prozent erreicht das obere Ende des Farbschemas. Die Helligkeit bleibt danach, wie sie ist.</s:String><s:String x:Key="MenuExportProbeCsv">Sonden_daten als CSV exportieren...</s:String><s:String x:Key="MenuFileExit">_Beenden</s:String><s:String x:Key="MenuView">_Ansicht</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.EN.xaml b/WaveDudeNext.WPF/Strings/Strings.EN.xamlindex 83a701a..2767c88 100644--- a/WaveDudeNext.WPF/Strings/Strings.EN.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.EN.xaml@@ -39,6 +39,10 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="MenuFileExportFieldFrame">Export field f_rame...</s:String><s:String x:Key="MenuFileExportIntensityFrame">Export intensity fra_me...</s:String><s:String x:Key="MenuExportThisFrame">Export _this frame...</s:String>+ <s:String x:Key="MenuBrightness">_Brightness</s:String>+ <s:String x:Key="MenuAutoBrightness">_Auto brightness</s:String>+ <s:String x:Key="ButtonAutoBrightness">Auto</s:String>+ <s:String x:Key="TipAutoBrightness">Fit the brightness once to the frame shown: the brightest half percent of it reaches the top of the colour scheme. The brightness then stays as it is.</s:String><s:String x:Key="MenuExportProbeCsv">Export probe _data as CSV...</s:String><s:String x:Key="MenuFileExit">E_xit</s:String><s:String x:Key="MenuView">_View</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.FR.xaml b/WaveDudeNext.WPF/Strings/Strings.FR.xamlindex 0b59346..72f2958 100644--- a/WaveDudeNext.WPF/Strings/Strings.FR.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.FR.xaml@@ -39,6 +39,10 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="MenuFileExportFieldFrame">Exporter l'i_mage du champ...</s:String><s:String x:Key="MenuFileExportIntensityFrame">Exporter l'image de l'intensi_té...</s:String><s:String x:Key="MenuExportThisFrame">Exporter _cette image...</s:String>+ <s:String x:Key="MenuBrightness">_Luminosité</s:String>+ <s:String x:Key="MenuAutoBrightness">Luminosité _automatique</s:String>+ <s:String x:Key="ButtonAutoBrightness">Auto</s:String>+ <s:String x:Key="TipAutoBrightness">Ajuster une fois la luminosité à l'image affichée : le demi-pour-cent le plus clair atteint le haut du jeu de couleurs. La luminosité reste ensuite telle quelle.</s:String><s:String x:Key="MenuExportProbeCsv">Exporter les _données de la sonde en CSV...</s:String><s:String x:Key="MenuFileExit">_Quitter</s:String><s:String x:Key="MenuView">_Affichage</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.NL.xaml b/WaveDudeNext.WPF/Strings/Strings.NL.xamlindex aa18fba..5526038 100644--- a/WaveDudeNext.WPF/Strings/Strings.NL.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.NL.xaml@@ -39,6 +39,10 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="MenuFileExportFieldFrame">Veld_beeld exporteren...</s:String><s:String x:Key="MenuFileExportIntensityFrame">Intensiteitsbeel_d exporteren...</s:String><s:String x:Key="MenuExportThisFrame">_Dit beeld exporteren...</s:String>+ <s:String x:Key="MenuBrightness">_Helderheid</s:String>+ <s:String x:Key="MenuAutoBrightness">_Automatische helderheid</s:String>+ <s:String x:Key="ButtonAutoBrightness">Auto</s:String>+ <s:String x:Key="TipAutoBrightness">De helderheid eenmalig aan het getoonde beeld aanpassen: de helderste halve procent bereikt de bovenkant van het kleurenschema. De helderheid blijft daarna zoals ze is.</s:String><s:String x:Key="MenuExportProbeCsv">Sonde_gegevens als CSV exporteren...</s:String><s:String x:Key="MenuFileExit">A_fsluiten</s:String><s:String x:Key="MenuView">Beel_d</s:String>diff --git a/WaveDudeNext/Rendering/BrightnessFit.cs b/WaveDudeNext/Rendering/BrightnessFit.csnew file mode 100644index 0000000..ef2e0ba--- /dev/null+++ b/WaveDudeNext/Rendering/BrightnessFit.cs@@ -0,0 +1,118 @@+// 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+// Jeroen Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026+// <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>+// 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 WaveDudeNext.Runs;++namespace WaveDudeNext.Rendering;++/// <summary>+/// The display brightness that fits a frame (the preview's Auto, 2026-10-20, Jeroen's point 9): the gain that brings+/// the <see cref="Percentile"/> of the coloured magnitude to the top of the palette, |value| for the field and+/// √value for the intensity (the renderer's own mappings, see <see cref="ColorLut"/>), so the brightest half percent+/// saturates and a source cell, far above the field around it, does not darken the picture. Pure arithmetic; any+/// thread.+/// </summary>+public static class BrightnessFit+{+ /// <summary>The share of the samples at or below the value brought to the top of the palette.</summary>+ public const double Percentile = 0.995;++ /// <summary>+ /// The brightness that fits <paramref name="samples"/> of <paramref name="layer"/>, rounded to three significant+ /// digits and clamped to the model's range (1e-4 to 1e5); null when the frame has nothing to fit (every sample+ /// zero or not finite).+ /// </summary>+ /// <param name="samples">One plane of a frame, as stored.</param>+ /// <param name="layer">The plane: the field is coloured by its value, the intensity by its square root.</param>+ public static double? For(ReadOnlySpan<Half> samples, FrameLayer layer)+ {+ float[] magnitudes = new float[samples.Length];+ int count = 0;+ foreach (Half sample in samples)+ {+ float value = (float)sample;+ if (float.IsFinite(value))+ {+ magnitudes[count++] = layer == FrameLayer.Intensity ? MathF.Sqrt(MathF.Max(0f, value)) : MathF.Abs(value);+ }+ }+ if (count == 0)+ {+ return null;+ }+ int rank = Math.Min(count - 1, (int)Math.Floor(Percentile * (count - 1)));+ double top = Select(magnitudes.AsSpan(0, count), rank);+ if (!(top > 0.0))+ {+ return null;+ }+ double brightness = Math.Clamp(1.0 / top, 1e-4, 1e5);+ // rounded by decimal places, which gives the nearest double (33.3, not 333 × 0.1 = 33.300000000000004)+ int digits = 2 - (int)Math.Floor(Math.Log10(brightness));+ if (digits >= 0)+ {+ return Math.Round(brightness, digits);+ }+ double unit = Math.Pow(10.0, -digits);+ return Math.Round(brightness / unit) * unit;+ }++ /// <summary>The value of rank <paramref name="rank"/> (0-based, ascending) of <paramref name="values"/>, which it reorders: Hoare's quickselect with a median-of-three pivot.</summary>+ private static float Select(Span<float> values, int rank)+ {+ int lo = 0;+ int hi = values.Length - 1;+ while (lo < hi)+ {+ int mid = lo + (hi - lo) / 2;+ float a = values[lo], b = values[mid], c = values[hi];+ float pivot = a < b ? (b < c ? b : a < c ? c : a) : (a < c ? a : b < c ? c : b);+ int i = lo;+ int j = hi;+ while (i <= j)+ {+ while (values[i] < pivot)+ {+ i++;+ }+ while (values[j] > pivot)+ {+ j--;+ }+ if (i <= j)+ {+ (values[i], values[j]) = (values[j], values[i]);+ i++;+ j--;+ }+ }+ if (rank <= j)+ {+ hi = j;+ }+ else if (rank >= i)+ {+ lo = i;+ }+ else+ {+ return values[rank];+ }+ }+ return values[lo];+ }+}diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.csindex 4c03a11..190e338 100644--- a/_tools/library_check/Program.cs+++ b/_tools/library_check/Program.cs@@ -266,6 +266,7 @@ internal static class ProgramCheckImport();CheckParts();CheckAbsorbingParts();+ CheckBrightnessFit();CheckRun();ExportChecks.Run(Check);@@ -2259,6 +2260,33 @@ internal static class Program}}+ private static void CheckBrightnessFit()+ {+ Console.WriteLine("--- brightness fit");+ // 10 000 samples: |v| = 0.001 × i for i in 0..9999 (sign alternating), one source cell of 50 among them+ var field = new Half[10_000];+ for (int i = 0; i < field.Length; i++)+ {+ field[i] = (Half)((i % 2 == 0 ? 1 : -1) * 0.001f * i);+ }+ field[1234] = (Half)50f;+ double? fit = BrightnessFit.For(field, FrameLayer.Field);+ // the 99.5th percentile of |v| is about 9.95 (the source cell moves it by one rank), so the gain is about 0.1+ Check(fit is >= 0.099 and <= 0.102, "the field fit brings the 99.5th percentile of |value| to the palette's top, a source cell of 50 aside (" + fit + ")");+ var intensity = new Half[10_000];+ for (int i = 0; i < intensity.Length; i++)+ {+ intensity[i] = (Half)(0.0001f * i);+ }+ double? intensityFit = BrightnessFit.For(intensity, FrameLayer.Intensity);+ // √(0.0001 × 9949) = 0.9974, its inverse 1.003, three digits+ Check(intensityFit == 1.0, "the intensity fit works on the square root, as the renderer colours it (" + intensityFit + ")");+ Check(BrightnessFit.For(new Half[100], FrameLayer.Field) == null && BrightnessFit.For([Half.NaN, Half.PositiveInfinity], FrameLayer.Field) == null, "an empty frame has nothing to fit");+ Check(BrightnessFit.For([(Half)1e-6f, (Half)1e-6f], FrameLayer.Field) == 1e5, "the fit is clamped to the model's range (1e5 at most)");+ double? rounded = BrightnessFit.For([(Half)0.03f, (Half)0.03f], FrameLayer.Field);+ Check(rounded is { } r && r.ToString(CultureInfo.InvariantCulture).Length <= 4, "the fit is rounded to three significant digits (" + rounded + ")");+ }+private static void CheckRun(){Console.WriteLine("--- run");diff --git a/_tools/ui_check/PreviewCheck.ps1 b/_tools/ui_check/PreviewCheck.ps1index abd25a3..bf22375 100644--- a/_tools/ui_check/PreviewCheck.ps1+++ b/_tools/ui_check/PreviewCheck.ps1@@ -45,9 +45,10 @@ try {FocusOn "PreviewPlay"Check "Tab reaches play while the window stays inactive" (((FocusedId) -eq "PreviewPlay") -and ((Foreground) -ne "APP")) (FocusedId)$order = @()- for ($i = 0; $i -lt 12; $i++) { Key $VK_TAB 120; $order += (FocusedId) }- # pause, clear-range and live are disabled and skipped; the split group is one stop (its checked radio); timeline; splitter; then the pane is left- Check "tab order play > step back/forward > in > out > loop > speed > show field/intensity > split > timeline > splitter > out of the pane" (($order[0..10] -join ",") -eq "PreviewStepBack,PreviewStepForward,PreviewSetIn,PreviewSetOut,PreviewLoop,PreviewSpeed,PreviewShowField,PreviewShowIntensity,PreviewSideBySide,PreviewTimeline,PreviewSplitter" -and $order[11] -notlike "Preview*") ($order -join ",")+ for ($i = 0; $i -lt 16; $i++) { Key $VK_TAB 120; $order += (FocusedId) }+ # pause, clear-range and live are disabled and skipped; the split group is one stop (its checked radio); timeline; each picture's+ # brightness box and Auto button in its header (2026-10-20), the splitter between them; then the pane is left+ Check "tab order play > step back/forward > in > out > loop > speed > show field/intensity > split > timeline > field brightness > splitter > intensity brightness > out of the pane" (($order[0..14] -join ",") -eq "PreviewStepBack,PreviewStepForward,PreviewSetIn,PreviewSetOut,PreviewLoop,PreviewSpeed,PreviewShowField,PreviewShowIntensity,PreviewSideBySide,PreviewTimeline,PreviewFieldImageBrightness,PreviewFieldImageAutoBrightness,PreviewSplitter,PreviewIntensityImageBrightness,PreviewIntensityImageAutoBrightness" -and $order[15] -notlike "Preview*") ($order -join ",")# the picture toggles: Space on the intensity toggle hides that picture, again shows itFocusOn "PreviewShowIntensity"$fwBoth = (Find "PreviewFieldImage").Current.BoundingRectangle.Width