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#
Probe graphs over the preview, live from scratch frames; probe edits never start a run
Alexander Graefc3107ec1716e
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8dd6ab8..210e222 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -46,7 +46,7 @@ WPF shell as it stands:and closing the window discard the run and delete its cache file.- **Live editing** (`MainWindow.Live.cs`, 2026-10-09): a `ProjectWatcher` reports every modelchange; a simulation-affecting one (`ProjectChange.AffectsSimulation`: scene, solver, seed,- sources; not display or probes) marks the run **stale** (`IsRunStale`: status text gets+ sources; not display settings and not probes) marks the run **stale** (`IsRunStale`: status text gets", edited since", the timeline's available shading turns grey), asks the `ScratchRunner` for theframe the preview shows (debounced 120 ms, also on scrubbing while stale or without a run) and,with the persisted setting **Simulation > Re-run automatically after edits** (`AutoRerun`, default@@ -69,7 +69,18 @@ WPF shell as it stands:Opening a project requests frame 0 right away so the engine (an OpenCL compile) is built beforethe first click. While a scratch frame computes, an active automatic run is paused (on the CPU therun would otherwise take every core and the frame never arrives) and resumed when it is there; an- automatic run is not started while a scratch frame computes. **A picture changes only when a frame+ automatic run is not started while a scratch frame computes or is requested. **A probe edit never+ starts a run** (the user's rule, 2026-10-14: a probe never changes the picture): what a probe measures+ (`Probe.AffectsMeasurement`: position, kind, layer, measurement, start step, name, active, add/remove;+ `ProjectChange.AffectsProbes`) marks only the run's recordings stale (`IsProbesStale`, no grey shading, no+ ", edited since"), the pictures keep the stored frames, a scratch frame is requested for the position and+ the graphs draw from its recording (`PreviewPane.GraphScratch`, also while the picture is the stored+ frame), and Play or F5 starts the run that refreshes the recordings (`OnEnsureRun`). A probe's graph+ settings change nothing but the drawing. Since 2026-10-14 (the user's+ rule: the frame being looked at comes first) **any** active run is paused while a scratch frame computes,+ one the user started too, and resumed when the frame is there; a run the user paused stays paused. The GPU+ engine compiles its probe program once per engine (`_probeProgram`), not per `SetProbes`, since the scratch+ runner installs the probes on every request. **A picture changes only when a framefor the position itself arrives** (scratch or stored); with nothing for it yet the last picturestays. Showing the run's newest frame meanwhile was tried twice and rejected both times: it readsas a replay from frame 0 (2026-10-10). That rule also holds without a run: the presenter is@@ -174,6 +185,51 @@ WPF shell as it stands:attributes said on 2026-10-14. **Adding a model property means adding its keys to all fourtables** (the key-set check in the notes' verification list catches a missing one). Notlocalised: log messages.+- **Probe graphs** (2026-10-14, the author's point 7, first half): every active probe's graph box is drawn+ over the picture of its layer, as the author's app did (translucent dark box, axes with "nice" ticks,+ yellow curve, title strip with the live readout "= value" / "max value"). The numbers live in the+ library, `Probes/ProbeGraph` (a port of `ProbeGraphPainter` without GDI+: `BoxInCanvas`, `ComputeRanges`,+ `NiceTicks`, `Snap`, `Layout` giving a `ProbeGraphLayout` of plot rectangle, ticks with labels, the curve+ reduced to a min/max pair per pixel column, title and readout; harness-checked against the author's+ arithmetic), the WPF side only draws: `Controls/ProbeGraphOverlay`, a panel in each picture cell under+ the `SceneOverlay` (so a handle over a box stays grabbable; the scene overlay lost its transparent+ background for that), told its layer by the attached `PreviewPane.Layer`. **The graph is as live as the+ picture** (the user's rule): it shows the run's recording as it stood at the frame shown, the series cut+ off at that step and, for a line probe, the profile recorded with that frame. For that the collector reads+ the line profiles once per recorded frame (`ProbeTrace.Profiles`, indexed by frame, `ProbeGraphData.At`),+ no longer at 20 Hz. **Before a run, or while it is stale, the graph is live from the scratch frame**: the+ `ScratchRunner` installs the spec's probes on its kept engine per request and samples them on its way to+ the frame (a kernel launch per step, nothing against the stepping), and `ScratchResult.Traces` carries the+ series up to that step and the frame's one profile; the pane exposes the scratch frame it shows as+ `ShownScratch`, and the overlay's data comes from it whenever it is set (the same "a picture changes only+ when its frame arrives" rule, so graph and picture always agree). A probe's trace is found through+ `ProbeSpec.Origin`, the model probe as an identity key, so a rename keeps the graph. **The graph follows+ the picture, whatever is on it** (2026-10-14, after a flicker on every scrub step): while the pane shows a+ stored frame of a stale run, the box shows that run's (stale) data for the frame, and a profile the run has+ not delivered yet (its probe batches trail its frames by up to 50 ms; a scrub can run ahead) is stood in for+ by the newest one (`ProbeGraphData.At`), so the axis never drops to the fixed range for a moment. **The box+ follows the probe while it is attached** (the user's rule, one attachment, not one per axis, 2026-10-14):+ `Probe.IsBoxAttached` is the box anchor sitting on point A; `Probe.AX`/`AY` then move `BoxX`/`BoxY` along (in+ the model, so every editor does it). Dragging the box within 14 screen pixels of point A snaps it on, and+ an attached box comes off only when dragged more than 28 pixels away (hysteresis, after an attach/detach+ flicker at the edge; `ProbeGraphOverlay.SetBoxPosition`, drags only, keyboard nudges stay exact); dragging+ the probe onto its detached box picks the box up the same way (`SceneOverlay.SetPoint`). Each box is a `MarkerThumb` (role `ProbeBox`, id `ProbeBox:<name>`): drag moves it,+ the arrow keys nudge it, writing `BoxX`/`BoxY`; a 12 px grip at the bottom-right corner (role+ `ProbeBoxCorner`, id `ProbeBoxCorner:<name>`) resizes it, **snapping to the fixed sizes** within 8 % or+ making it `ProbeBoxSize.Custom` with `Probe.BoxWidth`/`BoxHeight` (new, serialised only for Custom, 60 to+ 4096; the probe view's width/height boxes are enabled only then). Grabbing or focusing a box selects the+ probe in the tree; the tree node no longer takes the focus when the selection comes from the preview+ (`ProjectTree.Select(item, focus: false)`; it did, which broke the Tab cycle through the handles).+ Colours are the author's, fixed, not themed: the box sits on the picture. **Text does not scale with the+ box** (changed 2026-10-14 after the author's box-height-over-14 rule gave 9 px labels on small boxes):+ the overlay sets 11 px like the handle labels and hands the layout a `ProbeGraphStyle` (font size, line+ height, a measure function); the layout takes the margins from the measured labels (widest value label+ left, one line below), uses fewer ticks when labels would collide, drops the labels before the plot when+ the box is too small, and the renderer keeps the x labels inside the box. An export passes its own style+ in canvas pixels. **An auto-scaled value axis is symmetric about zero** for an amplitude (±largest+ magnitude + 8 %), from zero up for an intensity, and stays at the fixed range while the data is all zeros+ (`ProbeGraph.AutoRange`, 2026-10-14, the user's rule: the author's independent fit of both ends made the+ zero line wander and the labels flicker while the first oscillations arrived). Still open: the signal lane under the timeline (roadmap) and the box in exports.- Preview document: `Panes/PreviewPane`. Two pictures (field,intensity) side by side or stacked (`Orientation`, persisted as the `PreviewOrientation` usersetting), each centred in its cell with its label laid out by `Controls/PictureFrame` (label above@@ -304,7 +360,14 @@ passing harnesses for comfort, never all of them after an edit.and the embedded scene image bytes; editing a stop notifies once; a headless `SimulationRun` (CPU, Completed,frames and probe trace counted) and a GPU run paused, resumed and stopped; a 1 GB full-HD storemust dispose in under 1.5 s (no flush); `CaptureFrame`/`AwaitFrame` (deferred, both planes),- `Reset` reproducing a run and `SetEmitters` matching a fresh engine, on both engines. Prints+ `Reset` reproducing a run and `SetEmitters` matching a fresh engine, on both engines; the probe graph+ geometry (box clamping and shrinking, snapping, ranges in every scale mode, start-after trimming, nice+ ticks, locale labels, the 400 x 200 layout from measured labels, labels dropped on a low box, fewer step+ labels on a narrow one, min/max binning, the line probe's gate) and a run's line+ probe yielding one profile per frame, the box attached to the probe following it and a detached one staying put, and a+ scratch frame's traces matching the run's bit for bit (series up to the step, the frame's profile, a second+ request on the kept engine with an integrated line probe starting its sums afresh, and the same on the GPU+ after the cancelled GPU run), and a rotated 3 × 1 array. Prints`skip GPU: …` when no OpenCL device works. `dotnet run --project _tools/library_check -c Release-- bench [w h]` prints the per-step cost table above for this machine.@@ -343,6 +406,18 @@ The two legacy harnesses are console programs compiled with `csc` against the `Wswitches back to System. A window Windows never activated has no focused element and loses postedkeys; `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/ProbeGraphCheck.ps1` (2026-10-14, 29 checks, about 50 s) drives `tiny_probes.wdproj`+ (320 x 240, 100 steps, a point probe with a custom 120 x 60 box on the field, a line probe with a Small+ box at its own position on the intensity): one box per probe on its own picture at the box's canvas+ position and size, the Small box shrunk to half the canvas width, the grip in the corner, the graph+ showing the scratch frame's samples at frame 30 before any run, the box changing once the run has data+ and following the position, Tab reaching the box (selecting the probe in the tree), arrows moving it and+ resizing it from the grip without staling the run, a probe move leaving the run valid with the graph+ recomputed from scratch and no run started, Play afterwards starting the refreshing run, a box at its+ probe's position moving with the probe, and the composite source's rotation handle (on the row axis, Tab+ reaches it once the source is selected, hidden before, ten Right arrows lift it by 10° on its arc, the run+ goes stale); saves a screenshot+ to `%TEMP%\probe_graph.png` for the look.`_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@@ -385,16 +460,18 @@ SimulationRun (Task.Run worker; ManualResetEventSlim pause gate, CancellationTok| CPU: row copy) -> writer task: engine.AwaitFrame -> FrameStore.Write -> snapshot back to a pool of 3|- ProbeSampler/ProbeCollector -> ProbeUpdate batches (<= 20 Hz) applied to run.Traces on the UI context'- State/StepsDone/FrameCount/EngineDescription posted to the UI context (INotifyPropertyChanged, bindable)-ScratchRunner (one long-running task, one kept engine: Reset/SetEmitters between requests, rebuilt when the scene or- the options change; computes "frame k of the project as it is now" from step 0, newest request wins, skips when- the predicted cost exceeds Budget) -> ScratchResult (a FrameSnapshot) -> FramePresenter via SnapshotFrameSource+ScratchRunner (one long-running task, one kept engine: Reset/SetEmitters/SetProbes between requests, rebuilt when the+ scene or the options change; computes "frame k of the project as it is now" from step 0, sampling the probes on the+ way, newest request wins, skips when the predicted cost exceeds Budget) -> ScratchResult (a FrameSnapshot + a+ ProbeTrace per probe) -> FramePresenter via SnapshotFrameSource, ProbeGraphOverlay via PreviewPane.ShownScratchFrameStore (temporary file in %LOCALAPPDATA%\WaveDude\cache, DeleteOnClose, pre-sized; Half planes, padding stripped;| positional RandomAccess reads/writes through the OS cache, no memory mapping)'- read by FramePresenter (WPF): CopyLayer -> FrameRenderer (LUT, Parallel.For) -> WriteableBitmap```- Namespaces: `WaveDude.Engine` (engines, `SceneData`, `Emitter`, `EngineOptions`, `OpenClApi`),- `WaveDude.Probes` (`ProbeSpec`, sampler, collector, series, trace, update), `WaveDude.Rendering`+ `WaveDude.Probes` (`ProbeSpec`, sampler, collector, series, trace with per-frame profiles, update,+ `ProbeGraph` geometry), `WaveDude.Rendering`(`Rgb` with hex text and a `TypeConverter`, `ColorScheme` as one evenly spaced colour list that isobservable and XML-serialisable, `ColorLut`, `ColorSchemeStore` reading the author's JSON andreading/writing XML, built-in schemes embedded, `FrameRenderer`),@@ -471,8 +548,8 @@ FrameStore (temporary file in %LOCALAPPDATA%\WaveDude\cache, DeleteOnClose, pre-skipped (`ScratchRunner.Budget` is 6 s, predicted from the stepping cost of the last request withat least 50 steps; a request with no measurement yet always computes). Frames early in the run are proportionally cheaper (frame 0: 90 ms includingthe capture and the UI round trip).-- Known limits: probes are recorded (`SimulationRun.Traces`) but not drawn yet; export is not- wired; `OpenClApi` imports `"OpenCL"` (resolves to `OpenCL.dll` here, `libOpenCL.so` elsewhere).+- Known limits: the probe signal lane under the timeline is not drawn yet (the graph boxes are, 2026-10-14);+ export is not wired; `OpenClApi` imports `"OpenCL"` (resolves to `OpenCL.dll` here, `libOpenCL.so` elsewhere).The library is compiled with `<Optimize>true</Optimize>` in every configuration (2026-10-10): aDebug build of it ran the CPU engine's stencil loop at 33 ms per full-HD step instead of 14, whichmade the CPU preview unusable from the app. Flip it locally to step through engine code. The@@ -581,8 +658,8 @@ functional spec for the WPF UI.replace with `Program.Main` (`EnableVisualStyles`, `SetCompatibleTextRenderingDefault`) when convenient.- Private `ref` parameters that are really `out` remain outside the engines (`TryPictureToCanvas`,`TryParseInt`, `DampingProblem`, `PromptForCValue`, `ComputeRanges`, `RgbToHsv`, …).-- WPF: no progress bar for a run (status text only); the Simulation menu has no About/Help; probes- recorded but not drawn; export not rendered from the store yet; the preview skips frames at+- WPF: no progress bar for a run (status text only); the Simulation menu has no About/Help; the probe+ signal lane is not drawn yet (the graph boxes are); export not rendered from the store yet; the preview skips frames at1080p (see the numbers in the library architecture section).- WPF preview, frames vs. steps: the transport bar, scrubber and playback count **frames**(0..`LastFrame`, one per `VisualizeEvery` steps), while sources, probes, the export range and the@@ -630,8 +707,10 @@ Thirteen points on a sneak peek of the WPF app; status as of 2026-10-12:carry `Tree:<name>` automation ids and the boxes `Enabled:<name>`).(1, second half) the step buttons now draw the frame-step look, "◀|" "|▶", instead of the players'skip glyphs, and the Run glyph is a 14 px ring (2026-10-13).-- Still open: "re-run automatically does not always work" (by design: display and probe edits do- not re-run, and the run waits 1.5 s of quiet).+- Done 2026-10-14: (7, first half) the probe graph boxes over the pictures, draggable and resizable+ (see "Probe graphs" above); probe measurement edits now re-run automatically.+- Still open: "re-run automatically does not always work" (by design: display edits and a probe's graph+ settings do not re-run, and the run waits 1.5 s of quiet).- Roadmap already: (7) probe graphs, (10) export, (12) project format (the user answered: imagesembedded or relative, output next to the file, the JSON format imported).- The author also suggests dropping the 9-point Laplacian (confusing; only useful to show dispersion).@@ -646,20 +725,20 @@ the language switches live, and three UI harnesses plus `library_check` are greePreviewCheck 12 s, LanguageCheck 17 s, `library_check` about 20 s). The next session is meant for**probes** and **export**; here is what exists for each and what is decided.-**Probes (nothing drawn yet).**-- Recorded: `SimulationRun.Traces` (`ProbeTrace` per active probe, `ProbeSeries` of samples per- visualised step, line probes as profiles), filled on the UI context in `ProbeUpdate` batches- (at most 20 Hz). `ScratchRunner` does not sample probes; only a run has traces (decide whether a- scratch frame should carry a single sample).+**Probes (graph boxes done 2026-10-14, see "Probe graphs" in the WPF shell list; the lane is open).**+- Recorded: `SimulationRun.Traces` (`ProbeTrace` per active probe, `ProbeSeries` of one sample per+ step, line probes as one profile per recorded frame), filled on the UI context in `ProbeUpdate` batches+ (at most 20 Hz); the `ScratchRunner` records the same probes up to the frame it computes+ (`ScratchResult.Traces`), so the graph is live before a run too.- Model: `Probe` has everything the author's graph box used: `Kind` (point/line), `Layer`,`Measurement` (amplitude | value | integrated value), `BoxSize`, `BoxX/BoxY` (canvas pixels),`ScaleMode` (running window / full run), `Window` (steps), `AutoScaleX/Y`, `YMin/YMax`,`StartAfter`. The handles on the pictures exist (`SceneOverlay`, ids `Probe:<name>:A|B`).-- Spec: the author's `ProbeGraphPainter.cs` / `ProbeOverlay.cs` in `Wave_Dude_2D/` (GDI+, not- ported) draw the box over the output picture; `HelpForm.cs` describes the controls. Agreed plan: a- **probe signal lane** under the timeline on the same time axis (roadmap item 5), and the graph box- over the picture as the author had it. Rendering belongs in the library as pixel/geometry code (no- GDI+); the WPF side draws it (an `OnRender` layer like `TimelineBar`). Author's point 7.+- Spec: the author's `ProbeGraphPainter.cs` / `ProbeOverlay.cs` in `Wave_Dude_2D/` (GDI+), now ported+ as geometry to `WaveDude.Probes.ProbeGraph` and drawn by `ProbeGraphOverlay`. Still to do: the+ **probe signal lane** under the timeline on the same time axis (roadmap item 5), drawn from the same+ traces (`ProbeGraph.ComputeRanges` and its binning can be reused), and the box in exports (the layout is+ renderer-neutral; a `DrawingVisual` rendered into the frame would do). Author's point 7, second half.**Export (nothing wired).**- Frames: `FrameStore.CopyLayer(frame, layer, Span<Half>)` of a run (finished, or after@@ -695,8 +774,8 @@ pan (roadmap); Help > About has no content; dock pane titles are not exposed to4. ~~**Make the engine loop `Task`-based**~~ (`SimulationRun`, 2026-10-09).5. **WPF UI** in `WaveDude.WPF`: the preview shows a live run and replays it from the frame store(done 2026-10-09); editors, colour schemes, scene image and outline, languages (done 2026-10-14,- see the handoff section). Next, in this order of value: **probes** (graph box and signal lane),- **export from the store** (video and stills, rendered with the current display settings, the+ see the handoff section); probe graph boxes (done 2026-10-14). Next, in this order of value: the+ **probe signal lane**, **export from the store** (video and stills, rendered with the current display settings, theexport range, the outline when opted in), a progress bar.Store: a RAM-first frame store with a budget and background spill (see the numbers above),so a run is compute-bound instead of disk-bound.diff --git a/Project/test1.wdproj b/Project/test1.wdprojindex a3818c1..2eebd33 100644--- a/Project/test1.wdproj+++ b/Project/test1.wdproj@@ -8,5 +8,5 @@<Intensity ColorScheme="Default_intensity" /></Display><Source Name="Source 1" X="429" Y="614" />- <Source Name="Source 2" X="1637" Y="481" />+ <Probe Name="Probe 1" AX="1626" AY="603" BoxSize="Custom" BoxX="541" BoxY="23" BoxWidth="777" BoxHeight="454" /></Project>\ No newline at end of filediff --git a/WaveDude.WPF/Controls/MarkerThumb.cs b/WaveDude.WPF/Controls/MarkerThumb.csindex 34a7ec1..e5a6912 100644--- a/WaveDude.WPF/Controls/MarkerThumb.cs+++ b/WaveDude.WPF/Controls/MarkerThumb.cs@@ -14,12 +14,16 @@ public enum MarkerRoleProbeA,/// <summary>Point B of a line probe.</summary>ProbeB,+ /// <summary>The graph box of a probe (moves it), see <see cref="ProbeGraphOverlay"/>.</summary>+ ProbeBox,+ /// <summary>The bottom-right corner of a probe's graph box (resizes it).</summary>+ ProbeBoxCorner,}/// <summary>-/// One draggable handle of the <see cref="SceneOverlay"/>: a <see cref="Thumb"/> that knows which model-/// object and which of its points it moves. Focusable, so the arrow keys can move it too; the overlay-/// does the geometry and the model updates. UI thread.+/// One draggable handle of the <see cref="SceneOverlay"/> or <see cref="ProbeGraphOverlay"/>: a+/// <see cref="Thumb"/> that knows which model object and which of its points (or its graph box) it moves.+/// Focusable, so the arrow keys can move it too; the overlay does the geometry and the model updates. UI thread./// </summary>public sealed class MarkerThumb : Thumb{@@ -73,10 +77,10 @@ public sealed class MarkerThumb : Thumb/// <summary>Width of the dark outline drawn under the glyph: <see cref="StrokeThickness"/> plus <see cref="HaloWidth"/> on each side.</summary>public double HaloThickness => (double)GetValue(HaloThicknessProperty);- /// <summary>Model coordinate of the point when the current drag started (canvas pixels).</summary>+ /// <summary>Model coordinate of the point (or the box's width, for a corner) when the current drag started (canvas pixels).</summary>internal int DragStartX { get; set; }- /// <summary>Model coordinate of the point when the current drag started (canvas pixels).</summary>+ /// <summary>Model coordinate of the point (or the box's height, for a corner) when the current drag started (canvas pixels).</summary>internal int DragStartY { get; set; }/// <summary>Mouse movement since the drag started, in canvas pixels (fractional, so slow drags add up).</summary>diff --git a/WaveDude.WPF/Controls/ProbeGraphOverlay.cs b/WaveDude.WPF/Controls/ProbeGraphOverlay.csnew file mode 100644index 0000000..da25bc1--- /dev/null+++ b/WaveDude.WPF/Controls/ProbeGraphOverlay.cs@@ -0,0 +1,630 @@+using System.Collections.Immutable;+using System.Collections.Specialized;+using System.ComponentModel;+using System.Globalization;+using System.Windows;+using System.Windows.Automation;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Input;+using System.Windows.Media;+using WaveDude.Model;+using WaveDude.Probes;+using WaveDude.Runs;++namespace WaveDude.WPF.Controls;++/// <summary>+/// The graph boxes of the probes on one picture (the probes of this <see cref="Layer"/>), drawn over the+/// frame as the author's app did: a translucent dark box with axes, the curve and a title strip with the+/// live readout, placed where the probe's <see cref="Probe.BoxX"/>/<see cref="Probe.BoxY"/> say (canvas+/// pixels, mapped with the picture's uniform scale like <see cref="SceneOverlay"/>). The graph is as live as+/// the picture: while the picture shows a scratch frame (<see cref="Scratch"/>: no run, a stale one, or one+/// that has not got there) the data is that frame's recording; otherwise it is the run's recording as it+/// stood at <see cref="Frame"/> (the series cut off at that step, the profile of that frame), redrawn on+/// every probe batch. With only the probes edited since the run, the picture keeps the stored frame and the+/// pane hands this overlay the scratch frame computed for the position all the same. A stale run's data is shown while the pane shows its stored frame: the graph follows+/// the picture, whatever is on it, instead of dropping to an empty axis until the scratch frame arrives+/// (that was a flicker on every scrub step, 2026-10-14). Each box is a draggable <see cref="MarkerThumb"/> (moves the box; the arrow keys nudge it) with a+/// second thumb at its bottom-right corner that resizes it, snapping to the fixed sizes+/// (<see cref="ProbeGraph.Snap"/>) or making it <see cref="ProbeBoxSize.Custom"/>. Grabbing or focusing a box+/// selects its probe. The geometry comes from <see cref="ProbeGraph"/>; this class only draws. UI thread.+/// </summary>+public sealed class ProbeGraphOverlay : Panel+{+ /// <summary>Identifies the <see cref="Project"/> property.</summary>+ public static readonly DependencyProperty ProjectProperty = DependencyProperty.Register(+ nameof(Project), typeof(Project), typeof(ProbeGraphOverlay), new PropertyMetadata(null, OnProjectChanged));++ /// <summary>Identifies the <see cref="Run"/> property.</summary>+ public static readonly DependencyProperty RunProperty = DependencyProperty.Register(+ nameof(Run), typeof(SimulationRun), typeof(ProbeGraphOverlay), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender, OnRunChanged));++ /// <summary>Identifies the <see cref="Scratch"/> property.</summary>+ public static readonly DependencyProperty ScratchProperty = DependencyProperty.Register(+ nameof(Scratch), typeof(ScratchResult), typeof(ProbeGraphOverlay), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));++ /// <summary>Identifies the <see cref="Frame"/> property.</summary>+ public static readonly DependencyProperty FrameProperty = DependencyProperty.Register(+ nameof(Frame), typeof(int), typeof(ProbeGraphOverlay), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender));++ /// <summary>Identifies the <see cref="Layer"/> property.</summary>+ public static readonly DependencyProperty LayerProperty = DependencyProperty.Register(+ nameof(Layer), typeof(ProbeLayer), typeof(ProbeGraphOverlay), new PropertyMetadata(ProbeLayer.Field, (d, _) => ((ProbeGraphOverlay)d).Rebuild()));++ /// <summary>Identifies the <see cref="CanvasWidth"/> property.</summary>+ public static readonly DependencyProperty CanvasWidthProperty = DependencyProperty.Register(+ nameof(CanvasWidth), typeof(int), typeof(ProbeGraphOverlay), new FrameworkPropertyMetadata(1, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsRender));++ /// <summary>Identifies the <see cref="CanvasHeight"/> property.</summary>+ public static readonly DependencyProperty CanvasHeightProperty = DependencyProperty.Register(+ nameof(CanvasHeight), typeof(int), typeof(ProbeGraphOverlay), new FrameworkPropertyMetadata(1, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsRender));++ /// <summary>Identifies the <see cref="SelectedItem"/> property.</summary>+ public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register(+ nameof(SelectedItem), typeof(object), typeof(ProbeGraphOverlay),+ new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, (d, _) => ((ProbeGraphOverlay)d).UpdateSelection()));++ /// <summary>Identifies the <see cref="BoxStyle"/> property.</summary>+ public static readonly DependencyProperty BoxStyleProperty = DependencyProperty.Register(+ nameof(BoxStyle), typeof(Style), typeof(ProbeGraphOverlay), new PropertyMetadata(null, (d, _) => ((ProbeGraphOverlay)d).Rebuild()));++ /// <summary>Identifies the <see cref="CornerStyle"/> property.</summary>+ public static readonly DependencyProperty CornerStyleProperty = DependencyProperty.Register(+ nameof(CornerStyle), typeof(Style), typeof(ProbeGraphOverlay), new PropertyMetadata(null, (d, _) => ((ProbeGraphOverlay)d).Rebuild()));++ /// <summary>Identifies the <see cref="AccentBrush"/> property.</summary>+ public static readonly DependencyProperty AccentBrushProperty = DependencyProperty.Register(+ nameof(AccentBrush), typeof(Brush), typeof(ProbeGraphOverlay), new FrameworkPropertyMetadata(Brushes.DodgerBlue, FrameworkPropertyMetadataOptions.AffectsRender));++ /// <summary>Pixels a focused box moves or grows per arrow key, and with Shift.</summary>+ private const int KeyStep = 1;+ private const int KeyStepFast = 10;++ /// <summary>Screen distance within which a dragged anchor (the box's, or the probe's point A) snaps the box onto the probe and attaches it.</summary>+ public const double SnapRadius = 14.0;++ /// <summary>Screen distance an attached box must be dragged from the probe before it comes off: wider than <see cref="SnapRadius"/>, so a drag near the edge does not attach and detach in turn (hysteresis, 2026-10-14).</summary>+ public const double SnapRelease = 28.0;++ // the author's colours: the box sits on the picture, not on the window, so they do not follow the theme+ private static readonly Brush BackgroundBrush = Freeze(new SolidColorBrush(Color.FromArgb(235, 14, 16, 22)));+ private static readonly Pen BorderPen = Freeze(new Pen(Freeze(new SolidColorBrush(Color.FromArgb(170, 200, 200, 210))), 1.0));+ private static readonly Pen GridPen = Freeze(new Pen(Freeze(new SolidColorBrush(Color.FromArgb(46, 255, 255, 255))), 1.0));+ private static readonly Pen ZeroPen = Freeze(new Pen(Freeze(new SolidColorBrush(Color.FromArgb(120, 255, 255, 255))), 1.0));+ private static readonly Pen FramePen = Freeze(new Pen(Freeze(new SolidColorBrush(Color.FromArgb(130, 200, 200, 210))), 1.0));+ private static readonly Brush LabelBrush = Freeze(new SolidColorBrush(Color.FromArgb(225, 225, 225, 230)));+ private static readonly Brush TitleBrush = Freeze(new SolidColorBrush(Color.FromArgb(240, 240, 240, 245)));+ private static readonly Brush CurveBrush = Freeze(new SolidColorBrush(Color.FromArgb(255, 255, 208, 64)));+ private static readonly Typeface GraphTypeface = new("Segoe UI");++ /// <summary>Font height of the labels and the title in screen pixels: the handle labels' size, whatever the box size.</summary>+ private const double GraphFontSize = 11.0;++ /// <summary>The text metrics handed to the layout, built per DPI.</summary>+ private ProbeGraphStyle? _style;+ private double _stylePixelsPerDip;++ private readonly HashSet<INotifyPropertyChanged> _subscribed = [];++ public ProbeGraphOverlay()+ {+ // no background: clicks between the boxes fall through to the picture (and the pane's focus handling)+ IsHitTestVisible = true;+ Focusable = false;+ }++ /// <summary>The project whose probes are shown; null shows nothing.</summary>+ public Project? Project+ {+ get => (Project?)GetValue(ProjectProperty);+ set => SetValue(ProjectProperty, value);+ }++ /// <summary>The run whose recordings are drawn; null (or a stale run) draws the boxes without data.</summary>+ public SimulationRun? Run+ {+ get => (SimulationRun?)GetValue(RunProperty);+ set => SetValue(RunProperty, value);+ }++ /// <summary>The scratch frame the picture shows, or null; its recordings (the project as it is now) take precedence over the run's.</summary>+ public ScratchResult? Scratch+ {+ get => (ScratchResult?)GetValue(ScratchProperty);+ set => SetValue(ScratchProperty, value);+ }++ /// <summary>The frame the picture shows; the graphs show the run's recording as it stood there.</summary>+ public int Frame+ {+ get => (int)GetValue(FrameProperty);+ set => SetValue(FrameProperty, value);+ }++ /// <summary>Which picture this overlay sits on; only the probes of that layer are drawn.</summary>+ public ProbeLayer Layer+ {+ get => (ProbeLayer)GetValue(LayerProperty);+ set => SetValue(LayerProperty, value);+ }++ /// <summary>Canvas width in pixels, the x range of the model coordinates.</summary>+ public int CanvasWidth+ {+ get => (int)GetValue(CanvasWidthProperty);+ set => SetValue(CanvasWidthProperty, value);+ }++ /// <summary>Canvas height in pixels.</summary>+ public int CanvasHeight+ {+ get => (int)GetValue(CanvasHeightProperty);+ set => SetValue(CanvasHeightProperty, value);+ }++ /// <summary>The item selected in the project (its box gets the accent border); set when a box is grabbed or focused.</summary>+ public object? SelectedItem+ {+ get => GetValue(SelectedItemProperty);+ set => SetValue(SelectedItemProperty, value);+ }++ /// <summary>Style of the thumb covering a box (a <see cref="MarkerThumb"/> style; transparent, shows focus).</summary>+ public Style? BoxStyle+ {+ get => (Style?)GetValue(BoxStyleProperty);+ set => SetValue(BoxStyleProperty, value);+ }++ /// <summary>Style of the resize grip at a box's bottom-right corner.</summary>+ public Style? CornerStyle+ {+ get => (Style?)GetValue(CornerStyleProperty);+ set => SetValue(CornerStyleProperty, value);+ }++ /// <summary>Border of the selected probe's box.</summary>+ public Brush AccentBrush+ {+ get => (Brush)GetValue(AccentBrushProperty);+ set => SetValue(AccentBrushProperty, value);+ }++ // ---------------------------------------------------------------- model and run wiring++ private static void OnProjectChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)+ {+ var overlay = (ProbeGraphOverlay)d;+ if (e.OldValue is Project old)+ {+ old.Probes.CollectionChanged -= overlay.OnCollectionChanged;+ }+ if (e.NewValue is Project project)+ {+ project.Probes.CollectionChanged += overlay.OnCollectionChanged;+ }+ overlay.Rebuild();+ }++ private static void OnRunChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)+ {+ var overlay = (ProbeGraphOverlay)d;+ if (e.OldValue is SimulationRun old)+ {+ old.ProbesUpdated -= overlay.OnProbesUpdated;+ }+ if (e.NewValue is SimulationRun run)+ {+ run.ProbesUpdated += overlay.OnProbesUpdated;+ }+ }++ private void OnProbesUpdated(object? sender, ProbeUpdate e) => InvalidateVisual();++ private void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) => Rebuild();++ /// <summary>Recreates the thumbs for the active probes of this layer and re-subscribes to every probe.</summary>+ private void Rebuild()+ {+ foreach (INotifyPropertyChanged item in _subscribed)+ {+ item.PropertyChanged -= OnProbePropertyChanged;+ }+ _subscribed.Clear();+ Children.Clear();+ if (Project is { } project)+ {+ foreach (Probe probe in project.Probes)+ {+ if (_subscribed.Add(probe))+ {+ probe.PropertyChanged += OnProbePropertyChanged;+ }+ if (!IsShown(probe))+ {+ continue;+ }+ AddThumb(probe, MarkerRole.ProbeBox, BoxStyle, "TipProbeBoxFormat", "ProbeBox:" + probe.Name);+ AddThumb(probe, MarkerRole.ProbeBoxCorner, CornerStyle, "TipProbeBoxCornerFormat", "ProbeBoxCorner:" + probe.Name);+ }+ }+ UpdateSelection();+ InvalidateArrange();+ InvalidateVisual();+ }++ private bool IsShown(Probe probe) => probe.Active && probe.Layer == Layer;++ private void AddThumb(Probe probe, MarkerRole role, Style? style, string tipKey, string automationId)+ {+ var thumb = new MarkerThumb(probe, role) { Style = style };+ thumb.ToolTip = TryFindResource(tipKey) is string format ? string.Format(CultureInfo.CurrentUICulture, format, probe.Name) : probe.Name;+ AutomationProperties.SetName(thumb, probe.Name);+ AutomationProperties.SetAutomationId(thumb, automationId);+ thumb.DragStarted += OnDragStarted;+ thumb.DragDelta += OnDragDelta;+ thumb.GotKeyboardFocus += (_, _) => SelectedItem = probe;+ Children.Add(thumb);+ }++ private void OnProbePropertyChanged(object? sender, PropertyChangedEventArgs e)+ {+ if (e.PropertyName is nameof(Probe.Active) or nameof(Probe.Layer) or nameof(Probe.Name))+ {+ Rebuild();+ return;+ }+ InvalidateArrange();+ InvalidateVisual();+ }++ private void UpdateSelection()+ {+ object? selected = SelectedItem;+ foreach (MarkerThumb thumb in Children)+ {+ thumb.IsSelectedMarker = ReferenceEquals(thumb.Item, selected);+ }+ InvalidateVisual();+ }++ // ---------------------------------------------------------------- geometry++ /// <summary>Pixels per canvas pixel for an element of <paramref name="size"/>: the picture's uniform scale (see <see cref="SceneOverlay"/> for why the size is passed in).</summary>+ private double ScaleFor(Size size) => Math.Min(size.Width / Math.Max(1, CanvasWidth), size.Height / Math.Max(1, CanvasHeight));++ /// <summary>The box of <paramref name="probe"/> in this element's coordinates, for an element of <paramref name="size"/>; the picture is centred in it.</summary>+ private Rect BoxOf(Probe probe, Size size)+ {+ double scale = ScaleFor(size);+ double originX = (size.Width - CanvasWidth * scale) / 2;+ double originY = (size.Height - CanvasHeight * scale) / 2;+ BoxRect box = ProbeGraph.BoxInCanvas(probe, CanvasWidth, CanvasHeight);+ // whole view pixels, so the 1-pixel lines of the box stay crisp+ return new Rect(Math.Round(originX + box.X * scale), Math.Round(originY + box.Y * scale), Math.Max(1, Math.Round(box.Width * scale)), Math.Max(1, Math.Round(box.Height * scale)));+ }++ /// <inheritdoc/>+ protected override Size MeasureOverride(Size availableSize)+ {+ foreach (UIElement child in Children)+ {+ child.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));+ }+ return new Size(double.IsInfinity(availableSize.Width) ? 0 : availableSize.Width, double.IsInfinity(availableSize.Height) ? 0 : availableSize.Height);+ }++ /// <inheritdoc/>+ protected override Size ArrangeOverride(Size finalSize)+ {+ foreach (MarkerThumb thumb in Children)+ {+ Rect box = BoxOf((Probe)thumb.Item, finalSize);+ if (thumb.Role == MarkerRole.ProbeBoxCorner)+ {+ Size grip = thumb.DesiredSize;+ thumb.Arrange(new Rect(box.Right - grip.Width, box.Bottom - grip.Height, grip.Width, grip.Height));+ }+ else+ {+ thumb.Arrange(box);+ }+ }+ return finalSize;+ }++ // ---------------------------------------------------------------- drawing++ /// <summary>+ /// The recording of <paramref name="probe"/> as the picture shows it (the scratch frame's, else the run's as+ /// it stood at <see cref="Frame"/>), and the run length for the step axis; empty data without either.+ /// </summary>+ private ProbeGraphData DataFor(Probe probe, out int totalSteps)+ {+ if (Scratch is { } scratch)+ {+ totalSteps = Math.Max(1, scratch.Spec.Steps);+ // a scratch trace holds one profile, the frame's own, at index 0+ return TraceOf(scratch.Spec.Probes, scratch.Traces, probe) is { } scratchTrace+ ? ProbeGraphData.At(scratchTrace, scratch.Frame * scratch.Spec.VisualizeEvery, 0)+ : default;+ }+ SimulationRun? run = Run;+ totalSteps = Math.Max(1, run?.Spec.Steps ?? Project?.Simulation.Steps ?? 1);+ if (run == null)+ {+ return default;+ }+ return TraceOf(run.Spec.Probes, run.Traces, probe) is { } trace+ ? ProbeGraphData.At(trace, Frame * run.Spec.VisualizeEvery, Frame)+ : default;+ }++ /// <summary>The trace of the model probe among a spec's probes (matched by <see cref="ProbeSpec.Origin"/>), or null when it was not recorded.</summary>+ private static ProbeTrace? TraceOf(ImmutableArray<ProbeSpec> specs, ProbeTrace[] traces, Probe probe)+ {+ for (int i = 0; i < specs.Length && i < traces.Length; i++)+ {+ if (ReferenceEquals(specs[i].Origin, probe))+ {+ return traces[i];+ }+ }+ return null;+ }++ /// <inheritdoc/>+ protected override void OnRender(DrawingContext dc)+ {+ base.OnRender(dc);+ if (Project is not { } project || ActualWidth <= 0 || ActualHeight <= 0)+ {+ return;+ }+ double pixelsPerDip = VisualTreeHelper.GetDpi(this).PixelsPerDip;+ ProbeGraphStyle style = StyleFor(pixelsPerDip);+ object? selected = SelectedItem;+ foreach (Probe probe in project.Probes)+ {+ if (!IsShown(probe))+ {+ continue;+ }+ Rect box = BoxOf(probe, RenderSize);+ ProbeGraphData data = DataFor(probe, out int totalSteps);+ ProbeGraphLayout layout = ProbeGraph.Layout(probe, data, totalSteps, (float)box.Width, (float)box.Height, style, CultureInfo.CurrentCulture);+ if (!layout.IsVisible)+ {+ continue;+ }+ dc.PushTransform(new TranslateTransform(box.X, box.Y));+ DrawBox(dc, layout, ReferenceEquals(probe, selected), pixelsPerDip);+ dc.Pop();+ }+ }++ /// <summary>The text metrics of the fixed graph font at this DPI: the line height and the measured label widths.</summary>+ private ProbeGraphStyle StyleFor(double pixelsPerDip)+ {+ if (_style == null || _stylePixelsPerDip != pixelsPerDip)+ {+ _stylePixelsPerDip = pixelsPerDip;+ float lineHeight = (float)Text("0", GraphFontSize, LabelBrush, pixelsPerDip).Height;+ _style = new ProbeGraphStyle((float)GraphFontSize, lineHeight, text => (float)Text(text, GraphFontSize, LabelBrush, pixelsPerDip).Width);+ }+ return _style;+ }++ /// <summary>Draws one box from its layout, with the origin at the box's top-left corner.</summary>+ private void DrawBox(DrawingContext dc, ProbeGraphLayout layout, bool isSelected, double pixelsPerDip)+ {+ double w = layout.Width;+ double h = layout.Height;+ dc.DrawRectangle(BackgroundBrush, null, new Rect(0, 0, w, h));+ dc.DrawRectangle(null, isSelected ? new Pen(AccentBrush, 1.0) : BorderPen, new Rect(0.5, 0.5, w - 1, h - 1));+ double fontPx = layout.FontSize;+ if (layout.HasPlot)+ {+ double plotLeft = layout.PlotX;+ double plotTop = layout.PlotY;+ double plotRight = layout.PlotX + layout.PlotWidth;+ double plotBottom = layout.PlotY + layout.PlotHeight;+ // value axis: grid lines (the zero line brighter) with right-aligned labels in the left margin+ foreach (GraphTick tick in layout.YTicks)+ {+ double y = Math.Round(tick.Position) + 0.5;+ dc.DrawLine(tick.IsZero ? ZeroPen : GridPen, new Point(plotLeft, y), new Point(plotRight, y));+ if (tick.Label.Length == 0)+ {+ continue;+ }+ // right-aligned by position: a MaxTextWidth equal to the measured width made WPF wrap the label onto a+ // second line, which the one-line limit dropped (the labels vanished, 2026-10-14)+ FormattedText label = Text(tick.Label, fontPx, LabelBrush, pixelsPerDip);+ double lx = Math.Max(layout.LabelLeft, plotLeft - ProbeGraph.LabelGap - label.Width);+ dc.DrawText(label, new Point(lx, Math.Clamp(tick.Position - label.Height / 2, plotTop - label.Height / 2, plotBottom - label.Height / 2)));+ }+ // step axis (point probe) or position on the line (line probe): labels centred below the plot, kept inside the box+ foreach (GraphTick tick in layout.XTicks)+ {+ double x = Math.Round(tick.Position) + 0.5;+ dc.DrawLine(GridPen, new Point(x, plotTop), new Point(x, plotBottom));+ if (tick.Label.Length == 0)+ {+ continue;+ }+ FormattedText label = Text(tick.Label, fontPx, LabelBrush, pixelsPerDip);+ double lx = Math.Clamp(tick.Position - label.Width / 2, ProbeGraph.EdgePad, Math.Max(ProbeGraph.EdgePad, w - label.Width - ProbeGraph.EdgePad));+ dc.DrawText(label, new Point(lx, plotBottom + 2));+ }+ dc.DrawRectangle(null, FramePen, new Rect(plotLeft + 0.5, plotTop + 0.5, layout.PlotWidth, layout.PlotHeight));+ DrawCurve(dc, layout);+ }+ // the title strip: the readout right-aligned in its own colour, the title in the remaining width+ double readoutWidth = 0;+ if (layout.Readout.Length > 0)+ {+ FormattedText readout = Text(layout.Readout, fontPx, CurveBrush, pixelsPerDip);+ readoutWidth = readout.Width;+ dc.DrawText(readout, new Point(w - readoutWidth - 8, layout.TitleTop));+ }+ FormattedText title = Text(layout.Title, fontPx, TitleBrush, pixelsPerDip);+ title.MaxTextWidth = Math.Max(10, w - readoutWidth - 16);+ title.Trimming = TextTrimming.CharacterEllipsis;+ dc.DrawText(title, new Point(ProbeGraph.EdgePad + 3, layout.TitleTop));+ }++ /// <summary>Strokes the curve clipped to the plot area; a single point is a small dot.</summary>+ private static void DrawCurve(DrawingContext dc, ProbeGraphLayout layout)+ {+ if (layout.Curve.Length == 0)+ {+ return;+ }+ if (layout.Curve.Length == 1)+ {+ dc.DrawEllipse(CurveBrush, null, new Point(layout.Curve[0].X, layout.Curve[0].Y), 2, 2);+ return;+ }+ var geometry = new StreamGeometry();+ using (StreamGeometryContext context = geometry.Open())+ {+ context.BeginFigure(new Point(layout.Curve[0].X, layout.Curve[0].Y), false, false);+ for (int i = 1; i < layout.Curve.Length; i++)+ {+ context.LineTo(new Point(layout.Curve[i].X, layout.Curve[i].Y), true, false);+ }+ }+ geometry.Freeze();+ dc.PushClip(new RectangleGeometry(new Rect(layout.PlotX, layout.PlotY, layout.PlotWidth, layout.PlotHeight)));+ dc.DrawGeometry(null, new Pen(CurveBrush, layout.LineWidth) { LineJoin = PenLineJoin.Round }, geometry);+ dc.Pop();+ }++ private static FormattedText Text(string text, double size, Brush brush, double pixelsPerDip) =>+ new(text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, GraphTypeface, size, brush, pixelsPerDip) { MaxLineCount = 1 };++ private static T Freeze<T>(T freezable) where T : Freezable+ {+ freezable.Freeze();+ return freezable;+ }++ // ---------------------------------------------------------------- dragging and keys++ private void OnDragStarted(object sender, DragStartedEventArgs e)+ {+ var thumb = (MarkerThumb)sender;+ var probe = (Probe)thumb.Item;+ if (thumb.Role == MarkerRole.ProbeBoxCorner)+ {+ BoxSize size = ProbeGraph.BoxSizeOf(probe);+ (thumb.DragStartX, thumb.DragStartY) = (size.Width, size.Height);+ }+ else+ {+ (thumb.DragStartX, thumb.DragStartY) = (probe.BoxX, probe.BoxY);+ }+ thumb.DragDeltaX = 0;+ thumb.DragDeltaY = 0;+ SelectedItem = probe;+ thumb.Focus();+ }++ private void OnDragDelta(object sender, DragDeltaEventArgs e)+ {+ var thumb = (MarkerThumb)sender;+ double scale = ScaleFor(RenderSize);+ if (scale <= 0)+ {+ return;+ }+ thumb.DragDeltaX += e.HorizontalChange / scale;+ thumb.DragDeltaY += e.VerticalChange / scale;+ int x = thumb.DragStartX + (int)Math.Round(thumb.DragDeltaX);+ int y = thumb.DragStartY + (int)Math.Round(thumb.DragDeltaY);+ var probe = (Probe)thumb.Item;+ if (thumb.Role == MarkerRole.ProbeBoxCorner)+ {+ // the fixed sizes are snap points of the drag+ (ProbeBoxSize size, BoxSize box) = ProbeGraph.Snap(x, y);+ SetBoxSize(probe, size, box);+ }+ else+ {+ SetBoxPosition(probe, x, y, snap: true);+ }+ }++ /// <summary>+ /// Moves the box, kept inside the canvas. With <paramref name="snap"/> (a drag, not a keyboard nudge) a box+ /// whose anchor comes within <see cref="SnapRadius"/> screen pixels of the probe's point A lands on it and is+ /// attached from then on (<see cref="Probe.IsBoxAttached"/>); an attached box stays on the probe until it is+ /// dragged more than <see cref="SnapRelease"/> away. One radius, not a snap per axis, with hysteresis (the+ /// user's rule, 2026-10-14).+ /// </summary>+ private void SetBoxPosition(Probe probe, int x, int y, bool snap)+ {+ if (snap)+ {+ double scale = ScaleFor(RenderSize);+ double dx = (x - probe.AX) * scale;+ double dy = (y - probe.AY) * scale;+ double limit = probe.IsBoxAttached ? SnapRelease : SnapRadius;+ if (dx * dx + dy * dy <= limit * limit)+ {+ x = probe.AX;+ y = probe.AY;+ }+ }+ BoxRect box = ProbeGraph.BoxInCanvas(probe, CanvasWidth, CanvasHeight);+ probe.BoxX = Math.Clamp(x, 0, Math.Max(0, CanvasWidth - box.Width));+ probe.BoxY = Math.Clamp(y, 0, Math.Max(0, CanvasHeight - box.Height));+ }++ /// <summary>Applies a box size: a fixed size as it is, a custom one with its width and height.</summary>+ private static void SetBoxSize(Probe probe, ProbeBoxSize size, BoxSize box)+ {+ if (size == ProbeBoxSize.Custom)+ {+ probe.BoxWidth = box.Width;+ probe.BoxHeight = box.Height;+ }+ probe.BoxSize = size;+ }++ /// <summary>The arrow keys move a focused box by one canvas pixel (ten with Shift); on the corner grip they resize it, to a custom size.</summary>+ protected override void OnKeyDown(KeyEventArgs e)+ {+ base.OnKeyDown(e);+ if (e.Handled || e.OriginalSource is not MarkerThumb thumb)+ {+ return;+ }+ int step = (Keyboard.Modifiers & ModifierKeys.Shift) != 0 ? KeyStepFast : KeyStep;+ (int dx, int dy) = e.Key switch+ {+ Key.Left => (-step, 0),+ Key.Right => (step, 0),+ Key.Up => (0, -step),+ Key.Down => (0, step),+ _ => (0, 0),+ };+ if (dx == 0 && dy == 0)+ {+ return;+ }+ var probe = (Probe)thumb.Item;+ if (thumb.Role == MarkerRole.ProbeBoxCorner)+ {+ BoxSize size = ProbeGraph.BoxSizeOf(probe);+ SetBoxSize(probe, ProbeBoxSize.Custom, new BoxSize(Math.Clamp(size.Width + dx, Probe.MinBoxWidth, Probe.MaxBoxSide), Math.Clamp(size.Height + dy, Probe.MinBoxHeight, Probe.MaxBoxSide)));+ }+ else+ {+ SetBoxPosition(probe, probe.BoxX + dx, probe.BoxY + dy, snap: false);+ }+ e.Handled = true;+ }+}diff --git a/WaveDude.WPF/Controls/SceneOverlay.cs b/WaveDude.WPF/Controls/SceneOverlay.csindex 9b5eb1b..f570531 100644--- a/WaveDude.WPF/Controls/SceneOverlay.cs+++ b/WaveDude.WPF/Controls/SceneOverlay.cs@@ -85,7 +85,8 @@ public sealed class SceneOverlay : Panelpublic SceneOverlay(){- Background = Brushes.Transparent;+ // no background: a click beside the handles falls through to the probe graph boxes under this layer+ // (and on to the picture), 2026-10-14IsHitTestVisible = true;Focusable = false;}@@ -387,6 +388,18 @@ public sealed class SceneOverlay : Panelcase (Probe probe, _):probe.AX = x;probe.AY = y;+ // a probe dragged onto its (detached) graph box picks it up, as the box does when dragged onto the probe+ if (!probe.IsBoxAttached)+ {+ double scale = Scale;+ double dx = (probe.BoxX - x) * scale;+ double dy = (probe.BoxY - y) * scale;+ if (dx * dx + dy * dy <= ProbeGraphOverlay.SnapRadius * ProbeGraphOverlay.SnapRadius)+ {+ probe.BoxX = x;+ probe.BoxY = y;+ }+ }break;}}diff --git a/WaveDude.WPF/Controls/TreeViewExtensions.cs b/WaveDude.WPF/Controls/TreeViewExtensions.csindex 6d24fdd..111c9c9 100644--- a/WaveDude.WPF/Controls/TreeViewExtensions.cs+++ b/WaveDude.WPF/Controls/TreeViewExtensions.cs@@ -6,14 +6,15 @@ namespace WaveDude.WPF.Controls;public static class TreeViewExtensions{/// <summary>- /// Selects and focuses the container of a data item anywhere in the tree, optionally- /// expanding it. Only realised containers are searched, so call it once the tree has- /// generated its items. Returns false when the item was not found.+ /// Selects the container of a data item anywhere in the tree, optionally expanding it and+ /// giving it keyboard focus (not when the selection mirrors a handle on the preview, which+ /// keeps the focus, 2026-10-14). Only realised containers are searched, so call it once the+ /// tree has generated its items. Returns false when the item was not found./// </summary>- public static bool SetSelectedItem(this TreeView tree, object item, bool expand = false) =>- SetSelected(tree, item, expand);+ public static bool SetSelectedItem(this TreeView tree, object item, bool expand = false, bool focus = true) =>+ SetSelected(tree, item, expand, focus);- private static bool SetSelected(ItemsControl? parent, object item, bool expand)+ private static bool SetSelected(ItemsControl? parent, object item, bool expand, bool focus){if (parent == null){@@ -21,7 +22,10 @@ public static class TreeViewExtensions}if (parent.ItemContainerGenerator.ContainerFromItem(item) is TreeViewItem container){- container.Focus();+ if (focus)+ {+ container.Focus();+ }if (expand){container.IsExpanded = true;@@ -31,7 +35,7 @@ public static class TreeViewExtensions}foreach (object child in parent.Items){- if (SetSelected(parent.ItemContainerGenerator.ContainerFromItem(child) as ItemsControl, item, expand))+ if (SetSelected(parent.ItemContainerGenerator.ContainerFromItem(child) as ItemsControl, item, expand, focus)){return true;}diff --git a/WaveDude.WPF/MainWindow.Live.cs b/WaveDude.WPF/MainWindow.Live.csindex f310665..0da8111 100644--- a/WaveDude.WPF/MainWindow.Live.cs+++ b/WaveDude.WPF/MainWindow.Live.cs@@ -17,7 +17,8 @@ namespace WaveDude.WPF;/// starts a stored re-run once the user has been idle for a moment; an edit during an automatic run stops/// that run at once, since its snapshot is obsolete. Scrubbing asks for scratch frames whenever the store/// cannot show the position: no run, a stale run, or a run that has not got there yet. The scratch runner-/// has its own engine, so a stored run in progress does not hold it back.+/// has its own engine, and any run in progress is paused while a scratch frame computes, so the frame the+/// user looks at always comes first (the user's rule, 2026-10-14)./// </summary>public partial class MainWindow{@@ -31,6 +32,10 @@ public partial class MainWindowpublic static readonly DependencyProperty IsRunStaleProperty = DependencyProperty.Register(nameof(IsRunStale), typeof(bool), typeof(MainWindow), new PropertyMetadata(false));+ /// <summary>Identifies the <see cref="IsProbesStale"/> property.</summary>+ public static readonly DependencyProperty IsProbesStaleProperty = DependencyProperty.Register(+ nameof(IsProbesStale), typeof(bool), typeof(MainWindow), new PropertyMetadata(false));+/// <summary>Identifies the <see cref="ScratchFrame"/> property.</summary>public static readonly DependencyProperty ScratchFrameProperty = DependencyProperty.Register(nameof(ScratchFrame), typeof(ScratchResult), typeof(MainWindow), new PropertyMetadata(null));@@ -55,6 +60,18 @@ public partial class MainWindowset => SetValue(IsRunStaleProperty, value);}+ /// <summary>+ /// Whether a probe was edited (measurement, position, list) since the current run started: its frames are+ /// still right, its recordings are not. The graphs then draw from the scratch frame's recording, and Play+ /// or F5 starts a run that refreshes them; no run is started by the edit itself (the user's rule,+ /// 2026-10-14: a probe never changes the picture, and a drag must not launch a simulation).+ /// </summary>+ public bool IsProbesStale+ {+ get => (bool)GetValue(IsProbesStaleProperty);+ set => SetValue(IsProbesStaleProperty, value);+ }+/// <summary>The newest scratch frame (or skip notice) for the preview's position; null when none applies.</summary>public ScratchResult? ScratchFrame{@@ -83,6 +100,7 @@ public partial class MainWindowUpdateScenePixels();}, DispatcherPriority.Background);IsRunStale = false;+ IsProbesStale = false;ScratchFrame = null;if (project != null){@@ -101,6 +119,16 @@ public partial class MainWindowpreviewPane.RefreshColors();return;}+ if (change.AffectsProbes)+ {+ // the frames stay, the recordings are stale: the scratch frame brings the new recording for the position+ if (Run != null)+ {+ IsProbesStale = true;+ }+ ScheduleScratch();+ return;+ }if (!change.AffectsSimulation){return;@@ -122,8 +150,8 @@ public partial class MainWindowScheduleRerun();}- /// <summary>Whether the store cannot show the preview's position: no run, a stale one, or one that has not reached it.</summary>- private bool NeedsScratch => Run == null || IsRunStale || Run.FrameCount <= PreviewPosition;+ /// <summary>Whether the store cannot show the preview's position, or its recordings are stale: no run, a stale one, stale probes, or a run that has not reached it.</summary>+ private bool NeedsScratch => Run == null || IsRunStale || IsProbesStale || Run.FrameCount <= PreviewPosition;private void OnPreviewPositionChanged(){@@ -158,9 +186,10 @@ public partial class MainWindow_scratch = new ScratchRunner(SynchronizationContext.Current);_scratch.Completed += OnScratchCompleted;}- // the user's frame comes first: an automatic run in progress would otherwise take every core (CPU) or- // the card's time away from it; it continues once the frame is there- if (Run is { IsAutomatic: true, IsActive: true } run && !run.IsPauseRequested)+ // the user's frame comes first: a run in progress, automatic or started by the user, would otherwise take+ // every core (CPU) or the card's time away from it; it continues once the frame is there (any run since+ // 2026-10-14; a run the user paused stays paused)+ if (Run is { IsActive: true } run && !run.IsPauseRequested){run.Pause();_pausedForScratch = run;@@ -206,9 +235,9 @@ public partial class MainWindow{return;}- if (_scratch?.IsBusy == true)+ if (_scratch?.IsBusy == true || _scratchTimer?.IsEnabled == true){- // the frame the user is looking at comes first; the run would take the cores away from it+ // the frame the user is looking at comes first, requested or computing; the run would take the cores away from itScheduleRerun();return;}@@ -231,6 +260,10 @@ public partial class MainWindowScheduleScratch();ScheduleRerun();}+ else if (IsProbesStale)+ {+ ScheduleScratch();+ }}/// <summary>The project as a run spec with the scene image decoded (cached by path and write time), or null when it cannot run (logged at Debug).</summary>diff --git a/WaveDude.WPF/MainWindow.Simulation.cs b/WaveDude.WPF/MainWindow.Simulation.csindex e47193c..81ba10a 100644--- a/WaveDude.WPF/MainWindow.Simulation.cs+++ b/WaveDude.WPF/MainWindow.Simulation.cs@@ -67,6 +67,7 @@ public partial class MainWindowLogger.Info("{Kind} started: {Steps} steps, {Frames} frames of {Width}×{Height}; edits made from now on do not affect it",automatic ? "Re-run" : "Run", spec.Steps, spec.FrameCount, spec.Width, spec.Height);IsRunStale = false;+ IsProbesStale = false;Run = run;run.Start();}@@ -97,7 +98,7 @@ public partial class MainWindow/// <summary>Play pressed: a missing or stale run is started like an automatic one (position kept, not followed); errors go to the log and status bar.</summary>private void OnEnsureRun(object sender, ExecutedRoutedEventArgs e){- if (Run?.IsActive == true || (Run != null && !IsRunStale))+ if (Run?.IsActive == true || (Run != null && !IsRunStale && !IsProbesStale)){return;}@@ -126,6 +127,7 @@ public partial class MainWindow// would make it pick the old store for a moment (and wait on its file being deleted)Run = null;IsRunStale = false;+ IsProbesStale = false;if (old == null){return;diff --git a/WaveDude.WPF/MainWindow.xaml b/WaveDude.WPF/MainWindow.xamlindex d38e0f9..3ed0c59 100644--- a/WaveDude.WPF/MainWindow.xaml+++ b/WaveDude.WPF/MainWindow.xaml@@ -225,7 +225,7 @@<docking:DockHost.DocumentContent><Border BorderThickness="1" BorderBrush="{DynamicResource ToolWindowBorder}"><panes:PreviewPane x:Name="previewPane" Project="{Binding Project}" Run="{Binding Run}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}"- IsStale="{Binding IsRunStale}" ScratchFrame="{Binding ScratchFrame}"+ IsStale="{Binding IsRunStale}" IsProbesStale="{Binding IsProbesStale}" ScratchFrame="{Binding ScratchFrame}"Position="{Binding PreviewPosition, Mode=TwoWay}"Orientation="{Binding Source={x:Static p:Settings.Default}, Path=PreviewOrientation, Mode=TwoWay}" /></Border>diff --git a/WaveDude.WPF/MainWindow.xaml.cs b/WaveDude.WPF/MainWindow.xaml.csindex e5b3695..c5556c5 100644--- a/WaveDude.WPF/MainWindow.xaml.cs+++ b/WaveDude.WPF/MainWindow.xaml.cs@@ -105,13 +105,17 @@ public partial class MainWindow : Windowset => SetValue(SelectedItemProperty, value);}- /// <summary>A selection made elsewhere (a marker on the preview) is mirrored in the tree, which then raises its own change with the same item.</summary>+ /// <summary>+ /// A selection made elsewhere (a marker or graph box on the preview) is mirrored in the tree, which then+ /// raises its own change with the same item. The tree node does not take the focus: the handle keeps it,+ /// so Tab can move on to the next handle (the tree stole it and broke the Tab cycle, 2026-10-14).+ /// </summary>private void OnSelectedItemChanged(object? item){CommandManager.InvalidateRequerySuggested();if (item != null && !ReferenceEquals(projectTree.SelectedItem, item)){- projectTree.Select(item);+ projectTree.Select(item, focus: false);}}diff --git a/WaveDude.WPF/Panes/PreviewPane.xaml b/WaveDude.WPF/Panes/PreviewPane.xamlindex 7b895c2..e4ef664 100644--- a/WaveDude.WPF/Panes/PreviewPane.xaml+++ b/WaveDude.WPF/Panes/PreviewPane.xaml@@ -181,6 +181,53 @@</Setter.Value></Setter></Style>+ <!-- a probe's graph box: the thumb covering the box (transparent; focus and hover show a border) and the+ resize grip at its bottom-right corner. The box itself is drawn by the overlay -->+ <Style x:Key="ProbeBoxThumb" TargetType="{x:Type controls:MarkerThumb}">+ <Setter Property="Cursor" Value="SizeAll" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type controls:MarkerThumb}">+ <Border x:Name="Bd" Background="Transparent" BorderBrush="Transparent" BorderThickness="1" SnapsToDevicePixels="True" />+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Bd" Property="BorderBrush" Value="#80FFFFFF" />+ </Trigger>+ <Trigger Property="IsKeyboardFocused" Value="True">+ <Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource Accent}" />+ <Setter TargetName="Bd" Property="BorderThickness" Value="2" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ <StreamGeometry x:Key="ResizeGripGlyph">M11,1 L11,3 L3,11 L1,11 Z M11,6 L11,8 L8,11 L6,11 Z</StreamGeometry>+ <Style x:Key="ProbeBoxCornerThumb" TargetType="{x:Type controls:MarkerThumb}">+ <Setter Property="Width" Value="12" />+ <Setter Property="Height" Value="12" />+ <Setter Property="Cursor" Value="SizeNWSE" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Foreground" Value="#A0FFFFFF" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type controls:MarkerThumb}">+ <Grid Background="Transparent">+ <Path Data="{StaticResource ResizeGripGlyph}" Fill="{TemplateBinding Foreground}" />+ </Grid>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ <Style.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter Property="Foreground" Value="White" />+ </Trigger>+ <Trigger Property="IsKeyboardFocused" Value="True">+ <Setter Property="Foreground" Value="{DynamicResource Accent}" />+ </Trigger>+ </Style.Triggers>+ </Style><!-- the time axis: theme colours for the custom-drawn bar --><Style TargetType="{x:Type controls:TimelineBar}"><Setter Property="Background" Value="{DynamicResource ScrollBarBackground}" />@@ -365,6 +412,18 @@<!-- the scene outline, a translucent layer of the same pixel size, so it lands exactly on the frame --><Image Source="{Binding Path=(local:PreviewPane.OverlayImage), RelativeSource={RelativeSource TemplatedParent}}"Stretch="Uniform" IsHitTestVisible="False" />+ <!-- the probes' graph boxes, under the handles so a handle over a box stays grabbable; which+ probes depends on the cell's layer (the attached PreviewPane.Layer) -->+ <controls:ProbeGraphOverlay BoxStyle="{StaticResource ProbeBoxThumb}" CornerStyle="{StaticResource ProbeBoxCornerThumb}"+ AccentBrush="{DynamicResource Accent}"+ Layer="{Binding Path=(local:PreviewPane.Layer), RelativeSource={RelativeSource TemplatedParent}}"+ Project="{Binding Project, RelativeSource={RelativeSource AncestorType={x:Type local:PreviewPane}}}"+ Run="{Binding Run, RelativeSource={RelativeSource AncestorType={x:Type local:PreviewPane}}}"+ Scratch="{Binding GraphScratch, RelativeSource={RelativeSource AncestorType={x:Type local:PreviewPane}}}"+ Frame="{Binding Position, RelativeSource={RelativeSource AncestorType={x:Type local:PreviewPane}}}"+ CanvasWidth="{Binding CanvasWidth, RelativeSource={RelativeSource AncestorType={x:Type local:PreviewPane}}}"+ CanvasHeight="{Binding CanvasHeight, RelativeSource={RelativeSource AncestorType={x:Type local:PreviewPane}}}"+ SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType={x:Type local:PreviewPane}}, Mode=TwoWay}" /><!-- styled here, not implicitly: WPF applies implicit styles inside a template only to Controls, and the overlay is a Panel --><controls:SceneOverlay SourceStyle="{StaticResource SourceMarker}" ProbeStyle="{StaticResource ProbeMarker}" AngleStyle="{StaticResource AngleMarker}"LineBrush="White" LabelBrush="White" AccentBrush="{DynamicResource Accent}"@@ -438,14 +497,14 @@<RowDefinition Height="*" /></Grid.RowDefinitions><HeaderedContentControl x:Name="fieldCell" Style="{StaticResource PictureCell}" Header="{DynamicResource SectionField}"- Content="{Binding FieldImage, ElementName=pane}" Tag="PreviewFieldImage"+ Content="{Binding FieldImage, ElementName=pane}" Tag="PreviewFieldImage" local:PreviewPane.Layer="Field"local:PreviewPane.OverlayImage="{Binding FieldOverlay, ElementName=pane}"Visibility="{Binding FieldSettings.Preview, ElementName=pane, Converter={StaticResource BoolToVisibility}, FallbackValue=Visible}" /><GridSplitter x:Name="pictureSplitter" Style="{StaticResource PictureSplitter}" ToolTip="{DynamicResource TipPreviewSplitter}"AutomationProperties.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"+ Content="{Binding IntensityImage, ElementName=pane}" Tag="PreviewIntensityImage" local:PreviewPane.Layer="Intensity"local:PreviewPane.OverlayImage="{Binding IntensityOverlay, ElementName=pane}"Visibility="{Binding IntensitySettings.Preview, ElementName=pane, Converter={StaticResource BoolToVisibility}, FallbackValue=Visible}" /></Grid>diff --git a/WaveDude.WPF/Panes/PreviewPane.xaml.cs b/WaveDude.WPF/Panes/PreviewPane.xaml.csindex 8079183..6501f99 100644--- a/WaveDude.WPF/Panes/PreviewPane.xaml.cs+++ b/WaveDude.WPF/Panes/PreviewPane.xaml.cs@@ -158,6 +158,14 @@ public partial class PreviewPane : UserControlpublic static void SetOverlayImage(DependencyObject element, ImageSource? value) => element.SetValue(OverlayImageProperty, value);+ /// <summary>Attached to each picture cell: which output it shows, so its template draws the graph boxes of that layer's probes.</summary>+ public static readonly DependencyProperty LayerProperty = DependencyProperty.RegisterAttached(+ "Layer", typeof(ProbeLayer), typeof(PreviewPane), new PropertyMetadata(ProbeLayer.Field));++ public static ProbeLayer GetLayer(DependencyObject element) => (ProbeLayer)element.GetValue(LayerProperty);++ public static void SetLayer(DependencyObject element, ProbeLayer value) => element.SetValue(LayerProperty, value);+/// <summary>Identifies the <see cref="IntensityImage"/> property.</summary>public static readonly DependencyProperty IntensityImageProperty = DependencyProperty.Register(nameof(IntensityImage), typeof(ImageSource), typeof(PreviewPane));@@ -170,10 +178,20 @@ public partial class PreviewPane : UserControlpublic static readonly DependencyProperty IsStaleProperty = DependencyProperty.Register(nameof(IsStale), typeof(bool), typeof(PreviewPane), new PropertyMetadata(false, (d, _) => ((PreviewPane)d).UpdateSource()));+ /// <summary>Identifies the <see cref="IsProbesStale"/> property.</summary>+ public static readonly DependencyProperty IsProbesStaleProperty = DependencyProperty.Register(+ nameof(IsProbesStale), typeof(bool), typeof(PreviewPane), new PropertyMetadata(false, (d, _) => ((PreviewPane)d).UpdateSource()));+/// <summary>Identifies the <see cref="ScratchFrame"/> property.</summary>public static readonly DependencyProperty ScratchFrameProperty = DependencyProperty.Register(nameof(ScratchFrame), typeof(ScratchResult), typeof(PreviewPane), new PropertyMetadata(null, (d, _) => ((PreviewPane)d).UpdateSource()));+ private static readonly DependencyPropertyKey GraphScratchKey = DependencyProperty.RegisterReadOnly(+ nameof(GraphScratch), typeof(ScratchResult), typeof(PreviewPane), new PropertyMetadata(null));++ /// <summary>Identifies the <see cref="GraphScratch"/> property.</summary>+ public static readonly DependencyProperty GraphScratchProperty = GraphScratchKey.DependencyProperty;+private static readonly DependencyPropertyKey CanvasWidthKey = DependencyProperty.RegisterReadOnly(nameof(CanvasWidth), typeof(int), typeof(PreviewPane), new PropertyMetadata(1));@@ -429,6 +447,24 @@ public partial class PreviewPane : UserControlset => SetValue(ScratchFrameProperty, value);}+ /// <summary>+ /// The scratch frame the probe graphs draw from, or null while they draw from the run: the scratch frame the+ /// pictures show, or, with only the probes stale (<see cref="IsProbesStale"/>: the pictures keep the stored+ /// frame, a probe never changes it), the scratch frame computed for the position (2026-10-14).+ /// </summary>+ public ScratchResult? GraphScratch+ {+ get => (ScratchResult?)GetValue(GraphScratchProperty);+ private set => SetValue(GraphScratchKey, value);+ }++ /// <summary>Whether a probe was edited since the run started: its frames hold, its recordings do not. Bound to the main window.</summary>+ public bool IsProbesStale+ {+ get => (bool)GetValue(IsProbesStaleProperty);+ set => SetValue(IsProbesStaleProperty, value);+ }+/// <summary>Width in pixels of the canvas the pictures show: the run's while one exists, else the project's blank canvas size.</summary>public int CanvasWidth{@@ -545,12 +581,15 @@ public partial class PreviewPane : UserControl_scratchSource = new SnapshotFrameSource(scratch!.Snapshot!);}_presenter.Source = _scratchSource;+ GraphScratch = scratch;UpdateCanvas(_scratchSource);_presenter.Show(0);}else if (run != null && run.FrameCount > Position){_presenter.Source = run.Store;+ // the stored frame is right even with the probes stale; the graphs then take the scratch recording for this position once it is there+ GraphScratch = IsProbesStale && scratch is { Snapshot: not null } && scratch.Frame == Position ? scratch : null;UpdateCanvas(run.Store);_presenter.Show(Position);}@@ -560,6 +599,7 @@ public partial class PreviewPane : UserControl// scratch frame for another position pending, the last picture stays: clearing here made every scrub// without a run flash the empty picture before the new frame arrived (2026-10-13)_presenter.Source = null;+ GraphScratch = null;UpdateCanvas(null);}elsediff --git a/WaveDude.WPF/Panes/ProjectTree.xaml.cs b/WaveDude.WPF/Panes/ProjectTree.xaml.csindex 99b008d..6cca1d5 100644--- a/WaveDude.WPF/Panes/ProjectTree.xaml.cs+++ b/WaveDude.WPF/Panes/ProjectTree.xaml.cs@@ -58,9 +58,9 @@ public partial class ProjectTree : UserControl/// <summary>Raised when <see cref="SelectedItem"/> changes.</summary>public event RoutedPropertyChangedEventHandler<object>? SelectedItemChanged;- /// <summary>Selects the node of a model object once the tree has generated it.</summary>- public void Select(object item) =>- Dispatcher.InvokeAsync(() => tree.SetSelectedItem(item, expand: true), DispatcherPriority.Loaded);+ /// <summary>Selects the node of a model object once the tree has generated it; with <paramref name="focus"/> the node also takes keyboard focus.</summary>+ public void Select(object item, bool focus = true) =>+ Dispatcher.InvokeAsync(() => tree.SetSelectedItem(item, expand: true, focus), DispatcherPriority.Loaded);/// <summary>Selects the root node; call after setting <see cref="Project"/>.</summary>public void SelectRoot()diff --git a/WaveDude.WPF/Strings/Strings.DE.xaml b/WaveDude.WPF/Strings/Strings.DE.xamlindex 18f6e4f..81aea30 100644--- a/WaveDude.WPF/Strings/Strings.DE.xaml+++ b/WaveDude.WPF/Strings/Strings.DE.xaml@@ -87,6 +87,8 @@<s:String x:Key="TipPreviewShowIntensity">Intensitätsbild anzeigen</s:String><s:String x:Key="TipMarkerFormat">{0}: zum Verschieben ziehen; mit Tastaturfokus bewegen die Pfeiltasten um ein Pixel, mit Umschalt um zehn</s:String><s:String x:Key="TipAngleMarkerFormat">{0}: zum Drehen des Rasters ziehen (Umschalt rastet auf 15 Grad ein); mit Tastaturfokus drehen die Pfeiltasten um ein Grad, mit Umschalt um zehn</s:String>+ <s:String x:Key="TipProbeBoxFormat">Diagramm von {0}: zum Verschieben des Kastens ziehen; mit Tastaturfokus bewegen die Pfeiltasten um ein Pixel, mit Umschalt um zehn</s:String>+ <s:String x:Key="TipProbeBoxCornerFormat">Diagramm von {0}: zum Ändern der Kastengröße ziehen (rastet auf den festen Größen ein); mit Tastaturfokus ändern die Pfeiltasten die Größe um ein Pixel, mit Umschalt um zehn</s:String><s:String x:Key="LabelPreviewStep">Schritt</s:String><s:String x:Key="TipPreviewStep">Simulationsschritt des gezeigten Bildes</s:String><s:String x:Key="TipPreviewSplitter">Ziehen oder Pfeiltasten zum Umverteilen; Doppelklick oder Eingabe setzt auf die Mitte zurück</s:String>@@ -214,9 +216,13 @@<s:String x:Key="Label.Probe.BoxSize">Kastengröße</s:String><s:String x:Key="Hint.Probe.BoxSize">Nenngröße des Diagrammkastens über der Ausgabe.</s:String><s:String x:Key="Label.Probe.BoxX">Kasten x</s:String>- <s:String x:Key="Hint.Probe.BoxX">Linker Rand des Diagrammkastens in Leinwandpixeln.</s:String>+ <s:String x:Key="Hint.Probe.BoxX">Linker Rand des Diagrammkastens in Leinwandpixeln. Ein Kasten auf Punkt A der Sonde wandert mit ihr; in die Nähe gezogen rastet er dort ein.</s:String><s:String x:Key="Label.Probe.BoxY">Kasten y</s:String>- <s:String x:Key="Hint.Probe.BoxY">Oberer Rand des Diagrammkastens in Leinwandpixeln.</s:String>+ <s:String x:Key="Hint.Probe.BoxY">Oberer Rand des Diagrammkastens in Leinwandpixeln. Ein Kasten auf Punkt A der Sonde wandert mit ihr; in die Nähe gezogen rastet er dort ein.</s:String>+ <s:String x:Key="Label.Probe.BoxWidth">Kastenbreite</s:String>+ <s:String x:Key="Hint.Probe.BoxWidth">Breite des Diagrammkastens in Leinwandpixeln; nur bei eigener Kastengröße.</s:String>+ <s:String x:Key="Label.Probe.BoxHeight">Kastenhöhe</s:String>+ <s:String x:Key="Hint.Probe.BoxHeight">Höhe des Diagrammkastens in Leinwandpixeln; nur bei eigener Kastengröße.</s:String><s:String x:Key="Label.Probe.ScaleMode">Schrittachse</s:String><s:String x:Key="Hint.Probe.ScaleMode">Gleitendes Fenster der letzten Schritte oder der ganze Lauf; nur Punktsonden.</s:String><s:String x:Key="Label.Probe.AutoScaleX">Schritte automatisch skalieren</s:String>@@ -345,6 +351,7 @@<s:String x:Key="Enum.ProbeBoxSize.Medium">Mittel</s:String><s:String x:Key="Enum.ProbeBoxSize.Large">Groß</s:String><s:String x:Key="Enum.ProbeBoxSize.ExtraLarge">Sehr groß</s:String>+ <s:String x:Key="Enum.ProbeBoxSize.Custom">Eigene</s:String><s:String x:Key="Enum.ProbeScaleMode.Running">Gleitend</s:String><s:String x:Key="Enum.ProbeScaleMode.Full">Ganzer Lauf</s:String><s:String x:Key="Enum.SceneMode.Canvas">Leinwand</s:String>diff --git a/WaveDude.WPF/Strings/Strings.EN.xaml b/WaveDude.WPF/Strings/Strings.EN.xamlindex 9eb3e10..aedf8e4 100644--- a/WaveDude.WPF/Strings/Strings.EN.xaml+++ b/WaveDude.WPF/Strings/Strings.EN.xaml@@ -87,6 +87,8 @@<s:String x:Key="TipPreviewShowIntensity">Show the intensity picture</s:String><s:String x:Key="TipMarkerFormat">{0}: drag to move; with keyboard focus the arrow keys move it by a pixel, ten with Shift</s:String><s:String x:Key="TipAngleMarkerFormat">{0}: drag to turn the array (Shift snaps to 15 degrees); with keyboard focus the arrow keys turn it by a degree, ten with Shift</s:String>+ <s:String x:Key="TipProbeBoxFormat">Graph of {0}: drag to move the box; with keyboard focus the arrow keys move it by a pixel, ten with Shift</s:String>+ <s:String x:Key="TipProbeBoxCornerFormat">Graph of {0}: drag to resize the box (it snaps to the fixed sizes); with keyboard focus the arrow keys resize it by a pixel, ten with Shift</s:String><s:String x:Key="LabelPreviewStep">step</s:String><s:String x:Key="TipPreviewStep">Simulation step of the frame shown</s:String><s:String x:Key="TipPreviewSplitter">Drag or use the arrow keys to resize; double-click or Enter resets to half</s:String>@@ -214,9 +216,13 @@<s:String x:Key="Label.Probe.BoxSize">Box size</s:String><s:String x:Key="Hint.Probe.BoxSize">Nominal size of the graph box drawn over the output.</s:String><s:String x:Key="Label.Probe.BoxX">Box x</s:String>- <s:String x:Key="Hint.Probe.BoxX">Left edge of the graph box in canvas pixels.</s:String>+ <s:String x:Key="Hint.Probe.BoxX">Left edge of the graph box in canvas pixels. A box placed on the probe's point A moves with the probe; dragging it close snaps it on.</s:String><s:String x:Key="Label.Probe.BoxY">Box y</s:String>- <s:String x:Key="Hint.Probe.BoxY">Top edge of the graph box in canvas pixels.</s:String>+ <s:String x:Key="Hint.Probe.BoxY">Top edge of the graph box in canvas pixels. A box placed on the probe's point A moves with the probe; dragging it close snaps it on.</s:String>+ <s:String x:Key="Label.Probe.BoxWidth">Box width</s:String>+ <s:String x:Key="Hint.Probe.BoxWidth">Width of the graph box in canvas pixels; custom box size only.</s:String>+ <s:String x:Key="Label.Probe.BoxHeight">Box height</s:String>+ <s:String x:Key="Hint.Probe.BoxHeight">Height of the graph box in canvas pixels; custom box size only.</s:String><s:String x:Key="Label.Probe.ScaleMode">Step axis</s:String><s:String x:Key="Hint.Probe.ScaleMode">Sliding window of the last steps, or the whole run; point probes only.</s:String><s:String x:Key="Label.Probe.AutoScaleX">Auto-scale steps</s:String>@@ -345,6 +351,7 @@<s:String x:Key="Enum.ProbeBoxSize.Medium">Medium</s:String><s:String x:Key="Enum.ProbeBoxSize.Large">Large</s:String><s:String x:Key="Enum.ProbeBoxSize.ExtraLarge">Extra large</s:String>+ <s:String x:Key="Enum.ProbeBoxSize.Custom">Custom</s:String><s:String x:Key="Enum.ProbeScaleMode.Running">Running</s:String><s:String x:Key="Enum.ProbeScaleMode.Full">Full</s:String><s:String x:Key="Enum.SceneMode.Canvas">Canvas</s:String>diff --git a/WaveDude.WPF/Strings/Strings.FR.xaml b/WaveDude.WPF/Strings/Strings.FR.xamlindex cee2f74..bcbd316 100644--- a/WaveDude.WPF/Strings/Strings.FR.xaml+++ b/WaveDude.WPF/Strings/Strings.FR.xaml@@ -87,6 +87,8 @@<s:String x:Key="TipPreviewShowIntensity">Afficher l'image de l'intensité</s:String><s:String x:Key="TipMarkerFormat">{0} : glisser pour déplacer ; avec le focus clavier, les flèches déplacent d'un pixel, de dix avec Maj</s:String><s:String x:Key="TipAngleMarkerFormat">{0} : glisser pour tourner la grille (Maj aligne sur 15 degrés) ; avec le focus clavier, les flèches la tournent d'un degré, de dix avec Maj</s:String>+ <s:String x:Key="TipProbeBoxFormat">Graphique de {0} : glisser pour déplacer le cadre ; avec le focus clavier, les flèches le déplacent d'un pixel, de dix avec Maj</s:String>+ <s:String x:Key="TipProbeBoxCornerFormat">Graphique de {0} : glisser pour redimensionner le cadre (il s'aligne sur les tailles fixes) ; avec le focus clavier, les flèches le redimensionnent d'un pixel, de dix avec Maj</s:String><s:String x:Key="LabelPreviewStep">pas</s:String><s:String x:Key="TipPreviewStep">Pas de simulation de l'image affichée</s:String><s:String x:Key="TipPreviewSplitter">Glisser ou utiliser les flèches pour redimensionner ; double-clic ou Entrée remet au milieu</s:String>@@ -214,9 +216,13 @@<s:String x:Key="Label.Probe.BoxSize">Taille du cadre</s:String><s:String x:Key="Hint.Probe.BoxSize">Taille nominale du cadre du graphique dessiné sur la sortie.</s:String><s:String x:Key="Label.Probe.BoxX">Cadre x</s:String>- <s:String x:Key="Hint.Probe.BoxX">Bord gauche du cadre du graphique en pixels de toile.</s:String>+ <s:String x:Key="Hint.Probe.BoxX">Bord gauche du cadre du graphique en pixels de toile. Un cadre posé sur le point A de la sonde la suit ; approché en le glissant, il s'y accroche.</s:String><s:String x:Key="Label.Probe.BoxY">Cadre y</s:String>- <s:String x:Key="Hint.Probe.BoxY">Bord supérieur du cadre du graphique en pixels de toile.</s:String>+ <s:String x:Key="Hint.Probe.BoxY">Bord supérieur du cadre du graphique en pixels de toile. Un cadre posé sur le point A de la sonde la suit ; approché en le glissant, il s'y accroche.</s:String>+ <s:String x:Key="Label.Probe.BoxWidth">Largeur du cadre</s:String>+ <s:String x:Key="Hint.Probe.BoxWidth">Largeur du cadre du graphique en pixels de toile ; taille personnalisée seulement.</s:String>+ <s:String x:Key="Label.Probe.BoxHeight">Hauteur du cadre</s:String>+ <s:String x:Key="Hint.Probe.BoxHeight">Hauteur du cadre du graphique en pixels de toile ; taille personnalisée seulement.</s:String><s:String x:Key="Label.Probe.ScaleMode">Axe des pas</s:String><s:String x:Key="Hint.Probe.ScaleMode">Fenêtre glissante des derniers pas, ou toute l'exécution ; sondes ponctuelles seulement.</s:String><s:String x:Key="Label.Probe.AutoScaleX">Échelle auto des pas</s:String>@@ -345,6 +351,7 @@<s:String x:Key="Enum.ProbeBoxSize.Medium">Moyen</s:String><s:String x:Key="Enum.ProbeBoxSize.Large">Grand</s:String><s:String x:Key="Enum.ProbeBoxSize.ExtraLarge">Très grand</s:String>+ <s:String x:Key="Enum.ProbeBoxSize.Custom">Personnalisée</s:String><s:String x:Key="Enum.ProbeScaleMode.Running">Glissant</s:String><s:String x:Key="Enum.ProbeScaleMode.Full">Toute l'exécution</s:String><s:String x:Key="Enum.SceneMode.Canvas">Toile</s:String>diff --git a/WaveDude.WPF/Strings/Strings.NL.xaml b/WaveDude.WPF/Strings/Strings.NL.xamlindex 1f82c36..72137eb 100644--- a/WaveDude.WPF/Strings/Strings.NL.xaml+++ b/WaveDude.WPF/Strings/Strings.NL.xaml@@ -87,6 +87,8 @@<s:String x:Key="TipPreviewShowIntensity">Intensiteitsbeeld tonen</s:String><s:String x:Key="TipMarkerFormat">{0}: slepen om te verplaatsen; met toetsenbordfocus verplaatsen de pijltoetsen één pixel, tien met Shift</s:String><s:String x:Key="TipAngleMarkerFormat">{0}: slepen om het raster te draaien (Shift klikt vast op 15 graden); met toetsenbordfocus draaien de pijltoetsen het één graad, tien met Shift</s:String>+ <s:String x:Key="TipProbeBoxFormat">Grafiek van {0}: slepen om het kader te verplaatsen; met toetsenbordfocus verplaatsen de pijltoetsen het één pixel, tien met Shift</s:String>+ <s:String x:Key="TipProbeBoxCornerFormat">Grafiek van {0}: slepen om het kader te vergroten of verkleinen (het klikt vast op de vaste maten); met toetsenbordfocus wijzigen de pijltoetsen de maat één pixel, tien met Shift</s:String><s:String x:Key="LabelPreviewStep">stap</s:String><s:String x:Key="TipPreviewStep">Simulatiestap van het getoonde beeld</s:String><s:String x:Key="TipPreviewSplitter">Slepen of pijltoetsen om de verdeling te wijzigen; dubbelklik of Enter zet terug op de helft</s:String>@@ -214,9 +216,13 @@<s:String x:Key="Label.Probe.BoxSize">Kadergrootte</s:String><s:String x:Key="Hint.Probe.BoxSize">Nominale grootte van het grafiekkader over de uitvoer.</s:String><s:String x:Key="Label.Probe.BoxX">Kader x</s:String>- <s:String x:Key="Hint.Probe.BoxX">Linkerrand van het grafiekkader in canvaspixels.</s:String>+ <s:String x:Key="Hint.Probe.BoxX">Linkerrand van het grafiekkader in canvaspixels. Een kader op punt A van de sonde beweegt met haar mee; dichtbij gesleept klikt het daar vast.</s:String><s:String x:Key="Label.Probe.BoxY">Kader y</s:String>- <s:String x:Key="Hint.Probe.BoxY">Bovenrand van het grafiekkader in canvaspixels.</s:String>+ <s:String x:Key="Hint.Probe.BoxY">Bovenrand van het grafiekkader in canvaspixels. Een kader op punt A van de sonde beweegt met haar mee; dichtbij gesleept klikt het daar vast.</s:String>+ <s:String x:Key="Label.Probe.BoxWidth">Kaderbreedte</s:String>+ <s:String x:Key="Hint.Probe.BoxWidth">Breedte van het grafiekkader in canvaspixels; alleen bij een eigen kadermaat.</s:String>+ <s:String x:Key="Label.Probe.BoxHeight">Kaderhoogte</s:String>+ <s:String x:Key="Hint.Probe.BoxHeight">Hoogte van het grafiekkader in canvaspixels; alleen bij een eigen kadermaat.</s:String><s:String x:Key="Label.Probe.ScaleMode">Stappenas</s:String><s:String x:Key="Hint.Probe.ScaleMode">Schuivend venster van de laatste stappen, of de hele run; alleen puntsondes.</s:String><s:String x:Key="Label.Probe.AutoScaleX">Stappen automatisch schalen</s:String>@@ -345,6 +351,7 @@<s:String x:Key="Enum.ProbeBoxSize.Medium">Middel</s:String><s:String x:Key="Enum.ProbeBoxSize.Large">Groot</s:String><s:String x:Key="Enum.ProbeBoxSize.ExtraLarge">Extra groot</s:String>+ <s:String x:Key="Enum.ProbeBoxSize.Custom">Eigen maat</s:String><s:String x:Key="Enum.ProbeScaleMode.Running">Schuivend</s:String><s:String x:Key="Enum.ProbeScaleMode.Full">Hele run</s:String><s:String x:Key="Enum.SceneMode.Canvas">Canvas</s:String>diff --git a/WaveDude.WPF/Views/ProbeView.xaml b/WaveDude.WPF/Views/ProbeView.xamlindex 4aafb7a..906117c 100644--- a/WaveDude.WPF/Views/ProbeView.xaml+++ b/WaveDude.WPF/Views/ProbeView.xaml@@ -30,6 +30,15 @@</DataTrigger></Style.Triggers></Style>+ <!-- the box width and height only apply to a custom box size (set by dragging the box's corner, too) -->+ <Style x:Key="CustomSizeOnly" TargetType="{x:Type controls:NumberBox}" BasedOn="{StaticResource {x:Type controls:NumberBox}}">+ <Setter Property="IsEnabled" Value="False" />+ <Style.Triggers>+ <DataTrigger Binding="{Binding BoxSize}" Value="Custom">+ <Setter Property="IsEnabled" Value="True" />+ </DataTrigger>+ </Style.Triggers>+ </Style></UserControl.Resources><ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">@@ -88,6 +97,12 @@<TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.BoxY}" /><controls:NumberBox Text="{Binding BoxY}" Minimum="0" ToolTip="{meta:Hint model:Probe.BoxY}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.BoxWidth}" />+ <controls:NumberBox Style="{StaticResource CustomSizeOnly}" Text="{Binding BoxWidth}" Minimum="60" Maximum="4096" Increment="10" ToolTip="{meta:Hint model:Probe.BoxWidth}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.BoxHeight}" />+ <controls:NumberBox Style="{StaticResource CustomSizeOnly}" Text="{Binding BoxHeight}" Minimum="30" Maximum="4096" Increment="10" ToolTip="{meta:Hint model:Probe.BoxHeight}" /></controls:FormPanel><TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionAxes}" />diff --git a/WaveDude/Engine/GpuWaveSimulator.cs b/WaveDude/Engine/GpuWaveSimulator.csindex b4a0895..4d560e8 100644--- a/WaveDude/Engine/GpuWaveSimulator.cs+++ b/WaveDude/Engine/GpuWaveSimulator.cs@@ -957,7 +957,12 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable}try{- _probes.Program = BuildProgram(ProbeKernelSource(), "the probe program for the GPU");+ if (_probeProgram == IntPtr.Zero)+ {+ // compiled once per engine, not per SetProbes: the scratch runner installs the probes on every request+ // (2026-10-14), and a compile per request cost more than the frame it was for+ _probeProgram = BuildProgram(ProbeKernelSource(), "the probe program for the GPU");+ }if (sampler.HasSeries){SetUpSeriesProbes(sampler);@@ -1014,7 +1019,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable_historyBuffer = CreateBuffer((long)ProbeRows * count * 4L, _probes);for (int k = 0; k <= 1; k++){- IntPtr kernel = _probeKernel[k] = CreateKernel(_probes, "probe_sample");+ IntPtr kernel = _probeKernel[k] = CreateKernel(_probes, _probeProgram, "probe_sample");SetMem(kernel, 0U, _field[k]);SetMem(kernel, 1U, _intensityOutBuffer);SetMem(kernel, 2U, pixelBuffer);@@ -1084,7 +1089,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable_profileOutBuffer = CreateBuffer(new float[totalPixels], _probes);for (int k = 0; k <= 1; k++){- IntPtr kernel = _gatherKernel[k] = CreateKernel(_probes, "profile_gather");+ IntPtr kernel = _gatherKernel[k] = CreateKernel(_probes, _probeProgram, "profile_gather");SetMem(kernel, 0U, _field[k]);SetMem(kernel, 1U, _intensityOutBuffer);SetMem(kernel, 2U, pixelBuffer);@@ -1095,7 +1100,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable}if (_profileIntegrates){- IntPtr kernel = _accumulateKernel = CreateKernel(_probes, "profile_accumulate");+ IntPtr kernel = _accumulateKernel = CreateKernel(_probes, _probeProgram, "profile_accumulate");SetMem(kernel, 0U, _intensityOutBuffer);SetMem(kernel, 1U, pixelBuffer);SetMem(kernel, 2U, modeBuffer);@@ -1251,6 +1256,11 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposableQuietly(() => OpenClApi.clFinish(_queue));}_probes.Release();+ if (_probeProgram != IntPtr.Zero)+ {+ Quietly(() => OpenClApi.clReleaseProgram(_probeProgram));+ _probeProgram = IntPtr.Zero;+ }_emitters.Release();_scene.Release();if (_queue != IntPtr.Zero)@@ -1319,6 +1329,9 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable/// <summary>Rows (steps) the probe history buffer holds before it must be read back to the host.</summary>private const int ProbeRows = 2048;+ /// <summary>The probe program (<see cref="ProbeKernelSource"/>), built on the first <see cref="SetProbes"/> and kept for the engine's life; its kernels and buffers live in <see cref="_probes"/>.</summary>+ private IntPtr _probeProgram;+/// <summary>The device the context lives on; needed again to build the probe program.</summary>private readonly GpuDeviceInfo _device;diff --git a/WaveDude/Model/Probe.cs b/WaveDude/Model/Probe.csindex 3685e94..a38bc4f 100644--- a/WaveDude/Model/Probe.cs+++ b/WaveDude/Model/Probe.cs@@ -47,6 +47,8 @@ public enum ProbeBoxSizeLarge,/// <summary>Largest box.</summary>ExtraLarge,+ /// <summary>A box of <see cref="Probe.BoxWidth"/> × <see cref="Probe.BoxHeight"/> canvas pixels (set by dragging the box's corner).</summary>+ Custom,}/// <summary>How the step axis of a point probe's time series is chosen.</summary>@@ -70,6 +72,16 @@ public sealed class Probe : ObservableObjectpublic const int MinWindow = 10;/// <summary>Largest accepted <see cref="Window"/>.</summary>public const int MaxWindow = 1_000_000;+ /// <summary>Default <see cref="BoxWidth"/> in canvas pixels (the Medium box).</summary>+ public const int DefaultBoxWidth = 400;+ /// <summary>Default <see cref="BoxHeight"/> in canvas pixels (the Medium box).</summary>+ public const int DefaultBoxHeight = 200;+ /// <summary>Smallest accepted <see cref="BoxWidth"/>.</summary>+ public const int MinBoxWidth = 60;+ /// <summary>Smallest accepted <see cref="BoxHeight"/>.</summary>+ public const int MinBoxHeight = 30;+ /// <summary>Largest accepted <see cref="BoxWidth"/> and <see cref="BoxHeight"/>.</summary>+ public const int MaxBoxSide = 4096;private string _name = "";private bool _active = true;@@ -83,6 +95,8 @@ public sealed class Probe : ObservableObjectprivate ProbeBoxSize _boxSize = ProbeBoxSize.Medium;private int _boxX;private int _boxY;+ private int _boxWidth = DefaultBoxWidth;+ private int _boxHeight = DefaultBoxHeight;private ProbeScaleMode _scaleMode = ProbeScaleMode.Running;private bool _autoScaleX = true;private bool _autoScaleY = true;@@ -152,7 +166,11 @@ public sealed class Probe : ObservableObjectset => SetProperty(ref _kind, value);}- /// <summary>X of the probe pixel, or of the start of the line, in canvas pixels.</summary>+ /// <summary>+ /// X of the probe pixel, or of the start of the line, in canvas pixels. While the graph box is attached+ /// (<see cref="IsBoxAttached"/>: its anchor on this point) the box moves along; a box dragged away stays+ /// put (the user's rule, 2026-10-14: one attachment, not one per axis).+ /// </summary>[XmlAttribute][Category("Position")][DisplayName("A x")]@@ -160,10 +178,17 @@ public sealed class Probe : ObservableObjectpublic int AX{get => _aX;- set => SetProperty(ref _aX, value);+ set+ {+ bool attached = IsBoxAttached;+ if (SetProperty(ref _aX, value) && attached)+ {+ BoxX = value;+ }+ }}- /// <summary>Y of the probe pixel, or of the start of the line, in canvas pixels.</summary>+ /// <summary>Y of the probe pixel, or of the start of the line, in canvas pixels. An attached graph box follows it like <see cref="AX"/>.</summary>[XmlAttribute][Category("Position")][DisplayName("A y")]@@ -171,9 +196,25 @@ public sealed class Probe : ObservableObjectpublic int AY{get => _aY;- set => SetProperty(ref _aY, value);+ set+ {+ bool attached = IsBoxAttached;+ if (SetProperty(ref _aY, value) && attached)+ {+ BoxY = value;+ }+ }}+ /// <summary>+ /// Whether the graph box is attached to the probe: its anchor (<see cref="BoxX"/>, <see cref="BoxY"/>) sits on+ /// point A, so the box moves with the probe. The preview snaps a box dragged close to the probe onto it and+ /// detaches it when it is dragged away (2026-10-14).+ /// </summary>+ [XmlIgnore]+ [Browsable(false)]+ public bool IsBoxAttached => _boxX == _aX && _boxY == _aY;+/// <summary>X of the end of the line in canvas pixels; line probes only, omitted from the file otherwise.</summary>[XmlAttribute][DefaultValue(0)]@@ -210,30 +251,54 @@ public sealed class Probe : ObservableObjectset => SetProperty(ref _boxSize, value);}- /// <summary>Left edge of the graph box in canvas pixels.</summary>+ /// <summary>Left edge of the graph box in canvas pixels; with the box on point A (<see cref="IsBoxAttached"/>) it moves with the probe.</summary>[XmlAttribute][DefaultValue(0)][Category("Graph")][DisplayName("Box x")]- [Description("Left edge of the graph box in canvas pixels.")]+ [Description("Left edge of the graph box in canvas pixels. A box placed on the probe's point A moves with the probe; dragging it close snaps it on.")]public int BoxX{get => _boxX;set => SetProperty(ref _boxX, value);}- /// <summary>Top edge of the graph box in canvas pixels.</summary>+ /// <summary>Top edge of the graph box in canvas pixels; with the box on point A (<see cref="IsBoxAttached"/>) it moves with the probe.</summary>[XmlAttribute][DefaultValue(0)][Category("Graph")][DisplayName("Box y")]- [Description("Top edge of the graph box in canvas pixels.")]+ [Description("Top edge of the graph box in canvas pixels. A box placed on the probe's point A moves with the probe; dragging it close snaps it on.")]public int BoxY{get => _boxY;set => SetProperty(ref _boxY, value);}+ /// <summary>Width of the graph box in canvas pixels; used when <see cref="BoxSize"/> is <see cref="ProbeBoxSize.Custom"/>, omitted from the file otherwise.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultBoxWidth)]+ [Category("Graph")]+ [DisplayName("Box width")]+ [Description("Width of the graph box in canvas pixels; custom box size only.")]+ public int BoxWidth+ {+ get => _boxWidth;+ set => SetProperty(ref _boxWidth, value);+ }++ /// <summary>Height of the graph box in canvas pixels; used when <see cref="BoxSize"/> is <see cref="ProbeBoxSize.Custom"/>, omitted from the file otherwise.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultBoxHeight)]+ [Category("Graph")]+ [DisplayName("Box height")]+ [Description("Height of the graph box in canvas pixels; custom box size only.")]+ public int BoxHeight+ {+ get => _boxHeight;+ set => SetProperty(ref _boxHeight, value);+ }+/// <summary>Sliding window of the last steps, or the whole run; point probes only.</summary>[XmlAttribute][DefaultValue(ProbeScaleMode.Running)]@@ -324,14 +389,28 @@ public sealed class Probe : ObservableObject/// <summary>Tells <see cref="XmlSerializer"/> to write B only for line probes.</summary>public bool ShouldSerializeBY() => Kind == ProbeKind.Line;+ /// <summary>Tells <see cref="XmlSerializer"/> to write the box width only for a custom box size.</summary>+ public bool ShouldSerializeBoxWidth() => BoxSize == ProbeBoxSize.Custom;++ /// <summary>Tells <see cref="XmlSerializer"/> to write the box height only for a custom box size.</summary>+ public bool ShouldSerializeBoxHeight() => BoxSize == ProbeBoxSize.Custom;++ /// <summary>+ /// Whether a change of <paramref name="property"/> changes what a run measures (position, kind, layer,+ /// measurement, start step, name, active), as opposed to how the graph is drawn (box and axes).+ /// </summary>+ public static bool AffectsMeasurement(string? property) =>+ property is nameof(Name) or nameof(Active) or nameof(Layer) or nameof(Measurement) or nameof(Kind)+ or nameof(AX) or nameof(AY) or nameof(BX) or nameof(BY) or nameof(StartAfter);+/// <summary>The measurements a probe on <paramref name="layer"/> can record (the editor offers only these).</summary>public static ProbeMeasurement[] MeasurementsFor(ProbeLayer layer) =>layer == ProbeLayer.Field ? [ProbeMeasurement.Amplitude] : [ProbeMeasurement.Intensity, ProbeMeasurement.IntegratedIntensity];/// <summary>/// Forces a consistent state: the field only allows <see cref="ProbeMeasurement.Amplitude"/>,- /// the intensity output never does; an empty or inverted Y range becomes -1..1; the window- /// and start step are clamped.+ /// the intensity output never does; an empty or inverted Y range becomes -1..1; the window,+ /// the custom box size and the start step are clamped./// </summary>public void Normalize(){@@ -350,6 +429,8 @@ public sealed class Probe : ObservableObjectYMax = 1.0;}Window = Math.Clamp(Window, MinWindow, MaxWindow);+ BoxWidth = Math.Clamp(BoxWidth, MinBoxWidth, MaxBoxSide);+ BoxHeight = Math.Clamp(BoxHeight, MinBoxHeight, MaxBoxSide);StartAfter = Math.Max(0, StartAfter);}diff --git a/WaveDude/Model/ProjectWatcher.cs b/WaveDude/Model/ProjectWatcher.csindex e9e22ae..9408278 100644--- a/WaveDude/Model/ProjectWatcher.cs+++ b/WaveDude/Model/ProjectWatcher.cs@@ -11,17 +11,30 @@ namespace WaveDude.Model;public sealed record ProjectChange(object Item, string? Property){/// <summary>- /// Whether the change alters what a simulation computes: the scene, the solver settings, the seed or a- /// source. Display settings, probes and the description do not.+ /// Whether the change alters the frames a run computes: the scene, the solver settings, the seed or a+ /// source. Display settings, probes (see <see cref="AffectsProbes"/>) and the description do not./// </summary>public bool AffectsSimulation => Item switch{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> => false,+ ObservableCollection<ColorScheme> or ObservableCollection<Probe> => false,INotifyCollectionChanged => true,_ => false,};++ /// <summary>+ /// Whether the change alters what a run records for its probes, and nothing else: what a probe measures+ /// (<see cref="Probe.AffectsMeasurement"/>) or the probe list. A probe never changes the picture (the+ /// user's rule, 2026-10-14), so a run's frames stay valid and only its recordings go stale.+ /// </summary>+ public bool AffectsProbes => Item switch+ {+ Probe => Probe.AffectsMeasurement(Property),+ Project => Property == nameof(Project.Probes),+ ObservableCollection<Probe> => true,+ _ => false,+ };}/// <summary>diff --git a/WaveDude/Probes/ProbeCollector.cs b/WaveDude/Probes/ProbeCollector.csindex 8e687b8..7f436df 100644--- a/WaveDude/Probes/ProbeCollector.cs+++ b/WaveDude/Probes/ProbeCollector.cs@@ -4,11 +4,11 @@ namespace WaveDude.Probes;/// <summary>/// Accumulates probe samples and line profiles from the engine into <see cref="ProbeTrace"/>s and hands-/// incremental batches to the UI. Lives entirely on the run's worker: <see cref="Collect"/> /-/// <see cref="CollectProfiles"/> are called after every visualised step and about every 50 ms;-/// <see cref="TakeForUi"/> then packages what arrived since the previous batch into a <see cref="ProbeUpdate"/>,-/// which the run raises as <c>ProbesUpdated</c> and the UI applies to its own traces. The UI thread never touches-/// this object itself.+/// incremental batches to the UI. Lives entirely on the run's worker: <see cref="Collect"/> is called after+/// every recorded frame and about every 50 ms, <see cref="CollectProfiles"/> once per recorded frame (the+/// profiles are kept per frame); <see cref="TakeForUi"/> then packages what arrived since the previous batch+/// into a <see cref="ProbeUpdate"/>, which the run raises as <c>ProbesUpdated</c> and the UI applies to its own+/// traces. The UI thread never touches this object itself./// </summary>public sealed class ProbeCollector{@@ -19,11 +19,12 @@ public sealed class ProbeCollector_sampler = sampler;Traces = new ProbeTrace[sampler.Count];_totals = new double[sampler.Count];- _fresh = new bool[sampler.Count];+ _pendingProfiles = [];for (int i = 0; i < sampler.Count; i++){Traces[i] = new ProbeTrace();_pending.Add(new List<float>());+ _pendingProfiles.Add(new List<float[]>());}}@@ -87,9 +88,9 @@ public sealed class ProbeCollector/// <summary>/// Reads the current line-probe profiles from the engine (<see cref="IWaveEngine.ReadProbeProfiles"/>),- /// stores them in the traces and marks them as fresh for the next <see cref="TakeForUi"/>. Does nothing- /// when there are no line probes. The runner only calls this when a frame or UI batch actually needs the- /// profiles, since the GPU engine has to read them back from the device.+ /// appends them to the traces as the profiles of the next frame and queues them for the next+ /// <see cref="TakeForUi"/>. Does nothing when there are no line probes. The run calls this exactly once+ /// per recorded frame, in frame order, so a trace's profile list is indexed by frame./// </summary>/// <param name="engine">Engine holding the current profiles.</param>/// <param name="stepsDone">Steps completed so far; recorded as <see cref="ProbeTrace.StepsSampled"/>.</param>@@ -106,33 +107,31 @@ public sealed class ProbeCollector{continue;}- Traces[i].SetProfile(profile, _sampler.Lengths[i]);+ Traces[i].AddProfile(profile, _sampler.Lengths[i]);Traces[i].StepsSampled = stepsDone;- _fresh[i] = true;+ _pendingProfiles[i].Add(profile);}_lastStepsDone = stepsDone;}/// <summary>- /// Drains the pending series samples and any freshly updated profiles into a <see cref="ProbeUpdate"/> for- /// the UI thread. Sample arrays are copied; profile arrays are handed over by reference, which is safe- /// because the engine allocates a new array on every read and nobody writes to it afterwards.+ /// Drains the pending series samples and the profiles recorded since the previous call into a+ /// <see cref="ProbeUpdate"/> for the UI thread. Sample arrays are copied; profile arrays are handed over by+ /// reference, which is safe because the engine allocates a new array on every read and nobody writes to it+ /// afterwards./// </summary>/// <returns>A batch covering everything since the previous call; never null.</returns>public ProbeUpdate TakeForUi(){int count = _sampler.Count;float[][] samples = new float[count][];- float[]?[] profiles = new float[count][];+ float[][][] profiles = new float[count][][];for (int i = 0; i < count; i++){samples[i] = _pending[i].ToArray();_pending[i].Clear();- if (_fresh[i])- {- profiles[i] = Traces[i].Profile;- _fresh[i] = false;- }+ profiles[i] = _pendingProfiles[i].ToArray();+ _pendingProfiles[i].Clear();}return new ProbeUpdate(samples, profiles, _sampler.Lengths, _lastStepsDone);}@@ -149,8 +148,8 @@ public sealed class ProbeCollector/// <summary>Per probe: series values collected since the last <see cref="TakeForUi"/>.</summary>private readonly List<List<float>> _pending;- /// <summary>Per probe: true when a new profile arrived since the last <see cref="TakeForUi"/>.</summary>- private readonly bool[] _fresh;+ /// <summary>Per probe: the profiles recorded since the last <see cref="TakeForUi"/>, in frame order.</summary>+ private readonly List<List<float[]>> _pendingProfiles;/// <summary>Steps completed at the most recent collect call; numbers the samples of the next batch and is reported as <see cref="ProbeUpdate.StepsDone"/>.</summary>private int _lastStepsDone;diff --git a/WaveDude/Probes/ProbeGraph.cs b/WaveDude/Probes/ProbeGraph.csnew file mode 100644index 0000000..4bf31fa--- /dev/null+++ b/WaveDude/Probes/ProbeGraph.cs@@ -0,0 +1,649 @@+using System.Globalization;+using System.Numerics;+using WaveDude.Model;++namespace WaveDude.Probes;++/// <summary>A size in canvas pixels.</summary>+/// <param name="Width">Width in canvas pixels.</param>+/// <param name="Height">Height in canvas pixels.</param>+public readonly record struct BoxSize(int Width, int Height);++/// <summary>A rectangle in canvas pixels, origin at the top left.</summary>+/// <param name="X">Left edge.</param>+/// <param name="Y">Top edge.</param>+/// <param name="Width">Width, at least 1.</param>+/// <param name="Height">Height, at least 1.</param>+public readonly record struct BoxRect(int X, int Y, int Width, int Height);++/// <summary>One tick of a graph axis.</summary>+/// <param name="Position">Pixel position along the axis, relative to the box's top-left corner (x for the step/position axis, y for the value axis).</param>+/// <param name="Label">The tick's text.</param>+/// <param name="IsZero">Whether this is the zero line, drawn brighter than the grid.</param>+public readonly record struct GraphTick(float Position, string Label, bool IsZero);++/// <summary>+/// What a probe graph shows at one instant: the first <see cref="Count"/> samples of a point probe's series+/// (value i belongs to step i + 1), or the profile of a line probe at that instant. Taken from a+/// <see cref="ProbeTrace"/> with <see cref="At"/> for the frame the preview shows; <c>default</c> is an+/// empty graph. The arrays are the trace's own and are only read.+/// </summary>+/// <param name="Values">The series' backing array, or null; only the first <see cref="Count"/> entries are shown.</param>+/// <param name="Count">Samples shown, 0 for none.</param>+/// <param name="Profile">The line profile of the instant, or null for none.</param>+/// <param name="ProfileLength">Length of the probe line in canvas pixels, the x span of a profile graph.</param>+/// <param name="StepsSampled">Steps completed at the instant shown; gates a line probe's "start after step".</param>+public readonly record struct ProbeGraphData(float[]? Values, int Count, float[]? Profile, double ProfileLength, int StepsSampled)+{+ /// <summary>+ /// The trace as it stood when frame <paramref name="frame"/> was recorded, after 0-based step+ /// <paramref name="step"/>: the series cut off after that step (fewer when the run has not got there), and+ /// the profile recorded with that frame. When that frame's profile has not arrived yet (a run delivers its+ /// probe batches a little behind its frames, and a scrub can run ahead of it) the newest profile stands in,+ /// so the graph never drops to an empty axis for a moment (the user's flicker, 2026-10-14).+ /// </summary>+ /// <param name="trace">The probe's trace.</param>+ /// <param name="step">The 0-based index of the step shown (frame × visualise-every).</param>+ /// <param name="frame">The frame shown.</param>+ public static ProbeGraphData At(ProbeTrace trace, int step, int frame)+ {+ int count = Math.Clamp(step + 1, 0, trace.Series.Count);+ int profiles = trace.Profiles.Count;+ float[]? profile = profiles == 0 ? null : trace.Profiles[Math.Clamp(frame, 0, profiles - 1)];+ return new ProbeGraphData(trace.Series.Values, count, profile, trace.ProfileLength, Math.Min(trace.StepsSampled, step + 1));+ }+}++/// <summary>+/// How a renderer sets the text of a graph box: the font size and line height in the box's pixels, and how+/// wide a given label comes out. The text does not scale with the box (the author's rule, box height over+/// 14, gave 9 px labels on small boxes and 20 px on large ones, 2026-10-14): the preview passes its fixed+/// UI size, an export the size it wants in canvas pixels.+/// </summary>+/// <param name="fontSize">Font height in pixels.</param>+/// <param name="lineHeight">Height of one text line in pixels (what the renderer reserves for a label).</param>+/// <param name="measure">Width of a label in pixels, as the renderer will draw it.</param>+public sealed class ProbeGraphStyle(float fontSize, float lineHeight, Func<string, float> measure)+{+ /// <summary>Font height in pixels.</summary>+ public float FontSize { get; } = fontSize;++ /// <summary>Height of one text line in pixels.</summary>+ public float LineHeight { get; } = lineHeight;++ /// <summary>Width of a label in pixels.</summary>+ public Func<string, float> Measure { get; } = measure;++ /// <summary>A style without a renderer: 0.6 font sizes per character and 1.3 font sizes per line, for harnesses.</summary>+ public static ProbeGraphStyle Estimate(float fontSize) => new(fontSize, fontSize * 1.3f, text => text.Length * fontSize * 0.6f);+}++/// <summary>+/// The geometry of one probe graph box, in pixels relative to the box's top-left corner, ready to be drawn by+/// any renderer: the plot area, the ticks of both axes with their labels, the curve as a polyline (already+/// reduced to a min/max pair per pixel column when the data is denser than the plot), the title and the+/// readout. Produced by <see cref="ProbeGraph.Layout"/>. Immutable.+/// </summary>+/// <param name="Width">Box width in pixels.</param>+/// <param name="Height">Box height in pixels.</param>+/// <param name="IsVisible">False when the box is too small to draw at all (under 40 × 30).</param>+/// <param name="HasPlot">False when only the box, its border and title fit (plot under 20 × 15 even without labels); the axes and curve are then empty.</param>+/// <param name="FontSize">Label and title font height in pixels (the style's).</param>+/// <param name="LineWidth">Curve stroke width in pixels.</param>+/// <param name="PlotX">Left edge of the plot area.</param>+/// <param name="PlotY">Top edge of the plot area.</param>+/// <param name="PlotWidth">Width of the plot area.</param>+/// <param name="PlotHeight">Height of the plot area.</param>+/// <param name="YTicks">Value-axis ticks: horizontal grid lines at y = Position, labelled right-aligned in the left margin. Labels are empty when the box is too small for them (<see cref="ShowLabels"/>).</param>+/// <param name="XTicks">Step or position axis ticks: vertical grid lines at x = Position, labelled centred below the plot (kept inside the box).</param>+/// <param name="ShowLabels">Whether the tick labels fit; without them the plot takes the margins.</param>+/// <param name="Curve">The curve's points in order; one point is a dot, none is nothing. Clip to the plot area when stroking.</param>+/// <param name="Title">The box title (the probe's name).</param>+/// <param name="Readout">Live readout for the title strip's right end ("= value" or "max value"), empty for none.</param>+public sealed record ProbeGraphLayout(+ float Width,+ float Height,+ bool IsVisible,+ bool HasPlot,+ float FontSize,+ float LineWidth,+ float PlotX,+ float PlotY,+ float PlotWidth,+ float PlotHeight,+ IReadOnlyList<GraphTick> YTicks,+ IReadOnlyList<GraphTick> XTicks,+ bool ShowLabels,+ Vector2[] Curve,+ string Title,+ string Readout)+{+ /// <summary>Left edge of the y labels' column (right-aligned up to <see cref="PlotX"/> − <see cref="ProbeGraph.LabelGap"/>).</summary>+ public float LabelLeft => ProbeGraph.EdgePad;++ /// <summary>Top of the title strip's text.</summary>+ public float TitleTop => ProbeGraph.EdgePad;+}++/// <summary>+/// The numbers behind a probe graph box (a port of the author's GDI+ painter without the drawing): the box+/// rectangle on the canvas, the axis ranges, "nice" ticks, the curve reduced to the pixel grid, and the readout.+/// Everything is pure arithmetic over a <see cref="Probe"/>'s settings and a <see cref="ProbeGraphData"/>, so+/// the WPF preview and a later export draw the same graph. Thread-free: no state.+/// <list type="bullet">+/// <item><description>Point probe: value (y) against the simulation step (x), either the whole run or a running window.</description></item>+/// <item><description>Line probe: value (y) against the position on the line A–B in canvas pixels (x), at the instant shown.</description></item>+/// </list>+/// </summary>+public static class ProbeGraph+{+ /// <summary>Smallest box that is drawn at all, in pixels.</summary>+ public const int MinVisibleWidth = 40;++ /// <summary>Smallest box that is drawn at all, in pixels.</summary>+ public const int MinVisibleHeight = 30;++ /// <summary>Space between the box edge and its text, in pixels.</summary>+ public const float EdgePad = 3f;++ /// <summary>Space between a label and the plot frame, in pixels.</summary>+ public const float LabelGap = 4f;++ /// <summary>Right margin of the plot, in pixels (room for the last x label to overhang).</summary>+ private const float RightMargin = 8f;++ /// <summary>Margin on a side whose labels were dropped, in pixels.</summary>+ private const float BareMargin = 6f;++ /// <summary>Least space between two x labels, in pixels.</summary>+ private const float XLabelSpacing = 8f;++ /// <summary>Smallest plot that is drawn, in pixels.</summary>+ private const float MinPlotWidth = 20f;+ private const float MinPlotHeight = 15f;++ /// <summary>The fixed box sizes, in the order of the enum, for snapping a dragged size.</summary>+ private static readonly ProbeBoxSize[] Presets = [ProbeBoxSize.Tiny, ProbeBoxSize.Small, ProbeBoxSize.Medium, ProbeBoxSize.Large, ProbeBoxSize.ExtraLarge];++ /// <summary>Unscaled box size in canvas pixels for a fixed box size; Medium (and any unknown value, Custom included) is 400 × 200.</summary>+ public static BoxSize NominalBoxSize(ProbeBoxSize boxSize) => boxSize switch+ {+ ProbeBoxSize.Tiny => new BoxSize(200, 100),+ ProbeBoxSize.Small => new BoxSize(300, 150),+ ProbeBoxSize.Large => new BoxSize(500, 250),+ ProbeBoxSize.ExtraLarge => new BoxSize(700, 350),+ _ => new BoxSize(Probe.DefaultBoxWidth, Probe.DefaultBoxHeight),+ };++ /// <summary>The probe's box size in canvas pixels: its own width and height for a custom size, else the fixed size.</summary>+ public static BoxSize BoxSizeOf(Probe probe) => probe.BoxSize == ProbeBoxSize.Custom+ ? new BoxSize(Math.Clamp(probe.BoxWidth, Probe.MinBoxWidth, Probe.MaxBoxSide), Math.Clamp(probe.BoxHeight, Probe.MinBoxHeight, Probe.MaxBoxSide))+ : NominalBoxSize(probe.BoxSize);++ /// <summary>+ /// The graph box of a probe on a canvas: its size, shrunk (keeping the aspect ratio) so it fits into half+ /// the canvas width and the full canvas height, placed at the probe's box position and clamped to stay+ /// inside the canvas.+ /// </summary>+ /// <param name="probe">Provides the box size and the wanted position.</param>+ /// <param name="w">Canvas width in pixels.</param>+ /// <param name="h">Canvas height in pixels.</param>+ /// <returns>The box in canvas pixels, never smaller than 1 × 1.</returns>+ public static BoxRect BoxInCanvas(Probe probe, int w, int h)+ {+ BoxSize nominal = BoxSizeOf(probe);+ double scale = 1.0;+ if (nominal.Width > w / 2.0)+ {+ scale = Math.Min(scale, w / 2.0 / nominal.Width);+ }+ if (nominal.Height > h)+ {+ scale = Math.Min(scale, (double)h / nominal.Height);+ }+ int boxWidth = Math.Max(1, (int)Math.Round(nominal.Width * scale));+ int boxHeight = Math.Max(1, (int)Math.Round(nominal.Height * scale));+ int boxX = Math.Max(0, Math.Min(w - boxWidth, probe.BoxX));+ int boxY = Math.Max(0, Math.Min(h - boxHeight, probe.BoxY));+ return new BoxRect(boxX, boxY, boxWidth, boxHeight);+ }++ /// <summary>+ /// The box size setting for a size the user dragged: a fixed size when both sides are within 8 % (at+ /// least 8 pixels) of it, else a custom size clamped to the accepted range. Applied by the preview when the+ /// box's corner is dragged, so the fixed sizes act as snap points.+ /// </summary>+ /// <param name="width">Wanted width in canvas pixels.</param>+ /// <param name="height">Wanted height in canvas pixels.</param>+ /// <returns>The size setting and the size it stands for.</returns>+ public static (ProbeBoxSize Size, BoxSize Box) Snap(int width, int height)+ {+ foreach (ProbeBoxSize preset in Presets)+ {+ BoxSize nominal = NominalBoxSize(preset);+ if (Math.Abs(width - nominal.Width) <= Math.Max(8, nominal.Width * 0.08) && Math.Abs(height - nominal.Height) <= Math.Max(8, nominal.Height * 0.08))+ {+ return (preset, nominal);+ }+ }+ return (ProbeBoxSize.Custom, new BoxSize(Math.Clamp(width, Probe.MinBoxWidth, Probe.MaxBoxSide), Math.Clamp(height, Probe.MinBoxHeight, Probe.MaxBoxSide)));+ }++ /// <summary>+ /// The axis ranges of a probe graph. For series graphs x is the step number (sample i sits at x = i + 1),+ /// spanning either the whole run or a running window; for profiles x is the distance along the line in+ /// canvas pixels. y comes from the probe's fixed range (falling back to -1..1 when it is empty or inverted)+ /// or, with auto-scaling, from the visible data plus a small margin.+ /// </summary>+ /// <param name="probe">Selects kind, scale mode, fixed y range and auto-scaling.</param>+ /// <param name="data">The data shown; <c>default</c> yields the ranges of an empty graph.</param>+ /// <param name="totalSteps">Total steps of the run; the upper x limit of full-scale series graphs without auto-scaling.</param>+ /// <param name="xMin">Receives the lower x limit.</param>+ /// <param name="xMax">Receives the upper x limit, always greater than <paramref name="xMin"/>.</param>+ /// <param name="yMin">Receives the lower y limit.</param>+ /// <param name="yMax">Receives the upper y limit, always greater than <paramref name="yMin"/>.</param>+ public static void ComputeRanges(Probe probe, in ProbeGraphData data, int totalSteps, out double xMin, out double xMax, out double yMin, out double yMax)+ {+ if (probe.Kind == ProbeKind.Line)+ {+ ProfileRanges(probe, data, out xMin, out xMax, out yMin, out yMax);+ }+ else+ {+ SeriesRanges(probe, data, totalSteps, Math.Max(0, probe.StartAfter), out xMin, out xMax, out yMin, out yMax);+ }+ }++ /// <summary>+ /// Ranges of a time-series graph. Full mode spans from <paramref name="startStep"/> to the samples shown+ /// (auto-scaled x) or to the run length. Running mode shows a window of the probe's <see cref="Probe.Window"/>+ /// (at least 10) steps that slides with the samples shown; auto-scaled it starts narrow and grows to full+ /// width, otherwise it is full width from the start. Auto-scaled y is fitted to the samples inside the x+ /// range. With "start after step" the samples before that step are trimmed off: x never goes below it, so+ /// the visible range starts there (with more room for the data that follows, especially at full scale,+ /// which would otherwise show mostly empty space before the data starts).+ /// </summary>+ private static void SeriesRanges(Probe probe, in ProbeGraphData data, int totalSteps, double startStep, out double xMin, out double xMax, out double yMin, out double yMax)+ {+ int count = data.Values == null ? 0 : data.Count;+ double sampleCount = count;+ if (probe.ScaleMode == ProbeScaleMode.Full)+ {+ xMin = startStep;+ xMax = probe.AutoScaleX ? Math.Max(sampleCount, startStep + 1.0) : Math.Max(totalSteps, startStep + 1.0);+ }+ else+ {+ double window = Math.Max(Probe.MinWindow, probe.Window);+ if (probe.AutoScaleX)+ {+ xMax = Math.Max(sampleCount, startStep + 1.0);+ xMin = Math.Max(startStep, xMax - window);+ }+ else+ {+ xMax = Math.Max(sampleCount, startStep + window);+ xMin = Math.Max(startStep, xMax - window);+ }+ }+ if (xMax <= xMin)+ {+ xMax = xMin + 1.0;+ }+ FixedRange(probe, out yMin, out yMax);+ if (probe.AutoScaleY && count > 0)+ {+ int firstIndex = Math.Max(0, (int)Math.Floor(xMin) - 1);+ int lastIndex = Math.Min(count - 1, (int)Math.Ceiling(xMax));+ if (Extent(data.Values!, firstIndex, lastIndex, out float lo, out float hi))+ {+ AutoRange(probe, lo, hi, ref yMin, ref yMax);+ }+ }+ }++ /// <summary>+ /// Ranges of a line-profile graph: x spans 0..line length in canvas pixels (0..1 without a profile); y is+ /// the fixed range or, auto-scaled, fitted to the profile values. Intensity profiles that are entirely+ /// non-negative are fitted from 0 upwards.+ /// </summary>+ private static void ProfileRanges(Probe probe, in ProbeGraphData data, out double xMin, out double xMax, out double yMin, out double yMax)+ {+ xMin = 0.0;+ xMax = data.Profile != null && data.ProfileLength > 0.0 ? data.ProfileLength : 1.0;+ FixedRange(probe, out yMin, out yMax);+ if (probe.AutoScaleY && data.Profile is { } profile && Extent(profile, 0, profile.Length - 1, out float lo, out float hi))+ {+ AutoRange(probe, lo, hi, ref yMin, ref yMax);+ }+ }++ /// <summary>The probe's fixed y range, or -1..1 when it is empty, inverted or NaN (written so a NaN limit also falls back).</summary>+ private static void FixedRange(Probe probe, out double yMin, out double yMax)+ {+ yMin = probe.YMin;+ yMax = probe.YMax;+ if (!(yMax > yMin))+ {+ yMin = -1.0;+ yMax = 1.0;+ }+ }++ /// <summary>Smallest and largest finite value of <paramref name="values"/>[first..last]; false when there is none.</summary>+ private static bool Extent(float[] values, int first, int last, out float lo, out float hi)+ {+ lo = float.MaxValue;+ hi = float.MinValue;+ for (int i = Math.Max(0, first); i <= last && i < values.Length; i++)+ {+ float value = values[i];+ if (float.IsFinite(value))+ {+ lo = Math.Min(lo, value);+ hi = Math.Max(hi, value);+ }+ }+ return lo <= hi;+ }++ /// <summary>+ /// The auto-scaled value range for data spanning [lo, hi], written so the axis stays put as far as the data+ /// allows (the user's rule, 2026-10-14: fitting both ends independently made the zero line wander while the+ /// first oscillations arrived): a field amplitude gets a range symmetric about zero, ±(largest magnitude+ /// plus 8 %); an intensity (never negative) runs from 0 to the largest value plus 8 %; data that is still+ /// all zeros leaves the fixed range in place (the author's ±1e-6 fit flickered its labels until the first+ /// real value came). A range that goes negative on an intensity probe is treated like an amplitude.+ /// </summary>+ /// <param name="probe">Selects the measurement.</param>+ /// <param name="lo">Smallest data value.</param>+ /// <param name="hi">Largest data value, not below <paramref name="lo"/>.</param>+ /// <param name="yMin">The fixed lower limit; replaced unless the data is all zeros.</param>+ /// <param name="yMax">The fixed upper limit; replaced unless the data is all zeros.</param>+ private static void AutoRange(Probe probe, double lo, double hi, ref double yMin, ref double yMax)+ {+ double magnitude = Math.Max(Math.Abs(hi), Math.Abs(lo));+ if (magnitude <= 0.0)+ {+ return;+ }+ if (probe.Measurement == ProbeMeasurement.Amplitude || lo < 0.0)+ {+ yMax = magnitude * (1.0 + Margin);+ yMin = -yMax;+ }+ else+ {+ yMin = 0.0;+ yMax = hi * (1.0 + Margin);+ }+ }++ /// <summary>Room above the largest value (and below the smallest of a symmetric axis), as a fraction, so the curve does not touch the plot border.</summary>+ private const double Margin = 0.08;++ /// <summary>+ /// "Nice" (1/2/5 × 10ⁿ) tick positions covering [lo, hi], at most 40 of them. A tick within rounding+ /// distance of 0 is snapped to exactly 0 so the zero line can be recognised.+ /// </summary>+ /// <param name="lo">Lower end of the axis range.</param>+ /// <param name="hi">Upper end of the axis range.</param>+ /// <param name="target">Approximate number of ticks wanted.</param>+ /// <returns>Ascending tick values; empty when the range is empty, inverted or infinite.</returns>+ public static List<double> NiceTicks(double lo, double hi, int target)+ {+ var ticks = new List<double>();+ double span = hi - lo;+ // written this way round so a NaN span also yields no ticks+ if (!(span > 0.0) || double.IsInfinity(span))+ {+ return ticks;+ }+ double rawStep = span / Math.Max(1, target);+ double magnitude = Math.Pow(10.0, Math.Floor(Math.Log10(rawStep)));+ double mantissa = rawStep / magnitude;+ double step = mantissa switch+ {+ < 1.5 => 1.0,+ < 3.0 => 2.0,+ < 7.0 => 5.0,+ _ => 10.0,+ } * magnitude;+ double tick = Math.Ceiling(lo / step) * step;+ int guard = 0;+ while (tick <= hi + step * 1e-9 && guard < 40)+ {+ ticks.Add(Math.Abs(tick) < step * 1e-9 ? 0.0 : tick);+ tick += step;+ guard++;+ }+ return ticks;+ }++ /// <summary>Formats an axis value with three significant digits; 0 is just "0".</summary>+ public static string FormatTick(double v, IFormatProvider culture) => v == 0.0 ? "0" : v.ToString("G3", culture);++ /// <summary>Formats an x-axis position: as an integer when the visible <paramref name="span"/> is at least 10 units, otherwise with one decimal.</summary>+ public static string FormatPosition(double v, double span, IFormatProvider culture) =>+ span >= 10.0 ? Math.Round(v).ToString("0", culture) : v.ToString("0.#", culture);++ /// <summary>+ /// Lays out one graph box of <paramref name="width"/> × <paramref name="height"/> pixels. The text keeps+ /// the style's size; the margins come from the labels as measured (the widest value label on the left, a+ /// line below), the tick count is reduced when the labels would collide, and when the labels leave no room+ /// for a plot they are dropped before the plot is. A line probe with "start after step" shows neither+ /// profile nor readout until <see cref="ProbeGraphData.StepsSampled"/> has reached that step; a point+ /// probe's series is trimmed to the start step instead (see <see cref="ComputeRanges"/>) and drawn up to+ /// the current value even before it is reached.+ /// </summary>+ /// <param name="probe">Settings that select kind, scaling and the start-after gate; its name is the title.</param>+ /// <param name="data">The data shown; <c>default</c> for an empty graph.</param>+ /// <param name="totalSteps">Total steps of the run, see <see cref="ComputeRanges"/>.</param>+ /// <param name="width">Box width in pixels (view pixels for the preview, canvas pixels for an export).</param>+ /// <param name="height">Box height in pixels.</param>+ /// <param name="style">The renderer's text metrics in the same pixels.</param>+ /// <param name="culture">Number formatting of the labels; the current culture when null.</param>+ public static ProbeGraphLayout Layout(Probe probe, in ProbeGraphData data, int totalSteps, float width, float height, ProbeGraphStyle style, IFormatProvider? culture = null)+ {+ culture ??= CultureInfo.CurrentCulture;+ bool visible = width >= MinVisibleWidth && height >= MinVisibleHeight;+ float lineWidth = Math.Max(1.2f, height / 110f);+ float titleHeight = style.LineHeight + 2 * EdgePad;+ // a line probe (a profile of an instant) has nothing meaningful to show before the start step is reached,+ // so it stays blank until then; a point probe (a series) is trimmed instead, see SeriesRanges+ bool isLine = probe.Kind == ProbeKind.Line;+ bool started = probe.StartAfter <= 0 || data.StepsSampled >= probe.StartAfter;+ ProbeGraphData shown = isLine && !started ? default : data;+ // a point probe's own range/autoscale sees the real data (it is trimmed by "start after step" inside+ // SeriesRanges, not hidden); only a line probe uses the gated data, to stay blank until it starts+ ComputeRanges(probe, isLine ? shown : data, totalSteps, out double xMin, out double xMax, out double yMin, out double yMax);+ // the value labels decide the left margin; fewer of them when the plot is low+ List<double> yValues = NiceTicks(yMin, yMax, 4);+ float widestY = 0f;+ foreach (double tick in yValues)+ {+ widestY = Math.Max(widestY, style.Measure(FormatTick(tick, culture)));+ }+ float plotX = EdgePad + widestY + LabelGap;+ float plotY = titleHeight;+ float plotWidth = width - plotX - RightMargin;+ float plotHeight = height - plotY - (style.LineHeight + LabelGap);+ bool showLabels = visible && plotWidth >= MinPlotWidth && plotHeight >= MinPlotHeight;+ if (!showLabels)+ {+ // no room for labels: the plot takes their margins (the title strip stays)+ plotX = BareMargin;+ plotWidth = width - plotX - BareMargin;+ plotHeight = height - plotY - BareMargin;+ }+ bool hasPlot = visible && plotWidth >= MinPlotWidth && plotHeight >= MinPlotHeight;+ if (!hasPlot)+ {+ return new ProbeGraphLayout(width, height, visible, false, style.FontSize, lineWidth, plotX, plotY, Math.Max(0, plotWidth), Math.Max(0, plotHeight), [], [], false, [], probe.Name, "");+ }+ if (showLabels)+ {+ // the labels must not overlap: adjacent ticks at least 1.1 lines apart, else fewer ticks (asking for two+ // outright gave a single tick at zero where three fitted, 2026-10-14)+ foreach (int target in new[] { 3, 2 })+ {+ if ((yValues.Count - 1) * style.LineHeight * 1.1f <= plotHeight)+ {+ break;+ }+ yValues = NiceTicks(yMin, yMax, target);+ }+ }+ var yTicks = new List<GraphTick>();+ foreach (double tick in yValues)+ {+ yTicks.Add(new GraphTick(ToPixelY(tick, plotY, plotHeight, yMin, yMax), showLabels ? FormatTick(tick, culture) : "", tick == 0.0));+ }+ // the step/position labels: as many as fit side by side, 5 wanted+ var xTicks = new List<GraphTick>();+ foreach (int target in new[] { 5, 3, 2 })+ {+ xTicks.Clear();+ float labelsWidth = 0f;+ foreach (double tick in NiceTicks(xMin, xMax, target))+ {+ string label = showLabels ? FormatPosition(tick, xMax - xMin, culture) : "";+ labelsWidth += style.Measure(label) + XLabelSpacing;+ xTicks.Add(new GraphTick((float)(plotX + (tick - xMin) / (xMax - xMin) * plotWidth), label, tick == 0.0));+ }+ if (labelsWidth - XLabelSpacing <= plotWidth)+ {+ break;+ }+ }+ Vector2[] curve = isLine+ ? ProfilePoints(shown.Profile, plotX, plotY, plotWidth, plotHeight, yMin, yMax)+ : SeriesPoints(data.Values, data.Count, plotX, plotY, plotWidth, plotHeight, xMin, xMax, yMin, yMax);+ return new ProbeGraphLayout(width, height, true, true, style.FontSize, lineWidth, plotX, plotY, plotWidth, plotHeight, yTicks, xTicks, showLabels, curve, probe.Name, ReadoutText(isLine, shown, culture));+ }++ /// <summary>Short readout for the title strip: "max" of the profile or "=" the latest series value; empty when there is no valid value.</summary>+ private static string ReadoutText(bool isLine, in ProbeGraphData data, IFormatProvider culture)+ {+ if (isLine)+ {+ if (data.Profile is not { Length: > 0 } profile || !Extent(profile, 0, profile.Length - 1, out _, out float max))+ {+ return "";+ }+ return "max " + FormatTick(max, culture);+ }+ if (data.Values == null || data.Count <= 0)+ {+ return "";+ }+ float lastValue = data.Values[data.Count - 1];+ return float.IsFinite(lastValue) ? "= " + FormatTick(lastValue, culture) : "";+ }++ /// <summary>+ /// Maps a data value to a pixel y inside the plot (bottom edge = yMin, top edge = yMax). The result is+ /// clamped to ±30000 so a renderer never sees coordinates far outside its surface.+ /// </summary>+ private static float ToPixelY(double v, float plotY, float plotHeight, double yMin, double yMax)+ {+ double py = plotY + plotHeight - (v - yMin) / (yMax - yMin) * plotHeight;+ return (float)Math.Clamp(py, -30000.0, 30000.0);+ }++ /// <summary>+ /// The points of a time series: sample i is placed at x = i + 1 (its step number); NaN and infinite samples+ /// are skipped. With more than two samples per pixel column each column gets a vertical min/max segment+ /// instead of individual points.+ /// </summary>+ private static Vector2[] SeriesPoints(float[]? values, int count, float plotX, float plotY, float plotWidth, float plotHeight, double xMin, double xMax, double yMin, double yMax)+ {+ if (values == null || count < 1)+ {+ return [];+ }+ int firstIndex = Math.Max(0, (int)Math.Floor(xMin) - 1);+ int lastIndex = Math.Min(count - 1, (int)Math.Ceiling(xMax));+ if (lastIndex < firstIndex)+ {+ return [];+ }+ var points = new List<Vector2>();+ int visibleCount = lastIndex - firstIndex + 1;+ int columns = (int)plotWidth;+ if (visibleCount <= columns * 2)+ {+ // every value gets its own point (value i belongs to step i + 1)+ double xScale = plotWidth / (xMax - xMin);+ for (int i = firstIndex; i <= lastIndex; i++)+ {+ float value = values[i];+ if (float.IsFinite(value))+ {+ points.Add(new Vector2((float)(plotX + (i + 1 - xMin) * xScale), ToPixelY(value, plotY, plotHeight, yMin, yMax)));+ }+ }+ }+ else+ {+ BinColumns(values, firstIndex, visibleCount, lastIndex, columns, plotX, plotY, plotHeight, yMin, yMax, points);+ }+ return [.. points];+ }++ /// <summary>+ /// The points of a line profile stretched over the full plot width (first value at the left edge, last at+ /// the right edge), min/max binned per pixel column when dense. NaN and infinite values are skipped.+ /// </summary>+ private static Vector2[] ProfilePoints(float[]? profile, float plotX, float plotY, float plotWidth, float plotHeight, double yMin, double yMax)+ {+ if (profile == null || profile.Length < 1)+ {+ return [];+ }+ int count = profile.Length;+ var points = new List<Vector2>();+ int columns = (int)plotWidth;+ if (count <= columns * 2)+ {+ for (int i = 0; i < count; i++)+ {+ float value = profile[i];+ if (float.IsFinite(value))+ {+ double fraction = count > 1 ? i / (count - 1.0) : 0.0;+ points.Add(new Vector2((float)(plotX + fraction * plotWidth), ToPixelY(value, plotY, plotHeight, yMin, yMax)));+ }+ }+ }+ else+ {+ BinColumns(profile, 0, count, count - 1, columns, plotX, plotY, plotHeight, yMin, yMax, points);+ }+ return [.. points];+ }++ /// <summary>+ /// Reduces values[first..] to one vertical min/max segment per pixel column: column c covers the values+ /// from first + c × visible / columns on; the long arithmetic keeps c × visible inside the range for+ /// long runs. Columns without a finite value are skipped.+ /// </summary>+ private static void BinColumns(float[] values, int first, int visible, int last, int columns, float plotX, float plotY, float plotHeight, double yMin, double yMax, List<Vector2> points)+ {+ for (int column = 0; column < columns; column++)+ {+ int binStart = first + (int)((long)column * visible / columns);+ int binEnd = first + (int)((long)(column + 1) * visible / columns) - 1;+ if (binEnd < binStart)+ {+ binEnd = binStart;+ }+ if (Extent(values, binStart, Math.Min(binEnd, last), out float binMin, out float binMax))+ {+ float px = plotX + column + 0.5f;+ points.Add(new Vector2(px, ToPixelY(binMin, plotY, plotHeight, yMin, yMax)));+ points.Add(new Vector2(px, ToPixelY(binMax, plotY, plotHeight, yMin, yMax)));+ }+ }+ }+}diff --git a/WaveDude/Probes/ProbeSpec.cs b/WaveDude/Probes/ProbeSpec.csindex 54688f0..585b550 100644--- a/WaveDude/Probes/ProbeSpec.cs+++ b/WaveDude/Probes/ProbeSpec.cs@@ -16,6 +16,7 @@ namespace WaveDude.Probes;/// <param name="BX">X of point B in canvas pixels (line probes).</param>/// <param name="BY">Y of point B in canvas pixels (line probes).</param>/// <param name="StartAfter">Step from which an integrated probe records; 0 records from the first step.</param>+/// <param name="Origin">The model probe the spec was taken from, as an identity only: the preview finds a probe's trace through it and never reads its values, which may have changed since. Null for a spec not taken from the model.</param>public sealed record ProbeSpec(string Name,ProbeKind Kind,@@ -24,9 +25,10 @@ public sealed record ProbeSpec(int AY,int BX,int BY,- int StartAfter)+ int StartAfter,+ Probe? Origin = null){- /// <summary>The spec of a model probe.</summary>+ /// <summary>The spec of a model probe, remembering the probe as its <see cref="Origin"/>.</summary>public static ProbeSpec From(Probe probe) =>- new(probe.Name, probe.Kind, probe.Measurement, probe.AX, probe.AY, probe.BX, probe.BY, probe.StartAfter);+ new(probe.Name, probe.Kind, probe.Measurement, probe.AX, probe.AY, probe.BX, probe.BY, probe.StartAfter, probe);}diff --git a/WaveDude/Probes/ProbeTrace.cs b/WaveDude/Probes/ProbeTrace.csindex ab90463..f6621f6 100644--- a/WaveDude/Probes/ProbeTrace.cs+++ b/WaveDude/Probes/ProbeTrace.cs@@ -1,35 +1,39 @@namespace WaveDude.Probes;/// <summary>-/// Everything recorded for one probe during a run: the time series and, for line probes, the latest profile.+/// Everything recorded for one probe during a run: the time series (one value per step) and, for line probes,+/// one profile per recorded frame (so a scrubbed frame shows the profile of that instant, 2026-10-14)./// Two independent sets exist per run: <see cref="ProbeCollector.Traces"/> is owned by the run's worker; the UI/// keeps its own copies, filled from <see cref="ProbeUpdate"/> batches on the UI thread. An instance is never/// shared between threads./// </summary>public sealed class ProbeTrace{- /// <summary>Number of simulation steps completed when this trace was last updated; used to gate "start after step" line probes in the painter.</summary>+ /// <summary>Number of simulation steps completed when this trace was last updated; gates "start after step" line probes in the graph.</summary>public int StepsSampled { get; set; }- /// <summary>Latest line-probe profile (one value per pixel along the line, A to B), or null until the first profile arrives and always for point probes.</summary>- public float[]? Profile => _profile;+ /// <summary>Line-probe profiles (one value per pixel along the line, A to B), one per recorded frame in frame order; stays empty for point probes.</summary>+ public IReadOnlyList<float[]> Profiles => _profiles;++ /// <summary>The newest profile, or null until the first one arrives and always for point probes.</summary>+ public float[]? Profile => _profiles.Count == 0 ? null : _profiles[^1];/// <summary>Length of the probe line in canvas pixels (distance A to B); 0 for point probes. Used as the x-axis span of the profile graph.</summary>public double ProfileLength => _profileLength;- /// <summary>Replaces the current profile. The array is kept by reference, not copied, so callers must not modify it afterwards.</summary>+ /// <summary>Appends the profile of the next frame. The array is kept by reference, not copied, so callers must not modify it afterwards.</summary>/// <param name="values">Sampled values along the line, A to B.</param>/// <param name="length">Line length in canvas pixels.</param>- public void SetProfile(float[] values, double length)+ public void AddProfile(float[] values, double length){- _profile = values;+ _profiles.Add(values);_profileLength = length;}- /// <summary>Latest profile array; null until <see cref="SetProfile"/> is first called.</summary>- private float[]? _profile;+ /// <summary>The profiles in frame order.</summary>+ private readonly List<float[]> _profiles = [];- /// <summary>Line length in canvas pixels belonging to <see cref="_profile"/>.</summary>+ /// <summary>Line length in canvas pixels belonging to the profiles.</summary>private double _profileLength;/// <summary>Time series of a point probe, one value per sampled step; stays empty for line probes.</summary>diff --git a/WaveDude/Probes/ProbeUpdate.cs b/WaveDude/Probes/ProbeUpdate.csindex c21ca58..57530fe 100644--- a/WaveDude/Probes/ProbeUpdate.cs+++ b/WaveDude/Probes/ProbeUpdate.cs@@ -9,10 +9,10 @@ namespace WaveDude.Probes;public sealed class ProbeUpdate{/// <param name="samples">Per probe: series values since the previous batch (see <see cref="Samples"/>).</param>- /// <param name="profiles">Per probe: refreshed line profile or null (see <see cref="Profiles"/>).</param>+ /// <param name="profiles">Per probe: the line profiles recorded since the previous batch (see <see cref="Profiles"/>).</param>/// <param name="lengths">Per probe: line length in canvas pixels (see <see cref="Lengths"/>).</param>/// <param name="stepsDone">Steps completed when the batch was taken.</param>- public ProbeUpdate(float[][] samples, float[]?[] profiles, double[] lengths, int stepsDone)+ public ProbeUpdate(float[][] samples, float[][][] profiles, double[] lengths, int stepsDone){Samples = samples;Profiles = profiles;@@ -27,11 +27,11 @@ public sealed class ProbeUpdatepublic float[][] Samples { get; }/// <summary>- /// Per probe: the new line profile when it was refreshed since the previous batch, otherwise null. The array- /// is the very instance the worker's trace holds; it is never written to after the engine produced it, so- /// sharing it is safe.+ /// Per probe: the line profiles recorded since the previous batch, one per frame in frame order; empty+ /// (never null) for point probes or when no frame was recorded. The arrays are the very instances the+ /// worker's trace holds; they are never written to after the engine produced them, so sharing them is safe./// </summary>- public float[]?[] Profiles { get; }+ public float[][][] Profiles { get; }/// <summary>Per probe: line length in canvas pixels (0 for point probes). This is the <see cref="ProbeSampler.Lengths"/> array itself, shared read-only by all batches.</summary>public double[] Lengths { get; }diff --git a/WaveDude/Runs/ScratchRunner.cs b/WaveDude/Runs/ScratchRunner.csindex ce156d6..b0919de 100644--- a/WaveDude/Runs/ScratchRunner.cs+++ b/WaveDude/Runs/ScratchRunner.cs@@ -1,20 +1,24 @@using System.Diagnostics;using NLog;using WaveDude.Engine;+using WaveDude.Probes;namespace WaveDude.Runs;-/// <summary>The outcome of a scratch request: the frame, or why it was not computed.</summary>+/// <summary>The outcome of a scratch request: the frame and the probe recordings up to it, or why it was not computed.</summary>/// <param name="Spec">The snapshot of the project the frame was computed for.</param>/// <param name="Frame">The frame index requested.</param>/// <param name="Snapshot">The frame, or null when it was skipped; owned by the runner and valid until the next outcome.</param>/// <param name="Estimate">How long the runner expected (or took) to compute it.</param>-public sealed record ScratchResult(RunSpec Spec, int Frame, FrameSnapshot? Snapshot, TimeSpan Estimate);+/// <param name="Traces">Per probe of <see cref="RunSpec.Probes"/>: the series up to the frame's step and, for a line probe, its one profile at the frame (index 0); empty when skipped or without probes. Owned by the result; read on the UI thread.</param>+public sealed record ScratchResult(RunSpec Spec, int Frame, FrameSnapshot? Snapshot, TimeSpan Estimate, ProbeTrace[] Traces);/// <summary>/// Computes single frames of the current project state on demand, without a store: after an edit the/// preview asks for "frame k of the project as it is now", and the runner steps an engine from zero to that-/// frame and captures it. The engine is kept between requests (a GPU engine takes a few hundred+/// frame and captures it, sampling the project's probes along the way so their graphs are as live as the+/// picture (2026-10-14; the sampling costs a kernel launch per step and a few kilobytes of readback, nothing+/// against the stepping). The engine is kept between requests (a GPU engine takes a few hundred/// milliseconds to build) and only reset, or given new emitters when just the sources changed; it is rebuilt/// when the scene or the solver options change. Only the newest request is served: a request arriving/// while one is computing abandons it. A request whose predicted cost (steps × the measured cost per step)@@ -164,10 +168,13 @@ public sealed class ScratchRunner : IDisposableif (!double.IsNaN(msPerStep) && estimate > Budget){Logger.Debug("Preview frame {Frame} skipped: {Steps} steps would take {Estimate:0.0} s", frame, steps, estimate.TotalSeconds);- Post(new ScratchResult(spec, frame, null, estimate));+ Post(new ScratchResult(spec, frame, null, estimate, []));return;}IWaveEngine engine = EngineFor(spec);+ // the spec's probes, installed per request (Reset removes them; a fresh engine has none)+ ProbeSampler? sampler = spec.Probes.Length > 0 ? ProbeSampler.Build(spec.Probes, spec.Width, spec.Height) : null;+ engine.SetProbes(sampler);var clock = Stopwatch.StartNew();for (int i = 0; i < steps; i++){@@ -176,6 +183,10 @@ public sealed class ScratchRunner : IDisposablereturn; // the loop picks up the newer request}engine.AdvanceOneStep();+ if (sampler != null)+ {+ engine.SampleProbes();+ }}TimeSpan stepping = clock.Elapsed;FrameSnapshot snapshot = NextSnapshot(spec);@@ -183,6 +194,15 @@ public sealed class ScratchRunner : IDisposableengine.AwaitFrame(snapshot);snapshot.Frame = frame;snapshot.Step = steps - 1;+ // the recordings: every series up to this step (integrated probes summed by the collector), the profiles of this instant+ ProbeTrace[] traces = [];+ if (sampler != null)+ {+ var collector = new ProbeCollector(sampler);+ collector.Collect(engine, steps);+ collector.CollectProfiles(engine, steps);+ traces = collector.Traces;+ }clock.Stop();// the stepping loop alone rules the next prediction (the capture is a fixed cost, and the GPU's first// steps include its warm-up), and only when there were enough steps to measure@@ -191,7 +211,7 @@ public sealed class ScratchRunner : IDisposableVolatile.Write(ref _msPerStep, stepping.TotalMilliseconds / steps);}Logger.Debug("Preview frame {Frame}: {Steps} steps in {Elapsed:0} ms on {Engine}", frame, steps, clock.Elapsed.TotalMilliseconds, engine.Description);- Post(new ScratchResult(spec, frame, snapshot, clock.Elapsed));+ Post(new ScratchResult(spec, frame, snapshot, clock.Elapsed, traces));}/// <summary>The kept engine, reset to step 0 and given the spec's emitters; rebuilt when the scene or the options differ.</summary>diff --git a/WaveDude/Runs/SimulationRun.cs b/WaveDude/Runs/SimulationRun.csindex 86dd77f..8804f3b 100644--- a/WaveDude/Runs/SimulationRun.cs+++ b/WaveDude/Runs/SimulationRun.cs@@ -304,7 +304,10 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposablecomputeTicks += t1 - t0;if (i % every == 0 && frame < Store.Capacity){+ // the series up to this step and the line profiles of this frame (kept per frame, so the+ // preview shows the profile of the frame it scrubs to)collector?.Collect(engine, stepsDone);+ collector?.CollectProfiles(engine, stepsDone);// a free snapshot (waiting here is the back pressure when the writer lags), captured// without waiting for the copy; the writer awaits and stores itFrameSnapshot snapshot = pool.Take(token);@@ -394,20 +397,19 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposabledrain?.Invoke();}- /// <summary>Collects what the engine has, takes a batch and applies it to <see cref="Traces"/> on the UI context.</summary>+ /// <summary>Collects the series the engine has (the profiles are collected per frame), takes a batch and applies it to <see cref="Traces"/> on the UI context.</summary>private void PublishProbes(IWaveEngine engine, ProbeCollector collector, int stepsDone){collector.Collect(engine, stepsDone);- collector.CollectProfiles(engine, stepsDone);ProbeUpdate update = collector.TakeForUi();Post(() =>{for (int i = 0; i < Traces.Length && i < update.Samples.Length; i++){Traces[i].Series.Add(update.Samples[i]);- if (update.Profiles[i] is { } profile)+ foreach (float[] profile in update.Profiles[i]){- Traces[i].SetProfile(profile, update.Lengths[i]);+ Traces[i].AddProfile(profile, update.Lengths[i]);}Traces[i].StepsSampled = update.StepsDone;}diff --git a/Wave_Dude_Examples/Example2_Coherent_source/Example2_Coherent_source.wdproj b/Wave_Dude_Examples/Example2_Coherent_source/Example2_Coherent_source.wdprojnew file mode 100644index 0000000..118acb8--- /dev/null+++ b/Wave_Dude_Examples/Example2_Coherent_source/Example2_Coherent_source.wdproj@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<Project Version="1" Seed="1524560584">+ <Description>Featuring a 21 x 7 composite source that emits a continuous gaussian wave beam</Description>+ <Scene DampingEdge="64" />+ <Simulation Steps="4000" />+ <Display>+ <Field ColorScheme="Default_Field" Brightness="6" BlackLevel="-0.05" />+ <Intensity ColorScheme="inferno" Brightness="7" />+ </Display>+ <Source Name="Source 2" X="442" Y="580" Frequency="50" Amplitude="30">+ <Array SizeX="21" SizeY="7" SpacingX="32" SpacingY="16" />+ </Source>+ <Probe Name="Probe 1" Active="false" AX="1171" AY="226" BoxSize="Large" BoxX="13" BoxY="11" />+ <Probe Name="Probe 2" Layer="Intensity" Measurement="IntegratedIntensity" Kind="Line" AX="1051" AY="534" BX="1294" BY="957" BoxSize="ExtraLarge" BoxX="16" BoxY="13" YMin="0" YMax="0.005" />+</Project>\ No newline at end of filediff --git a/_tools/_edit_snap.py b/_tools/_edit_snap.pynew file mode 100644index 0000000..faca4b3--- /dev/null+++ b/_tools/_edit_snap.py@@ -0,0 +1,200 @@+import re++def edit(path, pairs):+ s = open(path, encoding='utf-8').read()+ for old, new in pairs:+ if old not in s:+ raise SystemExit('not found in ' + path + ': ' + old[:70])+ s = s.replace(old, new, 1)+ open(path, 'w', encoding='utf-8', newline='').write(s)++edit('WaveDude/Model/Probe.cs', [+(''' /// <summary>+ /// X of the probe pixel, or of the start of the line, in canvas pixels. While the graph box sits at the+ /// same x (<see cref="BoxX"/> equal), the box moves along; a box dragged elsewhere stays put+ /// (the user's rule, 2026-10-14).+ /// </summary>''', ''' /// <summary>+ /// X of the probe pixel, or of the start of the line, in canvas pixels. While the graph box is attached+ /// (<see cref="IsBoxAttached"/>: its anchor on this point) the box moves along; a box dragged away stays+ /// put (the user's rule, 2026-10-14: one attachment, not one per axis).+ /// </summary>'''),+(''' set+ {+ bool boxFollows = _boxX == _aX;+ if (SetProperty(ref _aX, value) && boxFollows)+ {+ BoxX = value;+ }+ }+ }++ /// <summary>Y of the probe pixel, or of the start of the line, in canvas pixels. The graph box follows it like <see cref="AX"/>.</summary>''', ''' set+ {+ bool attached = IsBoxAttached;+ if (SetProperty(ref _aX, value) && attached)+ {+ BoxX = value;+ }+ }+ }++ /// <summary>Y of the probe pixel, or of the start of the line, in canvas pixels. An attached graph box follows it like <see cref="AX"/>.</summary>'''),+(''' set+ {+ bool boxFollows = _boxY == _aY;+ if (SetProperty(ref _aY, value) && boxFollows)+ {+ BoxY = value;+ }+ }+ }''', ''' set+ {+ bool attached = IsBoxAttached;+ if (SetProperty(ref _aY, value) && attached)+ {+ BoxY = value;+ }+ }+ }++ /// <summary>+ /// Whether the graph box is attached to the probe: its anchor (<see cref="BoxX"/>, <see cref="BoxY"/>) sits on+ /// point A, so the box moves with the probe. The preview snaps a box dragged close to the probe onto it and+ /// detaches it when it is dragged away (2026-10-14).+ /// </summary>+ [XmlIgnore]+ [Browsable(false)]+ public bool IsBoxAttached => _boxX == _aX && _boxY == _aY;'''),+(''' /// <summary>Left edge of the graph box in canvas pixels; while it equals <see cref="AX"/>, the box moves with the probe.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("Graph")]+ [DisplayName("Box x")]+ [Description("Left edge of the graph box in canvas pixels; while it equals A x, the box moves with the probe.")]''',+ ''' /// <summary>Left edge of the graph box in canvas pixels; with the box on point A (<see cref="IsBoxAttached"/>) it moves with the probe.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("Graph")]+ [DisplayName("Box x")]+ [Description("Left edge of the graph box in canvas pixels. A box placed on the probe's point A moves with the probe; dragging it close snaps it on.")]'''),+(''' /// <summary>Top edge of the graph box in canvas pixels; while it equals <see cref="AY"/>, the box moves with the probe.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("Graph")]+ [DisplayName("Box y")]+ [Description("Top edge of the graph box in canvas pixels; while it equals A y, the box moves with the probe.")]''',+ ''' /// <summary>Top edge of the graph box in canvas pixels; with the box on point A (<see cref="IsBoxAttached"/>) it moves with the probe.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("Graph")]+ [DisplayName("Box y")]+ [Description("Top edge of the graph box in canvas pixels. A box placed on the probe's point A moves with the probe; dragging it close snaps it on.")]'''),+])++edit('WaveDude.WPF/Controls/ProbeGraphOverlay.cs', [+(''' /// <summary>Pixels a focused box moves or grows per arrow key, and with Shift.</summary>+ private const int KeyStep = 1;+ private const int KeyStepFast = 10;''', ''' /// <summary>Pixels a focused box moves or grows per arrow key, and with Shift.</summary>+ private const int KeyStep = 1;+ private const int KeyStepFast = 10;++ /// <summary>Screen distance within which a dragged box snaps onto its probe's point A and attaches to it.</summary>+ private const double SnapRadius = 14.0;'''),+(''' else+ {+ SetBoxPosition(probe, x, y);+ }+ }++ /// <summary>Moves the box, kept inside the canvas.</summary>+ private void SetBoxPosition(Probe probe, int x, int y)+ {+ BoxRect box = ProbeGraph.BoxInCanvas(probe, CanvasWidth, CanvasHeight);+ probe.BoxX = Math.Clamp(x, 0, Math.Max(0, CanvasWidth - box.Width));+ probe.BoxY = Math.Clamp(y, 0, Math.Max(0, CanvasHeight - box.Height));+ }''', ''' else+ {+ SetBoxPosition(probe, x, y, snap: true);+ }+ }++ /// <summary>+ /// Moves the box, kept inside the canvas. With <paramref name="snap"/> (a drag, not a keyboard nudge) a box+ /// whose anchor comes within <see cref="SnapRadius"/> screen pixels of the probe's point A lands on it and is+ /// attached from then on (<see cref="Probe.IsBoxAttached"/>); dragging it further away detaches it. One radius,+ /// not a snap per axis (the user's rule, 2026-10-14).+ /// </summary>+ private void SetBoxPosition(Probe probe, int x, int y, bool snap)+ {+ if (snap)+ {+ double scale = ScaleFor(RenderSize);+ double dx = (x - probe.AX) * scale;+ double dy = (y - probe.AY) * scale;+ if (dx * dx + dy * dy <= SnapRadius * SnapRadius)+ {+ x = probe.AX;+ y = probe.AY;+ }+ }+ BoxRect box = ProbeGraph.BoxInCanvas(probe, CanvasWidth, CanvasHeight);+ probe.BoxX = Math.Clamp(x, 0, Math.Max(0, CanvasWidth - box.Width));+ probe.BoxY = Math.Clamp(y, 0, Math.Max(0, CanvasHeight - box.Height));+ }'''),+(''' SetBoxPosition(probe, probe.BoxX + dx, probe.BoxY + dy);''', ''' SetBoxPosition(probe, probe.BoxX + dx, probe.BoxY + dy, snap: false);'''),+])++hints = {+ 'EN': ('Left edge of the graph box in canvas pixels. A box placed on the probe\'s point A moves with the probe; dragging it close snaps it on.',+ 'Top edge of the graph box in canvas pixels. A box placed on the probe\'s point A moves with the probe; dragging it close snaps it on.'),+ 'DE': ('Linker Rand des Diagrammkastens in Leinwandpixeln. Ein Kasten auf Punkt A der Sonde wandert mit ihr; in die Nähe gezogen rastet er dort ein.',+ 'Oberer Rand des Diagrammkastens in Leinwandpixeln. Ein Kasten auf Punkt A der Sonde wandert mit ihr; in die Nähe gezogen rastet er dort ein.'),+ 'FR': ('Bord gauche du cadre du graphique en pixels de toile. Un cadre posé sur le point A de la sonde la suit ; approché en le glissant, il s\'y accroche.',+ 'Bord supérieur du cadre du graphique en pixels de toile. Un cadre posé sur le point A de la sonde la suit ; approché en le glissant, il s\'y accroche.'),+ 'NL': ('Linkerrand van het grafiekkader in canvaspixels. Een kader op punt A van de sonde beweegt met haar mee; dichtbij gesleept klikt het daar vast.',+ 'Bovenrand van het grafiekkader in canvaspixels. Een kader op punt A van de sonde beweegt met haar mee; dichtbij gesleept klikt het daar vast.'),+}+for lang, (x, y) in hints.items():+ path = 'WaveDude.WPF/Strings/Strings.%s.xaml' % lang+ s = open(path, encoding='utf-8').read()+ s, n1 = re.subn(r'(<s:String x:Key="Hint.Probe.BoxX">)[^<]*(</s:String>)', lambda m: m.group(1) + x + m.group(2), s)+ s, n2 = re.subn(r'(<s:String x:Key="Hint.Probe.BoxY">)[^<]*(</s:String>)', lambda m: m.group(1) + y + m.group(2), s)+ if n1 != 1 or n2 != 1:+ raise SystemExit('hint not found in ' + path)+ open(path, 'w', encoding='utf-8', newline='').write(s)++edit('_tools/library_check/Program.cs', [+(''' var follower = new Probe { Name = "F" };+ follower.AX = 50;+ follower.AY = 60;+ Check(follower.BoxX == 50 && follower.BoxY == 60, "the graph box moves with the probe while they share its position");+ follower.BoxX = 10;+ follower.AX = 70;+ follower.AY = 61;+ Check(follower.BoxX == 10 && follower.BoxY == 61, "a box moved away stays put on that axis; the other axis still follows");''',+ ''' var follower = new Probe { Name = "F" };+ follower.AX = 50;+ follower.AY = 60;+ Check(follower.IsBoxAttached && follower.BoxX == 50 && follower.BoxY == 60, "an attached graph box moves with the probe");+ follower.BoxX = 10;+ follower.AX = 70;+ follower.AY = 61;+ Check(!follower.IsBoxAttached && follower.BoxX == 10 && follower.BoxY == 60, "a box moved away is detached on both axes and stays put");+ follower.BoxX = 70;+ follower.BoxY = 61;+ follower.AX = 75;+ Check(follower.IsBoxAttached && follower.BoxX == 75 && follower.BoxY == 61, "a box put back on the probe is attached again");'''),+])++edit('CLAUDE.md', [+('''**The box follows the+ probe while they share a position** (the user's rule): `Probe.AX`/`AY` move `BoxX`/`BoxY` along when they+ were equal (in the model, so every editor does it), and a box dragged elsewhere stays put per axis.''',+ '''**The box follows the+ probe while it is attached** (the user's rule, one attachment, not one per axis, 2026-10-14):+ `Probe.IsBoxAttached` is the box anchor sitting on point A; `Probe.AX`/`AY` then move `BoxX`/`BoxY` along+ (in the model, so every editor does it). Dragging the box within 14 screen pixels of point A snaps it on+ (`ProbeGraphOverlay.SetBoxPosition`, drags only; keyboard nudges stay exact), dragging it further away+ detaches it.'''),+])+print('ok')diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.csindex d9fadf8..d08db16 100644--- a/_tools/library_check/Program.cs+++ b/_tools/library_check/Program.cs@@ -168,6 +168,7 @@ internal static class ProgramCheckFrameStore(scene);CheckRenderer();CheckColorSchemes();+ CheckProbeGraph();CheckImport();CheckRun();@@ -685,6 +686,133 @@ internal static class ProgramCheck(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");}+ private static void CheckProbeGraph()+ {+ Console.WriteLine("--- probe graph geometry");+ var inv = CultureInfo.InvariantCulture;+ var probe = new Probe { Name = "P", BoxX = 1700, BoxY = 900 };+ Check(ProbeGraph.NominalBoxSize(ProbeBoxSize.Medium) == new BoxSize(400, 200) && ProbeGraph.NominalBoxSize(ProbeBoxSize.Tiny) == new BoxSize(200, 100), "nominal box sizes");+ var turned = new Source { Name = "Turned", X = 100, Y = 100, Array = new SourceArray { SizeX = 3, SizeY = 1, SpacingX = 10, Angle = 90 } };+ turned.GenerateElements(1);+ Check(turned.Elements.Select(e => (e.X, e.Y)).SequenceEqual([(100, 110), (100, 100), (100, 90)]), "a 3 x 1 array turned by 90 degrees stands vertical, counter-clockwise on the screen");+ turned.Array.Angle = 45;+ turned.GenerateElements(1);+ Check(turned.Elements.Select(e => (e.X, e.Y)).SequenceEqual([(93, 107), (100, 100), (107, 93)]), "45 degrees: the ends at (-7, +7) and (+7, -7)");+ turned.Array.Angle = 540;+ turned.Array.Normalize();+ bool wraps = turned.Array.Angle == 180;+ turned.Array.Angle = -180;+ turned.Array.Normalize();+ wraps &= turned.Array.Angle == 180;+ turned.Array.Angle = -190;+ turned.Array.Normalize();+ wraps &= turned.Array.Angle == 170;+ turned.Array.Angle = 190;+ turned.Array.Normalize();+ Check(wraps && turned.Array.Angle == -170, "an angle is normalised into (-180, 180]: 540 -> 180, -180 -> 180, -190 -> 170, 190 -> -170");+ var follower = new Probe { Name = "F" };+ follower.AX = 50;+ follower.AY = 60;+ Check(follower.IsBoxAttached && follower.BoxX == 50 && follower.BoxY == 60, "an attached graph box moves with the probe");+ follower.BoxX = 10;+ follower.AX = 70;+ follower.AY = 61;+ Check(!follower.IsBoxAttached && follower.BoxX == 10 && follower.BoxY == 60, "a box moved away is detached on both axes and stays put");+ follower.BoxX = 70;+ follower.BoxY = 61;+ follower.AX = 75;+ Check(follower.IsBoxAttached && follower.BoxX == 75 && follower.BoxY == 61, "a box put back on the probe is attached again");+ Check(ProbeGraph.BoxInCanvas(probe, 1920, 1080) == new BoxRect(1520, 880, 400, 200), "box clamped into a full-HD canvas");+ Check(ProbeGraph.BoxInCanvas(probe, 64, 48) == new BoxRect(32, 32, 32, 16), "box shrunk to half the width of a 64 x 48 canvas, aspect kept");+ probe.BoxSize = ProbeBoxSize.Custom;+ probe.BoxWidth = 500;+ probe.BoxHeight = 100;+ Check(ProbeGraph.BoxSizeOf(probe) == new BoxSize(500, 100) && ProbeGraph.BoxInCanvas(probe, 1920, 1080) == new BoxRect(1420, 900, 500, 100), "custom box size used as it is");+ Check(ProbeGraph.Snap(405, 195) == (ProbeBoxSize.Medium, new BoxSize(400, 200)) && ProbeGraph.Snap(690, 360) == (ProbeBoxSize.ExtraLarge, new BoxSize(700, 350)), "a dragged size near a preset snaps to it");+ Check(ProbeGraph.Snap(450, 230) == (ProbeBoxSize.Custom, new BoxSize(450, 230)) && ProbeGraph.Snap(10, 10) == (ProbeBoxSize.Custom, new BoxSize(60, 30)), "other sizes stay custom, clamped to the minimum");+ Check(ProbeGraph.NiceTicks(-1, 1, 4).SequenceEqual([-1.0, -0.5, 0.0, 0.5, 1.0]) && ProbeGraph.NiceTicks(0, 2500, 5).SequenceEqual([0.0, 500.0, 1000.0, 1500.0, 2000.0, 2500.0]), "nice ticks at 1/2/5 steps, zero exact");+ Check(ProbeGraph.NiceTicks(0.3, 0.3, 4).Count == 0 && ProbeGraph.NiceTicks(double.NaN, 1, 4).Count == 0, "no ticks for an empty or NaN range");+ Check(ProbeGraph.FormatTick(0.123456, inv) == "0.123" && ProbeGraph.FormatTick(0, inv) == "0" && ProbeGraph.FormatTick(0.5, new CultureInfo("de-DE")) == "0,5", "tick labels: 3 significant digits, locale decimal separator");+ Check(ProbeGraph.FormatPosition(1234.6, 2500, inv) == "1235" && ProbeGraph.FormatPosition(2.25, 5, inv) == "2.3", "position labels: integers over wide spans, one decimal otherwise");++ // a point probe's series: 120 samples, a sine between -0.5 and 0.5+ float[] values = new float[1024];+ for (int i = 0; i < 120; i++)+ {+ values[i] = 0.5f * MathF.Sin(i * 0.2f);+ }+ var point = new Probe { Name = "Point", Window = 500 };+ var data = new ProbeGraphData(values, 120, null, 0, 120);+ ProbeGraph.ComputeRanges(point, data, 2500, out double xMin, out double xMax, out double yMin, out double yMax);+ Check(xMin == 0 && xMax == 120, "running window, auto x: 0..samples shown (" + xMin + ".." + xMax + ")");+ Check(Math.Abs(yMin + 0.54) < 0.001 && Math.Abs(yMax - 0.54) < 0.001, "auto y: symmetric about zero, largest magnitude plus 8 % (" + yMin.ToString("0.000", inv) + ".." + yMax.ToString("0.000", inv) + ")");+ float[] lopsided = new float[16];+ lopsided[3] = -0.2f;+ lopsided[7] = 0.5f;+ ProbeGraph.ComputeRanges(point, new ProbeGraphData(lopsided, 16, null, 0, 16), 2500, out _, out _, out double lopMin, out double lopMax);+ Check(Math.Abs(lopMin + 0.54) < 0.001 && Math.Abs(lopMax - 0.54) < 0.001, "lopsided data still gets a symmetric axis (" + lopMin.ToString("0.00", inv) + ".." + lopMax.ToString("0.00", inv) + ")");+ ProbeGraph.ComputeRanges(point, new ProbeGraphData(new float[16], 16, null, 0, 16), 2500, out _, out _, out double zeroMin, out double zeroMax);+ Check(zeroMin == -1 && zeroMax == 1, "all-zero data keeps the fixed range instead of a 1e-6 fit");+ var intensityProbe = new Probe { Name = "I", Layer = ProbeLayer.Intensity, Measurement = ProbeMeasurement.Intensity };+ float[] positive = new float[16];+ positive[5] = 0.3f;+ ProbeGraph.ComputeRanges(intensityProbe, new ProbeGraphData(positive, 16, null, 0, 16), 2500, out _, out _, out double intMin, out double intMax);+ Check(intMin == 0 && Math.Abs(intMax - 0.324) < 0.001, "an intensity axis runs from zero to the largest value plus 8 %");+ point.AutoScaleX = false;+ ProbeGraph.ComputeRanges(point, data, 2500, out xMin, out xMax, out _, out _);+ Check(xMin == 0 && xMax == 500, "running window, fixed x: full window from the start");+ point.ScaleMode = ProbeScaleMode.Full;+ ProbeGraph.ComputeRanges(point, data, 2500, out xMin, out xMax, out _, out _);+ Check(xMin == 0 && xMax == 2500, "full scale, fixed x: the whole run");+ point.StartAfter = 100;+ point.AutoScaleX = true;+ ProbeGraph.ComputeRanges(point, data, 2500, out xMin, out xMax, out _, out _);+ Check(xMin == 100 && xMax == 120, "start after 100: x starts there");+ point.AutoScaleY = false;+ point.YMin = 2;+ point.YMax = 1;+ ProbeGraph.ComputeRanges(point, data, 2500, out _, out _, out yMin, out yMax);+ Check(yMin == -1 && yMax == 1, "inverted fixed y range falls back to -1..1");+ point.StartAfter = 0;+ point.AutoScaleY = true;+ point.ScaleMode = ProbeScaleMode.Running;+ // the text keeps the renderer's size (11 px, 14.3 px lines, 6.6 px per character here); the margins come from the labels+ ProbeGraphStyle style = ProbeGraphStyle.Estimate(11);+ ProbeGraphLayout layout = ProbeGraph.Layout(point, data, 2500, 400, 200, style, inv);+ float widest = layout.YTicks.Max(t => style.Measure(t.Label));+ Check(layout.IsVisible && layout.HasPlot && layout.ShowLabels && layout.FontSize == 11 && Math.Abs(layout.PlotX - (3 + widest + 4)) < 0.01 && Math.Abs(layout.PlotY - (14.3 + 6)) < 0.01+ && Math.Abs(layout.PlotWidth - (400 - layout.PlotX - 8)) < 0.01 && Math.Abs(layout.PlotHeight - (200 - layout.PlotY - 14.3 - 4)) < 0.01,+ "400 x 200 layout: font 11, plot at (" + layout.PlotX.ToString("0.0", inv) + ", " + layout.PlotY.ToString("0.0", inv) + ") " + layout.PlotWidth.ToString("0.0", inv) + " x " + layout.PlotHeight.ToString("0.0", inv) + " from the measured labels");+ Check(layout.Curve.Length == 120 && layout.Curve[0].X > layout.PlotX && layout.Curve[^1].X <= layout.PlotX + layout.PlotWidth + 0.01 && layout.Title == "Point" && layout.Readout == "= " + ProbeGraph.FormatTick(values[119], inv),+ "one point per sample inside the plot, title and readout");+ Check(layout.YTicks.Any(t => t.IsZero && Math.Abs(t.Position - (layout.PlotY + layout.PlotHeight / 2)) < 2) && layout.XTicks.Count >= 4 && layout.XTicks[0].Label == "0", "zero line in the middle, step ticks from 0");+ Check(ProbeGraph.Layout(point, data, 2500, 30, 20, style, inv).IsVisible == false && ProbeGraph.Layout(point, data, 2500, 80, 40, style, inv) is { IsVisible: true, HasPlot: false }, "too small: nothing, or the box alone");+ ProbeGraphLayout bare = ProbeGraph.Layout(point, data, 2500, 120, 45, style, inv);+ Check(bare is { HasPlot: true, ShowLabels: false } && bare.YTicks.All(t => t.Label == "") && bare.PlotX == 6 && Math.Abs(bare.PlotHeight - (45 - 20.3 - 6)) < 0.01, "a box too low for labels keeps the plot and drops the labels");+ // the UI harness's 172 x 86 box at frame 49: three value labels 23 px apart fit a 47 px plot (asking for two ticks gave only the zero)+ float[] lowValues = new float[1024];+ for (int i = 40; i < 99; i++)+ {+ lowValues[i] = (i % 7 == 3 ? 0.0135f : 0.0126f) * MathF.Sin((i - 40) * 0.5f);+ }+ ProbeGraphLayout low = ProbeGraph.Layout(point, new ProbeGraphData(lowValues, 99, null, 0, 99), 100, 172, 86, new ProbeGraphStyle(11, 14.65f, t => t.Length * 6.2f), inv);+ Check(low.ShowLabels && low.YTicks.Count == 3 && low.YTicks.All(t => t.Label.Length > 0), "a low plot keeps three value labels while they are a line apart (" + string.Join(" ", low.YTicks.Select(t => t.Label)) + ")");+ ProbeGraphLayout narrow = ProbeGraph.Layout(point, data, 2500, 110, 80, style, inv);+ Check(narrow.ShowLabels && narrow.XTicks.Count <= 3 && narrow.XTicks.Sum(t => style.Measure(t.Label) + 8) - 8 <= narrow.PlotWidth, "a narrow plot gets fewer step labels so they do not collide (" + narrow.XTicks.Count + ")");+ var dense = new ProbeGraphData(Enumerable.Range(0, 1024).Select(i => (float)Math.Sin(i)).ToArray(), 1024, null, 0, 1024);+ point.ScaleMode = ProbeScaleMode.Full;+ ProbeGraphLayout denseLayout = ProbeGraph.Layout(point, dense, 1024, 200, 100, style, inv);+ Check(denseLayout.Curve.Length <= 2 * (int)denseLayout.PlotWidth && denseLayout.Curve.Length > 100, "dense series binned to two points per pixel column (" + denseLayout.Curve.Length + ")");++ // a line probe: 50 values along a 49-pixel line, gated by "start after step"+ float[] profile = Enumerable.Range(0, 50).Select(i => 0.1f * i).ToArray();+ var line = new Probe { Name = "Line", Kind = ProbeKind.Line, StartAfter = 100, Layer = ProbeLayer.Intensity };+ ProbeGraphLayout before = ProbeGraph.Layout(line, new ProbeGraphData(null, 0, profile, 49, 50), 2500, 400, 200, style, inv);+ ProbeGraphLayout after = ProbeGraph.Layout(line, new ProbeGraphData(null, 0, profile, 49, 100), 2500, 400, 200, style, inv);+ Check(before.Curve.Length == 0 && before.Readout == "" && before.XTicks[^1].Label == "1", "line probe blank before its start step");+ Check(after.Curve.Length == 50 && after.Readout == "max 4.9" && after.XTicks[^1].Label == "40" && after.YTicks[0].Label == "0", "line probe after its start step: profile over 0..49 pixels, intensity fitted from 0");+ }+/// <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(){@@ -781,8 +909,24 @@ internal static class ProgramProbe probe = project.AddProbe();probe.AX = 20;probe.AY = 24;+ Probe lineProbe = project.AddProbe();+ lineProbe.Kind = ProbeKind.Line;+ lineProbe.AX = 5;+ lineProbe.AY = 5;+ lineProbe.BX = 40;+ lineProbe.BY = 30;+ Probe integrated = project.AddProbe();+ integrated.Layer = ProbeLayer.Intensity;+ integrated.Measurement = ProbeMeasurement.IntegratedIntensity;+ integrated.Kind = ProbeKind.Line;+ integrated.AX = 10;+ integrated.AY = 30;+ integrated.BX = 50;+ integrated.BY = 30;+ integrated.StartAfter = 50;RunSpec spec = RunSpec.Create(project, null, preferGpu: false);- Check(spec.FrameCount == 100 && spec.Layers == (FrameLayers.Field | FrameLayers.Intensity) && spec.Emitters.Length == 1 && spec.Probes.Length == 1, "spec: 100 frames, both layers (intensity preview on), 1 emitter, 1 probe");+ Check(spec.FrameCount == 100 && spec.Layers == (FrameLayers.Field | FrameLayers.Intensity) && spec.Emitters.Length == 1 && spec.Probes.Length == 3, "spec: 100 frames, both layers (intensity preview on), 1 emitter, 3 probes");+ Check(ReferenceEquals(spec.Probes[0].Origin, probe) && ReferenceEquals(spec.Probes[1].Origin, lineProbe), "probe specs remember their model probe as the origin");string path = Path.Combine(Path.GetTempPath(), "library_check-run-" + Guid.NewGuid().ToString("N") + FrameCache.Extension);using (var store = FrameStore.Create(path, spec.Width, spec.Height, spec.Layers, spec.FrameCount, spec.VisualizeEvery))@@ -806,6 +950,34 @@ internal static class ProgramCheck(states.SequenceEqual([RunState.Starting, RunState.Running, RunState.Completed]), "states: Starting, Running, Completed");Check(run.StepsDone == 200 && run.FrameCount == 100 && store.Count == 100, "200 steps, 100 frames in the store");Check(run.Traces[0].Series.Count == 200 && run.Traces[0].StepsSampled == 200, "probe trace has one sample per step");+ Check(run.Traces[1].Profiles.Count == 100 && run.Traces[1].Profiles.All(p => p.Length == 36) && run.Traces[1].ProfileLength > 42.0 && run.Traces[1].Series.Count == 0,+ "line probe trace has one profile per frame (36 pixels, length " + run.Traces[1].ProfileLength.ToString("0.0", CultureInfo.InvariantCulture) + "), no series");+ Check(run.Traces[1].Profiles[0].All(v => v == 0f) && run.Traces[1].Profiles[99].Any(v => v != 0f) && !ReferenceEquals(run.Traces[1].Profiles[0], run.Traces[1].Profiles[99]), "profiles: frame 0 quiet, frame 99 has a wave, distinct arrays");+ ProbeGraphData at = ProbeGraphData.At(run.Traces[0], 40, 20);+ Check(at.Count == 41 && at.StepsSampled == 41 && at.Profile == null, "graph data at frame 20 / step 40: 41 samples");+ ProbeGraphData lineAt = ProbeGraphData.At(run.Traces[1], 40, 20);+ Check(ReferenceEquals(lineAt.Profile, run.Traces[1].Profiles[20]) && ReferenceEquals(ProbeGraphData.At(run.Traces[1], 400, 200).Profile, run.Traces[1].Profiles[99]), "graph data of the line probe: frame 20's profile; the newest stands in beyond the recorded frames");+ Check(run.Traces[2].Profiles.Count == 100 && run.Traces[2].Profiles[20].All(v => v == 0f) && run.Traces[2].Profiles[99].Any(v => v > 0f) && run.Traces[2].Profiles[99].All(v => v >= 0f), "integrated line probe: nothing before its start step, non-negative sums after");+ // the scratch runner records the same probes on its way to a frame (the graph is live before a run, 2026-10-14)+ using (var scratch = new ScratchRunner(null))+ using (var arrived = new ManualResetEventSlim())+ {+ ScratchResult? result = null;+ scratch.Completed += (_, r) =>+ {+ result = r;+ arrived.Set();+ };+ scratch.Request(spec, 20);+ Check(arrived.Wait(30000) && result is { Snapshot: not null, Frame: 20 }, "scratch frame 20 computed");+ Check(result!.Traces.Length == 3 && result.Traces[0].Series.Count == 41 && result.Traces[0].StepsSampled == 41, "scratch traces: the point probe's 41 samples up to step 40");+ Check(result.Traces[0].Series.Values.AsSpan(0, 41).SequenceEqual(run.Traces[0].Series.Values.AsSpan(0, 41)), "scratch series equals the run's first 41 samples bit for bit");+ Check(result.Traces[1].Profiles.Count == 1 && result.Traces[1].Profiles[0].AsSpan().SequenceEqual(run.Traces[1].Profiles[20]), "scratch profile equals the run's frame 20 profile");+ // a second request on the kept engine, past the integrated probe's start step: its sums must start from zero again+ arrived.Reset();+ scratch.Request(spec, 60);+ Check(arrived.Wait(30000) && result is { Frame: 60 } && result.Traces[2].Profiles.Count == 1 && result.Traces[2].Profiles[0].AsSpan().SequenceEqual(run.Traces[2].Profiles[60]), "a second scratch frame (60): the integrated profile equals the run's, the kept engine started its sums afresh");+ }Check(run.EngineDescription.StartsWith("CPU"), "CPU engine used");var lastFrame = new Half[64 * 48];Check(store.CopyLayer(99, FrameLayer.Field, lastFrame) && (float)lastFrame[24 * 64 + 20] != 0f, "last frame has a field at the source");@@ -848,6 +1020,28 @@ internal static class Programrun.Stop();Check(run.Completion.Wait(10000) && run.State == RunState.Cancelled && !run.IsActive, "stopped -> Cancelled, " + run.StepsDone + " steps, " + run.FrameCount + " frames");Check(run.FrameCount == store.Count && run.FrameCount > 0, "frame count published matches the store");+ if (run.EngineDescription.StartsWith("GPU", StringComparison.Ordinal) && run.FrameCount > 60)+ {+ // the GPU scratch path: two requests on one kept engine (the probe program compiled once), compared with the GPU run+ using var scratch = new ScratchRunner(null);+ using var arrived = new ManualResetEventSlim();+ ScratchResult? result = null;+ scratch.Completed += (_, r) =>+ {+ result = r;+ arrived.Set();+ };+ scratch.Request(spec, 10);+ bool first = arrived.Wait(30000) && result is { Snapshot: not null, Frame: 10 };+ arrived.Reset();+ var clock = Stopwatch.StartNew();+ scratch.Request(spec, 60);+ bool second = arrived.Wait(30000) && result is { Snapshot: not null, Frame: 60 };+ clock.Stop();+ Check(first && second, "GPU scratch frames 10 and 60 computed (" + clock.ElapsedMilliseconds + " ms for the second, probes re-installed without a compile)");+ Check(second && MaxDiff(result!.Traces[0].Series.Values.AsSpan(0, 121), run.Traces[0].Series.Values.AsSpan(0, 121)) <= 1e-5f * Math.Max(1e-3f, MaxAbs(run.Traces[0].Series.Values.AsSpan(0, 121))), "GPU scratch series matches the GPU run's first 121 samples");+ Check(second && MaxDiff(result!.Traces[2].Profiles[0], run.Traces[2].Profiles[60]) <= 1e-5f * Math.Max(1e-3f, MaxAbs(run.Traces[2].Profiles[60])), "GPU scratch integrated profile matches the GPU run's frame 60");+ }}Check(!File.Exists(path), "second store deleted");}diff --git a/_tools/ui_check/ProbeGraphCheck.ps1 b/_tools/ui_check/ProbeGraphCheck.ps1new file mode 100644index 0000000..9226d3f--- /dev/null+++ b/_tools/ui_check/ProbeGraphCheck.ps1@@ -0,0 +1,145 @@+# Checks the probe graph boxes drawn over the preview pictures (2026-10-14): on tiny_probes.wdproj (320x240,+# 100 steps, a point probe with a custom 120x60 box on the field, a line probe with a Small box at its own+# position on the intensity) the boxes must sit on the right picture at the probe's box position, show the+# scratch frame's data before any run and the run's data after it, move with the arrow keys when focused,+# grow from their corner grip, and a box at its probe's position must move with the probe. A probe move leaves+# the run valid (a probe never changes the picture): the graph is recomputed from scratch, no run is started,+# and Play afterwards starts one to refresh the recordings. The composite source's rotation handle turns it. Also saves a screenshot+# of the window after the run for judging the look. 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\ProbeGraphCheck.ps1 [-Exe <path>] [-Shot <png>] [-Trace]++param(+ [string]$Exe = (Join-Path $PSScriptRoot "..\..\WaveDude.WPF\bin\Debug\net10.0-windows\WaveDude.WPF.exe"),+ [string]$Shot = (Join-Path $env:TEMP "probe_graph.png"),+ [switch]$Trace+)++. (Join-Path $PSScriptRoot "Common.ps1")++# all elements with an automation id+function FindAll([string]$id) {+ return $win.FindAll([System.Windows.Automation.TreeScope]::Descendants, (New-Object System.Windows.Automation.PropertyCondition($A::AutomationIdProperty, $id)))+}+# whether $inner lies inside $outer (screen rectangles)+function Inside($inner, $outer) {+ return ($inner.Left -ge $outer.Left - 1) -and ($inner.Top -ge $outer.Top - 1) -and ($inner.Right -le $outer.Right + 1) -and ($inner.Bottom -le $outer.Bottom + 1)+}+function BoxHash([string]$id) {+ $r = (Find $id).Current.BoundingRectangle+ return [Native]::Hash($script:hwnd, [int]$r.Left, [int]$r.Top, [int]$r.Width, [int]$r.Height)+}++Start-App $Exe (Join-Path $PSScriptRoot "tiny_probes.wdproj")+try {+ Check "project loaded: 50 frames" ((Frame) -eq "0 / 49") (Frame)+ $field = (Find "PreviewFieldImage").Current.BoundingRectangle+ $intensity = (Find "PreviewIntensityImage").Current.BoundingRectangle+ $box1 = FindAll "ProbeBox:Probe 1"+ $box2 = FindAll "ProbeBox:Probe 2"+ Check "one box per probe, each on its own picture" ($box1.Count -eq 1 -and $box2.Count -eq 1) ("found {0} and {1}" -f $box1.Count, $box2.Count)+ $r1 = $box1[0].Current.BoundingRectangle+ $r2 = $box2[0].Current.BoundingRectangle+ Check "the field probe's box lies on the field picture" (Inside $r1 $field) ("box {0:0},{1:0} {2:0}x{3:0} picture {4:0},{5:0} {6:0}x{7:0}" -f $r1.Left, $r1.Top, $r1.Width, $r1.Height, $field.Left, $field.Top, $field.Width, $field.Height)+ Check "the intensity probe's box lies on the intensity picture" (Inside $r2 $intensity) ("box {0:0},{1:0} {2:0}x{3:0}" -f $r2.Left, $r2.Top, $r2.Width, $r2.Height)+ # the custom 120 x 60 box at canvas (8, 8): its top-left corner is the edge of canvas pixel (8, 8), its size 120 x 60 canvas pixels+ $corner = CanvasPoint "PreviewFieldImage" 320 240 7.5 7.5+ $scale = $corner[2]+ Check "custom box at its canvas position and size" ([math]::Abs($r1.Left - $corner[0]) -lt 2 -and [math]::Abs($r1.Top - $corner[1]) -lt 2 -and [math]::Abs($r1.Width - 120 * $scale) -lt 2 -and [math]::Abs($r1.Height - 60 * $scale) -lt 2) ("box {0:0},{1:0} {2:0}x{3:0} expected {4:0},{5:0} {6:0}x{7:0}" -f $r1.Left, $r1.Top, $r1.Width, $r1.Height, $corner[0], $corner[1], (120 * $scale), (60 * $scale))+ # the Small box (300 x 150) is shrunk to half the canvas width: 160 x 80+ $scale2 = (CanvasPoint "PreviewIntensityImage" 320 240 0 0)[2]+ Check "the Small box is shrunk to half the canvas width (160 x 80)" ([math]::Abs($r2.Width - 160 * $scale2) -lt 2 -and [math]::Abs($r2.Height - 80 * $scale2) -lt 2) ("{0:0}x{1:0} expected {2:0}x{3:0}" -f $r2.Width, $r2.Height, (160 * $scale2), (80 * $scale2))+ $grip = (Find "ProbeBoxCorner:Probe 1").Current.BoundingRectangle+ Check "the resize grip sits in the box's bottom-right corner" ([math]::Abs($grip.Right - $r1.Right) -lt 2 -and [math]::Abs($grip.Bottom - $r1.Bottom) -lt 2) ("grip {0:0},{1:0} box corner {2:0},{3:0}" -f $grip.Right, $grip.Bottom, $r1.Right, $r1.Bottom)+ $empty = BoxHash "ProbeBox:Probe 1"+ # ------------------------------------------------------------ before any run: the scratch frame's recording+ FocusOn "PreviewTimeline"+ Key $VK_HOME 100; Key $VK_PRIOR 50; Key $VK_PRIOR 50; Key $VK_PRIOR 150 # frame 30+ Check "skipped to frame 30 with no run" ((Position) -eq 30) (Frame)+ Check "the graph shows the scratch frame's samples (box changed)" (WaitFor { (BoxHash "ProbeBox:Probe 1") -ne $empty } 8000 200)+ Key $VK_HOME 300+ # ------------------------------------------------------------ a run fills the graphs+ FocusOn "PreviewPlay"+ Key $VK_F5 100+ Check "run completes" (WaitFor { (RunStatus) -like "Completed:*" } 30000) (RunStatus)+ Start-Sleep -Milliseconds 300+ Check "preview on the last frame" ((Frame) -eq "49 / 49") (Frame)+ $full = BoxHash "ProbeBox:Probe 1"+ Check "the point probe's box changed once the run had data" ($full -ne $empty)+ [Native]::Capture($hwnd, $Shot)+ Write-Output ("screenshot: " + $Shot)+ Key $VK_HOME 400+ $first = BoxHash "ProbeBox:Probe 1"+ Check "the graph at frame 0 differs from the graph at the last frame (it follows the position)" ($first -ne $full)+ Key $VK_END 400+ # ------------------------------------------------------------ keyboard: move and resize+ FocusOn "ProbeBox:Probe 1"+ Check "Tab reaches the box, which selects Probe 1 in the tree" ((Focused "ProbeBox:Probe 1") -and (TreeItemSelected "Probe 1")) (FocusedId)+ Key $VK_RIGHT 200+ $moved = (Find "ProbeBox:Probe 1").Current.BoundingRectangle+ Check "Right arrow moves the box one canvas pixel" ([math]::Abs(($moved.Left - $r1.Left) - $scale) -lt 1.5 -and [math]::Abs($moved.Top - $r1.Top) -lt 1.5) ("dx {0:0.0} expected {1:0.0}" -f ($moved.Left - $r1.Left), $scale)+ Key $VK_LEFT 200+ $back = (Find "ProbeBox:Probe 1").Current.BoundingRectangle+ Check "Left arrow moves it back" ([math]::Abs($back.Left - $r1.Left) -lt 1.5) ("x {0:0} vs {1:0}" -f $back.Left, $r1.Left)+ # the graph settings are no simulation edit: the run must still be there, not stale+ Check "moving the box did not mark the run stale" ((RunStatus) -like "Completed:*" -and (RunStatus) -notlike "*edited*") (RunStatus)+ FocusOn "ProbeBoxCorner:Probe 1"+ Key $VK_RIGHT 200+ Key $VK_DOWN 200+ $grown = (Find "ProbeBox:Probe 1").Current.BoundingRectangle+ Check "arrows on the corner grip grow the box by a canvas pixel each way" ([math]::Abs(($grown.Width - $r1.Width) - $scale) -lt 1.5 -and [math]::Abs(($grown.Height - $r1.Height) - $scale) -lt 1.5) ("dw {0:0.0} dh {1:0.0} expected {2:0.0}" -f ($grown.Width - $r1.Width), ($grown.Height - $r1.Height), $scale)+ Key $VK_LEFT 200+ Key $VK_UP 200+ $restored = (Find "ProbeBox:Probe 1").Current.BoundingRectangle+ Check "and shrink it back" ([math]::Abs($restored.Width - $r1.Width) -lt 1.5 -and [math]::Abs($restored.Height - $r1.Height) -lt 1.5)+ # moving the probe itself: the picture stays (a probe never changes it), only the recordings are stale: the graph+ # is recomputed from scratch and no run is started+ $beforeMove = BoxHash "ProbeBox:Probe 1"+ FocusOn "Probe:Probe 1:A"+ for ($i = 0; $i -lt 10; $i++) { Key $VK_RIGHT 40 }+ Start-Sleep -Milliseconds 200+ Check "moving the probe leaves the run valid (no 'edited since')" ((RunStatus) -like "Completed:*" -and (RunStatus) -notlike "*edited*") (RunStatus)+ Check "the graph is recomputed from scratch after the probe move" (WaitFor { (BoxHash "ProbeBox:Probe 1") -ne $beforeMove } 8000 200)+ $still = $true+ for ($i = 0; $i -lt 10; $i++) { Start-Sleep -Milliseconds 250; if ((RunStatus) -notlike "Completed: 100 / 100*") { $still = $false } }+ Check "no automatic re-run follows a probe move" $still (RunStatus)+ # probe 2's box sits at the probe's own position: moving the probe moves the box along+ $box2 = (Find "ProbeBox:Probe 2").Current.BoundingRectangle+ FocusOn "Probe:Probe 2:A"+ Key $VK_RIGHT 300+ $box2Moved = (Find "ProbeBox:Probe 2").Current.BoundingRectangle+ Check "moving a probe whose box sits at its position moves the box along" ([math]::Abs(($box2Moved.Left - $box2.Left) - $scale2) -lt 1.5 -and [math]::Abs($box2Moved.Top - $box2.Top) -lt 1.5) ("dx {0:0.0} expected {1:0.0}" -f ($box2Moved.Left - $box2.Left), $scale2)+ Key $VK_LEFT 300+ Check "and back" ([math]::Abs((Find "ProbeBox:Probe 2").Current.BoundingRectangle.Left - $box2.Left) -lt 1.5)+ # Play after probe edits: the recordings are stale, so Play starts a run to refresh them (status: "Re-run started" then Running/Completed)+ FocusOn "PreviewPlay"+ Key $VK_SPACE 20+ Check "Play after a probe edit starts a run to refresh the recordings" (WaitFor { (RunStatus) -like "Running:*" -or ((Find "StatusMessage").Current.Name -like "Re-run started*") } 5000 10) ((Find "StatusMessage").Current.Name)+ Check "that run completes" (WaitFor { (RunStatus) -like "Completed: 100 / 100*" } 15000 100) (RunStatus)+ Key $VK_SPACE 100 # stop playback+ # the composite source's rotation handle: only while the source is selected; on the row axis right of the centre at+ # 0 degrees; arrows turn the array+ $angleCondition = New-Object System.Windows.Automation.PropertyCondition($A::AutomationIdProperty, "SourceAngle:Source 2")+ Check "the rotation handle is hidden while Source 2 is not selected" ($null -eq $win.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $angleCondition))+ FocusOn "Source:Source 2"+ Check "selecting Source 2 shows its rotation handle" (WaitFor { $null -ne $win.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $angleCondition) } 3000 100)+ $centre2 = CentreOf "Source:Source 2"+ $handle = CentreOf "SourceAngle:Source 2"+ Check "the rotation handle sits on the row axis, right of the array centre" ($handle[0] -gt $centre2[0] + 20 -and [math]::Abs($handle[1] - $centre2[1]) -lt 2) ("handle {0:0},{1:0} centre {2:0},{3:0}" -f $handle[0], $handle[1], $centre2[0], $centre2[1])+ FocusOn "SourceAngle:Source 2"+ Check "Tab reaches the rotation handle, which selects Source 2 in the tree" ((Focused "SourceAngle:Source 2") -and (TreeItemSelected "Source 2")) (FocusedId)+ for ($i = 0; $i -lt 10; $i++) { Key $VK_RIGHT 40 }+ Start-Sleep -Milliseconds 300+ $turned = CentreOf "SourceAngle:Source 2"+ $reach = $handle[0] - $centre2[0]+ $rise = $reach * [math]::Sin(10 * [math]::PI / 180)+ Check "ten Right arrows turn the array by 10 degrees: the handle rises on its arc" ([math]::Abs(($centre2[1] - $turned[1]) - $rise) -lt 2 -and [math]::Abs(($turned[0] - $centre2[0]) - $reach * [math]::Cos(10 * [math]::PI / 180)) -lt 2) ("rise {0:0.0} expected {1:0.0}" -f ($centre2[1] - $turned[1]), $rise)+ Check "turning the array marks the run stale (the picture changes)" ((RunStatus) -like "*edited*") (RunStatus)+ Check "app never became the foreground window" ((Foreground) -ne "APP") (Foreground)+}+finally {+ Stop-App+}+Write-Output ("{0} failure(s)" -f $script:failures)+exit $script:failuresdiff --git a/_tools/ui_check/tiny_probes.wdproj b/_tools/ui_check/tiny_probes.wdprojnew file mode 100644index 0000000..e9af12d--- /dev/null+++ b/_tools/ui_check/tiny_probes.wdproj@@ -0,0 +1,16 @@+<?xml version="1.0" encoding="utf-8"?>+<Project Version="1" Seed="12345">+ <Description>Harness project: a 320 x 240 canvas, 100 steps, a frame every 2 steps, one source, a point probe on the field (custom box) and a line probe on the intensity.</Description>+ <Scene Width="320" Height="240" DampingEdge="8" />+ <Simulation Steps="100" VisualizeEvery="2" />+ <Display>+ <Field ColorScheme="Default_Field" BlackLevel="-0.05" />+ <Intensity ColorScheme="Default_intensity" />+ </Display>+ <Source Name="Source 1" X="160" Y="120" Frequency="120" />+ <Source Name="Source 2" X="80" Y="60" Frequency="150" Amplitude="60">+ <Array SizeX="3" SpacingX="10" />+ </Source>+ <Probe Name="Probe 1" AX="200" AY="120" BoxSize="Custom" BoxX="8" BoxY="8" BoxWidth="120" BoxHeight="60" />+ <Probe Name="Probe 2" Layer="Intensity" Measurement="Intensity" Kind="Line" AX="40" AY="200" BX="280" BY="200" BoxSize="Small" BoxX="40" BoxY="200" />+</Project>