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#
Baseline: Wave Dude 2D v0.29 rebuilt from decompiled VB.NET into clean, documented C#
Alexander Graef1266f10a8754
diff --git a/.editorconfig b/.editorconfignew file mode 100644index 0000000..69de051--- /dev/null+++ b/.editorconfig@@ -0,0 +1,22 @@+root = true++[*]+charset = utf-8+end_of_line = crlf+insert_final_newline = true+trim_trailing_whitespace = true++[*.cs]+indent_style = tab+indent_size = 4++[*.{csproj,sln,resx,config,settings,manifest}]+indent_style = space+indent_size = 2++[*.{md,yml,yaml,json,py}]+indent_style = space+indent_size = 4++[*.md]+trim_trailing_whitespace = falsediff --git a/.gitattributes b/.gitattributesnew file mode 100644index 0000000..750559c--- /dev/null+++ b/.gitattributes@@ -0,0 +1,17 @@+# Normalize text files to LF in the repository; check out with the platform's native line endings.+* text=auto++*.cs text+*.csproj text+*.sln text eol=crlf+*.resx text+*.config text+*.settings text+*.md text+*.py text++*.ico binary+*.png binary+*.jpg binary+*.exe binary+*.dll binarydiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..384ba80--- /dev/null+++ b/.gitignore@@ -0,0 +1,12 @@+# Visual Studio / build output+.vs/+bin/+obj/+*.user+*.suo+*.cache+TestResults/++# local scratch+_tools/smoke.png+_tools/*.txtdiff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 100644index 0000000..b297ddd--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1,160 @@+# Wave Dude 2D — project notes for Claude++Analysis snapshot: 2026-10-06. Update this file when the facts below change.++## What this is++**Wave Dude 2D v0.29** — a 2D wave-equation simulator (field + accumulated intensity views,+refractive-index scenes from images, point/composite sources, probes with live graphs, video export).+Educational tool by Huygens Optics (`[email protected]`, patreon `huygens_optics`).++- WinForms, **.NET Framework 4.6.1**, legacy (non-SDK) `.csproj`, root namespace `_2D_wave_sim_V01`,+ assembly `Wave_Dude_2D`. Single project in `Wave_Dude_2D.sln`.+- **The C# in this repo started life as ILSpy-decompiled output of a VB.NET build.** As of+ 2026-10-07 it has been cleaned up to read like hand-written C#: closure artifacts, VB `WithEvents`+ wrappers, `// Token` comments, `checked {}` blocks, `bool flag = …` temps, VB runtime helper+ calls and placeholder locals (`num2`, `text3`, …) are gone from all hand-maintained files.+ What still betrays the origin: the `My/` namespace + `WindowsFormsApplicationBase` startup, the+ `*.Designer.cs` files (left verbatim apart from the field/event-wiring block), `ref` parameters+ that are really `out`, and `this.` on every member access.+- Git: repo was just initialised; **nothing is committed yet** and there is **no `.gitignore`**+ (`.vs/` is untracked junk that must not be committed).+- No tests. No CI. No README besides this file.++## Build++- Toolchain found on this machine: Visual Studio 18 (2026) Community. `dotnet` 10 SDK is installed but+ the legacy csproj needs full MSBuild:+ ```+ "C:\Program Files\Microsoft Visual Studio\18\Community\MSBuild\Current\Bin\MSBuild.exe" Wave_Dude_2D.sln -p:Configuration=Debug -v:minimal -nologo -m+ ```+- **Current state (2026-10-07): compiles and runs.** 0 errors, 6 cosmetic warnings+ (`components` never assigned in the Designer files, unused `_hasRun`, one sign-extension in+ `MfVideoWriter`). Smoke test = launch exe, main window appears with title+ `2D wave simulation - (new project) *`.+- Standalone compile check that does not touch `bin/obj` (safe to run in parallel with other work):+ `_tools/CLEANUP_GUIDE.md` has the full `csc.exe` command line.+- `_tools/` holds the one-off Python scripts used for the decompiler clean-up (`replace_method.py`,+ `fix_semantic.py`, `split_form1.py`, …) plus the guide. They are history, not build inputs.++## Architecture map++```+My/MyApplication.Main -> MyProject.Forms.Form1 (VB "My" application framework; replace with Program.Main)+Form1 (14,473 lines) -> SimulationRunner (own Thread; events ProgressChanged/EngineReady/ProbesUpdated/PreviewReady/Finished)+ |- WaveEngineFactory -> IWaveEngine+ | |- WaveSimulator CPU, Parallel.For+ | '- GpuWaveSimulator OpenCL via OpenClApi (P/Invoke OpenCL.dll), kernels as strings+ |- FrameRenderer + ColorLut/ColorScheme float field -> ARGB pixels+ |- IFrameSink -> MfVideoWriter (Media Foundation SinkWriter P/Invoke, .mp4)+ | AviMjpegWriter (.avi fallback)+ '- Probe* (Sampler/Collector/Series/Trace/GraphPainter/Overlay)+Persistence: ProjectStore / ProjectConfig / Project (JSON via System.Web.Extensions JavaScriptSerializer)+ AppSettings -> %AppData%\2D_wave_sim_V01\settings.json+ ColorSchemeStore -> *.json colour schemes in a user-chosen folder+Project folder layout: <root>/<project>/configuration.json (+ legacy Configuration.txt), assets/, output_frames/, output_video/+Model classes (plain POCOs, safe to reuse as-is): SceneSettings, SimulationSettings, SourceSettings(+SourceElement, enums), ProbeSettings(+enums), ColorScheme+```++UI -> engine marshalling is `Form1.PostToUi(Action)` = `BeginInvoke` guarded by `IsHandleCreated`.+Everything engine-side (`WaveSimulator`, `GpuWaveSimulator`, `OpenClApi`, `Mf*`, `IMF*Native`, `Probe*`,+`FrameRenderer`) is UI-independent and should be left alone during UI work beyond compile fixes.++## The UI as it stands (the thing to make viable)++`Form1` is still a god-class, but it is now a **partial class split along its feature seams**+(~6,500 lines of logic in total, ~347 methods, 161 event handlers, 78 `MessageBox.Show` calls):++| file | owns |+|---|---|+| `Form1.cs` | ctor, load/close, menu, project open/save/new, title, **all fields and nested types** (`ProjectListEntry`, `NativeSize`, `ThumbnailOptions`, `ProbeControlSet`) |+| `Form1.Projects.cs` | "Projects in current root" list on the Settings tab |+| `Form1.Output.cs` | Manage-output tab (scene/image/video lists, thumbnails, shell interop) |+| `Form1.Scene.cs` | scene properties, scene image, glow-edge overlay |+| `Form1.Colors.cs` | colour-scheme tab and stop editor |+| `Form1.Simulation.cs` | simulation settings, run/pause/stop, preview, export, Explorer view-mode COM hack |+| `Form1.Probes.cs` | probes tab (2 hard-wired probes via `ProbeControlSet[]`) |+| `Form1.Sources.cs` | sources tab |++Controls are plain private fields declared at the bottom of `Form1.Designer.cs`; event handlers are+attached in `InitializeComponent` under the comment `// event wiring (was VB WithEvents/Handles)`.+The VS designer has **not** been verified to open these forms — the Designer files are decompiled+output with `global::` prefixes; expect to regenerate them when the layout is rebuilt (roadmap 5).++`Form1.Designer.cs` (3,564 lines): **318 controls** — 91 Labels / 59 Buttons / 39 NumericUpDowns /+28 CheckBoxes / 15 TextBoxes / 13 GroupBoxes / 13 ComboBoxes / 11 Panels / 10 RadioButtons / 6 ListViews /+2 PictureBoxes; one `TabControl` (`tabMainFunctions`, owner-drawn, tabs gated via `Enabled` until a+project is open) with six pages: **Settings, Sources, Probes, Preview, Manage output, Colors**.+Persistent bottom strip: `grpSimulationControlButtons` (Start / Pause-Resume), `grpShareImage`,+`grpNavigateTabs` (jump buttons), `btnSaveConfiguration`; `MenuStrip1` (File: New / Open / Choose project+root / Set c-value / Save / Exit; Info: Help / About); `StatusStrip1`.++Why it is not viable today:++- **Fixed 1781x989 client size, 297 absolute `Location`s, zero `Dock`/`Anchor`, no `MinimumSize`,+ no `TableLayoutPanel`/`FlowLayoutPanel`.** Does not fit a 1080p screen with taskbar; nothing reflows.+- `AutoScaleMode.Font` at 6x13 with **Microsoft Sans Serif** in 7 sizes (9.75–20.25 pt); 2 stray Segoe UI.+ No `app.manifest`, no DPI awareness -> blurry/clipped on >100 % scaling.+- Ad-hoc colours (`Azure`, `Gainsboro`, `SystemColors.Menu`), hand-made owner-drawn tabs.+- Secondary UI: `AboutForm` (version string stale: code says 0.27, designer 0.29), `HelpForm` (long+ help text as string constants in code), `frmDescription`; `ColorPickerControl` is a code-only+ UserControl hard-sized to 423x411; `BrowseForFolder` builds its own folder dialog form by hand;+ `SetExplorerWindowViewMode` late-binds `Shell.Application` COM to restyle Explorer windows (fragile).+- Help text in `HelpForm.cs` documents the intended behaviour of every control — use it as the spec.++## Recommended roadmap ("make the UI viable")++Do these in order; each step leaves the app runnable.++0. ~~**Git hygiene**~~ — `.gitignore` added. **Nothing is committed yet**; the pre-cleanup+ decompiled baseline is not recoverable from git (only from the original binary).+1. ~~**Make it compile**~~ — done 2026-10-06.+2. **Strip VB residue** — done 2026-10-07 (WithEvents block, Token comments, VB runtime+ helpers, placeholder names, control flow), followed by an XML-doc pass: every type and member+ in the hand-maintained files has `///` docs (~1,400 members; `DocumentationFile` is on in the+ csproj so malformed docs are build warnings). Threading, units and coordinate systems are stated+ in the docs — read them before changing anything on the engine/UI boundary.+ **Latent issues found while documenting, left unchanged on purpose** (behaviour-preserving pass):+ - `AviMjpegWriter`: the header actually written is 236 bytes but the `Pos*` patch offsets assume+ 224, so the `movi` size is patched into the BITMAPINFOHEADER and `idx1` offsets are off by 12.+ Players may or may not tolerate it; see the class `<remarks>`.+ - `WaveEngineFactory.Create`: the "first choice failed" branch is dead (`GpuWaveSimulator.TryCreate`+ never returns an engine together with a message).+ - `SimulationSettings.FromConfig` per-key fallbacks differ from the constructor defaults+ (steps 2500 vs 0, 4th-order false vs true, c 0.563 vs 1.0, decay 10 vs 0).+ - `btnRenameProject_Click` re-opens the project from disk, silently discarding unsaved edits.+ - `GpuWaveSimulator.SetProbes` leaks earlier probe kernel handles if called twice; `SetProbes(null)`+ does not clear an installed sampler (CPU engine does).+ - Unused members kept for signature stability: `Form1.ThumbWidth/ThumbHeight/FVM_*`, `_hasRun`,+ `SourceElement.DetachRampSteps` (engines use literal 30), `SimulationRunner.JpegQuality`,+ `AviMjpegWriter.MaxFileSize`, `AppSettings.LastRootFolder/LastProjectName` (written, never read).+ Still open: replace `My/*` with a plain `Program.Main`+ (`EnableVisualStyles`, `SetCompatibleTextRenderingDefault`, `SetHighDpiMode`); convert+ `ref` parameters that are really `out`; drop the `Microsoft.VisualBasic` reference once nothing+ uses it.+3. **Retarget** — recommended: SDK-style csproj on **.NET 8 (or 10) `net8.0-windows` + `UseWindowsForms`**.+ Consequences: `JavaScriptSerializer` (System.Web.Extensions) -> `System.Text.Json` with the same+ snake_case keys (`last_root_folder`, ...) so existing projects still load; `Microsoft.VisualBasic`+ still exists on .NET; P/Invoke code (OpenCL, Media Foundation, shell32, gdi32) ports unchanged.+ Fallback if staying on Framework: 4.8 + `app.manifest` with PerMonitorV2.+4. **Split `Form1` by tab** into UserControls (`SettingsPage`, `SourcesPage`, `ProbesPage`,+ `PreviewPage`, `OutputPage`, `ColorsPage`) following the existing line-range seams; keep a thin+ shell form owning menu, status bar, bottom strip, and the `SimulationRunner` lifecycle. Move+ project/scene/simulation state out of the form into a small view-model/service so pages share it.+5. **Layout** — per page: `TableLayoutPanel`/`FlowLayoutPanel`, `Dock`/`Anchor`, `MinimumSize`,+ splitter between settings and preview, single font (Segoe UI 9 pt, let DPI scaling do the rest),+ drop custom colours and owner-drawn tabs; replace `MessageBox` validation with inline hints / `ErrorProvider`.+6. Only after 1–5: consider moving off WinForms (WPF/Avalonia). Not before — the engine/UI boundary+ must be clean first, and WinForms is sufficient for this app's needs.++## Conventions / gotchas when editing here++- Formatting is governed by `.editorconfig` (tabs in `.cs`). In Git Bash, `grep -E` needs `$' '` for+ tabs; `grep -P` is broken (locale error).+- Namespace stays `_2D_wave_sim_V01` until step 3 (settings path and resources depend on it).+- `Microsoft.VisualBasic` is still referenced only for `WindowsFormsApplicationBase` in `My/`.+- `ColorScheme.StopCount` is 9 and `Form1` asserts the nine `btnColorN` buttons match it.+- Probe count is hard-wired to 2 (`ProbeCount`, duplicated `*2` controls/handlers) — a `ProbeControlSet`+ array already abstracts it; generalising is cheap once the UI is split.+- Video export requires Media Foundation (Windows N editions need the Media Feature Pack); AVI/MJPEG is+ the fallback. GPU path needs an OpenCL ICD (`OpenCL.dll`); the CPU engine is the fallback.diff --git a/ColorSchemeList/Blue_to_yellow_GNU.json b/ColorSchemeList/Blue_to_yellow_GNU.jsonnew file mode 100644index 0000000..01d6d8a--- /dev/null+++ b/ColorSchemeList/Blue_to_yellow_GNU.json@@ -0,0 +1,42 @@+{+ "name": "Blue_to_yellow_GNU",+ "origin": "matplotlib colormap gnuplot2, sampled at 255 points",+ "category": "sequential",+ "scheme_type": "intensity",+ "bits_per_channel": 8,+ "entry_count": 255,+ "colors": [+ [0,0,0], [0,0,4], [0,0,8], [0,0,12], [0,0,16], [0,0,20], [0,0,24], [0,0,28],+ [0,0,32], [0,0,36], [0,0,40], [0,0,44], [0,0,48], [0,0,52], [0,0,56], [0,0,60],+ [0,0,64], [0,0,68], [0,0,72], [0,0,76], [0,0,80], [0,0,84], [0,0,88], [0,0,92],+ [0,0,96], [0,0,100], [0,0,104], [0,0,108], [0,0,112], [0,0,116], [0,0,120], [0,0,124],+ [0,0,128], [0,0,131], [0,0,136], [0,0,140], [0,0,144], [0,0,147], [0,0,152], [0,0,156],+ [0,0,160], [0,0,163], [0,0,168], [0,0,172], [0,0,176], [0,0,179], [0,0,184], [0,0,188],+ [0,0,192], [0,0,195], [0,0,200], [0,0,204], [0,0,208], [0,0,211], [0,0,216], [0,0,220],+ [0,0,224], [0,0,227], [0,0,232], [0,0,236], [0,0,240], [0,0,243], [0,0,248], [0,0,252],+ [0,0,255], [3,0,255], [7,0,255], [10,0,255], [13,0,255], [16,0,255], [19,0,255], [22,0,255],+ [25,0,255], [28,0,255], [32,0,255], [35,0,255], [38,0,255], [41,0,255], [44,0,255], [47,0,255],+ [50,0,255], [53,0,255], [57,0,255], [60,0,255], [63,0,255], [66,0,255], [69,0,255], [72,0,255],+ [75,0,255], [78,0,255], [82,0,255], [85,0,255], [88,0,255], [91,0,255], [94,0,255], [97,0,255],+ [100,0,255], [103,0,255], [107,0,255], [110,0,255], [113,0,255], [116,0,255], [119,0,255], [122,0,255],+ [125,0,255], [128,0,255], [132,0,255], [135,0,255], [138,1,253], [141,3,251], [144,5,249], [147,7,247],+ [150,9,245], [153,11,243], [157,13,241], [160,15,239], [163,17,237], [166,19,235], [169,21,233], [172,23,231],+ [175,25,229], [178,27,227], [182,29,225], [185,31,223], [188,33,221], [191,35,219], [194,37,217], [200,41,213],+ [203,43,211], [207,45,209], [210,47,207], [213,49,205], [216,51,203], [219,53,201], [222,55,199], [225,57,197],+ [228,59,195], [232,61,193], [235,63,191], [238,65,189], [241,67,187], [244,69,185], [247,71,183], [250,73,181],+ [253,75,179], [255,77,177], [255,79,175], [255,81,173], [255,83,171], [255,85,169], [255,87,167], [255,89,165],+ [255,91,163], [255,93,161], [255,95,159], [255,97,157], [255,99,155], [255,101,153], [255,103,151], [255,105,149],+ [255,107,147], [255,109,145], [255,111,143], [255,113,141], [255,115,139], [255,117,137], [255,119,135], [255,121,133],+ [255,123,131], [255,125,129], [255,127,127], [255,129,125], [255,131,123], [255,133,121], [255,135,119], [255,137,117],+ [255,139,115], [255,141,113], [255,143,111], [255,145,109], [255,147,107], [255,149,105], [255,151,103], [255,153,101],+ [255,155,99], [255,157,97], [255,159,95], [255,161,93], [255,163,91], [255,165,89], [255,167,87], [255,169,85],+ [255,171,83], [255,173,81], [255,175,79], [255,177,77], [255,179,75], [255,181,73], [255,183,71], [255,185,69],+ [255,187,67], [255,189,65], [255,191,63], [255,193,61], [255,195,59], [255,197,57], [255,199,55], [255,201,53],+ [255,203,51], [255,205,49], [255,207,47], [255,209,45], [255,211,43], [255,213,41], [255,215,39], [255,217,37],+ [255,219,35], [255,221,33], [255,223,31], [255,225,29], [255,227,27], [255,229,25], [255,231,23], [255,233,21],+ [255,235,19], [255,237,17], [255,239,15], [255,241,13], [255,243,11], [255,245,9], [255,247,7], [255,249,5],+ [255,251,3], [255,253,1], [255,255,4], [255,255,17], [255,255,29], [255,255,42], [255,255,54], [255,255,67],+ [255,255,79], [255,255,92], [255,255,104], [255,255,117], [255,255,130], [255,255,142], [255,255,154], [255,255,167],+ [255,255,179], [255,255,192], [255,255,204], [255,255,217], [255,255,230], [255,255,242], [255,255,255]+ ]+}diff --git a/ColorSchemeList/Bright_rainbow.json b/ColorSchemeList/Bright_rainbow.jsonnew file mode 100644index 0000000..a745ae2--- /dev/null+++ b/ColorSchemeList/Bright_rainbow.json@@ -0,0 +1,43 @@+{+ "name": "Bright_rainbow",+ "origin": "9-stop copy of scheme 'Bright_rainbow'",+ "category": "custom",+ "scheme_type": "intensity",+ "bits_per_channel": 8,+ "entry_count": 255,+ "stops": [[0,0,0], [128,5,182], [50,18,224], [32,164,224], [64,249,191], [96,240,109], [207,234,72], [252,168,29], [255,0,0]],+ "colors": [+ [0,0,0], [4,0,6], [8,0,11], [12,0,17], [16,1,23], [20,1,29], [24,1,34], [28,1,40],+ [32,1,46], [36,1,52], [40,2,57], [44,2,63], [48,2,69], [52,2,75], [56,2,80], [60,2,86],+ [65,3,92], [69,3,97], [73,3,103], [77,3,109], [81,3,115], [85,3,120], [89,3,126], [93,4,132],+ [97,4,138], [101,4,143], [105,4,149], [109,4,155], [113,4,161], [117,5,166], [121,5,172], [125,5,178],+ [127,5,182], [125,6,184], [122,6,185], [120,6,186], [118,7,188], [115,7,189], [113,8,190], [110,8,192],+ [108,8,193], [105,9,194], [103,9,196], [100,10,197], [98,10,198], [95,10,200], [93,11,201], [91,11,202],+ [88,12,203], [86,12,205], [83,12,206], [81,13,207], [78,13,209], [76,14,210], [73,14,211], [71,15,213],+ [68,15,214], [66,15,215], [64,16,217], [61,16,218], [59,17,219], [56,17,221], [54,17,222], [51,18,223],+ [50,20,224], [49,25,224], [49,29,224], [48,34,224], [47,39,224], [47,43,224], [46,48,224], [46,52,224],+ [45,57,224], [45,62,224], [44,66,224], [43,71,224], [43,75,224], [42,80,224], [42,85,224], [41,89,224],+ [41,94,224], [40,98,224], [40,103,224], [39,108,224], [38,112,224], [38,117,224], [37,121,224], [37,126,224],+ [36,131,224], [36,135,224], [35,140,224], [34,144,224], [34,149,224], [33,154,224], [33,158,224], [32,163,224],+ [33,166,223], [34,169,222], [35,171,221], [36,174,220], [37,177,219], [38,179,218], [39,182,217], [40,185,216],+ [41,187,215], [42,190,214], [43,193,213], [44,195,212], [45,198,211], [46,201,210], [47,203,209], [48,206,208],+ [49,209,207], [50,212,206], [51,214,205], [52,217,203], [53,220,202], [54,222,201], [55,225,200], [56,228,199],+ [57,230,198], [58,233,197], [59,236,196], [60,238,195], [61,241,194], [62,244,193], [63,246,192], [64,249,191],+ [65,249,188], [66,248,186], [67,248,183], [68,248,181], [69,248,178], [70,247,176], [71,247,173], [72,247,170],+ [73,246,168], [74,246,165], [75,246,163], [76,246,160], [77,245,157], [78,245,155], [79,245,152], [80,244,150],+ [81,244,147], [82,244,145], [83,244,142], [84,243,139], [85,243,137], [86,243,134], [87,242,132], [88,242,129],+ [89,242,126], [90,242,124], [91,241,121], [92,241,119], [93,241,116], [94,240,114], [95,240,111], [97,240,109],+ [100,240,108], [104,240,106], [107,239,105], [111,239,104], [114,239,103], [118,239,102], [121,239,101], [125,238,99],+ [128,238,98], [132,238,97], [135,238,96], [139,238,95], [142,237,94], [146,237,92], [149,237,91], [153,237,90],+ [156,237,89], [160,237,88], [163,236,87], [167,236,85], [170,236,84], [174,236,83], [177,236,82], [181,235,81],+ [184,235,80], [188,235,78], [191,235,77], [195,235,76], [198,234,75], [202,234,74], [205,234,73], [208,233,71],+ [209,231,70], [211,229,69], [212,227,67], [213,225,66], [215,223,65], [216,220,63], [218,218,62], [219,216,60],+ [220,214,59], [222,212,58], [223,210,56], [225,208,55], [226,206,54], [228,204,52], [229,202,51], [230,200,50],+ [232,198,48], [233,196,47], [235,193,46], [236,191,44], [237,189,43], [239,187,42], [240,185,40], [242,183,39],+ [243,181,37], [245,179,36], [246,177,35], [247,175,33], [249,173,32], [250,171,31], [252,169,29], [252,164,28],+ [252,159,27], [252,153,26], [252,148,26], [252,143,25], [253,138,24], [253,132,23], [253,127,22], [253,122,21],+ [253,116,20], [253,111,19], [253,106,18], [253,101,17], [253,95,16], [253,90,16], [253,85,15], [254,79,14],+ [254,74,13], [254,69,12], [254,63,11], [254,58,10], [254,53,9], [254,48,8], [254,42,7], [254,37,6],+ [254,32,5], [255,26,5], [255,21,4], [255,16,3], [255,11,2], [255,5,1], [255,0,0]+ ]+}diff --git a/ColorSchemeList/Copper.json b/ColorSchemeList/Copper.jsonnew file mode 100644index 0000000..ed36f93--- /dev/null+++ b/ColorSchemeList/Copper.json@@ -0,0 +1,42 @@+{+ "name": "Copper",+ "origin": "matplotlib colormap copper, sampled at 255 points",+ "category": "sequential",+ "scheme_type": "intensity",+ "bits_per_channel": 8,+ "entry_count": 255,+ "colors": [+ [0,0,0], [1,0,0], [2,1,0], [3,2,1], [4,3,1], [6,3,2], [7,4,2], [8,5,3],+ [9,6,3], [11,7,4], [12,7,4], [13,8,5], [14,9,5], [16,10,6], [17,10,6], [18,11,7],+ [19,12,7], [20,13,8], [22,14,8], [23,14,9], [24,15,9], [25,16,10], [27,17,10], [28,17,11],+ [29,18,11], [30,19,12], [32,20,12], [33,21,13], [34,21,13], [35,22,14], [37,23,14], [38,24,15],+ [39,24,15], [40,25,16], [41,26,16], [43,27,17], [44,28,17], [45,28,18], [46,29,18], [48,30,19],+ [49,31,19], [50,32,20], [51,32,20], [53,33,21], [54,34,21], [55,35,22], [56,35,22], [58,36,23],+ [59,37,23], [60,38,24], [61,39,24], [62,39,25], [64,40,25], [65,41,26], [66,42,26], [67,42,27],+ [69,43,27], [70,44,28], [71,45,28], [72,46,29], [74,46,29], [75,47,30], [76,48,30], [77,49,31],+ [79,49,31], [80,50,32], [81,51,32], [82,52,33], [83,53,33], [85,53,34], [86,54,34], [87,55,35],+ [88,56,35], [90,57,36], [91,57,36], [92,58,37], [93,59,37], [95,60,38], [96,60,38], [97,61,39],+ [98,62,39], [100,63,40], [101,64,40], [102,64,41], [103,65,41], [104,66,42], [106,67,42], [107,67,43],+ [108,68,43], [109,69,44], [111,70,44], [112,71,45], [113,71,45], [114,72,46], [116,73,46], [117,74,47],+ [118,74,47], [119,75,48], [121,76,48], [122,77,49], [123,78,49], [124,78,50], [125,79,50], [127,80,51],+ [128,81,51], [129,82,52], [130,82,52], [132,83,53], [133,84,53], [134,85,54], [135,85,54], [137,86,55],+ [138,87,55], [139,88,56], [140,89,56], [142,89,57], [143,90,57], [144,91,58], [145,92,58], [146,92,59],+ [148,93,59], [149,94,60], [150,95,60], [151,96,61], [153,96,61], [154,97,62], [155,98,62], [158,99,63],+ [159,100,64], [160,101,64], [161,102,65], [163,103,65], [164,103,66], [165,104,66], [166,105,67], [167,106,67],+ [169,107,68], [170,107,68], [171,108,69], [172,109,69], [174,110,70], [175,110,70], [176,111,71], [177,112,71],+ [179,113,72], [180,114,72], [181,114,73], [182,115,73], [184,116,74], [185,117,74], [186,117,75], [187,118,75],+ [188,119,76], [190,120,76], [191,121,77], [192,121,77], [193,122,78], [195,123,78], [196,124,79], [197,124,79],+ [198,125,80], [200,126,80], [201,127,81], [202,128,81], [203,128,82], [205,129,82], [206,130,83], [207,131,83],+ [208,132,84], [209,132,84], [211,133,85], [212,134,85], [213,135,86], [214,135,86], [216,136,87], [217,137,87],+ [218,138,88], [219,139,88], [221,139,89], [222,140,89], [223,141,90], [224,142,90], [226,142,91], [227,143,91],+ [228,144,92], [229,145,92], [230,146,93], [232,146,93], [233,147,94], [234,148,94], [235,149,95], [237,149,95],+ [238,150,96], [239,151,96], [240,152,97], [242,153,97], [243,153,98], [244,154,98], [245,155,99], [247,156,99],+ [248,157,99], [249,157,100], [250,158,100], [251,159,101], [253,160,101], [254,160,102], [255,161,102], [255,162,103],+ [255,163,103], [255,164,104], [255,164,104], [255,165,105], [255,166,105], [255,167,106], [255,167,106], [255,168,107],+ [255,169,107], [255,170,108], [255,171,108], [255,171,109], [255,172,109], [255,173,110], [255,174,110], [255,174,111],+ [255,175,111], [255,176,112], [255,177,112], [255,178,113], [255,178,113], [255,179,114], [255,180,114], [255,181,115],+ [255,182,115], [255,182,116], [255,183,116], [255,184,117], [255,185,117], [255,185,118], [255,186,118], [255,187,119],+ [255,188,119], [255,189,120], [255,189,120], [255,190,121], [255,191,121], [255,192,122], [255,192,122], [255,193,123],+ [255,194,123], [255,195,124], [255,196,124], [255,196,125], [255,197,125], [255,198,126], [255,199,126]+ ]+}diff --git a/ColorSchemeList/Default_Field.json b/ColorSchemeList/Default_Field.jsonnew file mode 100644index 0000000..a204ce4--- /dev/null+++ b/ColorSchemeList/Default_Field.json@@ -0,0 +1,43 @@+{+ "name": "Default_Field",+ "origin": "9-stop copy of scheme 'Default_Field'",+ "category": "custom",+ "scheme_type": "field",+ "bits_per_channel": 8,+ "entry_count": 255,+ "stops": [[253,253,253], [48,32,244], [22,11,210], [26,24,170], [0,0,0], [119,2,2], [191,21,21], [251,59,59], [255,255,255]],+ "colors": [+ [253,253,253], [247,246,253], [240,239,252], [234,232,252], [227,225,252], [221,218,252], [214,211,251], [208,204,251],+ [201,197,251], [195,190,250], [188,183,250], [182,176,250], [176,169,250], [169,163,249], [163,156,249], [156,149,249],+ [150,142,248], [143,135,248], [137,128,248], [130,121,248], [124,114,247], [117,107,247], [111,100,247], [104,93,246],+ [98,86,246], [92,79,246], [85,72,246], [79,65,245], [72,58,245], [66,51,245], [59,44,244], [53,37,244],+ [48,32,244], [47,31,243], [46,31,242], [45,30,241], [45,29,239], [44,29,238], [43,28,237], [42,27,236],+ [41,27,235], [40,26,234], [40,25,233], [39,25,232], [38,24,231], [37,23,230], [36,23,229], [36,22,228],+ [35,21,227], [34,21,226], [33,20,224], [32,19,223], [31,19,222], [31,18,221], [30,17,220], [29,17,219],+ [28,16,218], [27,15,217], [27,15,216], [26,14,215], [25,13,214], [24,13,213], [23,12,212], [22,11,211],+ [22,11,209], [22,12,208], [22,12,207], [22,12,206], [23,13,204], [23,13,203], [23,14,202], [23,14,201],+ [23,14,199], [23,15,198], [23,15,197], [23,16,196], [24,16,194], [24,17,193], [24,17,192], [24,17,190],+ [24,18,189], [24,18,188], [24,19,187], [24,19,185], [25,19,184], [25,20,183], [25,20,182], [25,21,180],+ [25,21,179], [25,21,178], [25,22,177], [25,22,175], [26,23,174], [26,23,173], [26,23,172], [26,24,170],+ [25,23,166], [25,23,161], [24,22,155], [23,21,150], [22,20,145], [21,20,139], [20,19,134], [20,18,129],+ [19,17,123], [18,17,118], [17,16,112], [16,15,107], [16,14,102], [15,14,96], [14,13,91], [13,12,86],+ [12,11,80], [11,11,75], [11,10,70], [10,9,64], [9,8,59], [8,8,54], [7,7,48], [7,6,43],+ [6,5,37], [5,5,32], [4,4,27], [3,3,21], [2,2,16], [2,2,11], [1,1,5], [0,0,0],+ [4,0,0], [7,0,0], [11,0,0], [15,0,0], [19,0,0], [22,0,0], [26,0,0], [30,1,1],+ [34,1,1], [37,1,1], [41,1,1], [45,1,1], [49,1,1], [52,1,1], [56,1,1], [60,1,1],+ [64,1,1], [67,1,1], [71,1,1], [75,1,1], [79,1,1], [82,1,1], [86,1,1], [90,2,2],+ [94,2,2], [97,2,2], [101,2,2], [105,2,2], [109,2,2], [112,2,2], [116,2,2], [120,2,2],+ [122,3,3], [124,3,3], [126,4,4], [129,5,5], [131,5,5], [133,6,6], [135,6,6], [138,7,7],+ [140,8,8], [142,8,8], [145,9,9], [147,9,9], [149,10,10], [151,11,11], [154,11,11], [156,12,12],+ [158,12,12], [160,13,13], [163,14,14], [165,14,14], [167,15,15], [169,15,15], [172,16,16], [174,17,17],+ [176,17,17], [179,18,18], [181,18,18], [183,19,19], [185,20,20], [188,20,20], [190,21,21], [192,22,22],+ [194,23,23], [196,24,24], [198,25,25], [200,26,26], [201,28,28], [203,29,29], [205,30,30], [207,31,31],+ [209,32,32], [211,34,34], [213,35,35], [215,36,36], [217,37,37], [218,38,38], [220,40,40], [222,41,41],+ [224,42,42], [226,43,43], [228,44,44], [230,46,46], [232,47,47], [234,48,48], [235,49,49], [237,50,50],+ [239,52,52], [241,53,53], [243,54,54], [245,55,55], [247,56,56], [249,58,58], [251,59,59], [251,64,64],+ [251,70,70], [251,76,76], [251,82,82], [252,88,88], [252,94,94], [252,101,101], [252,107,107], [252,113,113],+ [252,119,119], [252,125,125], [252,132,132], [253,138,138], [253,144,144], [253,150,150], [253,156,156], [253,162,162],+ [253,169,169], [253,175,175], [253,181,181], [254,187,187], [254,193,193], [254,199,199], [254,206,206], [254,212,212],+ [254,218,218], [254,224,224], [254,230,230], [255,236,236], [255,243,243], [255,249,249], [255,255,255]+ ]+}diff --git a/ColorSchemeList/Default_Intensity.json b/ColorSchemeList/Default_Intensity.jsonnew file mode 100644index 0000000..d492198--- /dev/null+++ b/ColorSchemeList/Default_Intensity.json@@ -0,0 +1,43 @@+{+ "name": "Default_Intensity",+ "origin": "9-stop copy of scheme 'rainbow_JV'",+ "category": "custom",+ "scheme_type": "intensity",+ "bits_per_channel": 8,+ "entry_count": 255,+ "stops": [[0,0,0], [14,68,148], [33,172,222], [32,224,211], [33,246,61], [242,249,77], [234,179,72], [240,77,29], [255,0,0]],+ "colors": [+ [0,0,0], [0,2,5], [1,4,9], [1,6,14], [2,9,19], [2,11,23], [3,13,28], [3,15,33],+ [4,17,37], [4,19,42], [4,21,47], [5,24,51], [5,26,56], [6,28,61], [6,30,65], [7,32,70],+ [7,34,75], [7,36,79], [8,39,84], [8,41,89], [9,43,93], [9,45,98], [10,47,103], [10,49,107],+ [11,51,112], [11,54,117], [11,56,121], [12,58,126], [12,60,131], [13,62,135], [13,64,140], [14,66,145],+ [14,69,149], [15,72,151], [15,75,153], [16,79,156], [17,82,158], [17,85,160], [18,88,163], [18,92,165],+ [19,95,167], [20,98,170], [20,102,172], [21,105,174], [21,108,177], [22,111,179], [23,115,181], [23,118,184],+ [24,121,186], [24,125,188], [25,128,191], [26,131,193], [26,134,195], [27,138,198], [27,141,200], [28,144,202],+ [29,147,205], [29,151,207], [30,154,209], [30,157,212], [31,161,214], [32,164,216], [32,167,219], [33,170,221],+ [33,173,222], [33,174,221], [33,176,221], [33,178,221], [33,179,220], [33,181,220], [33,183,220], [33,184,219],+ [33,186,219], [33,188,219], [33,189,218], [33,191,218], [33,192,218], [33,194,217], [33,196,217], [33,197,217],+ [32,199,216], [32,201,216], [32,202,216], [32,204,215], [32,206,215], [32,207,215], [32,209,214], [32,210,214],+ [32,212,214], [32,214,213], [32,215,213], [32,217,212], [32,219,212], [32,220,212], [32,222,211], [32,224,211],+ [32,225,207], [32,225,203], [32,226,198], [32,227,193], [32,227,189], [32,228,184], [32,229,179], [32,229,174],+ [32,230,170], [32,231,165], [32,231,160], [32,232,155], [32,233,151], [32,234,146], [32,234,141], [32,235,137],+ [33,236,132], [33,236,127], [33,237,122], [33,238,118], [33,238,113], [33,239,108], [33,240,104], [33,240,99],+ [33,241,94], [33,242,89], [33,243,85], [33,243,80], [33,244,75], [33,245,70], [33,245,66], [33,246,61],+ [40,246,62], [46,246,62], [53,246,63], [59,246,63], [66,246,64], [72,247,64], [79,247,65], [86,247,65],+ [92,247,66], [99,247,66], [105,247,67], [112,247,67], [119,247,68], [125,247,68], [132,247,69], [138,248,69],+ [145,248,70], [151,248,70], [158,248,71], [165,248,71], [171,248,72], [178,248,72], [184,248,73], [191,248,73],+ [198,248,74], [204,248,74], [211,249,75], [217,249,75], [224,249,76], [230,249,76], [237,249,77], [242,248,77],+ [242,246,77], [241,244,77], [241,242,76], [241,240,76], [241,237,76], [240,235,76], [240,233,76], [240,231,76],+ [240,229,76], [239,226,75], [239,224,75], [239,222,75], [239,220,75], [238,218,75], [238,215,75], [238,213,74],+ [238,211,74], [237,209,74], [237,207,74], [237,204,74], [237,202,74], [236,200,73], [236,198,73], [236,196,73],+ [236,193,73], [235,191,73], [235,189,73], [235,187,73], [235,185,72], [234,182,72], [234,180,72], [234,177,71],+ [234,174,70], [234,171,69], [235,168,67], [235,165,66], [235,161,65], [235,158,63], [235,155,62], [236,152,60],+ [236,148,59], [236,145,58], [236,142,56], [236,139,55], [237,136,54], [237,132,52], [237,129,51], [237,126,50],+ [237,123,48], [237,120,47], [238,116,46], [238,113,44], [238,110,43], [238,107,42], [238,104,40], [239,100,39],+ [239,97,37], [239,94,36], [239,91,35], [239,87,33], [240,84,32], [240,81,31], [240,78,29], [240,75,28],+ [241,73,27], [241,70,26], [242,68,26], [242,65,25], [243,63,24], [243,61,23], [244,58,22], [244,56,21],+ [245,53,20], [245,51,19], [246,49,18], [246,46,17], [246,44,16], [247,41,16], [247,39,15], [248,36,14],+ [248,34,13], [249,32,12], [249,29,11], [250,27,10], [250,24,9], [251,22,8], [251,19,7], [252,17,6],+ [252,15,5], [253,12,5], [253,10,4], [254,7,3], [254,5,2], [255,2,1], [255,0,0]+ ]+}diff --git a/ColorSchemeList/Flare_inv.json b/ColorSchemeList/Flare_inv.jsonnew file mode 100644index 0000000..5a592c2--- /dev/null+++ b/ColorSchemeList/Flare_inv.json@@ -0,0 +1,42 @@+{+ "name": "Flare_inv",+ "origin": "matplotlib colormap flare, sampled at 255 points",+ "category": "sequential",+ "scheme_type": "intensity",+ "bits_per_channel": 8,+ "entry_count": 255,+ "colors": [+ [236,175,128], [236,174,127], [236,173,127], [236,172,126], [236,171,126], [236,170,125], [236,169,124], [236,168,124],+ [236,167,123], [236,166,123], [236,166,122], [236,165,121], [235,164,121], [235,163,120], [235,162,120], [235,161,119],+ [235,160,118], [235,159,118], [235,158,117], [235,157,117], [235,156,116], [235,155,116], [235,154,115], [234,153,114],+ [234,152,114], [234,151,113], [234,150,113], [234,149,112], [234,148,111], [234,147,111], [234,146,110], [234,145,110],+ [233,144,109], [233,143,109], [233,142,108], [233,141,107], [233,140,107], [233,139,106], [233,138,106], [233,137,105],+ [232,136,105], [232,135,104], [232,134,103], [232,133,103], [232,132,102], [232,131,102], [232,130,101], [232,129,101],+ [231,128,100], [231,127,100], [231,126,99], [231,125,99], [231,124,98], [231,123,98], [230,122,98], [230,121,97],+ [230,120,97], [230,119,96], [230,118,96], [229,118,96], [229,117,95], [229,116,95], [229,115,95], [229,114,94],+ [228,113,94], [228,112,94], [228,111,93], [228,110,93], [227,109,93], [227,108,93], [227,107,92], [227,106,92],+ [226,105,92], [226,104,92], [226,103,92], [225,102,92], [225,101,91], [225,100,91], [224,99,91], [224,98,91],+ [224,97,91], [223,96,91], [223,95,91], [223,94,91], [222,93,91], [222,92,91], [221,91,91], [221,90,91],+ [221,89,91], [220,89,92], [220,88,92], [219,87,92], [219,86,92], [218,85,92], [218,84,92], [217,83,93],+ [217,83,93], [216,82,93], [215,81,93], [215,80,94], [214,79,94], [214,79,94], [213,78,94], [212,77,95],+ [212,77,95], [211,76,95], [211,75,96], [210,75,96], [209,74,96], [208,73,97], [208,73,97], [207,72,97],+ [206,71,98], [206,71,98], [205,70,98], [204,70,99], [203,69,99], [202,69,99], [202,68,100], [201,68,100],+ [200,67,101], [199,67,101], [198,66,101], [197,66,102], [197,66,102], [196,65,102], [195,65,103], [193,64,103],+ [192,64,104], [191,63,104], [190,63,104], [189,63,104], [188,63,105], [187,62,105], [186,62,105], [186,62,105],+ [185,61,106], [184,61,106], [183,61,106], [182,61,106], [181,60,107], [180,60,107], [179,60,107], [178,60,107],+ [177,59,108], [176,59,108], [175,59,108], [174,59,108], [173,58,108], [172,58,109], [171,58,109], [170,58,109],+ [169,57,109], [168,57,109], [168,57,110], [167,57,110], [166,56,110], [165,56,110], [164,56,110], [163,56,110],+ [162,55,110], [161,55,111], [160,55,111], [159,55,111], [158,54,111], [157,54,111], [156,54,111], [155,54,111],+ [154,53,111], [154,53,111], [153,53,112], [152,53,112], [151,52,112], [150,52,112], [149,52,112], [148,52,112],+ [147,51,112], [146,51,112], [145,51,112], [144,51,112], [143,50,112], [142,50,112], [141,50,112], [141,50,112],+ [140,49,112], [139,49,112], [138,49,112], [137,49,112], [136,48,112], [135,48,112], [134,48,112], [133,48,112],+ [132,48,112], [131,47,112], [130,47,112], [129,47,112], [128,47,112], [127,47,112], [126,46,112], [126,46,112],+ [125,46,111], [124,46,111], [123,46,111], [122,45,111], [121,45,111], [120,45,111], [119,45,111], [118,45,110],+ [117,44,110], [116,44,110], [115,44,110], [114,44,110], [113,44,109], [112,44,109], [111,43,109], [110,43,109],+ [109,43,109], [108,43,108], [108,43,108], [107,43,108], [106,42,108], [105,42,107], [104,42,107], [103,42,107],+ [102,42,107], [101,41,106], [100,41,106], [99,41,106], [98,41,105], [97,41,105], [96,40,105], [95,40,104],+ [94,40,104], [93,40,104], [93,40,104], [92,39,103], [91,39,103], [90,39,103], [89,39,102], [88,38,102],+ [87,38,102], [86,38,101], [85,38,101], [84,38,101], [83,37,100], [82,37,100], [82,37,100], [81,36,100],+ [80,36,99], [79,36,99], [78,36,99], [77,35,98], [76,35,98], [75,35,98], [74,34,98]+ ]+}diff --git a/ColorSchemeList/Gray_scales.json b/ColorSchemeList/Gray_scales.jsonnew file mode 100644index 0000000..73e8ba1--- /dev/null+++ b/ColorSchemeList/Gray_scales.json@@ -0,0 +1,43 @@+{+ "name": "Gray_scales",+ "origin": "9-stop copy of scheme 'Gray scales'",+ "category": "custom",+ "scheme_type": "intensity",+ "bits_per_channel": 8,+ "entry_count": 255,+ "stops": [[0,0,0], [35,35,35], [98,98,98], [135,134,134], [159,159,159], [185,185,185], [210,210,210], [235,235,235], [255,255,255]],+ "colors": [+ [0,0,0], [1,1,1], [2,2,2], [3,3,3], [4,4,4], [6,6,6], [7,7,7], [8,8,8],+ [9,9,9], [10,10,10], [11,11,11], [12,12,12], [13,13,13], [14,14,14], [15,15,15], [17,17,17],+ [18,18,18], [19,19,19], [20,20,20], [21,21,21], [22,22,22], [23,23,23], [24,24,24], [25,25,25],+ [26,26,26], [28,28,28], [29,29,29], [30,30,30], [31,31,31], [32,32,32], [33,33,33], [34,34,34],+ [35,35,35], [37,37,37], [39,39,39], [41,41,41], [43,43,43], [45,45,45], [47,47,47], [49,49,49],+ [51,51,51], [53,53,53], [55,55,55], [57,57,57], [59,59,59], [61,61,61], [63,63,63], [65,65,65],+ [67,67,67], [69,69,69], [71,71,71], [73,73,73], [75,75,75], [77,77,77], [79,79,79], [81,81,81],+ [83,83,83], [85,85,85], [87,87,87], [89,89,89], [91,91,91], [93,93,93], [95,95,95], [97,97,97],+ [99,99,99], [100,100,100], [101,101,101], [102,102,102], [103,103,103], [104,104,104], [106,105,105], [107,107,107],+ [108,108,108], [109,109,109], [110,110,110], [111,111,111], [113,112,112], [114,113,113], [115,114,114], [116,116,116],+ [117,117,117], [118,118,118], [120,119,119], [121,120,120], [122,121,121], [123,122,122], [124,124,124], [125,125,125],+ [127,126,126], [128,127,127], [129,128,128], [130,129,129], [131,130,130], [132,131,131], [134,133,133], [135,134,134],+ [136,135,135], [136,135,135], [137,136,136], [138,137,137], [139,138,138], [139,139,139], [140,139,139], [141,140,140],+ [142,141,141], [142,142,142], [143,142,142], [144,143,143], [145,144,144], [145,145,145], [146,146,146], [147,146,146],+ [148,147,147], [148,148,148], [149,149,149], [150,150,150], [151,150,150], [151,151,151], [152,152,152], [153,153,153],+ [154,153,153], [154,154,154], [155,155,155], [156,156,156], [157,157,157], [157,157,157], [158,158,158], [159,159,159],+ [160,160,160], [161,161,161], [161,161,161], [162,162,162], [163,163,163], [164,164,164], [165,165,165], [166,166,166],+ [166,166,166], [167,167,167], [168,168,168], [169,169,169], [170,170,170], [170,170,170], [171,171,171], [172,172,172],+ [173,173,173], [174,174,174], [175,175,175], [175,175,175], [176,176,176], [177,177,177], [178,178,178], [179,179,179],+ [179,179,179], [180,180,180], [181,181,181], [182,182,182], [183,183,183], [184,184,184], [184,184,184], [185,185,185],+ [186,186,186], [187,187,187], [188,188,188], [188,188,188], [189,189,189], [190,190,190], [191,191,191], [191,191,191],+ [192,192,192], [193,193,193], [194,194,194], [195,195,195], [195,195,195], [196,196,196], [197,197,197], [198,198,198],+ [199,199,199], [199,199,199], [200,200,200], [201,201,201], [202,202,202], [203,203,203], [203,203,203], [204,204,204],+ [205,205,205], [206,206,206], [206,206,206], [207,207,207], [208,208,208], [209,209,209], [210,210,210], [210,210,210],+ [211,211,211], [212,212,212], [213,213,213], [214,214,214], [214,214,214], [215,215,215], [216,216,216], [217,217,217],+ [217,217,217], [218,218,218], [219,219,219], [220,220,220], [221,221,221], [221,221,221], [222,222,222], [223,223,223],+ [224,224,224], [225,225,225], [225,225,225], [226,226,226], [227,227,227], [228,228,228], [229,229,229], [229,229,229],+ [230,230,230], [231,231,231], [232,232,232], [232,232,232], [233,233,233], [234,234,234], [235,235,235], [235,235,235],+ [236,236,236], [237,237,237], [237,237,237], [238,238,238], [239,239,239], [239,239,239], [240,240,240], [241,241,241],+ [241,241,241], [242,242,242], [242,242,242], [243,243,243], [244,244,244], [244,244,244], [245,245,245], [246,246,246],+ [246,246,246], [247,247,247], [247,247,247], [248,248,248], [249,249,249], [249,249,249], [250,250,250], [251,251,251],+ [251,251,251], [252,252,252], [252,252,252], [253,253,253], [254,254,254], [254,254,254], [255,255,255]+ ]+}diff --git a/ColorSchemeList/Gray_scales_inv.json b/ColorSchemeList/Gray_scales_inv.jsonnew file mode 100644index 0000000..80793be--- /dev/null+++ b/ColorSchemeList/Gray_scales_inv.json@@ -0,0 +1,43 @@+{+ "name": "Gray_scales_inv",+ "origin": "9-stop copy of scheme 'Gray scales'",+ "category": "custom",+ "scheme_type": "intensity",+ "bits_per_channel": 8,+ "entry_count": 255,+ "stops": [[252,251,251], [226,223,223], [200,198,198], [171,170,170], [136,135,135], [101,101,101], [71,70,70], [29,29,29], [0,0,0]],+ "colors": [+ [252,251,251], [251,250,250], [250,249,249], [250,248,248], [249,247,247], [248,247,247], [247,246,246], [246,245,245],+ [245,244,244], [245,243,243], [244,242,242], [243,241,241], [242,240,240], [241,240,240], [241,239,239], [240,238,238],+ [239,237,237], [238,236,236], [237,235,235], [236,234,234], [236,233,233], [235,232,232], [234,232,232], [233,231,231],+ [232,230,230], [232,229,229], [231,228,228], [230,227,227], [229,226,226], [228,225,225], [227,225,225], [227,224,224],+ [226,223,223], [225,222,222], [224,221,221], [223,220,220], [223,220,220], [222,219,219], [221,218,218], [220,217,217],+ [219,217,217], [218,216,216], [218,215,215], [217,214,214], [216,213,213], [215,213,213], [214,212,212], [214,211,211],+ [213,210,210], [212,209,209], [211,209,209], [210,208,208], [209,207,207], [209,206,206], [208,205,205], [207,205,205],+ [206,204,204], [205,203,203], [205,202,202], [204,202,202], [203,201,201], [202,200,200], [201,199,199], [200,198,198],+ [200,198,198], [199,197,197], [198,196,196], [197,195,195], [196,194,194], [195,193,193], [194,192,192], [193,191,191],+ [192,191,191], [191,190,190], [190,189,189], [189,188,188], [189,187,187], [188,186,186], [187,185,185], [186,184,184],+ [185,183,183], [184,183,183], [183,182,182], [182,181,181], [181,180,180], [180,179,179], [179,178,178], [179,177,177],+ [178,176,176], [177,176,176], [176,175,175], [175,174,174], [174,173,173], [173,172,172], [172,171,171], [171,170,170],+ [170,169,169], [169,168,168], [168,167,167], [167,166,166], [166,165,165], [165,164,164], [164,163,163], [162,161,161],+ [161,160,160], [160,159,159], [159,158,158], [158,157,157], [157,156,156], [156,155,155], [155,154,154], [154,153,153],+ [153,152,152], [151,150,150], [150,149,149], [149,148,148], [148,147,147], [147,146,146], [146,145,145], [145,144,144],+ [144,143,143], [143,142,142], [142,141,141], [140,139,139], [139,138,138], [138,137,137], [137,136,136], [136,135,135],+ [135,134,134], [134,133,133], [133,132,132], [132,131,131], [130,130,130], [129,129,129], [128,128,128], [127,126,126],+ [126,125,125], [125,124,124], [124,123,123], [123,122,122], [122,121,121], [121,120,120], [119,119,119], [118,118,118],+ [117,117,117], [116,116,116], [115,115,115], [114,114,114], [113,113,113], [112,111,111], [111,110,110], [110,109,109],+ [108,108,108], [107,107,107], [106,106,106], [105,105,105], [104,104,104], [103,103,103], [102,102,102], [101,101,101],+ [100,100,100], [99,99,99], [98,98,98], [97,97,97], [96,96,96], [95,95,95], [94,94,94], [93,93,93],+ [92,92,92], [91,91,91], [90,90,90], [89,89,89], [88,88,88], [88,87,87], [87,86,86], [86,85,85],+ [85,84,84], [84,83,83], [83,82,82], [82,81,81], [81,80,80], [80,79,79], [79,78,78], [78,77,77],+ [77,76,76], [76,75,75], [75,74,74], [74,73,73], [73,72,72], [72,71,71], [71,70,70], [70,69,69],+ [69,68,68], [68,67,67], [66,65,65], [65,64,64], [64,63,63], [62,62,62], [61,60,60], [60,59,59],+ [58,58,58], [57,56,56], [56,55,55], [54,54,54], [53,53,53], [52,51,51], [50,50,50], [49,49,49],+ [48,47,47], [47,46,46], [45,45,45], [44,44,44], [43,42,42], [41,41,41], [40,40,40], [39,38,38],+ [37,37,37], [36,36,36], [35,34,34], [33,33,33], [32,32,32], [31,31,31], [29,29,29], [28,28,28],+ [27,27,27], [26,26,26], [26,26,26], [25,25,25], [24,24,24], [23,23,23], [22,22,22], [21,21,21],+ [20,20,20], [19,19,19], [18,18,18], [17,17,17], [16,16,16], [16,16,16], [15,15,15], [14,14,14],+ [13,13,13], [12,12,12], [11,11,11], [10,10,10], [9,9,9], [8,8,8], [7,7,7], [6,6,6],+ [5,5,5], [5,5,5], [4,4,4], [3,3,3], [2,2,2], [1,1,1], [0,0,0]+ ]+}diff --git a/ColorSchemeList/Green_blue.json b/ColorSchemeList/Green_blue.jsonnew file mode 100644index 0000000..444c5b0--- /dev/null+++ b/ColorSchemeList/Green_blue.json@@ -0,0 +1,43 @@+{+ "name": "Green_blue",+ "origin": "9-stop copy of scheme 'afmhot (5-stop)'",+ "category": "custom",+ "scheme_type": "field",+ "bits_per_channel": 8,+ "entry_count": 255,+ "stops": [[255,250,250], [89,96,246], [35,49,220], [3,27,164], [0,0,0], [2,127,6], [27,197,42], [78,245,86], [255,255,255]],+ "colors": [+ [255,250,250], [250,245,250], [245,240,250], [239,235,250], [234,231,249], [229,226,249], [224,221,249], [218,216,249],+ [213,211,249], [208,206,249], [203,201,249], [197,197,249], [192,192,248], [187,187,248], [182,182,248], [177,177,248],+ [171,172,248], [166,168,248], [161,163,248], [156,158,248], [150,153,247], [145,148,247], [140,143,247], [135,138,247],+ [130,134,247], [124,129,247], [119,124,247], [114,119,247], [109,114,246], [103,109,246], [98,104,246], [93,100,246],+ [89,96,246], [87,94,245], [85,93,244], [83,91,243], [82,90,243], [80,88,242], [78,87,241], [77,85,240],+ [75,84,239], [73,82,238], [72,81,238], [70,79,237], [68,78,236], [66,76,235], [65,75,234], [63,73,234],+ [61,72,233], [60,70,232], [58,69,231], [56,68,230], [55,66,229], [53,65,229], [51,63,228], [49,62,227],+ [48,60,226], [46,59,225], [44,57,225], [43,56,224], [41,54,223], [39,53,222], [38,51,221], [36,50,220],+ [34,49,219], [33,48,217], [32,47,216], [31,47,214], [30,46,212], [29,45,210], [28,44,209], [27,44,207],+ [26,43,205], [25,42,203], [24,42,201], [23,41,200], [22,40,198], [21,40,196], [20,39,194], [19,38,193],+ [18,38,191], [17,37,189], [16,36,187], [15,35,186], [14,35,184], [13,34,182], [12,33,180], [11,33,179],+ [10,32,177], [9,31,175], [8,31,173], [7,30,171], [6,29,170], [5,29,168], [4,28,166], [3,27,164],+ [3,26,160], [3,26,155], [3,25,150], [3,24,145], [3,23,139], [2,22,134], [2,21,129], [2,20,124],+ [2,20,119], [2,19,114], [2,18,108], [2,17,103], [2,16,98], [2,15,93], [2,14,88], [2,14,83],+ [1,13,77], [1,12,72], [1,11,67], [1,10,62], [1,9,57], [1,9,52], [1,8,46], [1,7,41],+ [1,6,36], [1,5,31], [0,4,26], [0,3,21], [0,3,15], [0,2,10], [0,1,5], [0,0,0],+ [0,4,0], [0,8,0], [0,12,1], [0,16,1], [0,20,1], [0,24,1], [0,28,1], [1,32,2],+ [1,36,2], [1,40,2], [1,44,2], [1,48,2], [1,52,2], [1,56,3], [1,60,3], [1,64,3],+ [1,68,3], [1,72,3], [1,76,4], [1,80,4], [1,84,4], [1,88,4], [1,92,4], [2,96,5],+ [2,100,5], [2,104,5], [2,108,5], [2,112,5], [2,116,5], [2,120,6], [2,124,6], [2,128,6],+ [3,130,7], [4,132,9], [5,134,10], [5,136,11], [6,139,12], [7,141,13], [8,143,14], [8,145,15],+ [9,147,16], [10,150,18], [11,152,19], [12,154,20], [12,156,21], [13,158,22], [14,161,23], [15,163,24],+ [16,165,26], [16,167,27], [17,169,28], [18,172,29], [19,174,30], [20,176,31], [20,178,32], [21,180,33],+ [22,183,35], [23,185,36], [23,187,37], [24,189,38], [25,191,39], [26,194,40], [27,196,41], [28,198,43],+ [29,199,44], [31,201,45], [33,202,47], [34,204,48], [36,205,50], [37,207,51], [39,208,52], [41,210,54],+ [42,211,55], [44,213,57], [45,214,58], [47,216,59], [49,217,61], [50,219,62], [52,220,63], [54,222,65],+ [55,223,66], [57,225,68], [58,226,69], [60,228,70], [62,230,72], [63,231,73], [65,233,75], [66,234,76],+ [68,236,77], [70,237,79], [71,239,80], [73,240,81], [74,242,83], [76,243,84], [78,245,86], [82,245,90],+ [88,246,95], [93,246,101], [99,246,106], [104,246,111], [110,247,117], [116,247,122], [121,247,127], [127,248,133],+ [132,248,138], [138,248,143], [144,249,149], [149,249,154], [155,249,159], [160,250,165], [166,250,170], [171,250,175],+ [177,251,180], [183,251,186], [188,251,191], [194,252,196], [199,252,202], [205,252,207], [210,252,212], [216,253,218],+ [222,253,223], [227,253,228], [233,254,234], [238,254,239], [244,254,244], [249,255,250], [255,255,255]+ ]+}diff --git a/ColorSchemeList/Green_pink.json b/ColorSchemeList/Green_pink.jsonnew file mode 100644index 0000000..edd9f1a--- /dev/null+++ b/ColorSchemeList/Green_pink.json@@ -0,0 +1,42 @@+{+ "name": "Green_pink",+ "origin": "9-stop copy of scheme 'vanimo'",+ "category": "custom",+ "bits_per_channel": 8,+ "entry_count": 255,+ "stops": [[255,204,252], [205,120,189], [147,63,128], [65,27,56], [25,21,18], [41,55,21], [82,113,38], [126,173,69], [189,252,165]],+ "colors": [+ [255,204,252], [253,201,250], [252,199,248], [250,196,246], [249,193,244], [247,191,242], [246,188,240], [244,185,238],+ [242,183,236], [241,180,234], [239,178,232], [238,175,230], [236,172,228], [235,170,226], [233,167,224], [231,164,222],+ [230,162,220], [228,159,218], [227,156,216], [225,154,214], [224,151,212], [222,148,210], [220,146,208], [219,143,206],+ [217,141,204], [216,138,202], [214,135,200], [212,133,198], [211,130,196], [209,127,194], [208,125,192], [206,122,190],+ [205,120,189], [203,118,187], [201,116,185], [199,114,183], [197,112,181], [195,111,179], [194,109,177], [192,107,175],+ [190,105,173], [188,103,171], [186,102,169], [184,100,167], [183,98,165], [181,96,164], [179,94,162], [177,93,160],+ [175,91,158], [173,89,156], [172,87,154], [170,85,152], [168,84,150], [166,82,148], [164,80,146], [163,78,144],+ [161,76,142], [159,75,140], [157,73,139], [155,71,137], [153,69,135], [152,67,133], [150,66,131], [148,64,129],+ [146,62,127], [143,61,125], [141,60,122], [138,59,120], [135,58,118], [133,57,116], [130,56,113], [128,54,111],+ [125,53,109], [122,52,106], [120,51,104], [117,50,102], [115,49,100], [112,48,97], [110,47,95], [107,45,93],+ [104,44,91], [102,43,88], [99,42,86], [97,41,84], [94,40,82], [91,39,79], [89,37,77], [86,36,75],+ [84,35,72], [81,34,70], [79,33,68], [76,32,66], [73,31,63], [71,30,61], [68,28,59], [66,27,57],+ [64,27,55], [63,27,54], [62,26,53], [60,26,52], [59,26,50], [58,26,49], [56,26,48], [55,26,47],+ [54,25,46], [53,25,44], [51,25,43], [50,25,42], [49,25,41], [48,24,40], [46,24,38], [45,24,37],+ [44,24,36], [43,24,35], [41,23,34], [40,23,32], [39,23,31], [38,23,30], [36,23,29], [35,23,28],+ [34,22,26], [33,22,25], [31,22,24], [30,22,23], [29,22,22], [28,21,20], [26,21,19], [25,21,18],+ [26,22,18], [26,23,18], [27,24,18], [27,25,18], [28,26,18], [28,27,19], [29,28,19], [29,30,19],+ [30,31,19], [30,32,19], [31,33,19], [31,34,19], [32,35,19], [32,36,19], [33,37,19], [33,38,20],+ [34,39,20], [34,40,20], [35,41,20], [35,42,20], [36,43,20], [36,45,20], [37,46,20], [37,47,20],+ [38,48,20], [38,49,20], [39,50,21], [39,51,21], [40,52,21], [40,53,21], [41,54,21], [41,55,21],+ [43,57,22], [44,59,22], [45,61,23], [46,63,23], [48,65,24], [49,66,24], [50,68,25], [52,70,25],+ [53,72,26], [54,74,26], [56,76,27], [57,77,28], [58,79,28], [59,81,29], [61,83,29], [62,85,30],+ [63,87,30], [65,88,31], [66,90,31], [67,92,32], [68,94,32], [70,96,33], [71,97,33], [72,99,34],+ [74,101,35], [75,103,35], [76,105,36], [77,107,36], [79,108,37], [80,110,37], [81,112,38], [83,114,38],+ [84,116,39], [85,118,40], [87,120,41], [88,122,42], [90,123,43], [91,125,44], [92,127,45], [94,129,46],+ [95,131,47], [97,133,48], [98,135,49], [99,137,50], [101,139,51], [102,140,52], [103,142,53], [105,144,54],+ [106,146,55], [108,148,56], [109,150,57], [110,152,58], [112,154,59], [113,156,60], [115,157,61], [116,159,62],+ [117,161,63], [119,163,64], [120,165,65], [121,167,66], [123,169,67], [124,171,68], [126,173,69], [127,175,71],+ [129,177,74], [131,180,77], [133,182,80], [135,185,83], [137,187,86], [139,190,89], [141,192,92], [143,195,95],+ [145,197,98], [147,200,102], [149,202,105], [151,205,108], [153,207,111], [155,210,114], [157,212,117], [159,215,120],+ [161,217,123], [163,220,126], [165,222,129], [167,225,132], [169,227,135], [171,230,138], [173,232,141], [175,235,144],+ [177,237,147], [179,240,150], [181,242,153], [183,245,156], [185,247,159], [187,250,162], [189,252,165]+ ]+}diff --git a/ColorSchemeList/Greens.json b/ColorSchemeList/Greens.jsonnew file mode 100644index 0000000..ee4e9b3--- /dev/null+++ b/ColorSchemeList/Greens.json@@ -0,0 +1,42 @@+{+ "name": "Greens",+ "origin": "matplotlib colormap Greens, sampled at 255 points",+ "category": "sequential",+ "scheme_type": "field",+ "bits_per_channel": 8,+ "entry_count": 255,+ "colors": [+ [247,252,245], [246,251,244], [245,251,243], [245,251,243], [244,251,242], [244,250,241], [243,250,241], [243,250,240],+ [242,250,239], [241,250,239], [241,249,238], [240,249,237], [240,249,237], [239,249,236], [239,248,235], [238,248,235],+ [237,248,234], [237,248,233], [236,248,233], [236,247,232], [235,247,231], [235,247,231], [234,247,230], [234,246,229],+ [233,246,229], [232,246,228], [232,246,227], [231,246,227], [231,245,226], [230,245,225], [230,245,225], [229,245,224],+ [228,244,223], [227,244,222], [227,244,221], [226,243,220], [225,243,219], [224,243,218], [223,242,217], [222,242,216],+ [221,241,215], [220,241,214], [219,241,213], [218,240,212], [217,240,211], [216,240,210], [215,239,209], [214,239,208],+ [213,238,207], [212,238,206], [211,238,205], [211,237,204], [210,237,203], [209,237,202], [208,236,201], [207,236,200],+ [206,235,199], [205,235,198], [204,235,197], [203,234,196], [202,234,195], [201,234,194], [200,233,193], [199,233,192],+ [198,232,191], [197,232,190], [196,231,189], [195,231,188], [193,230,187], [192,230,185], [191,229,184], [190,229,183],+ [189,228,182], [187,228,181], [186,227,180], [185,227,178], [184,226,177], [183,226,176], [182,225,175], [180,225,174],+ [179,224,173], [178,224,171], [177,223,170], [176,223,169], [174,222,168], [173,222,167], [172,221,166], [171,221,165],+ [170,220,163], [168,220,162], [167,219,161], [166,219,160], [165,218,159], [164,218,158], [162,217,156], [161,217,155],+ [160,216,154], [159,216,153], [157,215,152], [156,214,151], [154,214,149], [153,213,148], [152,212,147], [150,212,146],+ [149,211,145], [147,210,144], [146,210,142], [144,209,141], [143,208,140], [142,208,139], [140,207,138], [139,206,137],+ [137,206,135], [136,205,134], [135,204,133], [133,204,132], [132,203,131], [130,202,130], [129,202,129], [128,201,127],+ [126,200,126], [125,200,125], [123,199,124], [122,198,123], [120,198,122], [119,197,120], [118,196,119], [115,195,117],+ [113,194,116], [112,194,116], [110,193,115], [108,192,114], [107,191,113], [105,190,112], [104,190,112], [102,189,111],+ [100,188,110], [99,187,109], [97,186,108], [96,186,108], [94,185,107], [92,184,106], [91,183,105], [89,183,105],+ [88,182,104], [86,181,103], [84,180,102], [83,179,101], [81,179,101], [80,178,100], [78,177,99], [76,176,98],+ [75,176,97], [73,175,97], [72,174,96], [70,173,95], [68,172,94], [67,172,94], [65,171,93], [64,170,92],+ [63,169,91], [62,168,91], [61,167,90], [60,166,89], [59,165,88], [58,164,88], [57,163,87], [56,162,86],+ [55,161,85], [55,160,85], [54,159,84], [53,158,83], [52,157,82], [51,156,81], [50,155,81], [49,154,80],+ [48,153,79], [47,152,78], [46,151,78], [45,150,77], [44,149,76], [43,148,75], [42,147,75], [41,146,74],+ [40,145,73], [39,144,72], [39,143,72], [38,142,71], [37,141,70], [36,140,69], [35,139,69], [34,138,68],+ [33,137,67], [31,136,66], [30,135,66], [29,134,65], [28,133,64], [27,132,63], [26,131,62], [25,130,62],+ [24,129,61], [23,128,60], [22,127,59], [21,126,58], [19,126,58], [18,125,57], [17,124,56], [16,123,55],+ [15,122,55], [14,121,54], [13,120,53], [12,119,52], [11,118,51], [10,117,51], [8,116,50], [7,115,49],+ [6,114,48], [5,113,48], [4,112,47], [3,111,46], [2,111,45], [1,110,44], [0,109,44], [0,107,43],+ [0,106,43], [0,105,42], [0,104,41], [0,102,41], [0,101,40], [0,100,40], [0,98,39], [0,97,39],+ [0,96,38], [0,95,38], [0,93,37], [0,92,37], [0,91,36], [0,89,36], [0,88,35], [0,87,35],+ [0,86,34], [0,84,33], [0,83,33], [0,82,32], [0,80,32], [0,79,31], [0,78,31], [0,77,30],+ [0,75,30], [0,74,29], [0,73,29], [0,71,28], [0,70,28], [0,69,27], [0,68,27]+ ]+}diff --git a/ColorSchemeList/Hot_orange.json b/ColorSchemeList/Hot_orange.jsonnew file mode 100644index 0000000..45a3f98--- /dev/null+++ b/ColorSchemeList/Hot_orange.json@@ -0,0 +1,41 @@+{+ "name": "Hot_orange",+ "origin": "matplotlib colormap afmhot, sampled at 255 points",+ "scheme_type": "intensity",+ "bits_per_channel": 8,+ "entry_count": 255,+ "colors": [+ [0,0,0], [2,0,0], [4,0,0], [6,0,0], [8,0,0], [10,0,0], [12,0,0], [14,0,0],+ [16,0,0], [18,0,0], [20,0,0], [22,0,0], [24,0,0], [26,0,0], [28,0,0], [30,0,0],+ [32,0,0], [34,0,0], [36,0,0], [38,0,0], [40,0,0], [42,0,0], [44,0,0], [46,0,0],+ [48,0,0], [50,0,0], [52,0,0], [54,0,0], [56,0,0], [58,0,0], [60,0,0], [62,0,0],+ [64,0,0], [65,0,0], [68,0,0], [70,0,0], [72,0,0], [73,0,0], [76,0,0], [78,0,0],+ [80,0,0], [81,0,0], [84,0,0], [86,0,0], [88,0,0], [89,0,0], [92,0,0], [94,0,0],+ [96,0,0], [97,0,0], [100,0,0], [102,0,0], [104,0,0], [105,0,0], [108,0,0], [110,0,0],+ [112,0,0], [113,0,0], [116,0,0], [118,0,0], [120,0,0], [121,0,0], [124,0,0], [126,0,0],+ [128,0,0], [130,2,0], [131,4,0], [134,6,0], [136,8,0], [138,10,0], [140,12,0], [142,14,0],+ [144,16,0], [146,18,0], [147,20,0], [150,22,0], [152,24,0], [154,26,0], [156,28,0], [158,30,0],+ [160,32,0], [162,34,0], [163,36,0], [166,38,0], [168,40,0], [170,42,0], [172,44,0], [174,46,0],+ [176,48,0], [178,50,0], [179,52,0], [182,54,0], [184,56,0], [186,58,0], [188,60,0], [190,62,0],+ [192,64,0], [194,66,0], [195,68,0], [198,70,0], [200,72,0], [202,74,0], [204,76,0], [206,78,0],+ [208,80,0], [210,82,0], [211,84,0], [214,86,0], [216,88,0], [218,90,0], [220,92,0], [222,94,0],+ [224,96,0], [226,98,0], [227,100,0], [230,102,0], [232,104,0], [234,106,0], [236,108,0], [238,110,0],+ [240,112,0], [242,114,0], [243,116,0], [246,118,0], [248,120,0], [250,122,0], [252,124,0], [255,128,0],+ [255,130,2], [255,132,4], [255,134,6], [255,136,8], [255,138,11], [255,140,13], [255,142,15], [255,144,16],+ [255,146,18], [255,148,20], [255,150,22], [255,152,25], [255,154,27], [255,156,29], [255,158,31], [255,160,32],+ [255,162,34], [255,164,36], [255,166,38], [255,168,40], [255,170,43], [255,172,45], [255,174,47], [255,176,48],+ [255,178,50], [255,180,52], [255,182,54], [255,184,57], [255,186,59], [255,188,61], [255,190,63], [255,192,65],+ [255,194,66], [255,196,68], [255,198,70], [255,200,72], [255,202,75], [255,204,77], [255,206,79], [255,208,81],+ [255,210,82], [255,212,84], [255,214,86], [255,216,89], [255,218,91], [255,220,93], [255,222,95], [255,224,97],+ [255,226,98], [255,228,100], [255,230,102], [255,232,104], [255,234,107], [255,236,109], [255,238,111], [255,240,113],+ [255,242,114], [255,244,116], [255,246,118], [255,248,121], [255,250,123], [255,252,125], [255,254,127], [255,255,129],+ [255,255,131], [255,255,132], [255,255,134], [255,255,136], [255,255,139], [255,255,141], [255,255,143], [255,255,145],+ [255,255,147], [255,255,148], [255,255,150], [255,255,153], [255,255,155], [255,255,157], [255,255,159], [255,255,161],+ [255,255,163], [255,255,164], [255,255,166], [255,255,168], [255,255,171], [255,255,173], [255,255,175], [255,255,177],+ [255,255,179], [255,255,180], [255,255,182], [255,255,185], [255,255,187], [255,255,189], [255,255,191], [255,255,193],+ [255,255,195], [255,255,196], [255,255,198], [255,255,200], [255,255,203], [255,255,205], [255,255,207], [255,255,209],+ [255,255,211], [255,255,212], [255,255,214], [255,255,217], [255,255,219], [255,255,221], [255,255,223], [255,255,225],+ [255,255,227], [255,255,228], [255,255,230], [255,255,232], [255,255,235], [255,255,237], [255,255,239], [255,255,241],+ [255,255,243], [255,255,244], [255,255,246], [255,255,249], [255,255,251], [255,255,253], [255,255,255]+ ]+}diff --git a/ColorSchemeList/Ice_and_fire.json b/ColorSchemeList/Ice_and_fire.jsonnew file mode 100644index 0000000..fe75dee--- /dev/null+++ b/ColorSchemeList/Ice_and_fire.json@@ -0,0 +1,41 @@+{+ "name": "Ice_and_fire",+ "origin": "embedded table in wave_visualizer.py",+ "scheme_type": "field",+ "bits_per_channel": 8,+ "entry_count": 255,+ "colors": [+ [179,224,216], [178,223,216], [176,222,215], [175,221,215], [173,219,214], [171,218,214], [169,217,214], [167,215,213],+ [165,214,213], [162,212,212], [160,210,212], [157,209,211], [154,207,211], [151,205,210], [148,203,210], [146,201,209],+ [143,199,209], [140,198,208], [137,196,208], [134,194,208], [131,192,207], [128,190,207], [125,188,207], [122,187,207],+ [119,185,206], [116,183,206], [113,181,206], [110,179,206], [108,177,206], [105,176,205], [102,174,205], [99,172,205],+ [97,170,205], [94,168,205], [91,166,205], [89,164,205], [86,162,205], [84,161,205], [82,159,205], [79,157,205],+ [77,155,205], [75,153,206], [73,151,206], [71,149,206], [69,147,206], [68,145,206], [66,143,206], [65,140,206],+ [64,138,206], [63,136,206], [62,134,206], [61,132,206], [61,130,205], [61,127,205], [60,125,205], [60,123,204],+ [60,121,203], [60,118,203], [61,116,202], [61,114,201], [61,112,200], [62,109,198], [62,107,197], [63,105,195],+ [64,103,194], [65,100,192], [65,98,190], [66,96,187], [67,94,185], [67,92,183], [68,90,180], [68,88,177],+ [69,86,174], [69,85,171], [69,83,168], [70,81,165], [70,79,162], [70,78,158], [69,76,155], [69,75,151],+ [69,73,148], [68,72,144], [68,70,141], [67,69,137], [66,67,134], [66,66,130], [65,65,127], [64,63,123],+ [63,62,120], [62,61,116], [61,60,113], [60,59,109], [59,57,106], [58,56,103], [57,55,99], [55,54,96],+ [54,53,93], [53,52,90], [52,50,87], [51,49,84], [50,48,81], [48,47,78], [47,46,75], [46,45,72],+ [45,44,70], [44,43,67], [43,42,65], [42,41,62], [41,40,60], [40,39,57], [39,38,55], [38,37,53],+ [37,37,51], [37,36,49], [36,35,47], [35,35,45], [35,34,44], [34,33,42], [34,33,41], [33,32,39],+ [33,32,38], [33,32,37], [33,31,36], [33,31,35], [33,31,35], [34,30,34], [34,30,33], [34,30,33],+ [35,30,32], [36,30,32], [36,30,32], [37,30,32], [38,30,32], [39,30,32], [40,30,32], [41,30,32],+ [42,30,33], [44,31,33], [46,31,34], [47,31,34], [49,31,35], [51,32,35], [53,32,36], [55,32,37],+ [57,33,38], [59,33,38], [61,33,39], [63,34,40], [65,34,41], [67,35,42], [70,35,43], [72,36,44],+ [74,36,45], [77,37,46], [79,37,47], [82,38,48], [84,38,49], [87,39,50], [90,39,51], [92,40,52],+ [95,40,53], [98,40,54], [100,41,55], [103,41,56], [106,42,57], [109,42,58], [111,42,59], [114,43,60],+ [117,43,60], [120,43,61], [123,44,62], [126,44,63], [129,44,63], [131,44,64], [134,45,64], [137,45,65],+ [140,45,65], [143,46,65], [146,46,65], [149,46,66], [152,47,66], [155,47,66], [158,48,66], [160,48,66],+ [163,49,65], [166,49,65], [169,50,65], [172,51,64], [174,52,64], [177,53,63], [180,54,63], [182,55,62],+ [185,56,62], [187,57,61], [190,58,61], [192,60,60], [195,61,59], [197,63,59], [199,65,58], [201,66,57],+ [203,68,57], [206,70,56], [208,72,55], [209,74,55], [211,76,54], [213,78,54], [215,81,54], [217,83,53],+ [218,85,53], [220,88,53], [221,90,53], [223,93,54], [224,95,54], [225,98,55], [227,101,55], [228,103,56],+ [229,106,57], [230,109,58], [231,111,60], [232,114,61], [233,117,62], [234,120,64], [235,123,66], [236,125,68],+ [237,128,70], [237,131,73], [238,134,75], [239,137,78], [240,139,80], [240,142,83], [241,145,86], [242,148,89],+ [242,151,93], [243,153,96], [243,156,99], [244,159,103], [245,162,106], [245,165,110], [246,167,113], [246,170,117],+ [247,173,120], [247,176,124], [248,178,127], [248,181,131], [249,184,134], [249,186,138], [250,188,141], [250,190,144],+ [251,192,147], [251,194,149], [251,196,152], [252,198,154], [252,200,156], [252,201,158], [253,203,160]+ ]+}diff --git a/ColorSchemeList/Orange_hot.json b/ColorSchemeList/Orange_hot.jsonnew file mode 100644index 0000000..0b4ccc0--- /dev/null+++ b/ColorSchemeList/Orange_hot.json@@ -0,0 +1,42 @@+{+ "name": "Orange_hot",+ "origin": "matplotlib colormap hot, sampled at 255 points",+ "category": "sequential",+ "scheme_type": "field",+ "bits_per_channel": 8,+ "entry_count": 255,+ "colors": [+ [10,0,0], [13,0,0], [15,0,0], [18,0,0], [21,0,0], [23,0,0], [26,0,0], [28,0,0],+ [31,0,0], [34,0,0], [36,0,0], [39,0,0], [42,0,0], [44,0,0], [47,0,0], [49,0,0],+ [52,0,0], [55,0,0], [57,0,0], [60,0,0], [63,0,0], [65,0,0], [68,0,0], [70,0,0],+ [73,0,0], [76,0,0], [78,0,0], [81,0,0], [84,0,0], [86,0,0], [89,0,0], [91,0,0],+ [94,0,0], [97,0,0], [99,0,0], [102,0,0], [105,0,0], [107,0,0], [110,0,0], [112,0,0],+ [115,0,0], [118,0,0], [120,0,0], [123,0,0], [126,0,0], [128,0,0], [131,0,0], [133,0,0],+ [136,0,0], [139,0,0], [141,0,0], [144,0,0], [147,0,0], [149,0,0], [152,0,0], [154,0,0],+ [157,0,0], [160,0,0], [162,0,0], [165,0,0], [168,0,0], [170,0,0], [173,0,0], [175,0,0],+ [178,0,0], [181,0,0], [183,0,0], [186,0,0], [189,0,0], [191,0,0], [194,0,0], [196,0,0],+ [199,0,0], [202,0,0], [204,0,0], [207,0,0], [210,0,0], [212,0,0], [215,0,0], [217,0,0],+ [220,0,0], [223,0,0], [225,0,0], [228,0,0], [231,0,0], [233,0,0], [236,0,0], [238,0,0],+ [241,0,0], [244,0,0], [246,0,0], [249,0,0], [252,0,0], [254,0,0], [255,2,0], [255,5,0],+ [255,7,0], [255,10,0], [255,12,0], [255,15,0], [255,18,0], [255,20,0], [255,23,0], [255,26,0],+ [255,28,0], [255,31,0], [255,33,0], [255,36,0], [255,39,0], [255,41,0], [255,44,0], [255,47,0],+ [255,49,0], [255,52,0], [255,54,0], [255,57,0], [255,60,0], [255,62,0], [255,65,0], [255,68,0],+ [255,70,0], [255,73,0], [255,75,0], [255,78,0], [255,81,0], [255,83,0], [255,86,0], [255,91,0],+ [255,94,0], [255,96,0], [255,99,0], [255,102,0], [255,104,0], [255,107,0], [255,110,0], [255,112,0],+ [255,115,0], [255,117,0], [255,120,0], [255,123,0], [255,125,0], [255,128,0], [255,131,0], [255,133,0],+ [255,136,0], [255,138,0], [255,141,0], [255,144,0], [255,146,0], [255,149,0], [255,151,0], [255,154,0],+ [255,157,0], [255,159,0], [255,162,0], [255,165,0], [255,167,0], [255,170,0], [255,172,0], [255,175,0],+ [255,178,0], [255,180,0], [255,183,0], [255,186,0], [255,188,0], [255,191,0], [255,193,0], [255,196,0],+ [255,199,0], [255,201,0], [255,204,0], [255,207,0], [255,209,0], [255,212,0], [255,214,0], [255,217,0],+ [255,220,0], [255,222,0], [255,225,0], [255,228,0], [255,230,0], [255,233,0], [255,235,0], [255,238,0],+ [255,241,0], [255,243,0], [255,246,0], [255,249,0], [255,251,0], [255,254,0], [255,255,2], [255,255,6],+ [255,255,10], [255,255,14], [255,255,18], [255,255,22], [255,255,26], [255,255,30], [255,255,34], [255,255,38],+ [255,255,42], [255,255,46], [255,255,50], [255,255,54], [255,255,58], [255,255,62], [255,255,65], [255,255,69],+ [255,255,73], [255,255,77], [255,255,81], [255,255,85], [255,255,89], [255,255,93], [255,255,97], [255,255,101],+ [255,255,105], [255,255,109], [255,255,113], [255,255,117], [255,255,121], [255,255,125], [255,255,128], [255,255,132],+ [255,255,136], [255,255,140], [255,255,144], [255,255,148], [255,255,152], [255,255,156], [255,255,160], [255,255,164],+ [255,255,168], [255,255,172], [255,255,176], [255,255,180], [255,255,184], [255,255,188], [255,255,191], [255,255,195],+ [255,255,199], [255,255,203], [255,255,207], [255,255,211], [255,255,215], [255,255,219], [255,255,223], [255,255,227],+ [255,255,231], [255,255,235], [255,255,239], [255,255,243], [255,255,247], [255,255,251], [255,255,255]+ ]+}diff --git a/ColorSchemeList/Orange_symmetry.json b/ColorSchemeList/Orange_symmetry.jsonnew file mode 100644index 0000000..49a9582--- /dev/null+++ b/ColorSchemeList/Orange_symmetry.json@@ -0,0 +1,41 @@+{+ "name": "Orange_symmetry",+ "origin": "embedded table in wave_visualizer.py",+ "scheme_type": "field",+ "bits_per_channel": 8,+ "entry_count": 255,+ "colors": [+ [253,203,160], [252,201,158], [252,200,156], [252,198,154], [251,196,152], [251,194,149], [251,192,147], [250,190,145],+ [250,189,142], [249,187,139], [249,185,135], [248,182,132], [248,179,129], [247,177,125], [247,175,122], [247,172,119],+ [246,168,115], [246,166,112], [245,164,108], [245,161,105], [244,158,102], [243,155,98], [243,152,95], [242,150,92],+ [242,147,88], [241,145,86], [240,142,83], [240,139,80], [239,137,78], [238,134,75], [237,131,73], [237,129,70],+ [236,126,68], [235,124,67], [234,121,65], [233,118,63], [232,115,61], [231,112,61], [230,110,59], [229,107,57],+ [228,104,56], [228,102,55], [226,100,55], [224,97,55], [224,94,54], [222,92,54], [221,89,53], [219,87,53],+ [218,84,53], [217,83,53], [215,80,54], [213,78,54], [211,76,54], [209,74,55], [208,72,55], [206,70,56],+ [203,68,57], [201,66,57], [199,65,58], [198,64,59], [196,62,59], [193,60,60], [191,59,61], [188,57,61],+ [186,56,62], [183,55,62], [181,55,63], [179,54,63], [176,53,63], [173,52,64], [171,51,64], [168,50,65],+ [165,49,65], [162,49,65], [159,48,66], [157,48,66], [155,47,66], [152,47,66], [149,46,66], [146,46,65],+ [143,46,65], [140,45,65], [138,45,65], [135,45,64], [132,44,64], [130,44,63], [127,44,63], [124,44,62],+ [121,43,61], [118,43,60], [115,43,60], [112,42,60], [110,42,59], [108,42,58], [105,42,57], [102,41,56],+ [99,41,55], [97,40,54], [94,40,53], [91,40,52], [89,39,51], [86,39,50], [84,38,49], [82,38,48],+ [79,37,47], [77,37,46], [74,36,45], [72,36,44], [70,35,43], [68,35,42], [65,34,41], [64,34,40],+ [62,33,39], [60,33,38], [58,33,38], [56,32,38], [54,32,36], [52,32,35], [50,32,35], [48,31,35],+ [47,31,34], [45,31,34], [43,31,33], [42,30,33], [41,30,32], [40,30,32], [39,30,32], [38,30,32],+ [37,30,32], [36,30,32], [36,30,32], [37,30,32], [38,30,32], [39,30,32], [40,30,32], [41,30,32],+ [42,30,33], [44,31,33], [46,31,34], [47,31,34], [49,31,35], [51,32,35], [53,32,36], [55,32,37],+ [57,33,38], [59,33,38], [61,33,39], [63,34,40], [65,34,41], [67,35,42], [70,35,43], [72,36,44],+ [74,36,45], [77,37,46], [79,37,47], [82,38,48], [84,38,49], [87,39,50], [90,39,51], [92,40,52],+ [95,40,53], [98,40,54], [100,41,55], [103,41,56], [106,42,57], [109,42,58], [111,42,59], [114,43,60],+ [117,43,60], [120,43,61], [123,44,62], [126,44,63], [129,44,63], [131,44,64], [134,45,64], [137,45,65],+ [140,45,65], [143,46,65], [146,46,65], [149,46,66], [152,47,66], [155,47,66], [158,48,66], [160,48,66],+ [163,49,65], [166,49,65], [169,50,65], [172,51,64], [174,52,64], [177,53,63], [180,54,63], [182,55,62],+ [185,56,62], [187,57,61], [190,58,61], [192,60,60], [195,61,59], [197,63,59], [199,65,58], [201,66,57],+ [203,68,57], [206,70,56], [208,72,55], [209,74,55], [211,76,54], [213,78,54], [215,81,54], [217,83,53],+ [218,85,53], [220,88,53], [221,90,53], [223,93,54], [224,95,54], [225,98,55], [227,101,55], [228,103,56],+ [229,106,57], [230,109,58], [231,111,60], [232,114,61], [233,117,62], [234,120,64], [235,123,66], [236,125,68],+ [237,128,70], [237,131,73], [238,134,75], [239,137,78], [240,139,80], [240,142,83], [241,145,86], [242,148,89],+ [242,151,93], [243,153,96], [243,156,99], [244,159,103], [245,162,106], [245,165,110], [246,167,113], [246,170,117],+ [247,173,120], [247,176,124], [248,178,127], [248,181,131], [249,184,134], [249,186,138], [250,188,141], [250,190,144],+ [251,192,147], [251,194,149], [251,196,152], [252,198,154], [252,200,156], [252,201,158], [253,203,160]+ ]+}diff --git a/ColorSchemeList/Purple_rain.json b/ColorSchemeList/Purple_rain.jsonnew file mode 100644index 0000000..12a28c1--- /dev/null+++ b/ColorSchemeList/Purple_rain.json@@ -0,0 +1,43 @@+{+ "name": "Purple_rain",+ "origin": "9-stop copy of scheme 'Gray scales'",+ "category": "custom",+ "scheme_type": "intensity",+ "bits_per_channel": 8,+ "entry_count": 255,+ "stops": [[0,0,0], [29,1,47], [50,1,81], [65,2,104], [107,2,128], [132,2,158], [167,5,198], [201,21,236], [228,105,252]],+ "colors": [+ [0,0,0], [1,0,1], [2,0,3], [3,0,4], [4,0,6], [5,0,7], [5,0,9], [6,0,10],+ [7,0,12], [8,0,13], [9,0,15], [10,0,16], [11,0,18], [12,0,19], [13,0,21], [14,0,22],+ [15,1,24], [16,1,25], [16,1,27], [17,1,28], [18,1,30], [19,1,31], [20,1,33], [21,1,34],+ [22,1,36], [23,1,37], [24,1,38], [25,1,40], [26,1,41], [26,1,43], [27,1,44], [28,1,46],+ [29,1,47], [30,1,48], [30,1,49], [31,1,50], [32,1,52], [32,1,53], [33,1,54], [34,1,55],+ [34,1,56], [35,1,57], [36,1,58], [36,1,59], [37,1,60], [38,1,61], [38,1,62], [39,1,63],+ [40,1,64], [40,1,65], [41,1,67], [42,1,68], [42,1,69], [43,1,70], [44,1,71], [44,1,72],+ [45,1,73], [46,1,74], [46,1,75], [47,1,76], [48,1,77], [48,1,78], [49,1,79], [50,1,80],+ [50,1,81], [51,1,82], [51,1,83], [52,1,84], [52,1,84], [53,1,85], [53,1,86], [54,1,86],+ [54,1,87], [54,1,88], [55,1,89], [55,1,89], [56,1,90], [56,1,91], [57,1,92], [57,1,92],+ [58,2,93], [58,2,94], [59,2,94], [59,2,95], [60,2,96], [60,2,97], [61,2,97], [61,2,98],+ [62,2,99], [62,2,99], [63,2,100], [63,2,101], [63,2,102], [64,2,102], [64,2,103], [65,2,104],+ [66,2,105], [67,2,105], [69,2,106], [70,2,107], [71,2,108], [73,2,108], [74,2,109], [75,2,110],+ [77,2,111], [78,2,111], [79,2,112], [81,2,113], [82,2,114], [83,2,114], [85,2,115], [86,2,116],+ [87,2,117], [88,2,117], [90,2,118], [91,2,119], [92,2,120], [94,2,120], [95,2,121], [96,2,122],+ [98,2,123], [99,2,123], [100,2,124], [102,2,125], [103,2,126], [104,2,126], [106,2,127], [107,2,128],+ [108,2,129], [109,2,130], [109,2,131], [110,2,132], [111,2,133], [112,2,134], [113,2,135], [113,2,136],+ [114,2,137], [115,2,137], [116,2,138], [116,2,139], [117,2,140], [118,2,141], [119,2,142], [120,2,143],+ [120,2,144], [121,2,145], [122,2,146], [123,2,147], [124,2,148], [124,2,149], [125,2,150], [126,2,151],+ [127,2,152], [127,2,153], [128,2,154], [129,2,154], [130,2,155], [131,2,156], [131,2,157], [132,2,158],+ [133,2,160], [134,2,161], [136,2,162], [137,2,163], [138,2,165], [139,3,166], [140,3,167], [141,3,168],+ [142,3,170], [143,3,171], [144,3,172], [146,3,173], [147,3,175], [148,3,176], [149,3,177], [150,4,178],+ [151,4,180], [152,4,181], [153,4,182], [154,4,184], [155,4,185], [157,4,186], [158,4,187], [159,4,189],+ [160,4,190], [161,4,191], [162,5,192], [163,5,194], [164,5,195], [165,5,196], [166,5,197], [168,5,199],+ [169,6,200], [170,6,201], [171,7,202], [172,7,203], [173,8,205], [174,8,206], [175,9,207], [176,9,208],+ [177,10,209], [178,10,211], [179,11,212], [180,11,213], [181,12,214], [183,12,215], [184,13,217], [185,13,218],+ [186,14,219], [187,14,220], [188,15,221], [189,15,223], [190,16,224], [191,16,225], [192,17,226], [193,17,227],+ [194,18,229], [195,18,230], [196,19,231], [198,19,232], [199,20,233], [200,20,235], [201,21,236], [202,23,236],+ [202,26,237], [203,28,237], [204,31,238], [205,34,238], [206,36,239], [207,39,239], [208,42,240], [208,44,240],+ [209,47,241], [210,49,241], [211,52,242], [212,55,242], [213,57,243], [214,60,243], [214,63,244], [215,65,244],+ [216,68,245], [217,71,245], [218,73,246], [219,76,246], [219,79,247], [220,81,247], [221,84,248], [222,86,248],+ [223,89,249], [224,92,249], [225,94,250], [225,97,250], [226,100,251], [227,102,251], [228,105,252]+ ]+}diff --git a/ColorSchemeList/Simply_red.json b/ColorSchemeList/Simply_red.jsonnew file mode 100644index 0000000..255f243--- /dev/null+++ b/ColorSchemeList/Simply_red.json@@ -0,0 +1,42 @@+{+ "name": "Simply_red",+ "origin": "7-stop copy of scheme 'afmhot'",+ "category": "custom",+ "scheme_type": "intensity",+ "bits_per_channel": 8,+ "entry_count": 255,+ "colors": [+ [0,0,0], [3,0,0], [6,0,0], [9,0,0], [12,0,0], [15,0,0], [18,0,0], [21,0,0],+ [24,0,0], [27,0,0], [30,0,0], [33,0,0], [36,0,0], [39,0,0], [42,0,0], [45,0,0],+ [48,0,0], [51,0,0], [54,0,0], [57,0,0], [60,0,0], [63,0,0], [65,1,1], [68,1,1],+ [71,1,1], [74,1,1], [77,1,1], [80,1,1], [83,1,1], [86,1,1], [89,1,1], [92,1,1],+ [95,1,1], [98,1,1], [101,1,1], [104,1,1], [107,1,1], [110,1,1], [113,1,1], [116,1,1],+ [119,1,1], [122,1,1], [125,1,1], [127,1,1], [128,1,1], [129,1,1], [130,1,1], [131,1,1],+ [132,1,1], [133,1,1], [134,1,1], [135,1,1], [136,1,1], [137,1,1], [138,1,1], [139,1,1],+ [140,1,1], [141,1,1], [142,1,1], [143,1,1], [144,1,1], [145,1,1], [146,1,1], [147,1,1],+ [148,0,0], [149,0,0], [150,0,0], [151,0,0], [152,0,0], [153,0,0], [154,0,0], [155,0,0],+ [156,0,0], [157,0,0], [158,0,0], [159,0,0], [160,0,0], [161,0,0], [162,0,0], [163,0,0],+ [164,0,0], [165,0,0], [166,0,0], [167,0,0], [168,0,0], [170,0,0], [171,1,1], [173,1,1],+ [174,1,1], [176,2,2], [177,2,2], [179,3,3], [180,3,3], [182,3,3], [184,4,4], [185,4,4],+ [187,5,5], [188,5,5], [190,5,5], [191,6,6], [193,6,6], [194,7,7], [196,7,7], [198,7,7],+ [199,8,8], [201,8,8], [202,9,9], [204,9,9], [205,9,9], [207,10,10], [208,10,10], [210,11,11],+ [212,11,11], [213,11,11], [215,12,12], [216,12,12], [218,13,13], [219,13,13], [221,13,13], [223,14,14],+ [224,14,14], [226,15,15], [227,15,15], [229,15,15], [230,16,16], [232,16,16], [233,17,17], [235,17,17],+ [235,19,19], [236,20,20], [236,22,22], [236,23,23], [236,25,25], [237,26,26], [237,28,28], [237,29,29],+ [237,31,31], [238,32,32], [238,34,34], [238,35,35], [238,37,37], [239,38,38], [239,40,40], [239,41,41],+ [239,43,43], [240,44,44], [240,46,46], [240,47,47], [240,49,49], [241,50,50], [241,52,52], [241,53,53],+ [241,55,55], [242,56,56], [242,58,58], [242,59,59], [243,61,61], [243,62,62], [243,64,64], [243,65,65],+ [244,67,67], [244,68,68], [244,70,70], [244,71,71], [245,73,73], [245,74,74], [245,76,76], [245,77,77],+ [246,79,79], [246,80,80], [246,82,82], [246,84,84], [246,85,85], [246,87,87], [246,88,88], [246,90,90],+ [246,91,91], [246,93,93], [246,94,94], [246,96,96], [246,97,97], [246,99,99], [246,100,100], [246,102,102],+ [246,103,103], [246,105,105], [246,106,106], [246,108,108], [246,109,109], [246,111,111], [246,112,112], [247,114,114],+ [247,115,115], [247,117,117], [247,118,118], [247,120,120], [247,121,121], [247,123,123], [247,124,124], [247,126,126],+ [247,127,127], [247,129,129], [247,130,130], [247,132,132], [247,133,133], [247,135,135], [247,136,136], [247,138,138],+ [247,139,139], [247,141,141], [247,142,142], [247,144,144], [247,146,146], [247,148,148], [247,150,150], [247,152,152],+ [248,154,154], [248,157,157], [248,159,159], [248,161,161], [248,163,163], [248,165,165], [248,167,167], [248,170,170],+ [248,172,172], [249,174,174], [249,176,176], [249,178,178], [249,180,180], [249,183,183], [249,185,185], [249,187,187],+ [249,189,189], [250,191,191], [250,194,194], [250,196,196], [250,198,198], [250,200,200], [250,202,202], [250,204,204],+ [250,207,207], [250,209,209], [251,211,211], [251,213,213], [251,215,215], [251,217,217], [251,220,220], [251,222,222],+ [251,224,224], [251,226,226], [252,228,228], [252,230,230], [252,233,233], [252,235,235], [252,237,237]+ ]+}diff --git a/ColorSchemeList/Turky_brown.json b/ColorSchemeList/Turky_brown.jsonnew file mode 100644index 0000000..35d8bd5--- /dev/null+++ b/ColorSchemeList/Turky_brown.json@@ -0,0 +1,43 @@+{+ "name": "Turky_brown",+ "origin": "9-stop copy of scheme 'Green_blown'",+ "category": "custom",+ "scheme_type": "field",+ "bits_per_channel": 8,+ "entry_count": 255,+ "stops": [[62,34,1], [153,93,18], [207,161,84], [239,222,176], [255,255,255], [180,226,219], [90,177,167], [14,114,106], [0,9,8]],+ "colors": [+ [62,34,1], [65,36,2], [68,38,2], [71,40,3], [73,41,3], [76,43,4], [79,45,4], [82,47,5],+ [85,49,5], [88,51,6], [91,53,6], [94,54,7], [96,56,7], [99,58,8], [102,60,8], [105,62,9],+ [108,64,10], [111,66,10], [114,67,11], [116,69,11], [119,71,12], [122,73,12], [125,75,13], [128,77,13],+ [131,79,14], [134,80,14], [137,82,15], [139,84,15], [142,86,16], [145,88,17], [148,90,17], [151,92,18],+ [153,94,19], [155,96,21], [157,98,23], [159,100,25], [160,102,27], [162,104,29], [164,106,31], [165,109,33],+ [167,111,35], [169,113,37], [170,115,39], [172,117,41], [174,119,43], [176,121,46], [177,124,48], [179,126,50],+ [181,128,52], [182,130,54], [184,132,56], [186,134,58], [187,136,60], [189,139,62], [191,141,64], [193,143,66],+ [194,145,68], [196,147,70], [198,149,73], [199,151,75], [201,154,77], [203,156,79], [204,158,81], [206,160,83],+ [208,162,85], [209,164,88], [210,166,91], [211,168,94], [212,170,97], [213,172,100], [214,173,103], [215,175,106],+ [216,177,109], [217,179,112], [218,181,114], [219,183,117], [220,185,120], [221,187,123], [222,189,126], [223,191,129],+ [224,193,132], [225,195,135], [226,197,138], [227,198,141], [228,200,143], [229,202,146], [230,204,149], [231,206,152],+ [232,208,155], [233,210,158], [234,212,161], [235,214,164], [236,216,167], [237,218,169], [238,220,172], [239,222,175],+ [239,223,178], [240,224,180], [240,225,183], [241,226,185], [241,227,188], [242,228,190], [242,229,193], [243,230,195],+ [243,231,198], [244,232,200], [244,233,203], [245,234,205], [245,235,208], [246,236,210], [246,237,213], [247,238,215],+ [247,239,218], [248,240,220], [248,241,223], [249,243,225], [249,244,228], [250,245,230], [250,246,233], [251,247,235],+ [251,248,238], [252,249,240], [252,250,243], [253,251,245], [253,252,248], [254,253,250], [254,254,253], [255,255,255],+ [253,254,254], [250,253,253], [248,252,252], [246,251,250], [243,250,249], [241,250,248], [238,249,247], [236,248,246],+ [234,247,245], [231,246,244], [229,245,243], [227,244,241], [224,243,240], [222,242,239], [220,241,238], [217,240,237],+ [215,239,236], [212,239,235], [210,238,233], [208,237,232], [205,236,231], [203,235,230], [201,234,229], [198,233,228],+ [196,232,227], [194,231,226], [191,230,224], [189,229,223], [186,229,222], [184,228,221], [182,227,220], [179,226,219],+ [176,224,217], [174,223,215], [171,221,214], [168,219,212], [165,218,210], [162,216,209], [159,215,207], [157,213,205],+ [154,212,204], [151,210,202], [148,209,201], [145,207,199], [142,206,197], [140,204,196], [137,202,194], [134,201,192],+ [131,199,191], [128,198,189], [125,196,187], [123,195,186], [120,193,184], [117,192,183], [114,190,181], [111,189,179],+ [108,187,178], [106,185,176], [103,184,174], [100,182,173], [97,181,171], [94,179,169], [91,178,168], [89,176,166],+ [86,174,164], [84,172,162], [82,170,160], [79,168,158], [77,166,156], [74,164,155], [72,162,153], [70,160,151],+ [67,158,149], [65,156,147], [62,154,145], [60,152,143], [58,150,141], [55,148,139], [53,146,137], [51,144,135],+ [48,142,133], [46,140,131], [43,138,130], [41,136,128], [39,134,126], [36,132,124], [34,130,122], [31,128,120],+ [29,126,118], [27,124,116], [24,122,114], [22,120,112], [19,118,110], [17,116,108], [15,114,106], [14,112,104],+ [13,108,101], [13,105,98], [12,102,94], [12,98,91], [11,95,88], [11,92,85], [11,88,82], [10,85,79],+ [10,82,76], [9,78,73], [9,75,70], [8,72,67], [8,69,64], [7,65,60], [7,62,57], [7,59,54],+ [6,55,51], [6,52,48], [5,49,45], [5,45,42], [4,42,39], [4,39,36], [4,35,33], [3,32,30],+ [3,29,27], [2,26,23], [2,22,20], [1,19,17], [1,16,14], [0,12,11], [0,9,8]+ ]+}diff --git a/ColorSchemeList/Yellow_purple.json b/ColorSchemeList/Yellow_purple.jsonnew file mode 100644index 0000000..148ad37--- /dev/null+++ b/ColorSchemeList/Yellow_purple.json@@ -0,0 +1,43 @@+{+ "name": "Yellow_purple",+ "origin": "9-stop copy of scheme 'gist_earth'",+ "category": "custom",+ "scheme_type": "field",+ "bits_per_channel": 8,+ "entry_count": 255,+ "stops": [[247,110,252], [190,2,190], [128,2,134], [77,2,79], [0,0,0], [111,105,2], [193,194,3], [250,246,15], [253,248,115]],+ "colors": [+ [247,110,252], [245,107,250], [243,103,248], [242,100,246], [240,96,244], [238,93,242], [236,90,240], [234,86,238],+ [233,83,236], [231,79,234], [229,76,232], [227,73,231], [225,69,229], [224,66,227], [222,62,225], [220,59,223],+ [218,56,221], [216,52,219], [215,49,217], [213,45,215], [211,42,213], [209,39,211], [208,35,209], [206,32,207],+ [204,28,205], [202,25,203], [200,22,201], [199,18,199], [197,15,197], [195,11,195], [193,8,193], [191,5,191],+ [190,2,190], [188,2,188], [186,2,186], [184,2,184], [182,2,183], [180,2,181], [178,2,179], [176,2,177],+ [174,2,175], [172,2,174], [170,2,172], [168,2,170], [166,2,168], [164,2,167], [162,2,165], [160,2,163],+ [158,2,161], [156,2,160], [154,2,158], [152,2,156], [150,2,154], [149,2,153], [147,2,151], [145,2,149],+ [143,2,147], [141,2,145], [139,2,144], [137,2,142], [135,2,140], [133,2,138], [131,2,137], [129,2,135],+ [127,2,133], [126,2,131], [124,2,130], [122,2,128], [121,2,126], [119,2,124], [118,2,123], [116,2,121],+ [114,2,119], [113,2,118], [111,2,116], [110,2,114], [108,2,112], [106,2,111], [105,2,109], [103,2,107],+ [101,2,105], [100,2,104], [98,2,102], [97,2,100], [95,2,98], [93,2,97], [92,2,95], [90,2,93],+ [89,2,92], [87,2,90], [85,2,88], [84,2,86], [82,2,85], [81,2,83], [79,2,81], [77,2,79],+ [75,2,77], [73,2,75], [70,2,72], [68,2,70], [65,2,67], [63,2,65], [61,2,62], [58,2,60],+ [56,1,57], [53,1,55], [51,1,52], [49,1,50], [46,1,47], [44,1,45], [41,1,42], [39,1,40],+ [36,1,37], [34,1,35], [32,1,32], [29,1,30], [27,1,27], [24,1,25], [22,1,22], [19,1,20],+ [17,0,17], [15,0,15], [12,0,12], [10,0,10], [7,0,7], [5,0,5], [2,0,2], [0,0,0],+ [3,3,0], [7,7,0], [10,10,0], [14,13,0], [17,17,0], [21,20,0], [24,23,0], [28,26,1],+ [31,30,1], [35,33,1], [38,36,1], [42,40,1], [45,43,1], [49,46,1], [52,50,1], [56,53,1],+ [59,56,1], [63,60,1], [66,63,1], [70,66,1], [73,69,1], [77,73,1], [80,76,1], [84,79,2],+ [87,83,2], [91,86,2], [94,89,2], [98,93,2], [101,96,2], [105,99,2], [108,103,2], [112,106,2],+ [114,109,2], [117,111,2], [119,114,2], [122,117,2], [125,120,2], [127,123,2], [130,125,2], [132,128,2],+ [135,131,2], [137,134,2], [140,137,2], [143,139,2], [145,142,2], [148,145,2], [150,148,2], [153,151,3],+ [156,153,3], [158,156,3], [161,159,3], [163,162,3], [166,165,3], [168,167,3], [171,170,3], [174,173,3],+ [176,176,3], [179,179,3], [181,181,3], [184,184,3], [187,187,3], [189,190,3], [192,193,3], [194,195,3],+ [196,196,4], [197,198,4], [199,200,4], [201,201,5], [203,203,5], [205,205,5], [206,206,6], [208,208,6],+ [210,210,7], [212,211,7], [214,213,7], [215,214,8], [217,216,8], [219,218,8], [221,219,9], [223,221,9],+ [224,223,10], [226,224,10], [228,226,10], [230,228,11], [232,229,11], [233,231,12], [235,232,12], [237,234,12],+ [239,236,13], [241,237,13], [242,239,13], [244,241,14], [246,242,14], [248,244,15], [250,246,15], [250,246,17],+ [250,246,21], [250,246,24], [250,246,27], [250,246,30], [251,246,33], [251,246,36], [251,246,39], [251,247,43],+ [251,247,46], [251,247,49], [251,247,52], [251,247,55], [251,247,58], [251,247,61], [251,247,65], [252,247,68],+ [252,247,71], [252,247,74], [252,247,77], [252,247,80], [252,247,84], [252,247,87], [252,247,90], [252,248,93],+ [252,248,96], [253,248,99], [253,248,102], [253,248,106], [253,248,109], [253,248,112], [253,248,115]+ ]+}diff --git a/ColorSchemeList/inferno.json b/ColorSchemeList/inferno.jsonnew file mode 100644index 0000000..155f031--- /dev/null+++ b/ColorSchemeList/inferno.json@@ -0,0 +1,42 @@+{+ "name": "inferno",+ "origin": "matplotlib colormap inferno, sampled at 255 points",+ "category": "sequential",+ "scheme_type": "intensity",+ "bits_per_channel": 8,+ "entry_count": 255,+ "colors": [+ [0,0,3], [0,0,4], [0,0,6], [1,0,7], [1,1,9], [1,1,11], [2,1,14], [2,2,16],+ [3,2,18], [4,3,20], [4,3,22], [5,4,24], [6,4,27], [7,5,29], [8,6,31], [9,6,33],+ [10,7,35], [11,7,38], [13,8,40], [14,8,42], [15,9,45], [16,9,47], [18,10,50], [19,10,52],+ [20,11,54], [22,11,57], [23,11,59], [25,11,62], [26,11,64], [28,12,67], [29,12,69], [31,12,71],+ [32,12,74], [34,11,76], [36,11,78], [38,11,80], [39,11,82], [41,11,84], [43,10,86], [45,10,88],+ [46,10,90], [48,10,92], [50,9,93], [52,9,95], [53,9,96], [55,9,97], [57,9,98], [59,9,100],+ [60,9,101], [62,9,102], [64,9,102], [65,9,103], [67,10,104], [69,10,105], [70,10,105], [72,11,106],+ [74,11,106], [75,12,107], [77,12,107], [79,13,108], [80,13,108], [82,14,108], [83,14,109], [85,15,109],+ [87,15,109], [88,16,109], [90,17,109], [91,17,110], [93,18,110], [95,18,110], [96,19,110], [98,20,110],+ [99,20,110], [101,21,110], [102,21,110], [104,22,110], [106,23,110], [107,23,110], [109,24,110], [110,24,110],+ [112,25,110], [114,25,109], [115,26,109], [117,27,109], [118,27,109], [120,28,109], [122,28,109], [123,29,108],+ [125,29,108], [126,30,108], [128,31,107], [129,31,107], [131,32,107], [133,32,106], [134,33,106], [136,33,106],+ [137,34,105], [139,34,105], [141,35,105], [142,36,104], [144,36,104], [145,37,103], [147,37,103], [149,38,102],+ [150,38,102], [152,39,101], [153,40,100], [155,40,100], [156,41,99], [158,41,99], [160,42,98], [161,43,97],+ [163,43,97], [164,44,96], [166,44,95], [167,45,95], [169,46,94], [171,46,93], [172,47,92], [174,48,91],+ [175,49,91], [177,49,90], [178,50,89], [180,51,88], [181,51,87], [183,52,86], [184,53,86], [187,55,84],+ [189,55,83], [190,56,82], [191,57,81], [193,58,80], [194,59,79], [196,60,78], [197,61,77], [199,62,76],+ [200,62,75], [201,63,74], [203,64,73], [204,65,72], [205,66,71], [207,68,70], [208,69,68], [209,70,67],+ [210,71,66], [212,72,65], [213,73,64], [214,74,63], [215,75,62], [217,77,61], [218,78,59], [219,79,58],+ [220,80,57], [221,82,56], [222,83,55], [223,84,54], [224,86,52], [226,87,51], [227,88,50], [228,90,49],+ [229,91,48], [230,92,46], [230,94,45], [231,95,44], [232,97,43], [233,98,42], [234,100,40], [235,101,39],+ [236,103,38], [237,104,37], [237,106,35], [238,108,34], [239,109,33], [240,111,31], [240,112,30], [241,114,29],+ [242,116,28], [242,117,26], [243,119,25], [243,121,24], [244,122,22], [245,124,21], [245,126,20], [246,128,18],+ [246,129,17], [247,131,16], [247,133,14], [248,135,13], [248,136,12], [248,138,11], [249,140,9], [249,142,8],+ [249,144,8], [250,145,7], [250,147,6], [250,149,6], [250,151,6], [251,153,6], [251,155,6], [251,157,6],+ [251,158,7], [251,160,7], [251,162,8], [251,164,10], [251,166,11], [251,168,13], [251,170,14], [251,172,16],+ [251,174,18], [251,176,20], [251,177,22], [251,179,24], [251,181,26], [251,183,28], [251,185,30], [250,187,33],+ [250,189,35], [250,191,37], [250,193,40], [249,195,42], [249,197,44], [249,199,47], [248,201,49], [248,203,52],+ [248,205,55], [247,207,58], [247,209,60], [246,211,63], [246,213,66], [245,215,69], [245,217,72], [244,219,75],+ [244,220,79], [243,222,82], [243,224,86], [243,226,89], [242,228,93], [242,230,96], [241,232,100], [241,233,104],+ [241,235,108], [241,237,112], [241,238,116], [241,240,121], [241,242,125], [242,243,129], [242,244,133], [243,246,137],+ [244,247,141], [245,248,145], [246,250,149], [247,251,153], [249,252,157], [250,253,160], [252,254,164]+ ]+}diff --git a/ColorSchemeList/magma.json b/ColorSchemeList/magma.jsonnew file mode 100644index 0000000..35f03bb--- /dev/null+++ b/ColorSchemeList/magma.json@@ -0,0 +1,42 @@+{+ "name": "magma",+ "origin": "matplotlib colormap magma, sampled at 255 points",+ "category": "sequential",+ "scheme_type": "intensity",+ "bits_per_channel": 8,+ "entry_count": 255,+ "colors": [+ [0,0,3], [0,0,4], [0,0,6], [1,0,7], [1,1,9], [1,1,11], [2,2,13], [2,2,15],+ [3,3,17], [4,3,19], [4,4,21], [5,4,23], [6,5,25], [7,5,27], [8,6,29], [9,7,31],+ [10,7,34], [11,8,36], [12,9,38], [13,10,40], [14,10,42], [15,11,44], [16,12,47], [17,12,49],+ [18,13,51], [20,13,53], [21,14,56], [22,14,58], [23,15,60], [24,15,63], [26,16,65], [27,16,68],+ [28,16,70], [30,16,73], [31,17,75], [32,17,77], [34,17,80], [35,17,82], [37,17,85], [38,17,87],+ [40,17,89], [42,17,92], [43,17,94], [45,16,96], [47,16,98], [48,16,101], [50,16,103], [52,16,104],+ [53,15,106], [55,15,108], [57,15,110], [59,15,111], [60,15,113], [62,15,114], [64,15,115], [66,15,116],+ [67,15,117], [69,15,118], [71,15,119], [72,16,120], [74,16,121], [75,16,121], [77,17,122], [79,17,123],+ [80,18,123], [82,18,124], [83,19,124], [85,19,125], [87,20,125], [88,21,126], [90,21,126], [91,22,126],+ [93,23,126], [94,23,127], [96,24,127], [97,24,127], [99,25,127], [101,26,128], [102,26,128], [104,27,128],+ [105,28,128], [107,28,128], [108,29,128], [110,30,129], [111,30,129], [113,31,129], [115,31,129], [116,32,129],+ [118,33,129], [119,33,129], [121,34,129], [122,34,129], [124,35,129], [126,36,129], [127,36,129], [129,37,129],+ [130,37,129], [132,38,129], [133,38,129], [135,39,129], [137,40,129], [138,40,129], [140,41,128], [141,41,128],+ [143,42,128], [145,42,128], [146,43,128], [148,43,128], [149,44,128], [151,44,127], [153,45,127], [154,45,127],+ [156,46,127], [158,46,126], [159,47,126], [161,47,126], [163,48,126], [164,48,125], [166,49,125], [167,49,125],+ [169,50,124], [171,51,124], [172,51,123], [174,52,123], [176,52,123], [177,53,122], [179,53,122], [182,54,121],+ [184,55,120], [185,55,120], [187,56,119], [189,57,119], [190,57,118], [192,58,117], [194,58,117], [195,59,116],+ [197,60,116], [198,60,115], [200,61,114], [202,62,114], [203,62,113], [205,63,112], [206,64,112], [208,65,111],+ [209,66,110], [211,66,109], [212,67,109], [214,68,108], [215,69,107], [217,70,106], [218,71,105], [220,72,105],+ [221,73,104], [222,74,103], [224,75,102], [225,76,102], [226,77,101], [228,78,100], [229,80,99], [230,81,98],+ [231,82,98], [232,84,97], [234,85,96], [235,86,96], [236,88,95], [237,89,95], [238,91,94], [238,93,93],+ [239,94,93], [240,96,93], [241,97,92], [242,99,92], [243,101,92], [243,103,91], [244,104,91], [245,106,91],+ [245,108,91], [246,110,91], [246,112,91], [247,113,91], [247,115,92], [248,117,92], [248,119,92], [249,121,92],+ [249,123,93], [249,125,93], [250,127,94], [250,128,94], [250,130,95], [251,132,96], [251,134,96], [251,136,97],+ [251,138,98], [252,140,99], [252,142,99], [252,144,100], [252,146,101], [252,147,102], [253,149,103], [253,151,104],+ [253,153,105], [253,155,106], [253,157,107], [253,159,108], [253,161,110], [253,162,111], [253,164,112], [254,166,113],+ [254,168,115], [254,170,116], [254,172,117], [254,174,118], [254,175,120], [254,177,121], [254,179,123], [254,181,124],+ [254,183,125], [254,185,127], [254,187,128], [254,188,130], [254,190,131], [254,192,133], [254,194,134], [254,196,136],+ [254,198,137], [254,199,139], [254,201,141], [254,203,142], [253,205,144], [253,207,146], [253,209,147], [253,210,149],+ [253,212,151], [253,214,152], [253,216,154], [253,218,156], [253,220,157], [253,221,159], [253,223,161], [253,225,163],+ [252,227,165], [252,229,166], [252,230,168], [252,232,170], [252,234,172], [252,236,174], [252,238,176], [252,240,177],+ [252,241,179], [252,243,181], [252,245,183], [251,247,185], [251,249,187], [251,250,189], [251,252,191]+ ]+}diff --git a/ColorSchemeList/plasma.json b/ColorSchemeList/plasma.jsonnew file mode 100644index 0000000..768aacb--- /dev/null+++ b/ColorSchemeList/plasma.json@@ -0,0 +1,43 @@+{+ "name": "plasma",+ "origin": "9-stop copy of scheme 'plasma'",+ "category": "custom",+ "scheme_type": "intensity",+ "bits_per_channel": 8,+ "entry_count": 255,+ "stops": [[12,7,134], [76,2,161], [125,3,167], [168,34,150], [203,71,119], [229,108,91], [248,148,65], [253,195,40], [239,248,33]],+ "colors": [+ [12,7,134], [14,7,135], [16,7,136], [18,7,137], [20,6,137], [22,6,138], [24,6,139], [26,6,140],+ [28,6,141], [30,6,142], [32,5,143], [34,5,143], [36,5,144], [38,5,145], [40,5,146], [42,5,147],+ [44,4,148], [46,4,148], [48,4,149], [50,4,150], [52,4,151], [54,4,152], [56,4,153], [58,3,154],+ [60,3,154], [62,3,155], [64,3,156], [66,3,157], [68,3,158], [70,2,159], [72,2,160], [74,2,160],+ [76,2,161], [78,2,161], [79,2,161], [81,2,162], [83,2,162], [84,2,162], [86,2,162], [87,2,162],+ [89,2,163], [90,2,163], [92,2,163], [93,2,163], [95,2,163], [96,2,164], [98,2,164], [100,2,164],+ [101,3,164], [103,3,164], [104,3,164], [106,3,165], [107,3,165], [109,3,165], [110,3,165], [112,3,165],+ [113,3,166], [115,3,166], [117,3,166], [118,3,166], [120,3,166], [121,3,167], [123,3,167], [124,3,167],+ [126,3,167], [127,4,166], [128,5,166], [130,6,165], [131,7,165], [132,8,164], [134,9,164], [135,10,163],+ [137,11,162], [138,12,162], [139,13,161], [141,14,161], [142,15,160], [143,16,160], [145,17,159], [146,18,159],+ [147,19,158], [149,20,158], [150,21,157], [151,22,157], [153,23,156], [154,24,155], [155,25,155], [157,26,154],+ [158,27,154], [160,28,153], [161,29,153], [162,30,152], [164,31,152], [165,32,151], [166,33,151], [168,34,150],+ [169,35,149], [170,36,148], [171,37,147], [172,38,146], [173,40,145], [174,41,144], [175,42,143], [177,43,142],+ [178,44,141], [179,45,140], [180,47,140], [181,48,139], [182,49,138], [183,50,137], [184,51,136], [185,52,135],+ [186,54,134], [188,55,133], [189,56,132], [190,57,131], [191,58,130], [192,59,129], [193,61,128], [194,62,127],+ [195,63,126], [196,64,125], [197,65,124], [199,66,123], [200,68,122], [201,69,121], [202,70,120], [203,71,119],+ [204,72,118], [205,73,117], [205,74,116], [206,76,115], [207,77,115], [208,78,114], [209,79,113], [210,80,112],+ [210,81,111], [211,83,110], [212,84,109], [213,85,108], [214,86,108], [214,87,107], [215,88,106], [216,90,105],+ [217,91,104], [218,92,103], [219,93,102], [219,94,101], [220,95,100], [221,97,100], [222,98,99], [223,99,98],+ [223,100,97], [224,101,96], [225,102,95], [226,104,94], [227,105,93], [228,106,93], [228,107,92], [229,108,91],+ [230,110,90], [230,111,89], [231,112,88], [232,113,88], [232,115,87], [233,116,86], [233,117,85], [234,118,84],+ [235,120,83], [235,121,83], [236,122,82], [236,123,81], [237,125,80], [238,126,79], [238,127,79], [239,128,78],+ [239,130,77], [240,131,76], [241,132,75], [241,134,74], [242,135,74], [242,136,73], [243,137,72], [244,139,71],+ [244,140,70], [245,141,70], [245,142,69], [246,144,68], [247,145,67], [247,146,66], [248,147,65], [248,149,65],+ [248,150,64], [248,152,63], [249,153,62], [249,155,61], [249,156,61], [249,158,60], [249,159,59], [249,161,58],+ [249,162,58], [250,164,57], [250,165,56], [250,167,55], [250,168,54], [250,169,54], [250,171,53], [251,172,52],+ [251,174,51], [251,175,50], [251,177,50], [251,178,49], [251,180,48], [252,181,47], [252,183,46], [252,184,46],+ [252,186,45], [252,187,44], [252,189,43], [252,190,43], [253,192,42], [253,193,41], [253,195,40], [253,196,40],+ [252,198,40], [252,200,39], [251,201,39], [251,203,39], [250,205,39], [250,206,39], [250,208,38], [249,210,38],+ [249,211,38], [248,213,38], [248,215,37], [247,216,37], [247,218,37], [246,220,37], [246,221,37], [246,223,36],+ [245,225,36], [245,226,36], [244,228,36], [244,230,35], [243,231,35], [243,233,35], [243,235,35], [242,236,35],+ [242,238,34], [241,240,34], [241,241,34], [240,243,34], [240,245,33], [239,246,33], [239,248,33]+ ]+}diff --git a/ColorSchemeList/rainbow.json b/ColorSchemeList/rainbow.jsonnew file mode 100644index 0000000..e865ade--- /dev/null+++ b/ColorSchemeList/rainbow.json@@ -0,0 +1,42 @@+{+ "name": "rainbow",+ "origin": "matplotlib colormap rainbow, sampled at 255 points",+ "category": "other",+ "scheme_type": "intensity",+ "bits_per_channel": 8,+ "entry_count": 255,+ "colors": [+ [127,0,255], [125,3,254], [123,6,254], [121,9,254], [119,12,254], [117,15,254], [115,18,254], [113,21,254],+ [111,25,254], [109,28,254], [107,31,254], [105,34,254], [103,37,254], [101,40,254], [99,43,254], [97,46,253],+ [95,49,253], [93,53,253], [91,56,253], [89,59,253], [87,62,253], [85,65,252], [83,68,252], [81,71,252],+ [79,74,252], [77,77,251], [75,80,251], [73,83,251], [71,86,251], [69,89,250], [67,92,250], [65,95,250],+ [63,97,250], [61,100,249], [59,103,249], [57,106,249], [55,109,248], [53,112,248], [51,115,248], [49,117,247],+ [47,120,247], [45,123,246], [43,126,246], [41,128,246], [39,131,245], [37,134,245], [35,136,244], [33,139,244],+ [31,142,243], [29,144,243], [27,147,243], [25,149,242], [23,152,242], [21,154,241], [19,157,241], [17,159,240],+ [15,162,239], [13,164,239], [11,167,238], [9,169,238], [7,171,237], [5,174,237], [3,176,236], [1,178,236],+ [0,180,235], [2,183,234], [4,185,234], [6,187,233], [8,189,232], [10,191,232], [12,193,231], [14,195,230],+ [16,197,230], [18,199,229], [20,201,228], [22,203,228], [24,205,227], [26,207,226], [28,209,226], [30,210,225],+ [32,212,224], [34,214,223], [36,215,223], [38,217,222], [40,219,221], [42,220,220], [44,222,220], [46,223,219],+ [48,225,218], [50,226,217], [52,228,216], [54,229,215], [56,230,215], [58,232,214], [60,233,213], [62,234,212],+ [64,236,211], [66,237,210], [68,238,209], [70,239,209], [72,240,208], [74,241,207], [76,242,206], [78,243,205],+ [80,244,204], [82,245,203], [84,246,202], [86,246,201], [88,247,200], [90,248,199], [92,249,198], [94,249,197],+ [96,250,196], [98,250,195], [100,251,194], [102,251,193], [104,252,192], [106,252,191], [108,253,190], [110,253,189],+ [112,253,188], [114,254,187], [116,254,186], [118,254,185], [120,254,184], [122,254,183], [124,254,181], [128,254,179],+ [130,254,178], [132,254,177], [134,254,176], [136,254,175], [138,254,174], [140,254,172], [142,253,171], [144,253,170],+ [146,253,169], [148,252,168], [150,252,167], [152,251,165], [154,251,164], [156,250,163], [158,250,162], [160,249,161],+ [162,249,159], [164,248,158], [166,247,157], [168,246,156], [170,246,154], [172,245,153], [174,244,152], [176,243,151],+ [178,242,149], [180,241,148], [182,240,147], [184,239,146], [186,238,144], [188,237,143], [190,236,142], [192,234,140],+ [194,233,139], [196,232,138], [198,230,136], [200,229,135], [202,228,134], [204,226,132], [206,225,131], [208,223,130],+ [210,222,128], [212,220,127], [214,219,126], [216,217,124], [218,215,123], [220,214,122], [222,212,120], [224,210,119],+ [226,209,117], [228,207,116], [230,205,115], [232,203,113], [234,201,112], [236,199,110], [238,197,109], [240,195,108],+ [242,193,106], [244,191,105], [246,189,103], [248,187,102], [250,185,100], [252,183,99], [254,180,97], [255,178,96],+ [255,176,95], [255,174,93], [255,171,92], [255,169,90], [255,167,89], [255,164,87], [255,162,86], [255,159,84],+ [255,157,83], [255,154,81], [255,152,80], [255,149,78], [255,147,77], [255,144,75], [255,142,74], [255,139,72],+ [255,136,71], [255,134,69], [255,131,68], [255,128,66], [255,126,65], [255,123,63], [255,120,62], [255,117,60],+ [255,115,59], [255,112,57], [255,109,56], [255,106,54], [255,103,53], [255,100,51], [255,97,49], [255,95,48],+ [255,92,46], [255,89,45], [255,86,43], [255,83,42], [255,80,40], [255,77,39], [255,74,37], [255,71,36],+ [255,68,34], [255,65,32], [255,62,31], [255,59,29], [255,56,28], [255,53,26], [255,49,25], [255,46,23],+ [255,43,21], [255,40,20], [255,37,18], [255,34,17], [255,31,15], [255,28,14], [255,25,12], [255,21,10],+ [255,18,9], [255,15,7], [255,12,6], [255,9,4], [255,6,3], [255,3,1], [255,0,0]+ ]+}diff --git a/Project/Test/configuration.json b/Project/Test/configuration.jsonnew file mode 100644index 0000000..6221a7f--- /dev/null+++ b/Project/Test/configuration.json@@ -0,0 +1,138 @@+{+ "format_version": 1,+ "project_name": "Test",+ "created": "2026-10-07T01:10:19Z",+ "modified": "2026-10-07T01:13:45Z",+ "scene": {+ "mode": "user_defined",+ "image_file": "",+ "user_width": 1920,+ "user_height": 1080,+ "damping_edge_enabled": true,+ "damping_edge_size_px": 64,+ "use_sources": false,+ "image_source_scale": 1,+ "use_object_sources": true,+ "background_refractive_index": 1+ },+ "simulation": {+ "steps": 3000,+ "visualize_every": 2,+ "export_field": false,+ "export_intensity": false,+ "preview_field": true,+ "preview_intensity": true,+ "field_color_scheme": "Default_Field",+ "intensity_color_scheme": "Default_intensity",+ "field_brightness": 30,+ "intensity_brightness": 30,+ "field_black_level": -0.05,+ "intensity_black_level": 0,+ "source_frequency_scale": 2,+ "video_fps": 60,+ "video_quality": 70,+ "use_gpu": true,+ "use_4th_order_laplacian": true,+ "wave_speed_c": 1,+ "time_decay_factor": 5,+ "intensity_scale": 1+ },+ "probes": {+ "count": 2,+ "items": [+ {+ "active": false,+ "place_on": "field",+ "measurement": "amplitude",+ "probe_type": "point",+ "ax": 100,+ "ay": 100,+ "bx": 300,+ "by": 100,+ "box_size": "medium",+ "box_x": 450,+ "box_y": 20,+ "scale_mode": "running",+ "auto_scale_x": true,+ "auto_scale_y": true,+ "y_min": -1,+ "y_max": 1,+ "running_window": 500,+ "use_start_after_step": false,+ "start_after_step": 0+ },+ {+ "active": false,+ "place_on": "field",+ "measurement": "amplitude",+ "probe_type": "point",+ "ax": 100,+ "ay": 100,+ "bx": 300,+ "by": 100,+ "box_size": "medium",+ "box_x": 450,+ "box_y": 20,+ "scale_mode": "running",+ "auto_scale_x": true,+ "auto_scale_y": true,+ "y_min": -1,+ "y_max": 1,+ "running_window": 500,+ "use_start_after_step": false,+ "start_after_step": 0+ }+ ]+ },+ "object_sources": {+ "count": 1,+ "items": [+ {+ "name": "Source 1",+ "main_type": "single",+ "x": 100,+ "y": 100,+ "has_position": false,+ "source_on": true,+ "detach_source": false,+ "detach_after_steps": 1000,+ "frequency": 100,+ "amplitude": 100,+ "phase_deg": 0,+ "mode": "continuous",+ "pulse_shape": "gaussian",+ "pulse_width_cycles": 10,+ "off_state_cycles": 10,+ "array_size_x": 1,+ "array_size_y": 1,+ "spacing_x": 10,+ "spacing_y": 10,+ "composite_mode": "inherit",+ "randomize_frequency": false,+ "randomize_frequency_amount": 0,+ "randomize_phase": false,+ "randomize_phase_amount": 0,+ "randomize_off_width": false,+ "randomize_off_width_amount": 0,+ "randomize_position": false,+ "randomize_position_amount": 0,+ "elements": [+ {+ "x": 100,+ "y": 100,+ "level": 100,+ "amplitude": 1,+ "phase_rad": 0,+ "mode": "continuous",+ "pulse_shape": "gaussian",+ "on_width_cycles": 10,+ "off_width_cycles": 10,+ "off_width_base": 10,+ "randomize_off_width_amount": 0,+ "detach_after_step": -1+ }+ ]+ }+ ]+ }+}diff --git a/Wave_Dude_2D.sln b/Wave_Dude_2D.slnnew file mode 100644index 0000000..fa65bab--- /dev/null+++ b/Wave_Dude_2D.sln@@ -0,0 +1,22 @@++Microsoft Visual Studio Solution File, Format Version 12.00+# Visual Studio Version 17+VisualStudioVersion = 17.0.31903.59+MinimumVisualStudioVersion = 10.0.40219.1+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Wave_Dude_2D", "Wave_Dude_2D\Wave_Dude_2D.csproj", "{C3F63FB8-2009-4631-AB8D-4E176E131C5F}"+EndProject+Global+ GlobalSection(SolutionConfigurationPlatforms) = preSolution+ Debug|Any CPU = Debug|Any CPU+ Release|Any CPU = Release|Any CPU+ EndGlobalSection+ GlobalSection(ProjectConfigurationPlatforms) = postSolution+ {C3F63FB8-2009-4631-AB8D-4E176E131C5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {C3F63FB8-2009-4631-AB8D-4E176E131C5F}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {C3F63FB8-2009-4631-AB8D-4E176E131C5F}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {C3F63FB8-2009-4631-AB8D-4E176E131C5F}.Release|Any CPU.Build.0 = Release|Any CPU+ EndGlobalSection+ GlobalSection(SolutionProperties) = preSolution+ HideSolutionNode = FALSE+ EndGlobalSection+EndGlobaldiff --git a/Wave_Dude_2D/AboutForm.Designer.cs b/Wave_Dude_2D/AboutForm.Designer.csnew file mode 100644index 0000000..2ecf4fd--- /dev/null+++ b/Wave_Dude_2D/AboutForm.Designer.cs@@ -0,0 +1,167 @@+using System;+using System.ComponentModel;+using System.Windows.Forms;++namespace _2D_wave_sim_V01+{+ public partial class AboutForm : global::System.Windows.Forms.Form+ {+ /// <summary>Releases the designer-managed components when <paramref name="disposing"/> is true, then the form itself.</summary>+ /// <param name="disposing">True when called from <see cref="System.ComponentModel.Component.Dispose()"/>; false from the finalizer.</param>+ [global::System.Diagnostics.DebuggerNonUserCode]+ protected override void Dispose(bool disposing)+ {+ try+ {+ bool flag = disposing && this.components != null;+ if (flag)+ {+ this.components.Dispose();+ }+ }+ finally+ {+ base.Dispose(disposing);+ }+ }++ [global::System.Diagnostics.DebuggerStepThrough]+ private void InitializeComponent()+ {+ this.picIcon = new global::System.Windows.Forms.PictureBox();+ this.lblTitle = new global::System.Windows.Forms.Label();+ this.lblVersion = new global::System.Windows.Forms.Label();+ this.lblDescription = new global::System.Windows.Forms.Label();+ this.lblCopyright = new global::System.Windows.Forms.Label();+ this.btnClose = new global::System.Windows.Forms.Button();+ this.Label1 = new global::System.Windows.Forms.Label();+ this.Label2 = new global::System.Windows.Forms.Label();+ this.Label3 = new global::System.Windows.Forms.Label();+ this.Label4 = new global::System.Windows.Forms.Label();+ this.picPaypallQR = new global::System.Windows.Forms.PictureBox();+ this.Label5 = new global::System.Windows.Forms.Label();+ ((global::System.ComponentModel.ISupportInitialize)this.picIcon).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.picPaypallQR).BeginInit();+ base.SuspendLayout();+ this.picIcon.Location = new global::System.Drawing.Point(20, 20);+ this.picIcon.Name = "picIcon";+ this.picIcon.Size = new global::System.Drawing.Size(48, 48);+ this.picIcon.SizeMode = global::System.Windows.Forms.PictureBoxSizeMode.Zoom;+ this.picIcon.TabIndex = 0;+ this.picIcon.TabStop = false;+ this.lblTitle.AutoSize = true;+ this.lblTitle.Font = new global::System.Drawing.Font("Segoe UI", 14f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblTitle.Location = new global::System.Drawing.Point(82, 18);+ this.lblTitle.Name = "lblTitle";+ this.lblTitle.Size = new global::System.Drawing.Size(143, 25);+ this.lblTitle.TabIndex = 1;+ this.lblTitle.Text = "Wave Dude 2D";+ this.lblVersion.AutoSize = true;+ this.lblVersion.Location = new global::System.Drawing.Point(84, 54);+ this.lblVersion.Name = "lblVersion";+ this.lblVersion.Size = new global::System.Drawing.Size(90, 18);+ this.lblVersion.TabIndex = 2;+ this.lblVersion.Text = "Version 0.29";+ this.lblDescription.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblDescription.Location = new global::System.Drawing.Point(15, 90);+ this.lblDescription.Name = "lblDescription";+ this.lblDescription.Size = new global::System.Drawing.Size(461, 28);+ this.lblDescription.TabIndex = 3;+ this.lblDescription.Text = "Build a scene and watch waves do their thing!";+ this.lblCopyright.AutoSize = true;+ this.lblCopyright.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblCopyright.Location = new global::System.Drawing.Point(15, 507);+ this.lblCopyright.Name = "lblCopyright";+ this.lblCopyright.Size = new global::System.Drawing.Size(71, 18);+ this.lblCopyright.TabIndex = 4;+ this.lblCopyright.Text = "Copyright";+ this.btnClose.Anchor = global::System.Windows.Forms.AnchorStyles.Bottom | global::System.Windows.Forms.AnchorStyles.Right;+ this.btnClose.DialogResult = global::System.Windows.Forms.DialogResult.OK;+ this.btnClose.Location = new global::System.Drawing.Point(319, 495);+ this.btnClose.Name = "btnClose";+ this.btnClose.Size = new global::System.Drawing.Size(90, 30);+ this.btnClose.TabIndex = 5;+ this.btnClose.Text = "OK";+ this.btnClose.UseVisualStyleBackColor = true;+ this.Label1.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label1.Location = new global::System.Drawing.Point(13, 254);+ this.Label1.Name = "Label1";+ this.Label1.Size = new global::System.Drawing.Size(392, 68);+ this.Label1.TabIndex = 3;+ this.Label1.Text = "If you use this software and found it useful, consider making a donation to support future projects.\r\n\r\n";+ this.Label2.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label2.Location = new global::System.Drawing.Point(15, 128);+ this.Label2.Name = "Label2";+ this.Label2.Size = new global::System.Drawing.Size(394, 58);+ this.Label2.TabIndex = 3;+ this.Label2.Text = "Developed by Huygens Optics / JJM Vleggaar with support of Claude Sonnet 5 (meaning Claude did most of the heavy lifting and I get the credits). ";+ this.Label3.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label3.Location = new global::System.Drawing.Point(12, 301);+ this.Label3.Name = "Label3";+ this.Label3.Size = new global::System.Drawing.Size(387, 46);+ this.Label3.TabIndex = 3;+ this.Label3.Text = "Patreon: www.patreon.com/c/huygens_optics";+ this.Label4.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label4.Location = new global::System.Drawing.Point(16, 341);+ this.Label4.Name = "Label4";+ this.Label4.Size = new global::System.Drawing.Size(81, 46);+ this.Label4.TabIndex = 3;+ this.Label4.Text = "Paypal:";+ this.picPaypallQR.Image = global::_2D_wave_sim_V01.My.Resources.Resources.QR_code;+ this.picPaypallQR.Location = new global::System.Drawing.Point(121, 341);+ this.picPaypallQR.Name = "picPaypallQR";+ this.picPaypallQR.Size = new global::System.Drawing.Size(139, 135);+ this.picPaypallQR.SizeMode = global::System.Windows.Forms.PictureBoxSizeMode.Zoom;+ this.picPaypallQR.TabIndex = 6;+ this.picPaypallQR.TabStop = false;+ this.Label5.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label5.Location = new global::System.Drawing.Point(15, 199);+ this.Label5.Name = "Label5";+ this.Label5.Size = new global::System.Drawing.Size(392, 42);+ this.Label5.TabIndex = 3;+ this.Label5.Text = "Send bugs or suggestions for improvement to : [email protected]";+ base.AcceptButton = this.btnClose;+ base.CancelButton = this.btnClose;+ base.ClientSize = new global::System.Drawing.Size(429, 545);+ base.Controls.Add(this.picPaypallQR);+ base.Controls.Add(this.btnClose);+ base.Controls.Add(this.lblCopyright);+ base.Controls.Add(this.Label2);+ base.Controls.Add(this.Label4);+ base.Controls.Add(this.Label3);+ base.Controls.Add(this.Label5);+ base.Controls.Add(this.Label1);+ base.Controls.Add(this.lblDescription);+ base.Controls.Add(this.lblVersion);+ base.Controls.Add(this.lblTitle);+ base.Controls.Add(this.picIcon);+ this.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ base.FormBorderStyle = global::System.Windows.Forms.FormBorderStyle.FixedDialog;+ base.MaximizeBox = false;+ base.MinimizeBox = false;+ base.Name = "AboutForm";+ base.ShowIcon = false;+ base.ShowInTaskbar = false;+ base.StartPosition = global::System.Windows.Forms.FormStartPosition.CenterParent;+ this.Text = "About 2D Wave Dude ";+ ((global::System.ComponentModel.ISupportInitialize)this.picIcon).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.picPaypallQR).EndInit();+ base.ResumeLayout(false);+ base.PerformLayout();+ }++ private PictureBox picIcon;+ private Label lblTitle;+ private Label lblVersion;+ private Label lblDescription;+ private Label lblCopyright;+ private Button btnClose;+ private Label Label1;+ private Label Label2;+ private Label Label3;+ private Label Label4;+ private PictureBox picPaypallQR;+ private Label Label5;+ private global::System.ComponentModel.IContainer components;+ }+}diff --git a/Wave_Dude_2D/AboutForm.cs b/Wave_Dude_2D/AboutForm.csnew file mode 100644index 0000000..38072d3--- /dev/null+++ b/Wave_Dude_2D/AboutForm.cs@@ -0,0 +1,48 @@+using System;+using System.Drawing;+using System.Windows.Forms;+using _2D_wave_sim_V01.My;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// "About" dialog: shows the display version, the assembly copyright and the program icon.+ /// Opened modally from the Info menu of <see cref="Form1"/>.+ /// </summary>+ public partial class AboutForm : Form+ {+ /// <summary>+ /// Fills in the version and copyright labels and the icon associated with the running+ /// executable. The icon is optional: any failure to extract it is swallowed and the+ /// picture box stays empty.+ /// </summary>+ public AboutForm()+ {+ base.Load += this.AboutForm_Load;+ this.InitializeComponent();+ this.lblVersion.Text = "Version " + DisplayVersion;+ this.lblCopyright.Text = MyProject.Application.Info.Copyright;+ try+ {+ using (Icon icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath))+ {+ if (icon != null)+ {+ this.picIcon.Image = icon.ToBitmap();+ }+ }+ }+ catch+ {+ }+ }++ /// <summary>Does nothing; still wired to <see cref="Form.Load"/> by the constructor.</summary>+ private void AboutForm_Load(object sender, EventArgs e)+ {+ }++ /// <summary>Version text shown in the dialog. A hand-maintained literal, not derived from the assembly version.</summary>+ private const string DisplayVersion = "0.27";+ }+}diff --git a/Wave_Dude_2D/AboutForm.resx b/Wave_Dude_2D/AboutForm.resxnew file mode 100644index 0000000..7c72981--- /dev/null+++ b/Wave_Dude_2D/AboutForm.resx@@ -0,0 +1,61 @@+<?xml version="1.0" encoding="utf-8"?>+<root>+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />+ <xsd:element name="root" msdata:IsDataSet="true">+ <xsd:complexType>+ <xsd:choice maxOccurs="unbounded">+ <xsd:element name="metadata">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" />+ </xsd:sequence>+ <xsd:attribute name="name" use="required" type="xsd:string" />+ <xsd:attribute name="type" type="xsd:string" />+ <xsd:attribute name="mimetype" type="xsd:string" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="assembly">+ <xsd:complexType>+ <xsd:attribute name="alias" type="xsd:string" />+ <xsd:attribute name="name" type="xsd:string" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="data">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="resheader">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" />+ </xsd:complexType>+ </xsd:element>+ </xsd:choice>+ </xsd:complexType>+ </xsd:element>+ </xsd:schema>+ <resheader name="resmimetype">+ <value>text/microsoft-resx</value>+ </resheader>+ <resheader name="version">+ <value>2.0</value>+ </resheader>+ <resheader name="reader">+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <resheader name="writer">+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+</root>\ No newline at end of filediff --git a/Wave_Dude_2D/AppSettings.cs b/Wave_Dude_2D/AppSettings.csnew file mode 100644index 0000000..f4b553d--- /dev/null+++ b/Wave_Dude_2D/AppSettings.cs@@ -0,0 +1,125 @@+using System;+using System.Collections.Generic;+using System.IO;+using System.Text;+using System.Web.Script.Serialization;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Per-user application settings, persisted as a small JSON object in+ /// <c>%AppData%\2D_wave_sim_V01\settings.json</c>. <see cref="Form1"/> loads one copy at+ /// start-up with <see cref="Load"/> and calls <see cref="Save"/> whenever the project root+ /// or the open project changes. Loading and saving never throw: on any error the defaults+ /// are used or the write is silently skipped.+ /// </summary>+ public sealed class AppSettings+ {+ /// <summary>Starts with all three values empty (no root chosen, no project remembered).</summary>+ public AppSettings()+ {+ this.LastRootFolder = "";+ this.LastProjectName = "";+ this.ProjectRoot = "";+ }++ /// <summary>+ /// Root folder of the project opened most recently. Written on every project open and+ /// persisted, but not read back by the application at present.+ /// </summary>+ public string LastRootFolder { get; set; }++ /// <summary>+ /// Name (folder name) of the project opened most recently. Written on every project open+ /// and persisted, but not read back by the application at present.+ /// </summary>+ public string LastProjectName { get; set; }++ /// <summary>+ /// The folder that contains the user's project folders (File > Choose project root).+ /// Empty until the user has chosen one; <see cref="Form1"/> keeps most of the UI disabled+ /// while it is empty.+ /// </summary>+ public string ProjectRoot { get; set; }++ /// <summary>Full path of the settings file under the roaming application-data folder.</summary>+ private static string SettingsFilePath()+ {+ return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "2D_wave_sim_V01", "settings.json");+ }++ /// <summary>+ /// Reads the settings file. Missing file, unreadable JSON or missing keys all yield the+ /// corresponding default (empty string); nothing is thrown.+ /// </summary>+ /// <returns>A new instance; never null.</returns>+ public static AppSettings Load()+ {+ AppSettings settings = new AppSettings();+ try+ {+ string path = AppSettings.SettingsFilePath();+ if (File.Exists(path))+ {+ JavaScriptSerializer serializer = new JavaScriptSerializer();+ Dictionary<string, object> values = serializer.DeserializeObject(File.ReadAllText(path, Encoding.UTF8)) as Dictionary<string, object>;+ if (values != null)+ {+ settings.LastRootFolder = AppSettings.ReadText(values, KeyRootFolder);+ settings.LastProjectName = AppSettings.ReadText(values, KeyProjectName);+ settings.ProjectRoot = AppSettings.ReadText(values, KeyProjectRoot);+ }+ }+ }+ catch+ {+ }+ return settings;+ }++ /// <summary>+ /// Writes the three values as a flat JSON object (UTF-8 without BOM), creating the folder+ /// if needed. Any I/O or serialisation error is swallowed.+ /// </summary>+ public void Save()+ {+ try+ {+ string path = AppSettings.SettingsFilePath();+ Directory.CreateDirectory(Path.GetDirectoryName(path));+ Dictionary<string, string> values = new Dictionary<string, string>();+ values[KeyRootFolder] = this.LastRootFolder;+ values[KeyProjectName] = this.LastProjectName;+ values[KeyProjectRoot] = this.ProjectRoot;+ JavaScriptSerializer serializer = new JavaScriptSerializer();+ File.WriteAllText(path, serializer.Serialize(values), new UTF8Encoding(false));+ }+ catch+ {+ }+ }++ /// <summary>+ /// Returns the value stored under <paramref name="key"/> as text, or an empty string when+ /// the key is absent or null. Non-string JSON values are converted with the current culture.+ /// </summary>+ private static string ReadText(Dictionary<string, object> root, string key)+ {+ object value;+ if (root.TryGetValue(key, out value) && value != null)+ {+ return Convert.ToString(value);+ }+ return "";+ }++ /// <summary>JSON key of <see cref="LastRootFolder"/>.</summary>+ private const string KeyRootFolder = "last_root_folder";++ /// <summary>JSON key of <see cref="LastProjectName"/>.</summary>+ private const string KeyProjectName = "last_project_name";++ /// <summary>JSON key of <see cref="ProjectRoot"/>.</summary>+ private const string KeyProjectRoot = "project_root";+ }+}diff --git a/Wave_Dude_2D/AviFrameSink.cs b/Wave_Dude_2D/AviFrameSink.csnew file mode 100644index 0000000..e6ae2a8--- /dev/null+++ b/Wave_Dude_2D/AviFrameSink.cs@@ -0,0 +1,106 @@+using System;+using System.Drawing;+using System.Drawing.Imaging;+using System.IO;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// <see cref="IFrameSink"/> that JPEG-encodes each frame with the GDI+ encoder and appends it to a Motion-JPEG+ /// AVI through <see cref="AviMjpegWriter"/>. Fallback used by <see cref="SimulationRunner"/> when MP4 is not+ /// requested or Media Foundation is unavailable. Used from the worker thread only.+ /// </summary>+ internal sealed class AviFrameSink : IFrameSink+ {+ /// <summary>Creates the AVI file immediately (header written); <paramref name="quality"/> is clamped to 1..100.</summary>+ /// <param name="filePath">Output .avi path (created or overwritten).</param>+ /// <param name="width">Frame width in pixels.</param>+ /// <param name="height">Frame height in pixels.</param>+ /// <param name="framesPerSecond">Playback frame rate.</param>+ /// <param name="quality">JPEG quality 1..100 passed to the GDI+ encoder.</param>+ public AviFrameSink(string filePath, int width, int height, int framesPerSecond, int quality)+ {+ this._buffer = new MemoryStream();+ this._jpegQuality = Math.Max(1, Math.Min(100, quality));+ this._path = filePath;+ this._width = width;+ this._height = height;+ this._writer = new AviMjpegWriter(filePath, width, height, framesPerSecond);+ }++ /// <summary>The AVI path given to the constructor.</summary>+ public string FilePath+ {+ get+ {+ return this._path;+ }+ }++ /// <summary>+ /// Wraps the ARGB buffer in a temporary bitmap, JPEG-encodes it into the reusable <see cref="_buffer"/>+ /// and appends the bytes as one AVI frame.+ /// </summary>+ public void AddPixels(int[] pixels)+ {+ using (Bitmap bitmap = FrameRenderer.ToBitmap(pixels, this._width, this._height))+ {+ this._buffer.SetLength(0L);+ using (EncoderParameters encoderParameters = new EncoderParameters(1))+ {+ encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, this._jpegQuality);+ bitmap.Save(this._buffer, AviFrameSink.JpegCodec, encoderParameters);+ }+ this._writer.AddFrame(this._buffer.GetBuffer(), (int)this._buffer.Length);+ }+ }++ /// <summary>Writes the AVI index and header patches and closes the file (idempotent).</summary>+ public void Close()+ {+ this._writer.Close();+ }++ /// <summary>Closes the AVI (if not already) and releases the encode buffer.</summary>+ public void Dispose()+ {+ this._writer.Close();+ this._buffer.Dispose();+ }++ /// <summary>Finds the GDI+ JPEG encoder; runs once in the static initializer.</summary>+ /// <exception cref="InvalidOperationException">No JPEG encoder is installed.</exception>+ private static ImageCodecInfo FindJpegCodec()+ {+ foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageEncoders())+ {+ if (codec.FormatID == ImageFormat.Jpeg.Guid)+ {+ return codec;+ }+ }+ throw new InvalidOperationException("The JPEG encoder is not available on this computer.");+ }++ /// <summary>The GDI+ JPEG encoder, resolved once per process (a missing encoder surfaces as a type-initializer exception).</summary>+ private static readonly ImageCodecInfo JpegCodec = AviFrameSink.FindJpegCodec();++ /// <summary>JPEG quality 1..100 as a long, the type <see cref="EncoderParameter"/> expects.</summary>+ private readonly long _jpegQuality;++ /// <summary>Output file path.</summary>+ private readonly string _path;++ /// <summary>The underlying RIFF/AVI container writer; owns the file stream.</summary>+ private readonly AviMjpegWriter _writer;++ /// <summary>Frame width in pixels.</summary>+ private readonly int _width;++ /// <summary>Frame height in pixels.</summary>+ private readonly int _height;++ /// <summary>Reused in-memory target for each JPEG encode; its backing array is handed to the writer directly.</summary>+ private readonly MemoryStream _buffer;+ }+}diff --git a/Wave_Dude_2D/AviMjpegWriter.cs b/Wave_Dude_2D/AviMjpegWriter.csnew file mode 100644index 0000000..3de9ee3--- /dev/null+++ b/Wave_Dude_2D/AviMjpegWriter.cs@@ -0,0 +1,256 @@+using System;+using System.Collections.Generic;+using System.IO;+using System.Text;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Minimal Motion-JPEG AVI (RIFF) writer, single video stream, no audio. The constructor writes the+ /// fixed-size header, <see cref="AddFrame"/> appends one <c>00dc</c> chunk per JPEG to the <c>movi</c>+ /// list and <see cref="Close"/> appends the <c>idx1</c> index and patches the size/count fields in the+ /// header. Used by <see cref="AviFrameSink"/>. All values are little-endian.+ /// </summary>+ /// <remarks>+ /// <para>Intended layout (byte offsets), which is what the <c>Pos*</c> constants encode:</para>+ /// <list type="table">+ /// <item><term>0</term><description><c>RIFF</c>, file size - 8 (patched at <see cref="PosRiffSize"/>), <c>AVI </c></description></item>+ /// <item><term>12</term><description><c>LIST</c> 192 <c>hdrl</c></description></item>+ /// <item><term>24</term><description><c>avih</c> 56: MainAVIHeader (microseconds/frame, flags = AVIF_HASINDEX, total frames at <see cref="PosTotalFrames"/>, 1 stream, suggested buffer at <see cref="PosBufferSize"/>, width, height)</description></item>+ /// <item><term>88</term><description><c>LIST</c> 116 <c>strl</c></description></item>+ /// <item><term>100</term><description><c>strh</c> 56: AVISTREAMHEADER (<c>vids</c>/<c>MJPG</c>, scale/rate, length at <see cref="PosStreamLength"/>, suggested buffer at <see cref="PosStreamBufferSize"/>, rcFrame)</description></item>+ /// <item><term>164</term><description><c>strf</c> 40: BITMAPINFOHEADER (24 bpp, compression <c>MJPG</c>)</description></item>+ /// <item><term>212</term><description><c>LIST</c> movi size (patched at <see cref="PosMoviSize"/>) <c>movi</c> at <see cref="PosMoviTag"/>, then the frame chunks</description></item>+ /// <item><term>end</term><description><c>idx1</c>: one 16-byte entry per frame (<c>00dc</c>, flags = AVIIF_KEYFRAME, offset relative to <see cref="PosMoviTag"/>, size)</description></item>+ /// </list>+ /// <para>Note (writes are deliberately left as they are): the constructor emits 236 header bytes rather+ /// than 224, because <c>strh</c> is written as 64 bytes (an extra zero DWORD before scale/rate, and+ /// rcFrame as two ints plus two ushorts) and <c>strf</c> as 44 bytes (planes and bit count as ints).+ /// The <c>Pos*</c> offsets therefore no longer line up with the bytes actually written: the <c>movi</c>+ /// tag is really at 232, <see cref="PosMoviSize"/> hits the BITMAPINFOHEADER and the real <c>movi</c>+ /// list size stays 0. Odd-length frames are padded with a 4-byte int, not a single byte.</para>+ /// </remarks>+ internal sealed class AviMjpegWriter : IDisposable+ {+ /// <summary>Creates (overwrites) the file and writes the complete header up to and including the <c>movi</c> tag.</summary>+ /// <param name="filePath">Output path; an existing file is truncated.</param>+ /// <param name="width">Frame width in pixels.</param>+ /// <param name="height">Frame height in pixels.</param>+ /// <param name="framesPerSecond">Playback rate; stored as microseconds per frame in <c>avih</c> and as the rate in <c>strh</c>.</param>+ public AviMjpegWriter(string filePath, int width, int height, int framesPerSecond)+ {+ this._offsets = new List<int>();+ this._sizes = new List<int>();+ this._stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read);+ this._writer = new BinaryWriter(this._stream);+ Encoding ascii = Encoding.ASCII;+ // RIFF header+ this._writer.Write(ascii.GetBytes("RIFF"));+ this._writer.Write(0U); // file size - 8, patched in Close+ this._writer.Write(ascii.GetBytes("AVI "));+ // LIST hdrl+ this._writer.Write(ascii.GetBytes("LIST"));+ this._writer.Write(192U);+ this._writer.Write(ascii.GetBytes("hdrl"));+ // avih (MainAVIHeader)+ this._writer.Write(ascii.GetBytes("avih"));+ this._writer.Write(56U);+ this._writer.Write((uint)(1000000 / framesPerSecond)); // dwMicroSecPerFrame+ this._writer.Write(0U); // dwMaxBytesPerSec+ this._writer.Write(0U); // dwPaddingGranularity+ this._writer.Write(16U); // dwFlags = AVIF_HASINDEX+ this._writer.Write(0U); // dwTotalFrames, patched in Close+ this._writer.Write(0U); // dwInitialFrames+ this._writer.Write(1U); // dwStreams+ this._writer.Write(0U); // dwSuggestedBufferSize, patched in Close+ this._writer.Write((uint)width);+ this._writer.Write((uint)height);+ for (int i = 0; i < 4; i++)+ {+ this._writer.Write(0U); // dwReserved[4]+ }+ // LIST strl+ this._writer.Write(ascii.GetBytes("LIST"));+ this._writer.Write(116U);+ this._writer.Write(ascii.GetBytes("strl"));+ // strh (AVISTREAMHEADER)+ this._writer.Write(ascii.GetBytes("strh"));+ this._writer.Write(56U);+ this._writer.Write(ascii.GetBytes("vids")); // fccType+ this._writer.Write(ascii.GetBytes("MJPG")); // fccHandler+ this._writer.Write(0U); // dwFlags+ this._writer.Write(0); // wPriority + wLanguage+ this._writer.Write(0); // dwInitialFrames+ this._writer.Write(0U); // extra DWORD (see class remarks); lands on dwScale+ this._writer.Write(1U); // intended dwScale; lands on dwRate+ this._writer.Write((uint)framesPerSecond); // intended dwRate; lands on dwStart+ this._writer.Write(0U); // dwLength, patched in Close+ this._writer.Write(0U); // dwSuggestedBufferSize, patched in Close+ this._writer.Write(0U); // dwQuality+ this._writer.Write(uint.MaxValue); // dwSampleSize (-1)+ this._writer.Write(0U); // rcFrame left/top+ this._writer.Write(0); // rcFrame right/bottom+ this._writer.Write(0); // extra DWORD (see class remarks)+ this._writer.Write((ushort)width); // extra; beyond the declared 56 bytes+ this._writer.Write((ushort)height);+ // strf (BITMAPINFOHEADER)+ this._writer.Write(ascii.GetBytes("strf"));+ this._writer.Write(40U);+ this._writer.Write(40U); // biSize+ this._writer.Write(width); // biWidth+ this._writer.Write(height); // biHeight+ this._writer.Write(1); // biPlanes (written as a DWORD, should be a WORD)+ this._writer.Write(24); // biBitCount (written as a DWORD, should be a WORD)+ this._writer.Write(ascii.GetBytes("MJPG")); // biCompression+ this._writer.Write((uint)(((long)width * height * 3L) & 0xFFFFFFFFL)); // biSizeImage+ this._writer.Write(0); // biXPelsPerMeter+ this._writer.Write(0); // biYPelsPerMeter+ this._writer.Write(0U); // biClrUsed+ this._writer.Write(0U); // biClrImportant+ // LIST movi; frames follow+ this._writer.Write(ascii.GetBytes("LIST"));+ this._writer.Write(0U); // movi size, patched in Close+ this._writer.Write(ascii.GetBytes("movi"));+ }++ /// <summary>Number of frames appended so far.</summary>+ public int FrameCount+ {+ get+ {+ return this._offsets.Count;+ }+ }++ /// <summary>+ /// Appends one JPEG frame as a <c>00dc</c> chunk and records its offset/size for the index. Odd lengths+ /// are followed by a pad (written as a 4-byte int, see class remarks).+ /// </summary>+ /// <param name="data">Buffer holding the JPEG; only the first <paramref name="length"/> bytes are used.</param>+ /// <param name="length">Number of JPEG bytes.</param>+ /// <exception cref="InvalidOperationException">The file is already closed.</exception>+ /// <exception cref="IOException">The frame plus the index that would follow would push the file past <see cref="MaxAviBytes"/>.</exception>+ public void AddFrame(byte[] data, int length)+ {+ if (this._closed)+ {+ throw new InvalidOperationException("The video file is already closed.");+ }+ // Reserve room for the idx1 that Close() will append (16 bytes per frame plus slack).+ if (this._stream.Position + length + 16L * (this._offsets.Count + 2) + 64L > MaxAviBytes)+ {+ throw new IOException("The video file would become larger than 4 GB, which the AVI format does not allow.");+ }+ this._offsets.Add((int)(this._stream.Position - PosMoviTag));+ this._sizes.Add(length);+ this._writer.Write(Encoding.ASCII.GetBytes("00dc"));+ this._writer.Write((uint)length);+ this._writer.Write(data, 0, length);+ if ((length & 1) == 1)+ {+ this._writer.Write(0); // 4-byte pad (int), not the 1-byte RIFF pad+ }+ if (length > this._largestFrame)+ {+ this._largestFrame = length;+ }+ }++ /// <summary>+ /// Appends the <c>idx1</c> chunk, patches the RIFF size, frame counts, buffer sizes and movi size in the+ /// header, then closes the stream. Idempotent; the stream is closed even if a write fails.+ /// </summary>+ public void Close()+ {+ if (this._closed)+ {+ return;+ }+ this._closed = true;+ try+ {+ long indexPosition = this._stream.Position;+ this._writer.Write(Encoding.ASCII.GetBytes("idx1"));+ this._writer.Write((uint)(16 * this._offsets.Count));+ for (int i = 0; i < this._offsets.Count; i++)+ {+ this._writer.Write(Encoding.ASCII.GetBytes("00dc"));+ this._writer.Write(16U); // AVIIF_KEYFRAME+ this._writer.Write((uint)this._offsets[i]);+ this._writer.Write((uint)this._sizes[i]);+ }+ long endPosition = this._stream.Position;+ this.Patch(PosRiffSize, (uint)(endPosition - 8L));+ this.Patch(PosTotalFrames, (uint)this._offsets.Count);+ this.Patch(PosBufferSize, (uint)this._largestFrame);+ this.Patch(PosStreamLength, (uint)this._offsets.Count);+ this.Patch(PosStreamBufferSize, (uint)this._largestFrame);+ this.Patch(PosMoviSize, (uint)(indexPosition - PosMoviSize));+ this._writer.Flush();+ }+ finally+ {+ this._writer.Close();+ this._stream.Dispose();+ }+ }++ /// <summary>Seeks to <paramref name="position"/> and overwrites one DWORD; leaves the stream positioned after it.</summary>+ private void Patch(long position, uint value)+ {+ this._stream.Seek(position, SeekOrigin.Begin);+ this._writer.Write(value);+ }++ /// <summary>Same as <see cref="Close"/>.</summary>+ public void Dispose()+ {+ this.Close();+ }++ /// <summary>Hard cap on the file size in bytes, kept safely below the 4 GB RIFF limit.</summary>+ private const long MaxAviBytes = 3900000000L;++ /// <summary>Unused duplicate of <see cref="MaxAviBytes"/>.</summary>+ private const long MaxFileSize = 3900000000L;++ /// <summary>Offset of the RIFF size DWORD (file size - 8).</summary>+ private const long PosRiffSize = 4L;++ /// <summary>Offset of avih.dwTotalFrames.</summary>+ private const long PosTotalFrames = 48L;++ /// <summary>Offset of avih.dwSuggestedBufferSize (largest frame).</summary>+ private const long PosBufferSize = 60L;++ /// <summary>Offset of strh.dwLength (frame count).</summary>+ private const long PosStreamLength = 140L;++ /// <summary>Offset of strh.dwSuggestedBufferSize (largest frame).</summary>+ private const long PosStreamBufferSize = 144L;++ /// <summary>Intended offset of the movi LIST size DWORD (actually written at 228, see class remarks).</summary>+ private const long PosMoviSize = 216L;++ /// <summary>Intended offset of the <c>movi</c> tag; idx1 offsets are relative to this (the tag is actually written at 232, see class remarks).</summary>+ private const long PosMoviTag = 220L;++ /// <summary>The output file; disposed by <see cref="Close"/>.</summary>+ private FileStream _stream;++ /// <summary>Little-endian writer over <see cref="_stream"/>.</summary>+ private BinaryWriter _writer;++ /// <summary>Per frame: chunk offset relative to <see cref="PosMoviTag"/>, for idx1.</summary>+ private readonly List<int> _offsets;++ /// <summary>Per frame: JPEG byte count, for idx1.</summary>+ private readonly List<int> _sizes;++ /// <summary>Largest JPEG so far, in bytes; becomes the suggested buffer size.</summary>+ private int _largestFrame;++ /// <summary>True once <see cref="Close"/> has run; further <see cref="AddFrame"/> calls throw.</summary>+ private bool _closed;+ }+}diff --git a/Wave_Dude_2D/ColorLut.cs b/Wave_Dude_2D/ColorLut.csnew file mode 100644index 0000000..820226e--- /dev/null+++ b/Wave_Dude_2D/ColorLut.cs@@ -0,0 +1,168 @@+using System;+using System.Drawing;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// An immutable palette of <see cref="Size"/> opaque ARGB entries built from a+ /// <see cref="ColorScheme"/> by <see cref="Build"/>, plus the static value-to-index+ /// mappings used when colouring frames. Built on the UI thread when a simulation is+ /// started; the <see cref="Argb"/> array is then handed to <see cref="SimulationRunner"/>+ /// and read from <see cref="FrameRenderer"/>'s parallel loops without locking (it is+ /// never modified after construction).+ /// </summary>+ public sealed class ColorLut+ {+ private ColorLut(int[] argb)+ {+ this._argb = argb;+ }++ /// <summary>+ /// The palette as packed opaque ARGB ints (<see cref="Color.ToArgb"/> layout), indices+ /// 0..<see cref="Size"/>-1. Returns the internal array, not a copy; callers must not modify it.+ /// </summary>+ public int[] Argb+ {+ get+ {+ return this._argb;+ }+ }++ /// <summary>Returns entry <paramref name="index"/> (0..<see cref="Size"/>-1) as a <see cref="Color"/>.</summary>+ public Color ColorAt(int index)+ {+ return Color.FromArgb(this._argb[index]);+ }++ /// <summary>+ /// Builds a palette from the <see cref="Size"/> entries of <paramref name="scheme"/>.+ /// Transformations are applied in this order: <paramref name="reverse"/> (entry i is read+ /// from entry <c>Size-1-i</c>), <paramref name="invert"/> (each channel becomes+ /// <c>1 - channel</c>), <paramref name="makeSymmetric"/> (entry i is read from entry+ /// <c>2 * min(i, Size-1-i)</c>, so the palette runs from entry 0 at both ends up to entry+ /// 254 in the middle), then <paramref name="blackLevel"/> lifts every channel linearly so+ /// that 0 becomes <paramref name="blackLevel"/> and 1 stays 1, clamped to 0..1. Alpha is always 255.+ /// </summary>+ /// <param name="scheme">Source colours; must have at least <see cref="Size"/> entries.</param>+ /// <param name="invert">Invert every channel (negative image).</param>+ /// <param name="blackLevel">Minimum channel level 0..1 after lifting (0 = unchanged).</param>+ /// <param name="makeSymmetric">Mirror the palette around its centre index.</param>+ /// <param name="reverse">Read the scheme back to front.</param>+ /// <exception cref="ArgumentNullException"><paramref name="scheme"/> is null.</exception>+ public static ColorLut Build(ColorScheme scheme, bool invert = false, double blackLevel = 0.0, bool makeSymmetric = false, bool reverse = false)+ {+ if (scheme == null)+ {+ throw new ArgumentNullException("scheme");+ }+ double[,] rgb = new double[Size, 3];+ for (int i = 0; i < Size; i++)+ {+ Color entry = scheme.GetEntry(reverse ? (Size - 1 - i) : i);+ rgb[i, 0] = entry.R / 255.0;+ rgb[i, 1] = entry.G / 255.0;+ rgb[i, 2] = entry.B / 255.0;+ }+ if (invert)+ {+ for (int i = 0; i < Size; i++)+ {+ for (int channel = 0; channel < 3; channel++)+ {+ rgb[i, channel] = 1.0 - rgb[i, channel];+ }+ }+ }+ int[] argb = new int[Size];+ for (int i = 0; i < Size; i++)+ {+ int sourceIndex = i;+ if (makeSymmetric)+ {+ sourceIndex = 2 * Math.Min(i, Size - 1 - i);+ }+ int[] components = new int[3];+ for (int channel = 0; channel < 3; channel++)+ {+ double level = rgb[sourceIndex, channel] * (1.0 - blackLevel) + blackLevel;+ if (level < 0.0)+ {+ level = 0.0;+ }+ if (level > 1.0)+ {+ level = 1.0;+ }+ int component = (int)(level * 255.0);+ if (component > 255)+ {+ component = 255;+ }+ components[channel] = component;+ }+ argb[i] = Color.FromArgb(255, components[0], components[1], components[2]).ToArgb();+ }+ return new ColorLut(argb);+ }++ /// <summary>+ /// Maps a signed field sample to a palette index: <c>value * brightness</c> is clamped to+ /// -1..1 and mapped linearly to 0..254 with 0 at index 127. NaN gives 127. Called per+ /// pixel from <see cref="FrameRenderer.RenderField"/> on worker threads.+ /// </summary>+ /// <param name="value">Raw field amplitude from the engine.</param>+ /// <param name="brightness">Gain applied before clamping.</param>+ public static int FieldIndex(float value, float brightness)+ {+ float scaled = value * brightness;+ if (float.IsNaN(scaled))+ {+ return 127;+ }+ if (scaled > 1f)+ {+ scaled = 1f;+ }+ if (scaled < -1f)+ {+ scaled = -1f;+ }+ return (int)(scaled * 127f + 127f);+ }++ /// <summary>+ /// Maps a non-negative intensity to a palette index 0..254: <c>intensity ^ exponent</c>+ /// (square root by default) times <paramref name="brightness"/>, clamped to 0..1 and+ /// scaled to 254. NaN or non-positive intensity gives 0. Not currently called;+ /// <see cref="FrameRenderer.RenderIntensity"/> inlines the equivalent square-root mapping.+ /// </summary>+ /// <param name="intensity">Accumulated intensity from the engine.</param>+ /// <param name="brightness">Gain applied after compression.</param>+ /// <param name="exponent">Compression exponent; 0.5 = square root.</param>+ public static int IntensityIndex(float intensity, float brightness, float exponent = 0.5f)+ {+ if (float.IsNaN(intensity) || intensity <= 0f)+ {+ return 0;+ }+ double scaled = Math.Pow(intensity, exponent) * brightness;+ if (double.IsNaN(scaled) || scaled < 0.0)+ {+ return 0;+ }+ if (scaled > 1.0)+ {+ scaled = 1.0;+ }+ return (int)(scaled * 254.0);+ }++ /// <summary>Number of entries in a palette (255, matching <see cref="ColorScheme.EntryCount"/>).</summary>+ public const int Size = 255;++ /// <summary>The packed opaque ARGB entries; never modified after construction.</summary>+ private readonly int[] _argb;+ }+}diff --git a/Wave_Dude_2D/ColorPickerControl.cs b/Wave_Dude_2D/ColorPickerControl.csnew file mode 100644index 0000000..2e2c6e2--- /dev/null+++ b/Wave_Dude_2D/ColorPickerControl.cs@@ -0,0 +1,577 @@+using System;+using System.ComponentModel;+using System.Drawing;+using System.Drawing.Drawing2D;+using System.Drawing.Imaging;+using System.Globalization;+using System.Runtime.InteropServices;+using System.Windows.Forms;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// HSV colour picker used by the colour-scheme tab (created in code by <see cref="Form1"/> and+ /// docked into a panel): a saturation/value square, a vertical hue strip, "New" / "Old" swatches+ /// (clicking "Old" restores <see cref="OriginalColor"/>), a hex text box, an RGB read-out and a+ /// "More..." button that opens the standard <see cref="ColorDialog"/>. The layout is fixed for a+ /// 423 x 411 client area. <see cref="ColorChanged"/> is raised for user edits only, not when+ /// <see cref="SelectedColor"/> is assigned from code. UI thread only.+ /// </summary>+ [DesignerCategory("Code")]+ public class ColorPickerControl : UserControl+ {+ /// <summary>+ /// Raised after the user changes the colour (dragging, a complete hex entry, the dialog or a click+ /// on the "Old" swatch). Not raised when <see cref="SelectedColor"/> or <see cref="OriginalColor"/> is set from code.+ /// </summary>+ public event EventHandler ColorChanged;++ /// <summary>+ /// Creates the child controls at fixed positions, enables double-buffered owner painting and+ /// starts with red selected and grey as the original colour.+ /// </summary>+ public ColorPickerControl()+ {+ this._svRect = new Rectangle(10, 10, 300, 300);+ this._hueRect = new Rectangle(326, 10, 28, 300);+ this._newRect = new Rectangle(10, 324, 150, 36);+ this._oldRect = new Rectangle(160, 324, 150, 36);+ this._lblHex = new Label();+ this._txtHex = new TextBox();+ this._lblRgb = new Label();+ this._btnDialog = new Button();+ this._color = Color.Red;+ this._original = Color.Gray;+ this._svHue = -1.0;+ base.SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);+ base.Size = new Size(423, 411);+ this._lblHex.Text = "Hex";+ this._lblHex.AutoSize = true;+ this._lblHex.Location = new Point(10, 377);+ this._txtHex.Location = new Point(48, 373);+ this._txtHex.Width = 90;+ this._txtHex.MaxLength = 7;+ this._lblRgb.AutoSize = true;+ this._lblRgb.Location = new Point(152, 377);+ this._btnDialog.Text = "More...";+ this._btnDialog.Location = new Point(326, 324);+ this._btnDialog.Size = new Size(90, 36);+ base.Controls.Add(this._lblHex);+ base.Controls.Add(this._txtHex);+ base.Controls.Add(this._lblRgb);+ base.Controls.Add(this._btnDialog);+ this._txtHex.TextChanged += this.HexTextChanged;+ this._btnDialog.Click += this.DialogButtonClick;+ this.ApplyColor(Color.Red, false, false);+ }++ /// <summary>+ /// Gets the current colour (always opaque). Setting it updates the HSV state, texts and swatch+ /// without raising <see cref="ColorChanged"/>.+ /// </summary>+ public Color SelectedColor+ {+ get+ {+ return this._color;+ }+ set+ {+ this.ApplyColor(value, false, false);+ }+ }++ /// <summary>The reference colour shown in the "Old" swatch and restored when it is clicked; alpha is discarded.</summary>+ public Color OriginalColor+ {+ get+ {+ return this._original;+ }+ set+ {+ this._original = Color.FromArgb(value.R, value.G, value.B);+ base.Invalidate();+ }+ }++ /// <summary>+ /// Makes <paramref name="c"/> (alpha discarded) the current colour and derives H/S/V from it. The+ /// hue is left unchanged for greys and black (saturation or value 0) so the hue marker does not+ /// jump to 0. Updates the texts, repaints and optionally raises <see cref="ColorChanged"/>.+ /// </summary>+ /// <param name="c">The new colour; its alpha is ignored.</param>+ /// <param name="raiseChanged">Raise <see cref="ColorChanged"/> (true for user edits only).</param>+ /// <param name="fromHexBox">Leave the hex box untouched because the user is typing in it.</param>+ private void ApplyColor(Color c, bool raiseChanged, bool fromHexBox)+ {+ this._color = Color.FromArgb(c.R, c.G, c.B);+ double hue = 0.0;+ double saturation = 0.0;+ double value = 0.0;+ ColorPickerControl.RgbToHsv(this._color, ref hue, ref saturation, ref value);+ if (saturation > 0.0 && value > 0.0)+ {+ this._h = hue;+ }+ this._s = saturation;+ this._v = value;+ this.UpdateTexts(fromHexBox);+ base.Invalidate();+ if (raiseChanged)+ {+ EventHandler colorChangedEvent = this.ColorChanged;+ if (colorChangedEvent != null)+ {+ colorChangedEvent(this, EventArgs.Empty);+ }+ }+ }++ /// <summary>Recomputes the colour from <see cref="_h"/>/<see cref="_s"/>/<see cref="_v"/> after a drag, updates the texts, repaints and raises <see cref="ColorChanged"/>.</summary>+ private void SyncFromHsv()+ {+ this._color = ColorPickerControl.HsvToColor(this._h, this._s, this._v);+ this.UpdateTexts(false);+ base.Invalidate();+ EventHandler colorChangedEvent = this.ColorChanged;+ if (colorChangedEvent != null)+ {+ colorChangedEvent(this, EventArgs.Empty);+ }+ }++ /// <summary>+ /// Writes "#RRGGBB" into the hex box (unless <paramref name="skipHexBox"/>) and "R G B" into the+ /// read-out label, with <see cref="_updatingText"/> set so <see cref="HexTextChanged"/> ignores the programmatic change.+ /// </summary>+ private void UpdateTexts(bool skipHexBox)+ {+ this._updatingText = true;+ try+ {+ if (!skipHexBox)+ {+ this._txtHex.Text = "#" + this._color.R.ToString("X2", CultureInfo.InvariantCulture) + this._color.G.ToString("X2", CultureInfo.InvariantCulture) + this._color.B.ToString("X2", CultureInfo.InvariantCulture);+ }+ this._lblRgb.Text = string.Format(CultureInfo.InvariantCulture, "R {0} G {1} B {2}", this._color.R, this._color.G, this._color.B);+ }+ finally+ {+ this._updatingText = false;+ }+ }++ /// <summary>Typing a complete 6-digit hex colour (optional leading '#') applies it and raises <see cref="ColorChanged"/>; incomplete or invalid text is ignored.</summary>+ private void HexTextChanged(object sender, EventArgs e)+ {+ if (this._updatingText)+ {+ return;+ }+ string hex = this._txtHex.Text.Trim().TrimStart('#');+ if (hex.Length != 6)+ {+ return;+ }+ int rgb;+ if (int.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out rgb))+ {+ this.ApplyColor(Color.FromArgb((rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255), true, true);+ }+ }++ /// <summary>"More..." opens the standard colour dialog (custom-colour panel expanded) preset to the current colour and applies the chosen colour.</summary>+ private void DialogButtonClick(object sender, EventArgs e)+ {+ using (ColorDialog colorDialog = new ColorDialog())+ {+ colorDialog.FullOpen = true;+ colorDialog.Color = this._color;+ if (colorDialog.ShowDialog(this) == DialogResult.OK)+ {+ this.ApplyColor(colorDialog.Color, true, false);+ }+ }+ }++ /// <summary>+ /// Left button: starts a drag in the S/V square (<see cref="_drag"/> = 1) or the hue strip+ /// (<see cref="_drag"/> = 2) and applies the pressed point immediately; a click on the "Old"+ /// swatch restores <see cref="OriginalColor"/>.+ /// </summary>+ protected override void OnMouseDown(MouseEventArgs e)+ {+ base.OnMouseDown(e);+ if (e.Button != MouseButtons.Left)+ {+ return;+ }+ if (this._svRect.Contains(e.Location))+ {+ this._drag = 1;+ this.UpdateFromMouse(e.Location);+ }+ else if (this._hueRect.Contains(e.Location))+ {+ this._drag = 2;+ this.UpdateFromMouse(e.Location);+ }+ else if (this._oldRect.Contains(e.Location))+ {+ this.ApplyColor(this._original, true, false);+ }+ }++ /// <summary>Continues an active drag; positions outside the square / strip are clamped to its edge.</summary>+ protected override void OnMouseMove(MouseEventArgs e)+ {+ base.OnMouseMove(e);+ if (this._drag != 0)+ {+ this.UpdateFromMouse(e.Location);+ }+ }++ /// <summary>Ends any drag.</summary>+ protected override void OnMouseUp(MouseEventArgs e)+ {+ base.OnMouseUp(e);+ this._drag = 0;+ }++ /// <summary>+ /// Converts a mouse position in control client pixels into S/V (square: saturation 0..1 left to+ /// right, value 1..0 top to bottom) or hue (strip: 0..360 degrees top to bottom) depending on+ /// <see cref="_drag"/>, clamped to the rectangle, and then calls <see cref="SyncFromHsv"/>.+ /// </summary>+ private void UpdateFromMouse(Point p)+ {+ if (this._drag == 1)+ {+ this._s = ColorPickerControl.Clamp01((p.X - this._svRect.X) / (double)(this._svRect.Width - 1));+ this._v = 1.0 - ColorPickerControl.Clamp01((p.Y - this._svRect.Y) / (double)(this._svRect.Height - 1));+ }+ else if (this._drag == 2)+ {+ this._h = ColorPickerControl.Clamp01((p.Y - this._hueRect.Y) / (double)(this._hueRect.Height - 1)) * 360.0;+ }+ else+ {+ return;+ }+ this.SyncFromHsv();+ }++ /// <summary>+ /// Paints the S/V square (bilinear upscale of the <see cref="SvResolution"/> cache), the hue strip,+ /// the two markers, the swatches with contrasting captions and, when the control is disabled, a+ /// translucent veil in the background colour over everything.+ /// </summary>+ protected override void OnPaint(PaintEventArgs e)+ {+ base.OnPaint(e);+ Graphics g = e.Graphics;+ g.Clear(this.BackColor);+ this.EnsureSvBitmap();+ g.InterpolationMode = InterpolationMode.HighQualityBilinear;+ g.PixelOffsetMode = PixelOffsetMode.Half;+ g.DrawImage(this._svBitmap, this._svRect);+ g.DrawRectangle(Pens.Black, this._svRect.X - 1, this._svRect.Y - 1, this._svRect.Width + 1, this._svRect.Height + 1);+ this.EnsureHueBitmap();+ g.InterpolationMode = InterpolationMode.NearestNeighbor;+ g.DrawImage(this._hueBitmap, this._hueRect);+ g.DrawRectangle(Pens.Black, this._hueRect.X - 1, this._hueRect.Y - 1, this._hueRect.Width + 1, this._hueRect.Height + 1);+ g.SmoothingMode = SmoothingMode.AntiAlias;+ float svX = (float)(this._svRect.X + this._s * (this._svRect.Width - 1));+ float svY = (float)(this._svRect.Y + (1.0 - this._v) * (this._svRect.Height - 1));+ g.DrawEllipse(Pens.Black, svX - 7f, svY - 7f, 14f, 14f);+ g.DrawEllipse(Pens.White, svX - 6f, svY - 6f, 12f, 12f);+ float hueY = (float)(this._hueRect.Y + this._h / 360.0 * (this._hueRect.Height - 1));+ g.DrawRectangle(Pens.Black, this._hueRect.X - 3, hueY - 3f, this._hueRect.Width + 5, 6f);+ g.DrawRectangle(Pens.White, this._hueRect.X - 2, hueY - 2f, this._hueRect.Width + 3, 4f);+ g.SmoothingMode = SmoothingMode.Default;+ using (SolidBrush newBrush = new SolidBrush(this._color))+ {+ g.FillRectangle(newBrush, this._newRect);+ }+ using (SolidBrush oldBrush = new SolidBrush(this._original))+ {+ g.FillRectangle(oldBrush, this._oldRect);+ }+ g.DrawRectangle(Pens.Black, this._newRect.X, this._newRect.Y, this._newRect.Width - 1, this._newRect.Height - 1);+ g.DrawRectangle(Pens.Black, this._oldRect.X, this._oldRect.Y, this._oldRect.Width - 1, this._oldRect.Height - 1);+ TextRenderer.DrawText(g, "New", this.Font, this._newRect, ColorPickerControl.ContrastColor(this._color), TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);+ TextRenderer.DrawText(g, "Old (click to restore)", this.Font, this._oldRect, ColorPickerControl.ContrastColor(this._original), TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);+ if (!base.Enabled)+ {+ using (SolidBrush overlayBrush = new SolidBrush(Color.FromArgb(150, this.BackColor)))+ {+ g.FillRectangle(overlayBrush, base.ClientRectangle);+ }+ }+ }++ /// <summary>Repaints so the disabled veil appears or disappears.</summary>+ protected override void OnEnabledChanged(EventArgs e)+ {+ base.OnEnabledChanged(e);+ base.Invalidate();+ }++ /// <summary>+ /// Rebuilds the <see cref="SvResolution"/>-square saturation/value bitmap for the current hue+ /// when it has never been built or the hue moved by 0.0001 degrees or more; otherwise keeps the+ /// cached bitmap. Pixels are written in one block via <c>LockBits</c>.+ /// </summary>+ private void EnsureSvBitmap()+ {+ if (this._svBitmap != null && Math.Abs(this._svHue - this._h) < 0.0001)+ {+ return;+ }+ if (this._svBitmap == null)+ {+ this._svBitmap = new Bitmap(SvResolution, SvResolution, PixelFormat.Format32bppArgb);+ }+ Color pure = ColorPickerControl.HsvToColor(this._h, 1.0, 1.0);+ double pureR = pure.R / 255.0;+ double pureG = pure.G / 255.0;+ double pureB = pure.B / 255.0;+ int[] pixels = new int[SvResolution * SvResolution];+ for (int y = 0; y < SvResolution; y++)+ {+ double value = 1.0 - y / (SvResolution - 1.0);+ for (int x = 0; x < SvResolution; x++)+ {+ double saturation = x / (SvResolution - 1.0);+ int r = (int)Math.Round(255.0 * value * (1.0 - saturation + saturation * pureR));+ int g = (int)Math.Round(255.0 * value * (1.0 - saturation + saturation * pureG));+ int b = (int)Math.Round(255.0 * value * (1.0 - saturation + saturation * pureB));+ pixels[y * SvResolution + x] = Color.FromArgb(255, r, g, b).ToArgb();+ }+ }+ BitmapData bitmapData = this._svBitmap.LockBits(new Rectangle(0, 0, SvResolution, SvResolution), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);+ try+ {+ Marshal.Copy(pixels, 0, bitmapData.Scan0, pixels.Length);+ }+ finally+ {+ this._svBitmap.UnlockBits(bitmapData);+ }+ this._svHue = this._h;+ }++ /// <summary>Creates the 1-pixel-wide hue gradient bitmap (hue 0 at the top, 360 at the bottom) on first use; it never changes afterwards.</summary>+ private void EnsureHueBitmap()+ {+ if (this._hueBitmap != null)+ {+ return;+ }+ this._hueBitmap = new Bitmap(1, this._hueRect.Height, PixelFormat.Format32bppArgb);+ for (int i = 0; i < this._hueRect.Height; i++)+ {+ this._hueBitmap.SetPixel(0, i, ColorPickerControl.HsvToColor(i / (double)(this._hueRect.Height - 1) * 360.0, 1.0, 1.0));+ }+ }++ /// <summary>Disposes the cached square and hue bitmaps; the child controls are disposed by the base class.</summary>+ protected override void Dispose(bool disposing)+ {+ if (disposing)+ {+ if (this._svBitmap != null)+ {+ this._svBitmap.Dispose();+ }+ if (this._hueBitmap != null)+ {+ this._hueBitmap.Dispose();+ }+ }+ base.Dispose(disposing);+ }++ /// <summary>Clamps <paramref name="x"/> to 0..1.</summary>+ private static double Clamp01(double x)+ {+ if (x < 0.0)+ {+ return 0.0;+ }+ if (x > 1.0)+ {+ return 1.0;+ }+ return x;+ }++ /// <summary>Black or white, whichever reads better on <paramref name="c"/> (Rec. 601 luma, threshold 140 of 255).</summary>+ private static Color ContrastColor(Color c)+ {+ double luma = 0.299 * c.R + 0.587 * c.G + 0.114 * c.B;+ return luma > 140.0 ? Color.Black : Color.White;+ }++ /// <summary>Converts HSV to an opaque <see cref="Color"/>.</summary>+ /// <param name="h">Hue in degrees; any value, wrapped into 0..360.</param>+ /// <param name="s">Saturation 0..1.</param>+ /// <param name="v">Value 0..1.</param>+ public static Color HsvToColor(double h, double s, double v)+ {+ double hue = h % 360.0;+ if (hue < 0.0)+ {+ hue += 360.0;+ }+ double chroma = v * s;+ double sector = hue / 60.0;+ double x = chroma * (1.0 - Math.Abs(sector % 2.0 - 1.0));+ double r;+ double g;+ double b;+ switch ((int)Math.Floor(sector))+ {+ case 0:+ r = chroma;+ g = x;+ b = 0.0;+ break;+ case 1:+ r = x;+ g = chroma;+ b = 0.0;+ break;+ case 2:+ r = 0.0;+ g = chroma;+ b = x;+ break;+ case 3:+ r = 0.0;+ g = x;+ b = chroma;+ break;+ case 4:+ r = x;+ g = 0.0;+ b = chroma;+ break;+ default:+ r = chroma;+ g = 0.0;+ b = x;+ break;+ }+ double m = v - chroma;+ return Color.FromArgb(ColorPickerControl.ToByte(r + m), ColorPickerControl.ToByte(g + m), ColorPickerControl.ToByte(b + m));+ }++ /// <summary>Scales 0..1 to 0..255 with rounding and clamping.</summary>+ private static int ToByte(double v)+ {+ int value = (int)Math.Round(v * 255.0);+ if (value < 0)+ {+ value = 0;+ }+ if (value > 255)+ {+ value = 255;+ }+ return value;+ }++ /// <summary>Converts <paramref name="c"/> to hue in degrees 0..360 (0 for greys), saturation 0..1 and value 0..1.</summary>+ private static void RgbToHsv(Color c, ref double h, ref double s, ref double v)+ {+ double r = c.R / 255.0;+ double g = c.G / 255.0;+ double b = c.B / 255.0;+ double max = Math.Max(r, Math.Max(g, b));+ double min = Math.Min(r, Math.Min(g, b));+ double delta = max - min;+ v = max;+ s = max <= 0.0 ? 0.0 : delta / max;+ if (delta <= 0.0)+ {+ h = 0.0;+ }+ else if (max == r)+ {+ h = 60.0 * ((g - b) / delta % 6.0);+ }+ else if (max == g)+ {+ h = 60.0 * ((b - r) / delta + 2.0);+ }+ else+ {+ h = 60.0 * ((r - g) / delta + 4.0);+ }+ if (h < 0.0)+ {+ h += 360.0;+ }+ }++ /// <summary>Pixel size of the cached saturation/value square; it is upscaled to <see cref="_svRect"/> when drawn.</summary>+ private const int SvResolution = 150;++ /// <summary>Bounds of the saturation/value square in client pixels.</summary>+ private readonly Rectangle _svRect;++ /// <summary>Bounds of the vertical hue strip in client pixels.</summary>+ private readonly Rectangle _hueRect;++ /// <summary>Bounds of the "New" (current colour) swatch.</summary>+ private readonly Rectangle _newRect;++ /// <summary>Bounds of the "Old" (original colour) swatch; clicking it restores the original.</summary>+ private readonly Rectangle _oldRect;++ /// <summary>"Hex" caption next to the hex box.</summary>+ private readonly Label _lblHex;++ /// <summary>Editable "#RRGGBB" box; see <see cref="HexTextChanged"/>.</summary>+ private readonly TextBox _txtHex;++ /// <summary>Read-only "R G B" decimal read-out.</summary>+ private readonly Label _lblRgb;++ /// <summary>"More..." button that opens the standard colour dialog.</summary>+ private readonly Button _btnDialog;++ /// <summary>Hue in degrees 0..360; preserved when the colour becomes grey or black.</summary>+ private double _h;++ /// <summary>Saturation 0..1.</summary>+ private double _s;++ /// <summary>Value (brightness) 0..1.</summary>+ private double _v;++ /// <summary>Current colour, always opaque.</summary>+ private Color _color;++ /// <summary>Original colour shown in the "Old" swatch, always opaque.</summary>+ private Color _original;++ /// <summary>Cached S/V square built for <see cref="_svHue"/>; null until first paint; owned and disposed here.</summary>+ private Bitmap _svBitmap;++ /// <summary>Hue the cached S/V square was built for; -1 forces a build on the first paint.</summary>+ private double _svHue;++ /// <summary>Cached 1-pixel-wide hue strip; null until first paint; owned and disposed here.</summary>+ private Bitmap _hueBitmap;++ /// <summary>Active drag target: 0 = none, 1 = S/V square, 2 = hue strip.</summary>+ private int _drag;++ /// <summary>True while <see cref="UpdateTexts"/> writes the hex box, so <see cref="HexTextChanged"/> ignores the change.</summary>+ private bool _updatingText;+ }+}diff --git a/Wave_Dude_2D/ColorScheme.cs b/Wave_Dude_2D/ColorScheme.csnew file mode 100644index 0000000..09810f2--- /dev/null+++ b/Wave_Dude_2D/ColorScheme.cs@@ -0,0 +1,300 @@+using System;+using System.Collections.Generic;+using System.Drawing;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// A 255-entry color table, optionally backed by 9 editable gradient stops.+ /// </summary>+ /// <remarks>+ /// Entry 0 is the start of the scale (field -1 / intensity 0), entry 254 the end (+1 / max), entry 127+ /// the centre of a field scheme. Instances are created by <see cref="ColorSchemeStore.Load"/> and the+ /// editor on the color scheme tab, live on the UI thread, and are turned into an <c>int[]</c> palette by+ /// <see cref="ColorLut.Build"/> before a simulation starts; the worker thread never touches them.+ /// The <see cref="Entries"/> and <see cref="Stops"/> getters return defensive copies, so the only way to+ /// change the table is <see cref="SetStop"/>. All colors are opaque RGB; alpha is ignored.+ /// </remarks>+ public class ColorScheme+ {+ /// <summary>Display name; also the JSON "name" and the basis of the file name (see <see cref="ColorSchemeStore.SafeFileName"/>).</summary>+ public string Name { get; set; }++ /// <summary>Free-text provenance of the colors (JSON "origin"), e.g. the matplotlib map it was sampled from.</summary>+ public string Origin { get; set; }++ /// <summary>Free-text grouping such as "sequential" or "custom" (JSON "category"); empty when unknown.</summary>+ public string Category { get; set; }++ /// <summary>+ /// What the scheme is meant to color: <see cref="SchemeTypeField"/>, <see cref="SchemeTypeIntensity"/>+ /// or "" when not specified. Decides which combo box on the simulation tab offers the scheme.+ /// </summary>+ public string SchemeType { get; set; }++ /// <summary>Full path of the JSON file the scheme was loaded from or last saved to; "" (or null) for an unsaved scheme.</summary>+ public string FilePath { get; set; }++ /// <summary>+ /// Creates a table-only scheme (no stops) by resampling <paramref name="colors"/> to+ /// <see cref="EntryCount"/> entries; the text properties start out empty.+ /// </summary>+ /// <param name="schemeName">Value for <see cref="Name"/>.</param>+ /// <param name="colors">At least two colors, in scale order; copied, not kept.</param>+ /// <exception cref="ArgumentNullException"><paramref name="colors"/> is null.</exception>+ /// <exception cref="ArgumentException">Fewer than two colors.</exception>+ public ColorScheme(string schemeName, IList<Color> colors)+ {+ if (colors == null)+ {+ throw new ArgumentNullException("colors");+ }+ this.Name = schemeName;+ this.Origin = "";+ this.Category = "";+ this.SchemeType = "";+ this.FilePath = "";+ this._entries = ColorScheme.Resample(colors, EntryCount);+ }++ /// <summary>A fresh copy of the full <see cref="EntryCount"/>-entry table (allocates on every call; use <see cref="GetEntry"/> in loops).</summary>+ public Color[] Entries+ {+ get+ {+ return (Color[])this._entries.Clone();+ }+ }++ /// <summary>Returns table entry <paramref name="index"/> (0..254) without copying the table.</summary>+ public Color GetEntry(int index)+ {+ return this._entries[index];+ }++ /// <summary>True when the scheme carries <see cref="StopCount"/> editable stops, i.e. <see cref="SetStop"/> may be called.</summary>+ public bool HasStops+ {+ get+ {+ return this._stops != null;+ }+ }++ /// <summary>A fresh copy of the <see cref="StopCount"/> stops, or null for a table-only scheme.</summary>+ public Color[] Stops+ {+ get+ {+ return this._stops == null ? null : (Color[])this._stops.Clone();+ }+ }++ /// <summary>Linearly interpolates between the table entries at a fractional position 0..254.</summary>+ /// <param name="position">Position on the entry scale; clamped to the first/last entry outside 0..254.</param>+ public Color SampleAt(double position)+ {+ if (position <= 0.0)+ {+ return this._entries[0];+ }+ if (position >= EntryCount - 1)+ {+ return this._entries[EntryCount - 1];+ }+ int index = (int)Math.Floor(position);+ return ColorScheme.Lerp(this._entries[index], this._entries[index + 1], position - index);+ }++ /// <summary>Returns <see cref="Name"/>, which is what the scheme combo boxes display.</summary>+ public override string ToString()+ {+ return this.Name;+ }++ /// <summary>+ /// Creates a stop scheme from exactly <see cref="StopCount"/> stops: the table is interpolated from+ /// them, <see cref="Origin"/> says it was made in the editor and <see cref="Category"/> is "custom".+ /// </summary>+ /// <exception cref="ArgumentException"><paramref name="stops"/> is null or not <see cref="StopCount"/> long.</exception>+ public static ColorScheme FromStops(string schemeName, IList<Color> stops)+ {+ ColorScheme scheme = new ColorScheme(schemeName, ColorScheme.InterpolateStops(stops));+ scheme.AttachStops(stops);+ scheme.Origin = StopCount.ToString() + "-stop gradient made in the color scheme editor";+ scheme.Category = "custom";+ return scheme;+ }++ /// <summary>+ /// Stores a copy of <paramref name="stops"/> as the editable stops without regenerating the+ /// table. Used by <see cref="ColorSchemeStore.Load"/> when a file has both "colors" and "stops", so the+ /// table may differ from the stops until the first <see cref="SetStop"/>.+ /// </summary>+ /// <exception cref="ArgumentException"><paramref name="stops"/> is null or not <see cref="StopCount"/> long.</exception>+ internal void AttachStops(IList<Color> stops)+ {+ if (stops == null || stops.Count != StopCount)+ {+ throw new ArgumentException("Exactly " + StopCount.ToString() + " stops are required.");+ }+ Color[] copy = new Color[StopCount];+ stops.CopyTo(copy, 0);+ this._stops = copy;+ }++ /// <summary>+ /// Replaces stop <paramref name="stopIndex"/> with the RGB part of <paramref name="value"/> (alpha dropped)+ /// and rebuilds the whole table from the stops.+ /// </summary>+ /// <param name="stopIndex">0..<see cref="StopCount"/>-1.</param>+ /// <param name="value">New stop color; only R, G and B are used.</param>+ /// <exception cref="InvalidOperationException">The scheme has no stops (<see cref="HasStops"/> is false).</exception>+ /// <exception cref="ArgumentOutOfRangeException"><paramref name="stopIndex"/> is outside 0..8.</exception>+ public void SetStop(int stopIndex, Color value)+ {+ if (this._stops == null)+ {+ throw new InvalidOperationException("This scheme has no editable stops. Use ToStopScheme first.");+ }+ if (stopIndex < 0 || stopIndex >= StopCount)+ {+ throw new ArgumentOutOfRangeException("stopIndex");+ }+ this._stops[stopIndex] = Color.FromArgb(value.R, value.G, value.B);+ this._entries = ColorScheme.InterpolateStops(this._stops);+ }++ /// <summary>+ /// Creates a 9-stop approximation of this scheme by sampling it at evenly spaced positions+ /// (k/8 of the 0..254 range). The result keeps this <see cref="SchemeType"/>, gets an+ /// <see cref="Origin"/> naming this scheme, <see cref="Category"/> "custom" and no file path.+ /// </summary>+ public ColorScheme ToStopScheme(string newName)+ {+ Color[] stops = new Color[StopCount];+ for (int i = 0; i < StopCount; i++)+ {+ stops[i] = this.SampleAt((i * 254) / 8.0);+ }+ ColorScheme scheme = ColorScheme.FromStops(newName, stops);+ scheme.Origin = StopCount.ToString() + "-stop copy of scheme '" + this.Name + "'";+ scheme.SchemeType = this.SchemeType;+ return scheme;+ }++ /// <summary>+ /// Deep copy with a new name: table, stops (if any), <see cref="Origin"/>, <see cref="Category"/> and+ /// <see cref="SchemeType"/> are copied; <see cref="FilePath"/> is not (the copy is "unsaved").+ /// </summary>+ public ColorScheme Clone(string newName)+ {+ ColorScheme scheme = new ColorScheme(newName, this._entries);+ scheme.Origin = this.Origin;+ scheme.Category = this.Category;+ scheme.SchemeType = this.SchemeType;+ if (this._stops != null)+ {+ scheme.AttachStops(this._stops);+ }+ return scheme;+ }++ /// <summary>Expands 9 stops into the full 255-entry table by linear RGB interpolation; stop k lands on entry k*254/8.</summary>+ /// <exception cref="ArgumentException"><paramref name="stops"/> is null or not <see cref="StopCount"/> long.</exception>+ public static Color[] InterpolateStops(IList<Color> stops)+ {+ if (stops == null || stops.Count != StopCount)+ {+ throw new ArgumentException("Exactly " + StopCount.ToString() + " stops are required.");+ }+ Color[] entries = new Color[EntryCount];+ for (int i = 0; i < EntryCount; i++)+ {+ // Position of entry i in stop units (0..8); the last entry must stay in segment 7.+ double position = (i * 8) / 254.0;+ int segment = (int)Math.Floor(position);+ if (segment > 7)+ {+ segment = 7;+ }+ entries[i] = ColorScheme.Lerp(stops[segment], stops[segment + 1], position - segment);+ }+ return entries;+ }++ /// <summary>+ /// Resamples an arbitrary-length color list to exactly <paramref name="count"/> entries by linear RGB+ /// interpolation (a plain copy when the lengths already match).+ /// </summary>+ /// <param name="source">At least two colors.</param>+ /// <param name="count">Number of entries wanted; must be at least 2.</param>+ /// <exception cref="ArgumentException"><paramref name="source"/> is null or has fewer than two colors.</exception>+ public static Color[] Resample(IList<Color> source, int count)+ {+ if (source == null || source.Count < 2)+ {+ throw new ArgumentException("A color scheme needs at least 2 colors.");+ }+ Color[] result = new Color[count];+ if (source.Count == count)+ {+ source.CopyTo(result, 0);+ return result;+ }+ for (int i = 0; i < count; i++)+ {+ double position = (double)(i * (source.Count - 1)) / (count - 1);+ int index = (int)Math.Floor(position);+ if (index >= source.Count - 1)+ {+ result[i] = source[source.Count - 1];+ }+ else+ {+ result[i] = ColorScheme.Lerp(source[index], source[index + 1], position - index);+ }+ }+ return result;+ }++ /// <summary>Per-channel linear blend of two opaque colors; <paramref name="t"/> = 0 gives <paramref name="a"/>, 1 gives <paramref name="b"/>.</summary>+ private static Color Lerp(Color a, Color b, double t)+ {+ return Color.FromArgb(ColorScheme.LerpChannel(a.R, b.R, t), ColorScheme.LerpChannel(a.G, b.G, t), ColorScheme.LerpChannel(a.B, b.B, t));+ }++ /// <summary>Blends one 0..255 channel, rounding halves away from zero and clamping to 0..255.</summary>+ private static int LerpChannel(int a, int b, double t)+ {+ int value = (int)Math.Round(a + (b - a) * t, MidpointRounding.AwayFromZero);+ if (value < 0)+ {+ value = 0;+ }+ if (value > 255)+ {+ value = 255;+ }+ return value;+ }++ /// <summary>Number of entries in the color table (indices 0..254).</summary>+ public const int EntryCount = 255;++ /// <summary>Number of editable gradient stops of a stop scheme (8 segments).</summary>+ public const int StopCount = 9;++ /// <summary>The <see cref="EntryCount"/> table entries; replaced wholesale by <see cref="SetStop"/>, never null.</summary>+ private Color[] _entries;++ /// <summary>The <see cref="StopCount"/> editable stops, or null for a table-only scheme.</summary>+ private Color[] _stops;++ /// <summary><see cref="SchemeType"/> value for schemes that color the signed field (-1..+1).</summary>+ public const string SchemeTypeField = "field";++ /// <summary><see cref="SchemeType"/> value for schemes that color the accumulated intensity (0..max).</summary>+ public const string SchemeTypeIntensity = "intensity";+ }+}diff --git a/Wave_Dude_2D/ColorSchemeStore.cs b/Wave_Dude_2D/ColorSchemeStore.csnew file mode 100644index 0000000..ee2b2ca--- /dev/null+++ b/Wave_Dude_2D/ColorSchemeStore.cs@@ -0,0 +1,393 @@+using System;+using System.Collections;+using System.Collections.Generic;+using System.Drawing;+using System.Globalization;+using System.IO;+using System.Text;+using System.Web.Script.Serialization;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Reads and writes <see cref="ColorScheme"/> objects as JSON files in the scheme folder.+ /// </summary>+ /// <remarks>+ /// Static-only helper (private constructor). File layout: an object with "name", "origin", optional+ /// "category" and "scheme_type", "bits_per_channel" (always 8), "entry_count" (255), an optional "stops"+ /// list of 9 <c>[r,g,b]</c> triplets and a "colors" list of triplets. Reading uses+ /// <see cref="JavaScriptSerializer"/>; writing emits the text by hand so the file stays human-readable.+ /// Called only from the UI thread (color scheme tab and start-up).+ /// </remarks>+ public sealed class ColorSchemeStore+ {+ /// <summary>Prevents instantiation; all members are static.</summary>+ private ColorSchemeStore()+ {+ }++ /// <summary>+ /// Returns the ColorSchemeList folder next to the executable, or the one next to the project+ /// file when running from the build output. The folder is created if it does not exist.+ /// </summary>+ /// <returns>+ /// The folder path. It walks up to five directory levels from the base directory looking for a+ /// <c>*.vbproj</c> (the original VB.NET project file) and prefers a <see cref="SchemeFolderName"/>+ /// folder beside it. Any I/O error is swallowed and the default path is returned uncreated.+ /// </returns>+ public static string FindDefaultFolder()+ {+ string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;+ string folder = Path.Combine(baseDirectory, SchemeFolderName);+ try+ {+ DirectoryInfo dir = new DirectoryInfo(baseDirectory);+ for (int level = 0; level <= 4 && dir != null; level++)+ {+ if (dir.GetFiles("*.vbproj").Length > 0)+ {+ string candidate = Path.Combine(dir.FullName, SchemeFolderName);+ if (Directory.Exists(candidate))+ {+ folder = candidate;+ }+ break;+ }+ dir = dir.Parent;+ }+ if (!Directory.Exists(folder))+ {+ Directory.CreateDirectory(folder);+ }+ }+ catch+ {+ }+ return folder;+ }++ /// <summary>+ /// Reads one scheme file. The table comes from "colors" (resampled to 255 entries) when that list has at+ /// least two entries, otherwise it is interpolated from "stops"; a "stops" list is attached as editable+ /// stops only if it has exactly <see cref="ColorScheme.StopCount"/> entries (otherwise it is ignored).+ /// "name" falls back to the file name, "scheme_type" is normalised (see <see cref="NormalizeSchemeType"/>),+ /// and <see cref="ColorScheme.FilePath"/> is set to <paramref name="filePath"/>.+ /// </summary>+ /// <param name="filePath">Full path of the JSON file.</param>+ /// <exception cref="InvalidDataException">The file is not a JSON object, has no usable color list or contains malformed triplets.</exception>+ public static ColorScheme Load(string filePath)+ {+ string json = File.ReadAllText(filePath, Encoding.UTF8);+ Dictionary<string, object> root = new JavaScriptSerializer+ {+ MaxJsonLength = int.MaxValue+ }.DeserializeObject(json) as Dictionary<string, object>;+ if (root == null)+ {+ throw new InvalidDataException("Not a color scheme file (a JSON object was expected).");+ }+ string name = ColorSchemeStore.GetString(root, "name", Path.GetFileNameWithoutExtension(filePath));+ List<Color> colors = null;+ if (root.ContainsKey("colors"))+ {+ colors = ColorSchemeStore.ParseColorList(root["colors"]);+ }+ List<Color> stops = null;+ if (root.ContainsKey("stops"))+ {+ stops = ColorSchemeStore.ParseColorList(root["stops"]);+ }+ if (stops != null && stops.Count != ColorScheme.StopCount)+ {+ stops = null;+ }+ ColorScheme scheme;+ if (colors != null && colors.Count >= 2)+ {+ scheme = new ColorScheme(name, colors);+ }+ else if (stops != null)+ {+ scheme = ColorScheme.FromStops(name, stops);+ }+ else+ {+ throw new InvalidDataException("The file contains no usable 'colors' list.");+ }+ if (stops != null)+ {+ scheme.AttachStops(stops);+ }+ scheme.Origin = ColorSchemeStore.GetString(root, "origin", scheme.Origin);+ scheme.Category = ColorSchemeStore.GetString(root, "category", scheme.Category);+ scheme.SchemeType = ColorSchemeStore.NormalizeSchemeType(ColorSchemeStore.GetString(root, "scheme_type", scheme.SchemeType));+ scheme.FilePath = filePath;+ return scheme;+ }++ /// <summary>+ /// Loads every <c>*.json</c> file in <paramref name="folder"/>, in case-insensitive file name order.+ /// Files that fail to load are skipped and reported as "file: message" lines in <paramref name="errors"/>.+ /// </summary>+ /// <param name="folder">Folder to scan; a null, empty or missing folder yields an empty list.</param>+ /// <param name="errors">Receives one line per unreadable file; may be null to discard them.</param>+ /// <returns>The schemes that loaded successfully (never null).</returns>+ public static List<ColorScheme> LoadFolder(string folder, List<string> errors)+ {+ List<ColorScheme> schemes = new List<ColorScheme>();+ if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder))+ {+ return schemes;+ }+ List<string> files = new List<string>(Directory.GetFiles(folder, "*.json"));+ files.Sort(StringComparer.OrdinalIgnoreCase);+ foreach (string file in files)+ {+ try+ {+ schemes.Add(ColorSchemeStore.Load(file));+ }+ catch (Exception ex)+ {+ if (errors != null)+ {+ errors.Add(Path.GetFileName(file) + ": " + ex.Message);+ }+ }+ }+ return schemes;+ }++ /// <summary>+ /// Writes <paramref name="scheme"/> as a UTF-8 (no BOM) JSON file, eight color triplets per line, with+ /// "category" / "scheme_type" omitted when empty and "stops" present only for stop schemes. Creates the+ /// target directory, writes to <c><filePath>.tmp</c> first and then replaces the target, and finally+ /// sets <see cref="ColorScheme.FilePath"/> on the scheme.+ /// </summary>+ /// <param name="scheme">Scheme to write.</param>+ /// <param name="filePath">Destination file path (usually from <see cref="PathFor"/>).</param>+ /// <exception cref="ArgumentNullException"><paramref name="scheme"/> is null.</exception>+ public static void Save(ColorScheme scheme, string filePath)+ {+ if (scheme == null)+ {+ throw new ArgumentNullException("scheme");+ }+ StringBuilder json = new StringBuilder();+ json.AppendLine("{");+ json.AppendLine(" \"name\": " + ColorSchemeStore.Quote(scheme.Name) + ",");+ json.AppendLine(" \"origin\": " + ColorSchemeStore.Quote(scheme.Origin) + ",");+ if (!string.IsNullOrEmpty(scheme.Category))+ {+ json.AppendLine(" \"category\": " + ColorSchemeStore.Quote(scheme.Category) + ",");+ }+ if (!string.IsNullOrEmpty(scheme.SchemeType))+ {+ json.AppendLine(" \"scheme_type\": " + ColorSchemeStore.Quote(scheme.SchemeType) + ",");+ }+ json.AppendLine(" \"bits_per_channel\": 8,");+ json.AppendLine(" \"entry_count\": " + ColorScheme.EntryCount.ToString(CultureInfo.InvariantCulture) + ",");+ if (scheme.HasStops)+ {+ List<string> stopTriplets = new List<string>();+ foreach (Color stop in scheme.Stops)+ {+ stopTriplets.Add(ColorSchemeStore.FormatRgb(stop));+ }+ json.AppendLine(" \"stops\": [" + string.Join(", ", stopTriplets) + "],");+ }+ Color[] entries = scheme.Entries;+ json.AppendLine(" \"colors\": [");+ for (int rowStart = 0; rowStart < entries.Length; rowStart += 8)+ {+ int rowEnd = Math.Min(rowStart + 7, entries.Length - 1);+ List<string> rowTriplets = new List<string>();+ for (int k = rowStart; k <= rowEnd; k++)+ {+ rowTriplets.Add(ColorSchemeStore.FormatRgb(entries[k]));+ }+ json.Append(" ");+ json.Append(string.Join(", ", rowTriplets));+ if (rowEnd < entries.Length - 1)+ {+ json.Append(",");+ }+ json.AppendLine();+ }+ json.AppendLine(" ]");+ json.AppendLine("}");+ string directoryName = Path.GetDirectoryName(filePath);+ if (!string.IsNullOrEmpty(directoryName))+ {+ Directory.CreateDirectory(directoryName);+ }+ string tempPath = filePath + ".tmp";+ File.WriteAllText(tempPath, json.ToString(), new UTF8Encoding(false));+ if (File.Exists(filePath))+ {+ File.Delete(filePath);+ }+ File.Move(tempPath, filePath);+ scheme.FilePath = filePath;+ }++ /// <summary>+ /// Turns a scheme name into a file name (without extension): invalid file name characters become+ /// '_', surrounding whitespace and trailing dots are removed.+ /// </summary>+ /// <returns>The sanitised name, or "color_scheme" when nothing usable is left.</returns>+ public static string SafeFileName(string schemeName)+ {+ if (string.IsNullOrEmpty(schemeName))+ {+ return "color_scheme";+ }+ char[] invalidChars = Path.GetInvalidFileNameChars();+ StringBuilder safeName = new StringBuilder();+ foreach (char c in schemeName.Trim())+ {+ safeName.Append(Array.IndexOf(invalidChars, c) >= 0 ? '_' : c);+ }+ string result = safeName.ToString().Trim().TrimEnd('.');+ return result.Length == 0 ? "color_scheme" : result;+ }++ /// <summary>The file path a scheme named <paramref name="schemeName"/> is stored at in <paramref name="folder"/>: <see cref="SafeFileName"/> plus ".json".</summary>+ public static string PathFor(string folder, string schemeName)+ {+ return Path.Combine(folder, ColorSchemeStore.SafeFileName(schemeName) + ".json");+ }++ /// <summary>Maps a raw "scheme_type" value to <see cref="ColorScheme.SchemeTypeField"/> or <see cref="ColorScheme.SchemeTypeIntensity"/> (trimmed, case-insensitive); anything else, including null, becomes "".</summary>+ private static string NormalizeSchemeType(string value)+ {+ if (value == null)+ {+ return "";+ }+ string normalized = value.Trim().ToLowerInvariant();+ if (normalized == ColorScheme.SchemeTypeField || normalized == ColorScheme.SchemeTypeIntensity)+ {+ return normalized;+ }+ return "";+ }++ /// <summary>+ /// Reads <paramref name="key"/> from the JSON object as a string (non-string scalars are converted with+ /// the invariant culture), or <paramref name="fallback"/> when the key is missing or null.+ /// </summary>+ private static string GetString(Dictionary<string, object> root, string key, string fallback)+ {+ object value;+ if (root.TryGetValue(key, out value) && value != null)+ {+ return Convert.ToString(value, CultureInfo.InvariantCulture);+ }+ return fallback;+ }++ /// <summary>+ /// Converts a deserialised JSON list of <c>[r,g,b]</c> lists into colors. Each inner list needs at least+ /// three numbers (extra values are ignored); non-integers are rounded and every channel is clamped to+ /// 0..255. Strings are rejected even though they enumerate as characters.+ /// </summary>+ /// <param name="node">The value of "colors" or "stops" as returned by <see cref="JavaScriptSerializer"/>.</param>+ /// <exception cref="InvalidDataException">The node or one of its items is not a list, or a triplet is too short.</exception>+ private static List<Color> ParseColorList(object node)+ {+ IEnumerable items = node as IEnumerable;+ if (items == null || node is string)+ {+ throw new InvalidDataException("Expected a list of [r,g,b] triplets.");+ }+ List<Color> colors = new List<Color>();+ foreach (object item in items)+ {+ IEnumerable channels = item as IEnumerable;+ if (channels == null || item is string)+ {+ throw new InvalidDataException("Expected a list of [r,g,b] triplets.");+ }+ List<int> values = new List<int>();+ foreach (object channel in channels)+ {+ values.Add(Convert.ToInt32(channel, CultureInfo.InvariantCulture));+ }+ if (values.Count < 3)+ {+ throw new InvalidDataException("A color needs three values [r,g,b].");+ }+ colors.Add(Color.FromArgb(ColorSchemeStore.Clamp255(values[0]), ColorSchemeStore.Clamp255(values[1]), ColorSchemeStore.Clamp255(values[2])));+ }+ return colors;+ }++ /// <summary>Clamps a channel value to 0..255.</summary>+ private static int Clamp255(int v)+ {+ if (v < 0)+ {+ return 0;+ }+ if (v > 255)+ {+ return 255;+ }+ return v;+ }++ /// <summary>Formats a color as the JSON triplet <c>[r,g,b]</c> (no spaces, alpha dropped).</summary>+ private static string FormatRgb(Color c)+ {+ return string.Format(CultureInfo.InvariantCulture, "[{0},{1},{2}]", c.R, c.G, c.B);+ }++ /// <summary>Returns <paramref name="text"/> as a double-quoted JSON string literal (null becomes <c>""</c>); escapes quotes, backslashes and control characters, leaves non-ASCII as UTF-8.</summary>+ private static string Quote(string text)+ {+ if (text == null)+ {+ return "\"\"";+ }+ StringBuilder quoted = new StringBuilder();+ quoted.Append('"');+ foreach (char c in text)+ {+ switch (c)+ {+ case '"':+ quoted.Append("\\\"");+ break;+ case '\\':+ quoted.Append("\\\\");+ break;+ case '\t':+ quoted.Append("\\t");+ break;+ case '\n':+ quoted.Append("\\n");+ break;+ case '\r':+ quoted.Append("\\r");+ break;+ default:+ if (c < ' ')+ {+ quoted.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));+ }+ else+ {+ quoted.Append(c);+ }+ break;+ }+ }+ quoted.Append('"');+ return quoted.ToString();+ }++ /// <summary>Name of the scheme folder looked for next to the executable / project: "ColorSchemeList".</summary>+ public const string SchemeFolderName = "ColorSchemeList";+ }+}diff --git a/Wave_Dude_2D/Form1.Colors.cs b/Wave_Dude_2D/Form1.Colors.csnew file mode 100644index 0000000..e80b41d--- /dev/null+++ b/Wave_Dude_2D/Form1.Colors.cs@@ -0,0 +1,745 @@+using System;+using System.Collections.Generic;+using System.Drawing;+using System.Drawing.Drawing2D;+using System.Drawing.Imaging;+using System.IO;+using System.Windows.Forms;+using Microsoft.VisualBasic;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Color scheme tab: scheme list, stop editor and preview bar.+ /// </summary>+ /// <remarks>+ /// Two schemes matter here: <c>_previewScheme</c> is the (read-only) list selection and <c>_current</c>+ /// is the editable copy loaded from it. The editor always shows the preview when one is selected,+ /// otherwise the current scheme (<see cref="DisplayedScheme"/>). Everything in this file runs on+ /// the UI thread; the simulation never sees these objects, only the <see cref="ColorLut"/> built+ /// from them when a run starts.+ /// </remarks>+ public partial class Form1+ {+ /// <summary>Lets the user pick a scheme folder in a folder dialog and reloads the list from it.</summary>+ private void btbChooseFFolder_Click(object sender, EventArgs e)+ {+ using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())+ {+ folderBrowserDialog.Description = "Choose the folder that contains the color scheme (.json) files";+ if (Directory.Exists(this.txtSchemeFolder.Text))+ {+ folderBrowserDialog.SelectedPath = this.txtSchemeFolder.Text;+ }+ if (folderBrowserDialog.ShowDialog(this) == DialogResult.OK)+ {+ this.txtSchemeFolder.Text = folderBrowserDialog.SelectedPath;+ this.LoadSchemeList();+ }+ }+ }++ /// <summary>Enter in the folder box reloads the scheme list from the typed folder (and swallows the beep).</summary>+ private void txtSchemeFolder_KeyDown(object sender, KeyEventArgs e)+ {+ if (e.KeyCode == Keys.Return)+ {+ e.SuppressKeyPress = true;+ this.LoadSchemeList();+ }+ }++ /// <summary>+ /// Reloads all scheme files from the folder in <c>txtSchemeFolder</c> and rebuilds the list view.+ /// Also sorts by the current column, regenerates the thumbnails (disposing the old bitmaps),+ /// refills the field/intensity combo boxes on the simulation tab, reports unreadable files in one+ /// message box and clears the preview selection. The current (editable) scheme is left alone.+ /// </summary>+ private void LoadSchemeList()+ {+ string folder = this.txtSchemeFolder.Text.Trim();+ if (!Directory.Exists(folder))+ {+ MessageBox.Show(this, "The folder '" + folder + "' does not exist.", "Color schemes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ return;+ }+ List<string> errors = new List<string>();+ this._schemes = ColorSchemeStore.LoadFolder(folder, errors);+ this.SortSchemes(this._schemes, this._schemeSortColumn, this._schemeSortAscending);+ this.ListView1.BeginUpdate();+ try+ {+ this.ListView1.Items.Clear();+ this._thumbs.Images.Clear();+ foreach (Bitmap thumb in this._thumbBitmaps)+ {+ thumb.Dispose();+ }+ this._thumbBitmaps.Clear();+ foreach (ColorScheme scheme in this._schemes)+ {+ Bitmap thumb = Form1.MakeThumbnail(scheme);+ this._thumbBitmaps.Add(thumb);+ this._thumbs.Images.Add(thumb);+ ListViewItem item = new ListViewItem(scheme.Name, this._thumbs.Images.Count - 1);+ item.SubItems.Add(scheme.HasStops ? (ColorScheme.StopCount.ToString() + "-stop") : "table");+ item.SubItems.Add(string.IsNullOrEmpty(scheme.SchemeType) ? "-" : scheme.SchemeType);+ item.Tag = scheme;+ this.ListView1.Items.Add(item);+ }+ }+ finally+ {+ this.ListView1.EndUpdate();+ }+ this.UpdateSchemeListSortHeaders();+ if (errors.Count > 0)+ {+ // Show at most 8 file errors; the rest is summarised as a count.+ int shown = Math.Min(errors.Count, 8);+ string message = string.Join("\r\n", errors.GetRange(0, shown));+ if (errors.Count > shown)+ {+ message = message + "\r\n... and " + (errors.Count - shown).ToString() + " more";+ }+ MessageBox.Show(this, "Some files could not be read as color schemes:\r\n\r\n" + message, "Color schemes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ }+ this.RefreshSchemeCombos();+ this._previewScheme = null;+ this.RefreshEditorState();+ }++ /// <summary>+ /// Sorts <paramref name="schemes"/> in place, case-insensitively: column 0 by name, any other+ /// column by scheme type and then name. <paramref name="ascending"/> false reverses the result.+ /// </summary>+ /// <param name="schemes">The list to sort.</param>+ /// <param name="sortColumn">List view column index; 0 = name, otherwise type then name.</param>+ /// <param name="ascending">False reverses the sorted order.</param>+ private void SortSchemes(List<ColorScheme> schemes, int sortColumn, bool ascending)+ {+ if (sortColumn == 0)+ {+ schemes.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));+ }+ else+ {+ schemes.Sort((a, b) =>+ {+ int byType = string.Compare(a.SchemeType, b.SchemeType, StringComparison.OrdinalIgnoreCase);+ return byType != 0 ? byType : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);+ });+ }+ if (!ascending)+ {+ schemes.Reverse();+ }+ }++ /// <summary>+ /// Clicking the Scheme (0) or Type (2) header sorts by that column, or flips the direction when it+ /// is already the sort column; the Kind column is ignored. Sorting re-reads the folder from disk.+ /// </summary>+ private void ListView1_ColumnClick(object sender, ColumnClickEventArgs e)+ {+ if (e.Column != 0 && e.Column != 2)+ {+ return;+ }+ if (e.Column == this._schemeSortColumn)+ {+ this._schemeSortAscending = !this._schemeSortAscending;+ }+ else+ {+ this._schemeSortColumn = e.Column;+ this._schemeSortAscending = true;+ }+ this.LoadSchemeList();+ }++ /// <summary>Appends a " ^" / " v" direction marker to the header of the column the list is sorted by.</summary>+ private void UpdateSchemeListSortHeaders()+ {+ if (this.ListView1.Columns.Count < 3)+ {+ return;+ }+ string arrow = this._schemeSortAscending ? " ^" : " v";+ this.ListView1.Columns[0].Text = "Scheme" + (this._schemeSortColumn == 0 ? arrow : "");+ this.ListView1.Columns[2].Text = "Type" + (this._schemeSortColumn == 2 ? arrow : "");+ }++ /// <summary>Selecting a list row previews that scheme in the editor; clearing the selection shows the current scheme again.</summary>+ private void ListView1_SelectedIndexChanged(object sender, EventArgs e)+ {+ this._previewScheme = this.ListView1.SelectedItems.Count == 0 ? null : (ColorScheme)this.ListView1.SelectedItems[0].Tag;+ this.RefreshEditorState();+ }++ /// <summary>Double-clicking a row loads it as the current scheme.</summary>+ private void ListView1_DoubleClick(object sender, EventArgs e)+ {+ this.LoadPreviewedScheme();+ }++ /// <summary>Loads the previewed scheme as the current one, or asks the user to select a row first.</summary>+ private void btnLoadScheme_Click(object sender, EventArgs e)+ {+ if (this._previewScheme == null)+ {+ MessageBox.Show(this, "Select a scheme in the list first.", "Load scheme", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ }+ else+ {+ this.LoadPreviewedScheme();+ }+ }++ /// <summary>Escape in the list clears the selection, which ends the preview.</summary>+ private void ListView1_KeyDown(object sender, KeyEventArgs e)+ {+ if (e.KeyCode == Keys.Escape)+ {+ this.ListView1.SelectedItems.Clear();+ e.Handled = true;+ }+ }++ /// <summary>+ /// Makes a copy of the previewed scheme the current (editable) one, after asking to discard unsaved+ /// changes. The copy keeps the file path of the original (<see cref="ColorScheme.Clone"/> does not),+ /// so a later Save overwrites that file. Clears the stop selection and the list selection.+ /// </summary>+ /// <returns>False if there is no preview or the user kept the unsaved current scheme.</returns>+ private bool LoadPreviewedScheme()+ {+ if (this._previewScheme == null)+ {+ return false;+ }+ if (!this.ConfirmDiscardChanges())+ {+ return false;+ }+ ColorScheme previewScheme = this._previewScheme;+ this._current = previewScheme.Clone(previewScheme.Name);+ this._current.FilePath = previewScheme.FilePath;+ this._dirty = false;+ this._selectedStop = -1;+ this.ListView1.SelectedItems.Clear();+ this.RefreshEditorState();+ return true;+ }++ /// <summary>Asks whether unsaved edits of the current scheme may be thrown away.</summary>+ /// <returns>True if there are no unsaved changes or the user answered Yes.</returns>+ private bool ConfirmDiscardChanges()+ {+ if (!this._dirty)+ {+ return true;+ }+ DialogResult answer = MessageBox.Show(this, "The current color scheme '" + this._current.Name + "' has unsaved changes. Discard them?", "Unsaved changes", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);+ return answer == DialogResult.Yes;+ }++ /// <summary>+ /// Clicking one of the nine Color buttons selects that stop for editing and loads its color into the+ /// picker. While previewing, the preview is first loaded as the current scheme (may be cancelled).+ /// A table-only scheme is converted to an unsaved 9-stop approximation after confirmation.+ /// </summary>+ private void StopButton_Click(object sender, EventArgs e)+ {+ int stopIndex = Array.IndexOf(this._stopButtons, (Button)sender);+ if (stopIndex < 0)+ {+ return;+ }+ if (this._previewScheme != null && !this.LoadPreviewedScheme())+ {+ return;+ }+ if (this._current == null)+ {+ return;+ }+ if (!this._current.HasStops)+ {+ DialogResult answer = MessageBox.Show(this, "The scheme '" + this._current.Name + "' is a full table of 255 colors without " + ColorScheme.StopCount.ToString() + " editable stops.\r\n\r\nEditing it creates a smooth " + ColorScheme.StopCount.ToString() + "-stop approximation as a new, unsaved scheme (the original file stays unchanged). Continue?", "Edit scheme", MessageBoxButtons.YesNo, MessageBoxIcon.Question);+ if (answer != DialogResult.Yes)+ {+ return;+ }+ this._current = this._current.ToStopScheme(this._current.Name + " (" + ColorScheme.StopCount.ToString() + "-stop)");+ this._dirty = true;+ }+ this._selectedStop = stopIndex;+ Color color = this._current.Stops[stopIndex];+ this._picker.OriginalColor = color;+ this._picker.SelectedColor = color;+ this.RefreshEditorState();+ }++ /// <summary>+ /// A color change in the picker writes the new color into the selected stop of the current scheme+ /// (which regenerates its whole table), marks it dirty and repaints. Raised by+ /// <see cref="ColorPickerControl.ColorChanged"/>; ignored when no editable stop is selected.+ /// </summary>+ private void Picker_ColorChanged(object sender, EventArgs e)+ {+ if (this._current == null || !this._current.HasStops || this._selectedStop < 0)+ {+ return;+ }+ this._current.SetStop(this._selectedStop, this._picker.SelectedColor);+ this._dirty = true;+ this.RefreshEditorState();+ }++ /// <summary>+ /// Saves the current scheme to its own file, or behaves like Save As when it has never been saved.+ /// Reloads the list afterwards so the list reflects the file.+ /// </summary>+ private void btnSaveCurrentScheme_Click(object sender, EventArgs e)+ {+ if (this._current == null)+ {+ return;+ }+ if (string.IsNullOrEmpty(this._current.FilePath))+ {+ this.SaveAsNew();+ return;+ }+ try+ {+ ColorSchemeStore.Save(this._current, this._current.FilePath);+ this._dirty = false;+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The scheme could not be saved:\r\n" + ex.Message, "Save scheme", MessageBoxButtons.OK, MessageBoxIcon.Hand);+ return;+ }+ this.ReloadListAfterSave();+ }++ /// <summary>Saves the current scheme under a new name (see <see cref="SaveAsNew"/>).</summary>+ private void btnSaveAsColorScheme_Click(object sender, EventArgs e)+ {+ this.SaveAsNew();+ }++ /// <summary>+ /// Asks for a name (VB <see cref="Interaction.InputBox"/>), writes a copy of the current scheme as+ /// <c><folder>/<safe name>.json</c> in the scheme folder (confirming an overwrite) and makes+ /// that copy the current scheme. A stop scheme without a category is saved as "custom".+ /// </summary>+ private void SaveAsNew()+ {+ if (this._current == null)+ {+ return;+ }+ string folder = this.txtSchemeFolder.Text.Trim();+ if (!Directory.Exists(folder))+ {+ MessageBox.Show(this, "Choose an existing scheme folder first.", "Save scheme", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ string newName = Interaction.InputBox("Name for the new color scheme:", "Save as new scheme", this._current.Name, -1, -1).Trim();+ if (newName.Length == 0)+ {+ return;+ }+ string targetPath = ColorSchemeStore.PathFor(folder, newName);+ if (File.Exists(targetPath))+ {+ DialogResult answer = MessageBox.Show(this, "A scheme file named '" + Path.GetFileName(targetPath) + "' already exists. Overwrite it?", "Save scheme", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);+ if (answer != DialogResult.Yes)+ {+ return;+ }+ }+ try+ {+ ColorScheme copy = this._current.Clone(newName);+ if (copy.HasStops && string.IsNullOrEmpty(copy.Category))+ {+ copy.Category = "custom";+ }+ ColorSchemeStore.Save(copy, targetPath);+ this._current = copy;+ this._dirty = false;+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The scheme could not be saved:\r\n" + ex.Message, "Save scheme", MessageBoxButtons.OK, MessageBoxIcon.Hand);+ return;+ }+ this.ReloadListAfterSave();+ }++ /// <summary>Re-reads the scheme folder after a save so the list and combo boxes show the new file.</summary>+ private void ReloadListAfterSave()+ {+ this.LoadSchemeList();+ }++ /// <summary>+ /// Renames the previewed scheme: prompts for a new name, saves the scheme under the new file name,+ /// deletes the old file and, if the current scheme was loaded from that file, renames it too.+ /// Refuses to overwrite a different existing file. Reloads the list and reselects the renamed row.+ /// </summary>+ private void btnRenameColorScheme_Click(object sender, EventArgs e)+ {+ if (this._previewScheme == null)+ {+ MessageBox.Show(this, "Select a scheme in the list first.", "Rename color scheme", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ ColorScheme previewScheme = this._previewScheme;+ string oldName = previewScheme.Name;+ string oldPath = previewScheme.FilePath;+ string newName = oldName;+ if (!this.PromptForText("Rename color scheme", "New name for '" + oldName + "':", oldName, ref newName))+ {+ return;+ }+ newName = newName.Trim();+ if (newName.Length == 0 || newName == oldName)+ {+ return;+ }+ string folder = string.IsNullOrEmpty(oldPath) ? this.txtSchemeFolder.Text.Trim() : Path.GetDirectoryName(oldPath);+ string newPath = ColorSchemeStore.PathFor(folder, newName);+ if (!string.Equals(newPath, oldPath, StringComparison.OrdinalIgnoreCase) && File.Exists(newPath))+ {+ MessageBox.Show(this, "A scheme file named '" + Path.GetFileName(newPath) + "' already exists.", "Rename color scheme", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ return;+ }+ try+ {+ previewScheme.Name = newName;+ ColorSchemeStore.Save(previewScheme, newPath);+ if (!string.IsNullOrEmpty(oldPath) && !string.Equals(oldPath, newPath, StringComparison.OrdinalIgnoreCase) && File.Exists(oldPath))+ {+ File.Delete(oldPath);+ }+ if (this._current != null && !string.IsNullOrEmpty(oldPath) && string.Equals(this._current.FilePath, oldPath, StringComparison.OrdinalIgnoreCase))+ {+ this._current.Name = newName;+ this._current.FilePath = newPath;+ }+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The scheme could not be renamed:\r\n" + ex.Message, "Rename color scheme", MessageBoxButtons.OK, MessageBoxIcon.Hand);+ return;+ }+ this.LoadSchemeList();+ this.SelectSchemeInList(newName);+ this.ToolStripStatusLabel1.Text = "Color scheme '" + oldName + "' renamed to '" + newName + "'.";+ }++ /// <summary>+ /// Deletes the previewed scheme's file from disk after confirmation. If the current scheme came from+ /// that file it stays loaded but loses its path (the next Save becomes Save As). Reloads the list.+ /// </summary>+ private void btnDeleteColorScheme_Click(object sender, EventArgs e)+ {+ if (this._previewScheme == null)+ {+ MessageBox.Show(this, "Select a scheme in the list first.", "Delete color scheme", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ ColorScheme previewScheme = this._previewScheme;+ string name = previewScheme.Name;+ string filePath = previewScheme.FilePath;+ if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))+ {+ MessageBox.Show(this, "That scheme has no file on disk (nothing to delete).", "Delete color scheme", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ DialogResult answer = MessageBox.Show(this, "Permanently delete the color scheme '" + name + "'?\r\n\r\n" + filePath, "Delete color scheme", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);+ if (answer != DialogResult.Yes)+ {+ return;+ }+ try+ {+ File.Delete(filePath);+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The scheme could not be deleted:\r\n" + ex.Message, "Delete color scheme", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ return;+ }+ if (this._current != null && string.Equals(this._current.FilePath, filePath, StringComparison.OrdinalIgnoreCase))+ {+ this._current.FilePath = null;+ }+ this._previewScheme = null;+ this.LoadSchemeList();+ this.ToolStripStatusLabel1.Text = "Color scheme '" + name + "' deleted.";+ }++ /// <summary>Selects and scrolls to the first list row whose scheme name matches <paramref name="name"/> (case-insensitive); does nothing if there is none.</summary>+ private void SelectSchemeInList(string name)+ {+ foreach (ListViewItem item in this.ListView1.Items)+ {+ ColorScheme scheme = item.Tag as ColorScheme;+ if (scheme != null && string.Equals(scheme.Name, name, StringComparison.OrdinalIgnoreCase))+ {+ item.Selected = true;+ item.EnsureVisible();+ break;+ }+ }+ }++ /// <summary>+ /// Checking the "field" or "intensity" radio button changes the type of the current scheme and marks it+ /// dirty. Ignored while <see cref="RefreshEditorState"/> is setting the radios programmatically+ /// (<c>_updatingRadios</c>), while previewing, and for the radio that just became unchecked.+ /// </summary>+ private void SchemeType_CheckedChanged(object sender, EventArgs e)+ {+ if (this._updatingRadios)+ {+ return;+ }+ if (this._current == null || this._previewScheme != null)+ {+ return;+ }+ RadioButton radio = (RadioButton)sender;+ if (!radio.Checked)+ {+ return;+ }+ string schemeType = radio == this.radSchemeTypeField ? ColorScheme.SchemeTypeField : ColorScheme.SchemeTypeIntensity;+ if (this._current.SchemeType != schemeType)+ {+ this._current.SchemeType = schemeType;+ this._dirty = true;+ this.RefreshEditorState();+ }+ }++ /// <summary>The scheme shown in the editor: the previewed list selection if any, otherwise the current one.</summary>+ /// <returns>Null when nothing is previewed and no scheme has been loaded.</returns>+ private ColorScheme DisplayedScheme()+ {+ return this._previewScheme ?? this._current;+ }++ /// <summary>+ /// Brings every editor control in line with the current/preview state: name box (with an+ /// "(unsaved changes)" suffix), the nine stop buttons (color, contrasting text, thick border on the+ /// selected stop), picker enabling and caption, Load/Save button enabling, the type radios (set with+ /// <c>_updatingRadios</c> raised so <see cref="SchemeType_CheckedChanged"/> ignores it) and finally a+ /// repaint of the preview bar.+ /// </summary>+ private void RefreshEditorState()+ {+ bool previewing = this._previewScheme != null;+ ColorScheme scheme = this.DisplayedScheme();+ bool hasCurrent = this._current != null;+ bool editingStop = hasCurrent && !previewing && this._selectedStop >= 0;+ if (hasCurrent)+ {+ this.txtCurrentColorScheme.Text = this._current.Name + (this._dirty ? " (unsaved changes)" : "");+ }+ else+ {+ this.txtCurrentColorScheme.Text = "(none loaded)";+ }+ for (int k = 0; k < ColorScheme.StopCount; k++)+ {+ Button button = this._stopButtons[k];+ button.Enabled = scheme != null;+ if (scheme != null)+ {+ Color color = Form1.StopColorOf(scheme, k);+ button.BackColor = color;+ button.ForeColor = Form1.ContrastColor(color);+ }+ else+ {+ button.BackColor = SystemColors.Control;+ button.ForeColor = SystemColors.ControlText;+ }+ button.FlatAppearance.BorderSize = (editingStop && k == this._selectedStop) ? 4 : 1;+ }+ this._picker.Enabled = editingStop;+ if (editingStop)+ {+ this.lblColorPicker.Text = "Color Picker - editing Color " + (this._selectedStop + 1).ToString() + Form1.StopRole(this._selectedStop);+ }+ else+ {+ this.lblColorPicker.Text = "Color Picker (click a Color button to edit it)";+ }+ this.btnLoadScheme.Enabled = previewing;+ this.btnSaveCurrentScheme.Enabled = hasCurrent && this._dirty;+ this.btnSaveAsColorScheme.Enabled = hasCurrent;+ this._updatingRadios = true;+ try+ {+ string schemeType = scheme == null ? "" : scheme.SchemeType;+ this.radSchemeTypeField.Checked = schemeType == ColorScheme.SchemeTypeField;+ this.radSchemeTypeIntensity.Checked = schemeType == ColorScheme.SchemeTypeIntensity;+ this.radSchemeTypeField.Enabled = hasCurrent && !previewing;+ this.radSchemeTypeIntensity.Enabled = hasCurrent && !previewing;+ }+ finally+ {+ this._updatingRadios = false;+ }+ this.pnlScheme.Invalidate();+ }++ /// <summary>+ /// Paints the vertical preview bar: entry 0 at the top, entry 254 at the bottom, stretched from a+ /// 1x255 strip without smoothing; white-on-black tick marks at the nine stop positions (a full-width+ /// thick line for the stop being edited) and the scale labels for the scheme type ("-1 / 0 / +1" for+ /// field, "0 / max" for intensity). A plain light fill when there is nothing to show.+ /// </summary>+ private void pnlScheme_Paint(object sender, PaintEventArgs e)+ {+ ColorScheme scheme = this.DisplayedScheme();+ Graphics g = e.Graphics;+ Rectangle bar = this.pnlScheme.ClientRectangle;+ if (scheme == null)+ {+ g.Clear(SystemColors.ControlLight);+ return;+ }+ using (Bitmap strip = new Bitmap(1, ColorScheme.EntryCount, PixelFormat.Format32bppArgb))+ {+ for (int i = 0; i < ColorScheme.EntryCount; i++)+ {+ strip.SetPixel(0, i, scheme.GetEntry(i));+ }+ g.InterpolationMode = InterpolationMode.NearestNeighbor;+ g.PixelOffsetMode = PixelOffsetMode.Half;+ g.DrawImage(strip, bar);+ }+ bool editingStop = this._previewScheme == null && this._selectedStop >= 0;+ for (int k = 0; k < ColorScheme.StopCount; k++)+ {+ // Stop k sits at fraction k/8 of the bar height (9 stops = 8 segments).+ int y = (int)Math.Round((k * (bar.Height - 1)) / 8.0);+ bool highlighted = editingStop && k == this._selectedStop;+ int tickLength = highlighted ? bar.Width : 9;+ int tickWidth = highlighted ? 3 : 1;+ using (Pen outline = new Pen(Color.Black, tickWidth + 2))+ {+ g.DrawLine(outline, 0, y, tickLength, y);+ g.DrawLine(outline, bar.Width - tickLength, y, bar.Width, y);+ }+ using (Pen tick = new Pen(Color.White, tickWidth))+ {+ g.DrawLine(tick, 0, y, tickLength, y);+ g.DrawLine(tick, bar.Width - tickLength, y, bar.Width, y);+ }+ }+ if (scheme.SchemeType == ColorScheme.SchemeTypeField)+ {+ this.DrawScaleLabel(g, bar, "-1", 0, scheme);+ this.DrawScaleLabel(g, bar, "0", 127, scheme);+ this.DrawScaleLabel(g, bar, "+1", 254, scheme);+ }+ else if (scheme.SchemeType == ColorScheme.SchemeTypeIntensity)+ {+ this.DrawScaleLabel(g, bar, "0", 0, scheme);+ this.DrawScaleLabel(g, bar, "max", 254, scheme);+ }+ }++ /// <summary>+ /// Draws <paramref name="text"/> horizontally centred on the preview bar at the height of table entry+ /// <paramref name="entryIndex"/> (0..254 mapped onto the bar height), kept at least 12 px away from the+ /// top and bottom edges, in black or white depending on the entry color underneath.+ /// </summary>+ /// <param name="g">Target graphics of the preview panel.</param>+ /// <param name="bar">Client rectangle of the preview panel.</param>+ /// <param name="text">Label text.</param>+ /// <param name="entryIndex">Table entry (0..254) whose vertical position the label is centred on.</param>+ /// <param name="scheme">Scheme being painted; used only to pick a contrasting text color.</param>+ private void DrawScaleLabel(Graphics g, Rectangle bar, string text, int entryIndex, ColorScheme scheme)+ {+ Size textSize = TextRenderer.MeasureText(g, text, this.pnlScheme.Font);+ int centerY = (int)Math.Round((entryIndex * (bar.Height - 1)) / 254.0);+ int top = centerY - textSize.Height / 2;+ if (top < 12)+ {+ top = 12;+ }+ if (top + textSize.Height > bar.Height - 12)+ {+ top = bar.Height - 12 - textSize.Height;+ }+ Rectangle labelBounds = new Rectangle(0, top, bar.Width, textSize.Height);+ TextRenderer.DrawText(g, text, this.pnlScheme.Font, labelBounds, Form1.ContrastColor(scheme.GetEntry(entryIndex)), TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);+ }++ /// <summary>+ /// Color shown on stop button <paramref name="k"/>: the real stop for a stop scheme, otherwise the table+ /// sampled at the position the stop would have (k/8 of the 0..254 range).+ /// </summary>+ private static Color StopColorOf(ColorScheme scheme, int k)+ {+ return scheme.HasStops ? scheme.Stops[k] : scheme.SampleAt((k * 254) / 8.0);+ }++ /// <summary>Suffix for the picker caption describing what stop <paramref name="k"/> represents (first, centre, last); empty for the others.</summary>+ private static string StopRole(int k)+ {+ switch (k)+ {+ case 0:+ return " (start of the scale)";+ case 8:+ return " (end of the scale)";+ case 4:+ return " (centre = zero field)";+ default:+ return "";+ }+ }++ /// <summary>Black or white, whichever reads better on top of <paramref name="c"/> (Rec. 601 luma, threshold 140 of 255).</summary>+ private static Color ContrastColor(Color c)+ {+ double luma = 0.299 * c.R + 0.587 * c.G + 0.114 * c.B;+ return luma > 140.0 ? Color.Black : Color.White;+ }++ /// <summary>+ /// Renders a 120x16 horizontal strip of the scheme (entry 0 left, 254 right) with a gray border, for the+ /// list view image list. The caller owns the returned bitmap; <see cref="LoadSchemeList"/> keeps them in+ /// <c>_thumbBitmaps</c> and disposes them on the next reload.+ /// </summary>+ private static Bitmap MakeThumbnail(ColorScheme scheme)+ {+ Bitmap thumb = new Bitmap(120, 16, PixelFormat.Format32bppArgb);+ using (Graphics g = Graphics.FromImage(thumb))+ {+ for (int x = 0; x < 120; x++)+ {+ int entryIndex = (int)Math.Round((x * 254) / 119.0);+ using (SolidBrush brush = new SolidBrush(scheme.GetEntry(entryIndex)))+ {+ g.FillRectangle(brush, x, 0, 1, 16);+ }+ }+ g.DrawRectangle(Pens.Gray, 0, 0, 119, 15);+ }+ return thumb;+ }+ }+}diff --git a/Wave_Dude_2D/Form1.Designer.cs b/Wave_Dude_2D/Form1.Designer.csnew file mode 100644index 0000000..69f4d34--- /dev/null+++ b/Wave_Dude_2D/Form1.Designer.cs@@ -0,0 +1,3563 @@+using System;+using System.ComponentModel;+using System.Windows.Forms;++namespace _2D_wave_sim_V01+{+ public partial class Form1 : global::System.Windows.Forms.Form+ {+ /// <summary>Releases the designer-managed components when <paramref name="disposing"/> is true, then the form itself.</summary>+ /// <param name="disposing">True when called from <see cref="System.ComponentModel.Component.Dispose()"/>; false from the finalizer.</param>+ [global::System.Diagnostics.DebuggerNonUserCode]+ protected override void Dispose(bool disposing)+ {+ try+ {+ bool flag = disposing && this.components != null;+ if (flag)+ {+ this.components.Dispose();+ }+ }+ finally+ {+ base.Dispose(disposing);+ }+ }++ [global::System.Diagnostics.DebuggerStepThrough]+ private void InitializeComponent()+ {+ global::System.ComponentModel.ComponentResourceManager componentResourceManager = new global::System.ComponentModel.ComponentResourceManager(typeof(global::_2D_wave_sim_V01.Form1));+ this.tabMainFunctions = new global::System.Windows.Forms.TabControl();+ this.tabConfiguration = new global::System.Windows.Forms.TabPage();+ this.grpProjects = new global::System.Windows.Forms.GroupBox();+ this.btnPickRoot = new global::System.Windows.Forms.Button();+ this.btnSaveConfiguration2 = new global::System.Windows.Forms.Button();+ this.lstAllProjects = new global::System.Windows.Forms.ListView();+ this.colProjectName = new global::System.Windows.Forms.ColumnHeader();+ this.colLastEdit = new global::System.Windows.Forms.ColumnHeader();+ this.btnNewProject = new global::System.Windows.Forms.Button();+ this.btnRenameProject = new global::System.Windows.Forms.Button();+ this.btnLoadProject = new global::System.Windows.Forms.Button();+ this.btnDeleteProject = new global::System.Windows.Forms.Button();+ this.btnSaveAs = new global::System.Windows.Forms.Button();+ this.grpSimulationSettings = new global::System.Windows.Forms.GroupBox();+ this.Label61 = new global::System.Windows.Forms.Label();+ this.numTimeDecayFactor = new global::System.Windows.Forms.NumericUpDown();+ this.numSimulationSteps = new global::System.Windows.Forms.NumericUpDown();+ this.lblInfo = new global::System.Windows.Forms.Label();+ this.chkUse4thOrderLaplacian = new global::System.Windows.Forms.CheckBox();+ this.chkUseGPU = new global::System.Windows.Forms.CheckBox();+ this.numQuality = new global::System.Windows.Forms.NumericUpDown();+ this.lblVideoQuality = new global::System.Windows.Forms.Label();+ this.numIntensityScaling = new global::System.Windows.Forms.NumericUpDown();+ this.numOffsetIntensity = new global::System.Windows.Forms.NumericUpDown();+ this.numOffsetField = new global::System.Windows.Forms.NumericUpDown();+ this.numFieldScaling = new global::System.Windows.Forms.NumericUpDown();+ this.Label3 = new global::System.Windows.Forms.Label();+ this.numScaleIntensityValues = new global::System.Windows.Forms.Label();+ this.Label6 = new global::System.Windows.Forms.Label();+ this.lblOffsetField = new global::System.Windows.Forms.Label();+ this.Label5 = new global::System.Windows.Forms.Label();+ this.Label2 = new global::System.Windows.Forms.Label();+ this.cmbIntensityColorScheme = new global::System.Windows.Forms.ComboBox();+ this.cmbFieldColorScheme = new global::System.Windows.Forms.ComboBox();+ this.chkPreviewVideoIntensity = new global::System.Windows.Forms.CheckBox();+ this.chkExportVideoIntensity = new global::System.Windows.Forms.CheckBox();+ this.chkPreviewVideoField = new global::System.Windows.Forms.CheckBox();+ this.chkExportVideoField = new global::System.Windows.Forms.CheckBox();+ this.lblPreviewVideo = new global::System.Windows.Forms.Label();+ this.lblExportVideo = new global::System.Windows.Forms.Label();+ this.numVisualizeEvery = new global::System.Windows.Forms.NumericUpDown();+ this.Label4 = new global::System.Windows.Forms.Label();+ this.lblVisualizeEvery = new global::System.Windows.Forms.Label();+ this.Label7 = new global::System.Windows.Forms.Label();+ this.lblSimulationSteps = new global::System.Windows.Forms.Label();+ this.grpSceneProperties = new global::System.Windows.Forms.GroupBox();+ this.Label20 = new global::System.Windows.Forms.Label();+ this.numRefractiveIndex = new global::System.Windows.Forms.NumericUpDown();+ this.picImagePreview = new global::System.Windows.Forms.PictureBox();+ this.lblScaleImgSourceIntensity = new global::System.Windows.Forms.Label();+ this.numScaleImageSource = new global::System.Windows.Forms.NumericUpDown();+ this.btnEditObjectSourceList = new global::System.Windows.Forms.Button();+ this.txtDampingEdgeSize = new global::System.Windows.Forms.TextBox();+ this.chkUseObjectSources = new global::System.Windows.Forms.CheckBox();+ this.chkUseImageSources = new global::System.Windows.Forms.CheckBox();+ this.chkDampingEdge = new global::System.Windows.Forms.CheckBox();+ this.btnLoadSceneImage = new global::System.Windows.Forms.Button();+ this.Label1 = new global::System.Windows.Forms.Label();+ this.lblPix = new global::System.Windows.Forms.Label();+ this.lblX = new global::System.Windows.Forms.Label();+ this.txtYsize = new global::System.Windows.Forms.TextBox();+ this.txtXSize = new global::System.Windows.Forms.TextBox();+ this.radUserDefinedScene = new global::System.Windows.Forms.RadioButton();+ this.radUseSceneImage = new global::System.Windows.Forms.RadioButton();+ this.lblImageNameAndSize = new global::System.Windows.Forms.Label();+ this.tabSourceList = new global::System.Windows.Forms.TabPage();+ this.Label62 = new global::System.Windows.Forms.Label();+ this.Label60 = new global::System.Windows.Forms.Label();+ this.chkAutoRescaleSourceOn = new global::System.Windows.Forms.CheckBox();+ this.picPreviewSource = new global::System.Windows.Forms.PictureBox();+ this.grpPlaceSource = new global::System.Windows.Forms.GroupBox();+ this.pnlPosition = new global::System.Windows.Forms.Panel();+ this.numSourcePositionX = new global::System.Windows.Forms.NumericUpDown();+ this.Label36 = new global::System.Windows.Forms.Label();+ this.lblPosition = new global::System.Windows.Forms.Label();+ this.btnPickSourcePosition = new global::System.Windows.Forms.Button();+ this.numSourcePositionY = new global::System.Windows.Forms.NumericUpDown();+ this.Label35 = new global::System.Windows.Forms.Label();+ this.btnDelete = new global::System.Windows.Forms.Button();+ this.btnNew = new global::System.Windows.Forms.Button();+ this.btnCopy = new global::System.Windows.Forms.Button();+ this.lstSources = new global::System.Windows.Forms.ListBox();+ this.pnlSourceImage = new global::System.Windows.Forms.Panel();+ this.grpSourceDetails = new global::System.Windows.Forms.GroupBox();+ this.txtDetachAfterSteps = new global::System.Windows.Forms.TextBox();+ this.btnSaveSource = new global::System.Windows.Forms.Button();+ this.Label47 = new global::System.Windows.Forms.Label();+ this.chkDetachSource = new global::System.Windows.Forms.CheckBox();+ this.lblLambdaIs = new global::System.Windows.Forms.Label();+ this.chkSourceOn = new global::System.Windows.Forms.CheckBox();+ this.grpComposite = new global::System.Windows.Forms.GroupBox();+ this.Label59 = new global::System.Windows.Forms.Label();+ this.Label58 = new global::System.Windows.Forms.Label();+ this.numRandomizeOffWidth = new global::System.Windows.Forms.NumericUpDown();+ this.numRandomizePosition = new global::System.Windows.Forms.NumericUpDown();+ this.NumRandomizePhase = new global::System.Windows.Forms.NumericUpDown();+ this.numRandomizeFrequency = new global::System.Windows.Forms.NumericUpDown();+ this.chkRandomizePhase = new global::System.Windows.Forms.CheckBox();+ this.chkRandomizePosition = new global::System.Windows.Forms.CheckBox();+ this.chkOffWidth = new global::System.Windows.Forms.CheckBox();+ this.chkRandomizeFrequency = new global::System.Windows.Forms.CheckBox();+ this.numSpacingSizeY = new global::System.Windows.Forms.NumericUpDown();+ this.numSpacingSizeX = new global::System.Windows.Forms.NumericUpDown();+ this.numArraySizeY = new global::System.Windows.Forms.NumericUpDown();+ this.numArraySizeX = new global::System.Windows.Forms.NumericUpDown();+ this.Label50 = new global::System.Windows.Forms.Label();+ this.Label51 = new global::System.Windows.Forms.Label();+ this.Label52 = new global::System.Windows.Forms.Label();+ this.Label53 = new global::System.Windows.Forms.Label();+ this.cmbCompositeProperties = new global::System.Windows.Forms.ComboBox();+ this.grpSingleSource = new global::System.Windows.Forms.GroupBox();+ this.numOffStateCycles = new global::System.Windows.Forms.NumericUpDown();+ this.numPhase = new global::System.Windows.Forms.NumericUpDown();+ this.numAmplitude = new global::System.Windows.Forms.NumericUpDown();+ this.numFrequency = new global::System.Windows.Forms.NumericUpDown();+ this.numPulseWidthCycles = new global::System.Windows.Forms.NumericUpDown();+ this.Label44 = new global::System.Windows.Forms.Label();+ this.Label46 = new global::System.Windows.Forms.Label();+ this.Label45 = new global::System.Windows.Forms.Label();+ this.Label43 = new global::System.Windows.Forms.Label();+ this.Label42 = new global::System.Windows.Forms.Label();+ this.Label54 = new global::System.Windows.Forms.Label();+ this.Label41 = new global::System.Windows.Forms.Label();+ this.Label40 = new global::System.Windows.Forms.Label();+ this.cmbPulseShape = new global::System.Windows.Forms.ComboBox();+ this.radModePulsed = new global::System.Windows.Forms.RadioButton();+ this.radModeContinuous = new global::System.Windows.Forms.RadioButton();+ this.txtName = new global::System.Windows.Forms.TextBox();+ this.cmbMainType = new global::System.Windows.Forms.ComboBox();+ this.Label39 = new global::System.Windows.Forms.Label();+ this.lblName = new global::System.Windows.Forms.Label();+ this.Label38 = new global::System.Windows.Forms.Label();+ this.tabProbeList = new global::System.Windows.Forms.TabPage();+ this.GroupBox2 = new global::System.Windows.Forms.GroupBox();+ this.Label49 = new global::System.Windows.Forms.Label();+ this.Label48 = new global::System.Windows.Forms.Label();+ this.Label37 = new global::System.Windows.Forms.Label();+ this.grpProbe2 = new global::System.Windows.Forms.GroupBox();+ this.Label22 = new global::System.Windows.Forms.Label();+ this.numRunningWindow2 = new global::System.Windows.Forms.NumericUpDown();+ this.chkProbeOn2 = new global::System.Windows.Forms.CheckBox();+ this.txtStartAfterStep2 = new global::System.Windows.Forms.TextBox();+ this.chkStartAfterStep2 = new global::System.Windows.Forms.CheckBox();+ this.Label23 = new global::System.Windows.Forms.Label();+ this.Label24 = new global::System.Windows.Forms.Label();+ this.txtMaxScaleY2 = new global::System.Windows.Forms.TextBox();+ this.txtMinScaleY2 = new global::System.Windows.Forms.TextBox();+ this.radFullScale2 = new global::System.Windows.Forms.RadioButton();+ this.radRunningScale2 = new global::System.Windows.Forms.RadioButton();+ this.chkAutoScaleY2 = new global::System.Windows.Forms.CheckBox();+ this.chkAutoScaleX2 = new global::System.Windows.Forms.CheckBox();+ this.numBPosY2 = new global::System.Windows.Forms.NumericUpDown();+ this.numAPosY2 = new global::System.Windows.Forms.NumericUpDown();+ this.numBPosX2 = new global::System.Windows.Forms.NumericUpDown();+ this.numAPosX2 = new global::System.Windows.Forms.NumericUpDown();+ this.butPicPositions2 = new global::System.Windows.Forms.Button();+ this.Label25 = new global::System.Windows.Forms.Label();+ this.cmbPlaceOn2 = new global::System.Windows.Forms.ComboBox();+ this.cmbMeasurement2 = new global::System.Windows.Forms.ComboBox();+ this.Label26 = new global::System.Windows.Forms.Label();+ this.Label27 = new global::System.Windows.Forms.Label();+ this.cmbBoxSize2 = new global::System.Windows.Forms.ComboBox();+ this.cmbProbeType2 = new global::System.Windows.Forms.ComboBox();+ this.Label28 = new global::System.Windows.Forms.Label();+ this.Label29 = new global::System.Windows.Forms.Label();+ this.Label30 = new global::System.Windows.Forms.Label();+ this.Label31 = new global::System.Windows.Forms.Label();+ this.Label32 = new global::System.Windows.Forms.Label();+ this.Label33 = new global::System.Windows.Forms.Label();+ this.Label34 = new global::System.Windows.Forms.Label();+ this.grpProbe1 = new global::System.Windows.Forms.GroupBox();+ this.Label21 = new global::System.Windows.Forms.Label();+ this.numRunningWindow = new global::System.Windows.Forms.NumericUpDown();+ this.chkProbeOn1 = new global::System.Windows.Forms.CheckBox();+ this.txtStartAfterStep = new global::System.Windows.Forms.TextBox();+ this.chkStartAfterStep = new global::System.Windows.Forms.CheckBox();+ this.Label19 = new global::System.Windows.Forms.Label();+ this.Label18 = new global::System.Windows.Forms.Label();+ this.txtMaxScaleY = new global::System.Windows.Forms.TextBox();+ this.txtMinScaleY = new global::System.Windows.Forms.TextBox();+ this.radFullScale = new global::System.Windows.Forms.RadioButton();+ this.radRunningScale = new global::System.Windows.Forms.RadioButton();+ this.chkAutoScaleY = new global::System.Windows.Forms.CheckBox();+ this.chkAutoScaleX = new global::System.Windows.Forms.CheckBox();+ this.numBPosY = new global::System.Windows.Forms.NumericUpDown();+ this.numAPosY = new global::System.Windows.Forms.NumericUpDown();+ this.numBPosX = new global::System.Windows.Forms.NumericUpDown();+ this.numAPosX = new global::System.Windows.Forms.NumericUpDown();+ this.butPicPositions = new global::System.Windows.Forms.Button();+ this.Label16 = new global::System.Windows.Forms.Label();+ this.cmbPlaceOn = new global::System.Windows.Forms.ComboBox();+ this.cmbMeasurement = new global::System.Windows.Forms.ComboBox();+ this.Label13 = new global::System.Windows.Forms.Label();+ this.Label15 = new global::System.Windows.Forms.Label();+ this.cmbBoxSize = new global::System.Windows.Forms.ComboBox();+ this.cmbProbeType = new global::System.Windows.Forms.ComboBox();+ this.Label14 = new global::System.Windows.Forms.Label();+ this.Label12 = new global::System.Windows.Forms.Label();+ this.Label11 = new global::System.Windows.Forms.Label();+ this.Label17 = new global::System.Windows.Forms.Label();+ this.Label10 = new global::System.Windows.Forms.Label();+ this.Label9 = new global::System.Windows.Forms.Label();+ this.Label8 = new global::System.Windows.Forms.Label();+ this.pnlProbeImage = new global::System.Windows.Forms.Panel();+ this.tabViewer = new global::System.Windows.Forms.TabPage();+ this.pnlPreviewIntensityProps = new global::System.Windows.Forms.Panel();+ this.chkExportVideoIntensity2 = new global::System.Windows.Forms.CheckBox();+ this.Label64 = new global::System.Windows.Forms.Label();+ this.numBrightnessIntensityOverlay = new global::System.Windows.Forms.NumericUpDown();+ this.numIntensityScaling2 = new global::System.Windows.Forms.NumericUpDown();+ this.chkDiplayOverlayInIntensity = new global::System.Windows.Forms.CheckBox();+ this.Label66 = new global::System.Windows.Forms.Label();+ this.Panel3 = new global::System.Windows.Forms.Panel();+ this.Label63 = new global::System.Windows.Forms.Label();+ this.chkExportVideoField2 = new global::System.Windows.Forms.CheckBox();+ this.numFieldScaling2 = new global::System.Windows.Forms.NumericUpDown();+ this.Label65 = new global::System.Windows.Forms.Label();+ this.numBrightnessFieldOverlay = new global::System.Windows.Forms.NumericUpDown();+ this.chkDiplayOverlayInField = new global::System.Windows.Forms.CheckBox();+ this.Label56 = new global::System.Windows.Forms.Label();+ this.Label55 = new global::System.Windows.Forms.Label();+ this.lblWarningIntensity = new global::System.Windows.Forms.Label();+ this.lblWarningField = new global::System.Windows.Forms.Label();+ this.btnExportIntensityFrame = new global::System.Windows.Forms.Button();+ this.btnExportFieldFrame = new global::System.Windows.Forms.Button();+ this.btnOpenImageFolder = new global::System.Windows.Forms.Button();+ this.btnOpenVideoFolder = new global::System.Windows.Forms.Button();+ this.btnViewIntensityVideo = new global::System.Windows.Forms.Button();+ this.btnViewFieldVideo = new global::System.Windows.Forms.Button();+ this.pnlPreviewIntensity = new global::System.Windows.Forms.Panel();+ this.pnlPreviewField = new global::System.Windows.Forms.Panel();+ this.tabOutput = new global::System.Windows.Forms.TabPage();+ this.btnRenameVideo = new global::System.Windows.Forms.Button();+ this.btnShareWithEditors = new global::System.Windows.Forms.Button();+ this.btnCopyToClipboard = new global::System.Windows.Forms.Button();+ this.btnOpenImageFolder2 = new global::System.Windows.Forms.Button();+ this.btnViewVIdeoInPlayer2 = new global::System.Windows.Forms.Button();+ this.btnOpenVIdeoFolder2 = new global::System.Windows.Forms.Button();+ this.lblPreview = new global::System.Windows.Forms.Label();+ this.btnDeleteVideos = new global::System.Windows.Forms.Button();+ this.btnDeleteImages = new global::System.Windows.Forms.Button();+ this.btnDeleteScene = new global::System.Windows.Forms.Button();+ this.btnLoadExternal = new global::System.Windows.Forms.Button();+ this.pnlPreview = new global::System.Windows.Forms.Panel();+ this.Label57 = new global::System.Windows.Forms.Label();+ this.lstScenes = new global::System.Windows.Forms.ListView();+ this.colSceneName = new global::System.Windows.Forms.ColumnHeader();+ this.colSceneCreated = new global::System.Windows.Forms.ColumnHeader();+ this.lstImages = new global::System.Windows.Forms.ListView();+ this.colImageName = new global::System.Windows.Forms.ColumnHeader();+ this.colCreatedOn = new global::System.Windows.Forms.ColumnHeader();+ this.lstVideo = new global::System.Windows.Forms.ListView();+ this.colVideoName = new global::System.Windows.Forms.ColumnHeader();+ this.colCreatedOn2 = new global::System.Windows.Forms.ColumnHeader();+ this.lstAllProjects3 = new global::System.Windows.Forms.ListView();+ this.colProjectName2 = new global::System.Windows.Forms.ColumnHeader();+ this.colLastEdited2 = new global::System.Windows.Forms.ColumnHeader();+ this.tabColorScheme = new global::System.Windows.Forms.TabPage();+ this.lblType = new global::System.Windows.Forms.Label();+ this.radSchemeTypeIntensity = new global::System.Windows.Forms.RadioButton();+ this.radSchemeTypeField = new global::System.Windows.Forms.RadioButton();+ this.btnLoadScheme = new global::System.Windows.Forms.Button();+ this.btbChooseFFolder = new global::System.Windows.Forms.Button();+ this.lblSchemeFolder = new global::System.Windows.Forms.Label();+ this.ListView1 = new global::System.Windows.Forms.ListView();+ this.txtSchemeFolder = new global::System.Windows.Forms.TextBox();+ this.txtCurrentColorScheme = new global::System.Windows.Forms.TextBox();+ this.lblCurrentCOlorScheme = new global::System.Windows.Forms.Label();+ this.lblColorSchemeEditor = new global::System.Windows.Forms.Label();+ this.btnColor9 = new global::System.Windows.Forms.Button();+ this.btnColor8 = new global::System.Windows.Forms.Button();+ this.btnColor7 = new global::System.Windows.Forms.Button();+ this.btnColor6 = new global::System.Windows.Forms.Button();+ this.btnColor5 = new global::System.Windows.Forms.Button();+ this.btnColor4 = new global::System.Windows.Forms.Button();+ this.btnColor3 = new global::System.Windows.Forms.Button();+ this.btnCOlor2 = new global::System.Windows.Forms.Button();+ this.btnColor1 = new global::System.Windows.Forms.Button();+ this.lblColorPicker = new global::System.Windows.Forms.Label();+ this.Panel2 = new global::System.Windows.Forms.Panel();+ this.pnlScheme = new global::System.Windows.Forms.Panel();+ this.btnDeleteColorScheme = new global::System.Windows.Forms.Button();+ this.btnRenameColorScheme = new global::System.Windows.Forms.Button();+ this.btnSaveAsColorScheme = new global::System.Windows.Forms.Button();+ this.btnSaveCurrentScheme = new global::System.Windows.Forms.Button();+ this.btnSaveConfiguration = new global::System.Windows.Forms.Button();+ this.btnStartSimulation = new global::System.Windows.Forms.Button();+ this.btnPauzeResume = new global::System.Windows.Forms.Button();+ this.MenuStrip1 = new global::System.Windows.Forms.MenuStrip();+ this.itemFile = new global::System.Windows.Forms.ToolStripMenuItem();+ this.NewToolStripMenuItem = new global::System.Windows.Forms.ToolStripMenuItem();+ this.OpenToolStripMenuItem = new global::System.Windows.Forms.ToolStripMenuItem();+ this.ChooseProjectRootToolStripMenuItem = new global::System.Windows.Forms.ToolStripMenuItem();+ this.SetCValueToolStripMenuItem = new global::System.Windows.Forms.ToolStripMenuItem();+ this.SaveToolStripMenuItem = new global::System.Windows.Forms.ToolStripMenuItem();+ this.ExitToolStripMenuItem = new global::System.Windows.Forms.ToolStripMenuItem();+ this.InfoToolStripMenuItem = new global::System.Windows.Forms.ToolStripMenuItem();+ this.HelpToolStripMenuItem = new global::System.Windows.Forms.ToolStripMenuItem();+ this.AboutToolStripMenuItem = new global::System.Windows.Forms.ToolStripMenuItem();+ this.lblProjectName = new global::System.Windows.Forms.Label();+ this.txtProjectName = new global::System.Windows.Forms.TextBox();+ this.txtRootFolder = new global::System.Windows.Forms.TextBox();+ this.lblRootFolder = new global::System.Windows.Forms.Label();+ this.btnBrowseRoot = new global::System.Windows.Forms.Button();+ this.StatusStrip1 = new global::System.Windows.Forms.StatusStrip();+ this.ToolStripStatusLabel1 = new global::System.Windows.Forms.ToolStripStatusLabel();+ this.grpNavigateTabs = new global::System.Windows.Forms.GroupBox();+ this.btnGotoPreview = new global::System.Windows.Forms.Button();+ this.btnGotoProbes = new global::System.Windows.Forms.Button();+ this.btnGotoSources = new global::System.Windows.Forms.Button();+ this.btnGotoConfiguration = new global::System.Windows.Forms.Button();+ this.grpSimulationControlButtons = new global::System.Windows.Forms.GroupBox();+ this.Panel1 = new global::System.Windows.Forms.Panel();+ this.btnDescription = new global::System.Windows.Forms.Button();+ this.grpShareImage = new global::System.Windows.Forms.GroupBox();+ this.btnShareIntensityImage = new global::System.Windows.Forms.Button();+ this.btnShareFieldImage = new global::System.Windows.Forms.Button();+ this.btnShareSceneImage = new global::System.Windows.Forms.Button();+ this.tabMainFunctions.SuspendLayout();+ this.tabConfiguration.SuspendLayout();+ this.grpProjects.SuspendLayout();+ this.grpSimulationSettings.SuspendLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numTimeDecayFactor).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numSimulationSteps).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numQuality).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numIntensityScaling).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numOffsetIntensity).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numOffsetField).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numFieldScaling).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numVisualizeEvery).BeginInit();+ this.grpSceneProperties.SuspendLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numRefractiveIndex).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.picImagePreview).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numScaleImageSource).BeginInit();+ this.tabSourceList.SuspendLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.picPreviewSource).BeginInit();+ this.grpPlaceSource.SuspendLayout();+ this.pnlPosition.SuspendLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numSourcePositionX).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numSourcePositionY).BeginInit();+ this.grpSourceDetails.SuspendLayout();+ this.grpComposite.SuspendLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numRandomizeOffWidth).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numRandomizePosition).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.NumRandomizePhase).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numRandomizeFrequency).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numSpacingSizeY).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numSpacingSizeX).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numArraySizeY).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numArraySizeX).BeginInit();+ this.grpSingleSource.SuspendLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numOffStateCycles).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numPhase).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numAmplitude).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numFrequency).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numPulseWidthCycles).BeginInit();+ this.tabProbeList.SuspendLayout();+ this.GroupBox2.SuspendLayout();+ this.grpProbe2.SuspendLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numRunningWindow2).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numBPosY2).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numAPosY2).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numBPosX2).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numAPosX2).BeginInit();+ this.grpProbe1.SuspendLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numRunningWindow).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numBPosY).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numAPosY).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numBPosX).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numAPosX).BeginInit();+ this.tabViewer.SuspendLayout();+ this.pnlPreviewIntensityProps.SuspendLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numBrightnessIntensityOverlay).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numIntensityScaling2).BeginInit();+ this.Panel3.SuspendLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numFieldScaling2).BeginInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numBrightnessFieldOverlay).BeginInit();+ this.tabOutput.SuspendLayout();+ this.tabColorScheme.SuspendLayout();+ this.MenuStrip1.SuspendLayout();+ this.StatusStrip1.SuspendLayout();+ this.grpNavigateTabs.SuspendLayout();+ this.grpSimulationControlButtons.SuspendLayout();+ this.Panel1.SuspendLayout();+ this.grpShareImage.SuspendLayout();+ base.SuspendLayout();+ this.tabMainFunctions.Controls.Add(this.tabConfiguration);+ this.tabMainFunctions.Controls.Add(this.tabSourceList);+ this.tabMainFunctions.Controls.Add(this.tabProbeList);+ this.tabMainFunctions.Controls.Add(this.tabViewer);+ this.tabMainFunctions.Controls.Add(this.tabOutput);+ this.tabMainFunctions.Controls.Add(this.tabColorScheme);+ this.tabMainFunctions.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 15.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.tabMainFunctions.Location = new global::System.Drawing.Point(16, 89);+ this.tabMainFunctions.Name = "tabMainFunctions";+ this.tabMainFunctions.Padding = new global::System.Drawing.Point(10, 3);+ this.tabMainFunctions.SelectedIndex = 0;+ this.tabMainFunctions.Size = new global::System.Drawing.Size(1750, 731);+ this.tabMainFunctions.TabIndex = 0;+ this.tabConfiguration.Controls.Add(this.grpProjects);+ this.tabConfiguration.Controls.Add(this.grpSimulationSettings);+ this.tabConfiguration.Controls.Add(this.grpSceneProperties);+ this.tabConfiguration.Location = new global::System.Drawing.Point(4, 34);+ this.tabConfiguration.Name = "tabConfiguration";+ this.tabConfiguration.Padding = new global::System.Windows.Forms.Padding(3);+ this.tabConfiguration.Size = new global::System.Drawing.Size(1742, 693);+ this.tabConfiguration.TabIndex = 1;+ this.tabConfiguration.Text = " Settings ";+ this.tabConfiguration.UseVisualStyleBackColor = true;+ this.grpProjects.Controls.Add(this.btnPickRoot);+ this.grpProjects.Controls.Add(this.btnSaveConfiguration2);+ this.grpProjects.Controls.Add(this.lstAllProjects);+ this.grpProjects.Controls.Add(this.btnNewProject);+ this.grpProjects.Controls.Add(this.btnRenameProject);+ this.grpProjects.Controls.Add(this.btnLoadProject);+ this.grpProjects.Controls.Add(this.btnDeleteProject);+ this.grpProjects.Controls.Add(this.btnSaveAs);+ this.grpProjects.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.grpProjects.Location = new global::System.Drawing.Point(23, 25);+ this.grpProjects.Name = "grpProjects";+ this.grpProjects.Size = new global::System.Drawing.Size(473, 641);+ this.grpProjects.TabIndex = 8;+ this.grpProjects.TabStop = false;+ this.grpProjects.Text = "Projects in current root";+ this.btnPickRoot.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnPickRoot.Location = new global::System.Drawing.Point(363, 506);+ this.btnPickRoot.Name = "btnPickRoot";+ this.btnPickRoot.Size = new global::System.Drawing.Size(88, 27);+ this.btnPickRoot.TabIndex = 10;+ this.btnPickRoot.Text = "Pick root";+ this.btnPickRoot.UseVisualStyleBackColor = true;+ this.btnSaveConfiguration2.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 15.75f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnSaveConfiguration2.Location = new global::System.Drawing.Point(252, 562);+ this.btnSaveConfiguration2.Name = "btnSaveConfiguration2";+ this.btnSaveConfiguration2.Size = new global::System.Drawing.Size(191, 49);+ this.btnSaveConfiguration2.TabIndex = 9;+ this.btnSaveConfiguration2.Text = "Save";+ this.btnSaveConfiguration2.UseVisualStyleBackColor = true;+ this.lstAllProjects.BackColor = global::System.Drawing.SystemColors.MenuBar;+ this.lstAllProjects.Columns.AddRange(new global::System.Windows.Forms.ColumnHeader[] { this.colProjectName, this.colLastEdit });+ this.lstAllProjects.FullRowSelect = true;+ this.lstAllProjects.HideSelection = false;+ this.lstAllProjects.Location = new global::System.Drawing.Point(16, 28);+ this.lstAllProjects.MultiSelect = false;+ this.lstAllProjects.Name = "lstAllProjects";+ this.lstAllProjects.Size = new global::System.Drawing.Size(435, 472);+ this.lstAllProjects.TabIndex = 8;+ this.lstAllProjects.UseCompatibleStateImageBehavior = false;+ this.lstAllProjects.View = global::System.Windows.Forms.View.Details;+ this.colProjectName.Text = "ProjectName";+ this.colProjectName.Width = 280;+ this.colLastEdit.Text = "Last edited";+ this.colLastEdit.Width = 150;+ this.btnNewProject.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 15.75f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnNewProject.Location = new global::System.Drawing.Point(16, 560);+ this.btnNewProject.Name = "btnNewProject";+ this.btnNewProject.Size = new global::System.Drawing.Size(191, 51);+ this.btnNewProject.TabIndex = 7;+ this.btnNewProject.Text = "New project";+ this.btnNewProject.UseVisualStyleBackColor = true;+ this.btnRenameProject.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnRenameProject.Location = new global::System.Drawing.Point(188, 505);+ this.btnRenameProject.Name = "btnRenameProject";+ this.btnRenameProject.Size = new global::System.Drawing.Size(78, 28);+ this.btnRenameProject.TabIndex = 6;+ this.btnRenameProject.Text = "Rename";+ this.btnRenameProject.UseVisualStyleBackColor = true;+ this.btnLoadProject.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnLoadProject.Location = new global::System.Drawing.Point(16, 507);+ this.btnLoadProject.Name = "btnLoadProject";+ this.btnLoadProject.Size = new global::System.Drawing.Size(77, 29);+ this.btnLoadProject.TabIndex = 6;+ this.btnLoadProject.Text = "Load";+ this.btnLoadProject.UseVisualStyleBackColor = true;+ this.btnDeleteProject.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnDeleteProject.Location = new global::System.Drawing.Point(272, 506);+ this.btnDeleteProject.Name = "btnDeleteProject";+ this.btnDeleteProject.Size = new global::System.Drawing.Size(73, 27);+ this.btnDeleteProject.TabIndex = 6;+ this.btnDeleteProject.Text = "Delete";+ this.btnDeleteProject.UseVisualStyleBackColor = true;+ this.btnSaveAs.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnSaveAs.Location = new global::System.Drawing.Point(99, 507);+ this.btnSaveAs.Name = "btnSaveAs";+ this.btnSaveAs.Size = new global::System.Drawing.Size(83, 27);+ this.btnSaveAs.TabIndex = 4;+ this.btnSaveAs.Text = "Save as";+ this.btnSaveAs.UseVisualStyleBackColor = true;+ this.grpSimulationSettings.Controls.Add(this.Label61);+ this.grpSimulationSettings.Controls.Add(this.numTimeDecayFactor);+ this.grpSimulationSettings.Controls.Add(this.numSimulationSteps);+ this.grpSimulationSettings.Controls.Add(this.lblInfo);+ this.grpSimulationSettings.Controls.Add(this.chkUse4thOrderLaplacian);+ this.grpSimulationSettings.Controls.Add(this.chkUseGPU);+ this.grpSimulationSettings.Controls.Add(this.numQuality);+ this.grpSimulationSettings.Controls.Add(this.lblVideoQuality);+ this.grpSimulationSettings.Controls.Add(this.numIntensityScaling);+ this.grpSimulationSettings.Controls.Add(this.numOffsetIntensity);+ this.grpSimulationSettings.Controls.Add(this.numOffsetField);+ this.grpSimulationSettings.Controls.Add(this.numFieldScaling);+ this.grpSimulationSettings.Controls.Add(this.Label3);+ this.grpSimulationSettings.Controls.Add(this.numScaleIntensityValues);+ this.grpSimulationSettings.Controls.Add(this.Label6);+ this.grpSimulationSettings.Controls.Add(this.lblOffsetField);+ this.grpSimulationSettings.Controls.Add(this.Label5);+ this.grpSimulationSettings.Controls.Add(this.Label2);+ this.grpSimulationSettings.Controls.Add(this.cmbIntensityColorScheme);+ this.grpSimulationSettings.Controls.Add(this.cmbFieldColorScheme);+ this.grpSimulationSettings.Controls.Add(this.chkPreviewVideoIntensity);+ this.grpSimulationSettings.Controls.Add(this.chkExportVideoIntensity);+ this.grpSimulationSettings.Controls.Add(this.chkPreviewVideoField);+ this.grpSimulationSettings.Controls.Add(this.chkExportVideoField);+ this.grpSimulationSettings.Controls.Add(this.lblPreviewVideo);+ this.grpSimulationSettings.Controls.Add(this.lblExportVideo);+ this.grpSimulationSettings.Controls.Add(this.numVisualizeEvery);+ this.grpSimulationSettings.Controls.Add(this.Label4);+ this.grpSimulationSettings.Controls.Add(this.lblVisualizeEvery);+ this.grpSimulationSettings.Controls.Add(this.Label7);+ this.grpSimulationSettings.Controls.Add(this.lblSimulationSteps);+ this.grpSimulationSettings.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.grpSimulationSettings.Location = new global::System.Drawing.Point(516, 432);+ this.grpSimulationSettings.Name = "grpSimulationSettings";+ this.grpSimulationSettings.Size = new global::System.Drawing.Size(1200, 234);+ this.grpSimulationSettings.TabIndex = 3;+ this.grpSimulationSettings.TabStop = false;+ this.grpSimulationSettings.Text = "Simulation Settings";+ this.Label61.AutoSize = true;+ this.Label61.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label61.Location = new global::System.Drawing.Point(27, 152);+ this.Label61.Name = "Label61";+ this.Label61.Size = new global::System.Drawing.Size(133, 16);+ this.Label61.TabIndex = 16;+ this.Label61.Text = "Intensity decay factor";+ this.numTimeDecayFactor.Location = new global::System.Drawing.Point(179, 150);+ global::System.Windows.Forms.NumericUpDown numTimeDecayFactor = this.numTimeDecayFactor;+ int[] array = new int[4];+ array[0] = 20;+ numTimeDecayFactor.Maximum = new decimal(array);+ global::System.Windows.Forms.NumericUpDown numTimeDecayFactor2 = this.numTimeDecayFactor;+ int[] array2 = new int[4];+ array2[0] = 1;+ numTimeDecayFactor2.Minimum = new decimal(array2);+ this.numTimeDecayFactor.Name = "numTimeDecayFactor";+ this.numTimeDecayFactor.Size = new global::System.Drawing.Size(80, 24);+ this.numTimeDecayFactor.TabIndex = 15;+ this.numTimeDecayFactor.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numTimeDecayFactor3 = this.numTimeDecayFactor;+ int[] array3 = new int[4];+ array3[0] = 5;+ numTimeDecayFactor3.Value = new decimal(array3);+ global::System.Windows.Forms.NumericUpDown numSimulationSteps = this.numSimulationSteps;+ int[] array4 = new int[4];+ array4[0] = 500;+ numSimulationSteps.Increment = new decimal(array4);+ this.numSimulationSteps.Location = new global::System.Drawing.Point(179, 188);+ global::System.Windows.Forms.NumericUpDown numSimulationSteps2 = this.numSimulationSteps;+ int[] array5 = new int[4];+ array5[0] = 100000;+ numSimulationSteps2.Maximum = new decimal(array5);+ global::System.Windows.Forms.NumericUpDown numSimulationSteps3 = this.numSimulationSteps;+ int[] array6 = new int[4];+ array6[0] = 100;+ numSimulationSteps3.Minimum = new decimal(array6);+ this.numSimulationSteps.Name = "numSimulationSteps";+ this.numSimulationSteps.Size = new global::System.Drawing.Size(80, 24);+ this.numSimulationSteps.TabIndex = 14;+ this.numSimulationSteps.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numSimulationSteps4 = this.numSimulationSteps;+ int[] array7 = new int[4];+ array7[0] = 3000;+ numSimulationSteps4.Value = new decimal(array7);+ this.lblInfo.AutoSize = true;+ this.lblInfo.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Underline, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblInfo.Location = new global::System.Drawing.Point(1051, 193);+ this.lblInfo.Name = "lblInfo";+ this.lblInfo.Size = new global::System.Drawing.Size(37, 16);+ this.lblInfo.TabIndex = 13;+ this.lblInfo.Text = "(Info)";+ this.chkUse4thOrderLaplacian.AutoSize = true;+ this.chkUse4thOrderLaplacian.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.chkUse4thOrderLaplacian.Location = new global::System.Drawing.Point(786, 191);+ this.chkUse4thOrderLaplacian.Name = "chkUse4thOrderLaplacian";+ this.chkUse4thOrderLaplacian.Size = new global::System.Drawing.Size(266, 20);+ this.chkUse4thOrderLaplacian.TabIndex = 12;+ this.chkUse4thOrderLaplacian.Text = "Use 4th order Laplacian + sub-sampling ";+ this.chkUse4thOrderLaplacian.UseVisualStyleBackColor = true;+ this.chkUseGPU.AutoSize = true;+ this.chkUseGPU.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.chkUseGPU.Location = new global::System.Drawing.Point(787, 153);+ this.chkUseGPU.Name = "chkUseGPU";+ this.chkUseGPU.Size = new global::System.Drawing.Size(187, 20);+ this.chkUseGPU.TabIndex = 11;+ this.chkUseGPU.Text = "Use GPU (generally faster)";+ this.chkUseGPU.UseVisualStyleBackColor = true;+ this.numQuality.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.numQuality.Location = new global::System.Drawing.Point(491, 191);+ this.numQuality.Name = "numQuality";+ this.numQuality.Size = new global::System.Drawing.Size(61, 22);+ this.numQuality.TabIndex = 10;+ this.numQuality.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numQuality = this.numQuality;+ int[] array8 = new int[4];+ array8[0] = 70;+ numQuality.Value = new decimal(array8);+ this.lblVideoQuality.AutoSize = true;+ this.lblVideoQuality.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblVideoQuality.Location = new global::System.Drawing.Point(377, 193);+ this.lblVideoQuality.Name = "lblVideoQuality";+ this.lblVideoQuality.Size = new global::System.Drawing.Size(109, 16);+ this.lblVideoQuality.TabIndex = 9;+ this.lblVideoQuality.Text = "Video quality (%)";+ this.numIntensityScaling.DecimalPlaces = 1;+ this.numIntensityScaling.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.numIntensityScaling.Increment = new decimal(new int[] { 1, 0, 0, 65536 });+ this.numIntensityScaling.Location = new global::System.Drawing.Point(904, 79);+ this.numIntensityScaling.Name = "numIntensityScaling";+ this.numIntensityScaling.Size = new global::System.Drawing.Size(74, 22);+ this.numIntensityScaling.TabIndex = 8;+ this.numIntensityScaling.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numIntensityScaling = this.numIntensityScaling;+ int[] array9 = new int[4];+ array9[0] = 30;+ numIntensityScaling.Value = new decimal(array9);+ this.numOffsetIntensity.DecimalPlaces = 1;+ this.numOffsetIntensity.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.numOffsetIntensity.Increment = new decimal(new int[] { 1, 0, 0, 131072 });+ this.numOffsetIntensity.Location = new global::System.Drawing.Point(1044, 80);+ global::System.Windows.Forms.NumericUpDown numOffsetIntensity = this.numOffsetIntensity;+ int[] array10 = new int[4];+ array10[0] = 1;+ numOffsetIntensity.Maximum = new decimal(array10);+ this.numOffsetIntensity.Minimum = new decimal(new int[] { 1, 0, 0, int.MinValue });+ this.numOffsetIntensity.Name = "numOffsetIntensity";+ this.numOffsetIntensity.Size = new global::System.Drawing.Size(82, 22);+ this.numOffsetIntensity.TabIndex = 8;+ this.numOffsetIntensity.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.numOffsetField.DecimalPlaces = 1;+ this.numOffsetField.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.numOffsetField.Increment = new decimal(new int[] { 1, 0, 0, 131072 });+ this.numOffsetField.Location = new global::System.Drawing.Point(1044, 40);+ global::System.Windows.Forms.NumericUpDown numOffsetField = this.numOffsetField;+ int[] array11 = new int[4];+ array11[0] = 1;+ numOffsetField.Maximum = new decimal(array11);+ this.numOffsetField.Minimum = new decimal(new int[] { 1, 0, 0, int.MinValue });+ this.numOffsetField.Name = "numOffsetField";+ this.numOffsetField.Size = new global::System.Drawing.Size(82, 22);+ this.numOffsetField.TabIndex = 8;+ this.numOffsetField.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.numFieldScaling.DecimalPlaces = 1;+ this.numFieldScaling.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.numFieldScaling.Increment = new decimal(new int[] { 1, 0, 0, 65536 });+ this.numFieldScaling.Location = new global::System.Drawing.Point(904, 40);+ this.numFieldScaling.Name = "numFieldScaling";+ this.numFieldScaling.Size = new global::System.Drawing.Size(74, 22);+ this.numFieldScaling.TabIndex = 8;+ this.numFieldScaling.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numFieldScaling = this.numFieldScaling;+ int[] array12 = new int[4];+ array12[0] = 30;+ numFieldScaling.Value = new decimal(array12);+ this.Label3.AutoSize = true;+ this.Label3.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label3.Location = new global::System.Drawing.Point(363, 83);+ this.Label3.Name = "Label3";+ this.Label3.Size = new global::System.Drawing.Size(140, 16);+ this.Label3.TabIndex = 6;+ this.Label3.Text = "Intensity color scheme";+ this.numScaleIntensityValues.AutoSize = true;+ this.numScaleIntensityValues.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.numScaleIntensityValues.Location = new global::System.Drawing.Point(785, 81);+ this.numScaleIntensityValues.Name = "numScaleIntensityValues";+ this.numScaleIntensityValues.Size = new global::System.Drawing.Size(105, 16);+ this.numScaleIntensityValues.TabIndex = 6;+ this.numScaleIntensityValues.Text = "Scale Int. values";+ this.Label6.AutoSize = true;+ this.Label6.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label6.Location = new global::System.Drawing.Point(997, 82);+ this.Label6.Name = "Label6";+ this.Label6.Size = new global::System.Drawing.Size(42, 16);+ this.Label6.TabIndex = 6;+ this.Label6.Text = "Offset";+ this.lblOffsetField.AutoSize = true;+ this.lblOffsetField.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblOffsetField.Location = new global::System.Drawing.Point(996, 42);+ this.lblOffsetField.Name = "lblOffsetField";+ this.lblOffsetField.Size = new global::System.Drawing.Size(42, 16);+ this.lblOffsetField.TabIndex = 6;+ this.lblOffsetField.Text = "Offset";+ this.Label5.AutoSize = true;+ this.Label5.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label5.Location = new global::System.Drawing.Point(783, 42);+ this.Label5.Name = "Label5";+ this.Label5.Size = new global::System.Drawing.Size(114, 16);+ this.Label5.TabIndex = 6;+ this.Label5.Text = "Scale field values";+ this.Label2.AutoSize = true;+ this.Label2.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label2.Location = new global::System.Drawing.Point(363, 44);+ this.Label2.Name = "Label2";+ this.Label2.Size = new global::System.Drawing.Size(122, 16);+ this.Label2.TabIndex = 6;+ this.Label2.Text = "Field color scheme";+ this.cmbIntensityColorScheme.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.cmbIntensityColorScheme.FormattingEnabled = true;+ this.cmbIntensityColorScheme.Location = new global::System.Drawing.Point(509, 79);+ this.cmbIntensityColorScheme.Name = "cmbIntensityColorScheme";+ this.cmbIntensityColorScheme.Size = new global::System.Drawing.Size(165, 24);+ this.cmbIntensityColorScheme.TabIndex = 5;+ this.cmbFieldColorScheme.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.cmbFieldColorScheme.FormattingEnabled = true;+ this.cmbFieldColorScheme.Location = new global::System.Drawing.Point(509, 40);+ this.cmbFieldColorScheme.Name = "cmbFieldColorScheme";+ this.cmbFieldColorScheme.Size = new global::System.Drawing.Size(165, 24);+ this.cmbFieldColorScheme.TabIndex = 5;+ this.chkPreviewVideoIntensity.AutoSize = true;+ this.chkPreviewVideoIntensity.Checked = true;+ this.chkPreviewVideoIntensity.CheckState = global::System.Windows.Forms.CheckState.Checked;+ this.chkPreviewVideoIntensity.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.chkPreviewVideoIntensity.Location = new global::System.Drawing.Point(193, 80);+ this.chkPreviewVideoIntensity.Name = "chkPreviewVideoIntensity";+ this.chkPreviewVideoIntensity.Size = new global::System.Drawing.Size(75, 20);+ this.chkPreviewVideoIntensity.TabIndex = 4;+ this.chkPreviewVideoIntensity.Text = "Intensity";+ this.chkPreviewVideoIntensity.UseVisualStyleBackColor = true;+ this.chkExportVideoIntensity.AutoSize = true;+ this.chkExportVideoIntensity.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.chkExportVideoIntensity.Location = new global::System.Drawing.Point(193, 41);+ this.chkExportVideoIntensity.Name = "chkExportVideoIntensity";+ this.chkExportVideoIntensity.Size = new global::System.Drawing.Size(75, 20);+ this.chkExportVideoIntensity.TabIndex = 4;+ this.chkExportVideoIntensity.Text = "Intensity";+ this.chkExportVideoIntensity.UseVisualStyleBackColor = true;+ this.chkPreviewVideoField.AutoSize = true;+ this.chkPreviewVideoField.Checked = true;+ this.chkPreviewVideoField.CheckState = global::System.Windows.Forms.CheckState.Checked;+ this.chkPreviewVideoField.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.chkPreviewVideoField.Location = new global::System.Drawing.Point(130, 81);+ this.chkPreviewVideoField.Name = "chkPreviewVideoField";+ this.chkPreviewVideoField.Size = new global::System.Drawing.Size(57, 20);+ this.chkPreviewVideoField.TabIndex = 4;+ this.chkPreviewVideoField.Text = "Field";+ this.chkPreviewVideoField.UseVisualStyleBackColor = true;+ this.chkExportVideoField.AutoSize = true;+ this.chkExportVideoField.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.chkExportVideoField.Location = new global::System.Drawing.Point(130, 42);+ this.chkExportVideoField.Name = "chkExportVideoField";+ this.chkExportVideoField.Size = new global::System.Drawing.Size(57, 20);+ this.chkExportVideoField.TabIndex = 4;+ this.chkExportVideoField.Text = "Field";+ this.chkExportVideoField.UseVisualStyleBackColor = true;+ this.lblPreviewVideo.AutoSize = true;+ this.lblPreviewVideo.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblPreviewVideo.Location = new global::System.Drawing.Point(24, 82);+ this.lblPreviewVideo.Name = "lblPreviewVideo";+ this.lblPreviewVideo.Size = new global::System.Drawing.Size(93, 16);+ this.lblPreviewVideo.TabIndex = 3;+ this.lblPreviewVideo.Text = "Preview video";+ this.lblExportVideo.AutoSize = true;+ this.lblExportVideo.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblExportVideo.Location = new global::System.Drawing.Point(24, 43);+ this.lblExportVideo.Name = "lblExportVideo";+ this.lblExportVideo.Size = new global::System.Drawing.Size(100, 16);+ this.lblExportVideo.TabIndex = 3;+ this.lblExportVideo.Text = "Export video of:";+ this.numVisualizeEvery.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.numVisualizeEvery.Location = new global::System.Drawing.Point(491, 152);+ global::System.Windows.Forms.NumericUpDown numVisualizeEvery = this.numVisualizeEvery;+ int[] array13 = new int[4];+ array13[0] = 6;+ numVisualizeEvery.Maximum = new decimal(array13);+ this.numVisualizeEvery.Name = "numVisualizeEvery";+ this.numVisualizeEvery.Size = new global::System.Drawing.Size(61, 22);+ this.numVisualizeEvery.TabIndex = 1;+ this.numVisualizeEvery.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numVisualizeEvery2 = this.numVisualizeEvery;+ int[] array14 = new int[4];+ array14[0] = 2;+ numVisualizeEvery2.Value = new decimal(array14);+ this.Label4.AutoSize = true;+ this.Label4.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label4.Location = new global::System.Drawing.Point(558, 155);+ this.Label4.Name = "Label4";+ this.Label4.Size = new global::System.Drawing.Size(49, 16);+ this.Label4.TabIndex = 0;+ this.Label4.Text = "frames";+ this.lblVisualizeEvery.AutoSize = true;+ this.lblVisualizeEvery.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblVisualizeEvery.Location = new global::System.Drawing.Point(377, 154);+ this.lblVisualizeEvery.Name = "lblVisualizeEvery";+ this.lblVisualizeEvery.Size = new global::System.Drawing.Size(99, 16);+ this.lblVisualizeEvery.TabIndex = 0;+ this.lblVisualizeEvery.Text = "Visualize every";+ this.Label7.AutoSize = true;+ this.Label7.Location = new global::System.Drawing.Point(386, 195);+ this.Label7.Name = "Label7";+ this.Label7.Size = new global::System.Drawing.Size(0, 18);+ this.Label7.TabIndex = 0;+ this.lblSimulationSteps.AutoSize = true;+ this.lblSimulationSteps.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblSimulationSteps.Location = new global::System.Drawing.Point(32, 193);+ this.lblSimulationSteps.Name = "lblSimulationSteps";+ this.lblSimulationSteps.Size = new global::System.Drawing.Size(106, 16);+ this.lblSimulationSteps.TabIndex = 0;+ this.lblSimulationSteps.Text = "Simulation steps";+ this.grpSceneProperties.Controls.Add(this.Label20);+ this.grpSceneProperties.Controls.Add(this.numRefractiveIndex);+ this.grpSceneProperties.Controls.Add(this.picImagePreview);+ this.grpSceneProperties.Controls.Add(this.lblScaleImgSourceIntensity);+ this.grpSceneProperties.Controls.Add(this.numScaleImageSource);+ this.grpSceneProperties.Controls.Add(this.btnEditObjectSourceList);+ this.grpSceneProperties.Controls.Add(this.txtDampingEdgeSize);+ this.grpSceneProperties.Controls.Add(this.chkUseObjectSources);+ this.grpSceneProperties.Controls.Add(this.chkUseImageSources);+ this.grpSceneProperties.Controls.Add(this.chkDampingEdge);+ this.grpSceneProperties.Controls.Add(this.btnLoadSceneImage);+ this.grpSceneProperties.Controls.Add(this.Label1);+ this.grpSceneProperties.Controls.Add(this.lblPix);+ this.grpSceneProperties.Controls.Add(this.lblX);+ this.grpSceneProperties.Controls.Add(this.txtYsize);+ this.grpSceneProperties.Controls.Add(this.txtXSize);+ this.grpSceneProperties.Controls.Add(this.radUserDefinedScene);+ this.grpSceneProperties.Controls.Add(this.radUseSceneImage);+ this.grpSceneProperties.Controls.Add(this.lblImageNameAndSize);+ this.grpSceneProperties.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.grpSceneProperties.Location = new global::System.Drawing.Point(516, 25);+ this.grpSceneProperties.Name = "grpSceneProperties";+ this.grpSceneProperties.Size = new global::System.Drawing.Size(1200, 390);+ this.grpSceneProperties.TabIndex = 1;+ this.grpSceneProperties.TabStop = false;+ this.grpSceneProperties.Text = "Scene properties";+ this.Label20.AutoSize = true;+ this.Label20.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label20.Location = new global::System.Drawing.Point(366, 80);+ this.Label20.Name = "Label20";+ this.Label20.Size = new global::System.Drawing.Size(104, 16);+ this.Label20.TabIndex = 12;+ this.Label20.Text = "Refractive index";+ this.numRefractiveIndex.DecimalPlaces = 2;+ this.numRefractiveIndex.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.numRefractiveIndex.Increment = new decimal(new int[] { 1, 0, 0, 131072 });+ this.numRefractiveIndex.Location = new global::System.Drawing.Point(476, 78);+ this.numRefractiveIndex.Maximum = new decimal(new int[] { 25, 0, 0, 65536 });+ this.numRefractiveIndex.Minimum = new decimal(new int[] { 10, 0, 0, 65536 });+ this.numRefractiveIndex.Name = "numRefractiveIndex";+ this.numRefractiveIndex.Size = new global::System.Drawing.Size(60, 22);+ this.numRefractiveIndex.TabIndex = 11;+ this.numRefractiveIndex.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.numRefractiveIndex.Value = new decimal(new int[] { 10, 0, 0, 65536 });+ this.picImagePreview.BackColor = global::System.Drawing.SystemColors.Control;+ this.picImagePreview.Location = new global::System.Drawing.Point(587, 22);+ this.picImagePreview.Name = "picImagePreview";+ this.picImagePreview.Size = new global::System.Drawing.Size(600, 338);+ this.picImagePreview.TabIndex = 1;+ this.picImagePreview.TabStop = false;+ this.lblScaleImgSourceIntensity.AutoSize = true;+ this.lblScaleImgSourceIntensity.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblScaleImgSourceIntensity.Location = new global::System.Drawing.Point(179, 183);+ this.lblScaleImgSourceIntensity.Name = "lblScaleImgSourceIntensity";+ this.lblScaleImgSourceIntensity.Size = new global::System.Drawing.Size(155, 16);+ this.lblScaleImgSourceIntensity.TabIndex = 10;+ this.lblScaleImgSourceIntensity.Text = "Scale intensity values by";+ this.numScaleImageSource.DecimalPlaces = 1;+ this.numScaleImageSource.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.numScaleImageSource.Increment = new decimal(new int[] { 1, 0, 0, 65536 });+ this.numScaleImageSource.Location = new global::System.Drawing.Point(337, 181);+ this.numScaleImageSource.Name = "numScaleImageSource";+ this.numScaleImageSource.Size = new global::System.Drawing.Size(65, 22);+ this.numScaleImageSource.TabIndex = 9;+ this.numScaleImageSource.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numScaleImageSource = this.numScaleImageSource;+ int[] array15 = new int[4];+ array15[0] = 1;+ numScaleImageSource.Value = new decimal(array15);+ this.btnEditObjectSourceList.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnEditObjectSourceList.Location = new global::System.Drawing.Point(201, 214);+ this.btnEditObjectSourceList.Name = "btnEditObjectSourceList";+ this.btnEditObjectSourceList.Size = new global::System.Drawing.Size(117, 23);+ this.btnEditObjectSourceList.TabIndex = 8;+ this.btnEditObjectSourceList.Text = "Edit source list";+ this.btnEditObjectSourceList.UseVisualStyleBackColor = true;+ this.txtDampingEdgeSize.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.txtDampingEdgeSize.Location = new global::System.Drawing.Point(152, 143);+ this.txtDampingEdgeSize.Name = "txtDampingEdgeSize";+ this.txtDampingEdgeSize.Size = new global::System.Drawing.Size(100, 22);+ this.txtDampingEdgeSize.TabIndex = 7;+ this.chkUseObjectSources.AutoSize = true;+ this.chkUseObjectSources.Checked = true;+ this.chkUseObjectSources.CheckState = global::System.Windows.Forms.CheckState.Checked;+ this.chkUseObjectSources.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.chkUseObjectSources.Location = new global::System.Drawing.Point(26, 218);+ this.chkUseObjectSources.Name = "chkUseObjectSources";+ this.chkUseObjectSources.Size = new global::System.Drawing.Size(143, 20);+ this.chkUseObjectSources.TabIndex = 6;+ this.chkUseObjectSources.Text = "Use object sources";+ this.chkUseObjectSources.UseVisualStyleBackColor = true;+ this.chkUseImageSources.AutoSize = true;+ this.chkUseImageSources.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.chkUseImageSources.Location = new global::System.Drawing.Point(26, 182);+ this.chkUseImageSources.Name = "chkUseImageSources";+ this.chkUseImageSources.Size = new global::System.Drawing.Size(157, 20);+ this.chkUseImageSources.TabIndex = 6;+ this.chkUseImageSources.Text = "Use image sources -";+ this.chkUseImageSources.UseVisualStyleBackColor = true;+ this.chkDampingEdge.AutoSize = true;+ this.chkDampingEdge.Checked = true;+ this.chkDampingEdge.CheckState = global::System.Windows.Forms.CheckState.Checked;+ this.chkDampingEdge.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.chkDampingEdge.Location = new global::System.Drawing.Point(26, 145);+ this.chkDampingEdge.Name = "chkDampingEdge";+ this.chkDampingEdge.Size = new global::System.Drawing.Size(120, 20);+ this.chkDampingEdge.TabIndex = 6;+ this.chkDampingEdge.Text = "Damping edge ";+ this.chkDampingEdge.UseVisualStyleBackColor = true;+ this.btnLoadSceneImage.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnLoadSceneImage.Location = new global::System.Drawing.Point(138, 39);+ this.btnLoadSceneImage.Name = "btnLoadSceneImage";+ this.btnLoadSceneImage.Size = new global::System.Drawing.Size(75, 23);+ this.btnLoadSceneImage.TabIndex = 5;+ this.btnLoadSceneImage.Text = "load";+ this.btnLoadSceneImage.UseVisualStyleBackColor = true;+ this.Label1.AutoSize = true;+ this.Label1.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label1.Location = new global::System.Drawing.Point(258, 146);+ this.Label1.Name = "Label1";+ this.Label1.Size = new global::System.Drawing.Size(22, 16);+ this.Label1.TabIndex = 4;+ this.Label1.Text = "px";+ this.lblPix.AutoSize = true;+ this.lblPix.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblPix.Location = new global::System.Drawing.Point(327, 80);+ this.lblPix.Name = "lblPix";+ this.lblPix.Size = new global::System.Drawing.Size(22, 16);+ this.lblPix.TabIndex = 4;+ this.lblPix.Text = "px";+ this.lblX.AutoSize = true;+ this.lblX.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblX.Location = new global::System.Drawing.Point(243, 80);+ this.lblX.Name = "lblX";+ this.lblX.Size = new global::System.Drawing.Size(12, 16);+ this.lblX.TabIndex = 4;+ this.lblX.Text = "/";+ this.txtYsize.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.txtYsize.Location = new global::System.Drawing.Point(258, 77);+ this.txtYsize.Name = "txtYsize";+ this.txtYsize.Size = new global::System.Drawing.Size(64, 22);+ this.txtYsize.TabIndex = 3;+ this.txtXSize.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.txtXSize.Location = new global::System.Drawing.Point(169, 76);+ this.txtXSize.Name = "txtXSize";+ this.txtXSize.Size = new global::System.Drawing.Size(72, 22);+ this.txtXSize.TabIndex = 3;+ this.radUserDefinedScene.AutoSize = true;+ this.radUserDefinedScene.Checked = true;+ this.radUserDefinedScene.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.radUserDefinedScene.Location = new global::System.Drawing.Point(26, 77);+ this.radUserDefinedScene.Name = "radUserDefinedScene";+ this.radUserDefinedScene.Size = new global::System.Drawing.Size(141, 20);+ this.radUserDefinedScene.TabIndex = 2;+ this.radUserDefinedScene.TabStop = true;+ this.radUserDefinedScene.Text = "User defined (X /Y)";+ this.radUserDefinedScene.UseVisualStyleBackColor = true;+ this.radUseSceneImage.AutoSize = true;+ this.radUseSceneImage.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.radUseSceneImage.Location = new global::System.Drawing.Point(26, 40);+ this.radUseSceneImage.Name = "radUseSceneImage";+ this.radUseSceneImage.Size = new global::System.Drawing.Size(106, 20);+ this.radUseSceneImage.TabIndex = 0;+ this.radUseSceneImage.Text = "Scene image";+ this.radUseSceneImage.UseVisualStyleBackColor = true;+ this.lblImageNameAndSize.AutoSize = true;+ this.lblImageNameAndSize.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblImageNameAndSize.Location = new global::System.Drawing.Point(228, 41);+ this.lblImageNameAndSize.Name = "lblImageNameAndSize";+ this.lblImageNameAndSize.Size = new global::System.Drawing.Size(103, 16);+ this.lblImageNameAndSize.TabIndex = 4;+ this.lblImageNameAndSize.Text = "(name and size)";+ this.tabSourceList.Controls.Add(this.Label62);+ this.tabSourceList.Controls.Add(this.Label60);+ this.tabSourceList.Controls.Add(this.chkAutoRescaleSourceOn);+ this.tabSourceList.Controls.Add(this.picPreviewSource);+ this.tabSourceList.Controls.Add(this.grpPlaceSource);+ this.tabSourceList.Controls.Add(this.btnDelete);+ this.tabSourceList.Controls.Add(this.btnNew);+ this.tabSourceList.Controls.Add(this.btnCopy);+ this.tabSourceList.Controls.Add(this.lstSources);+ this.tabSourceList.Controls.Add(this.pnlSourceImage);+ this.tabSourceList.Controls.Add(this.grpSourceDetails);+ this.tabSourceList.Location = new global::System.Drawing.Point(4, 34);+ this.tabSourceList.Name = "tabSourceList";+ this.tabSourceList.Size = new global::System.Drawing.Size(1742, 693);+ this.tabSourceList.TabIndex = 6;+ this.tabSourceList.Text = " Sources ";+ this.tabSourceList.UseVisualStyleBackColor = true;+ this.Label62.AutoSize = true;+ this.Label62.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label62.Location = new global::System.Drawing.Point(1187, 18);+ this.Label62.Name = "Label62";+ this.Label62.Size = new global::System.Drawing.Size(121, 18);+ this.Label62.TabIndex = 8;+ this.Label62.Text = "List of sources";+ this.Label60.AutoSize = true;+ this.Label60.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label60.Location = new global::System.Drawing.Point(1185, 408);+ this.Label60.Name = "Label60";+ this.Label60.Size = new global::System.Drawing.Size(124, 18);+ this.Label60.TabIndex = 7;+ this.Label60.Text = "Source preview";+ this.chkAutoRescaleSourceOn.AutoSize = true;+ this.chkAutoRescaleSourceOn.Checked = true;+ this.chkAutoRescaleSourceOn.CheckState = global::System.Windows.Forms.CheckState.Checked;+ this.chkAutoRescaleSourceOn.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.chkAutoRescaleSourceOn.Location = new global::System.Drawing.Point(1192, 651);+ this.chkAutoRescaleSourceOn.Name = "chkAutoRescaleSourceOn";+ this.chkAutoRescaleSourceOn.Size = new global::System.Drawing.Size(186, 20);+ this.chkAutoRescaleSourceOn.TabIndex = 6;+ this.chkAutoRescaleSourceOn.Text = "Auto-rescale source layout";+ this.chkAutoRescaleSourceOn.UseVisualStyleBackColor = true;+ this.picPreviewSource.Location = new global::System.Drawing.Point(1185, 430);+ this.picPreviewSource.Name = "picPreviewSource";+ this.picPreviewSource.Size = new global::System.Drawing.Size(273, 215);+ this.picPreviewSource.TabIndex = 5;+ this.picPreviewSource.TabStop = false;+ this.grpPlaceSource.Controls.Add(this.pnlPosition);+ this.grpPlaceSource.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.grpPlaceSource.Location = new global::System.Drawing.Point(1185, 285);+ this.grpPlaceSource.Name = "grpPlaceSource";+ this.grpPlaceSource.Size = new global::System.Drawing.Size(273, 117);+ this.grpPlaceSource.TabIndex = 4;+ this.grpPlaceSource.TabStop = false;+ this.grpPlaceSource.Text = "Place current source";+ this.pnlPosition.BackColor = global::System.Drawing.Color.Azure;+ this.pnlPosition.Controls.Add(this.numSourcePositionX);+ this.pnlPosition.Controls.Add(this.Label36);+ this.pnlPosition.Controls.Add(this.lblPosition);+ this.pnlPosition.Controls.Add(this.btnPickSourcePosition);+ this.pnlPosition.Controls.Add(this.numSourcePositionY);+ this.pnlPosition.Controls.Add(this.Label35);+ this.pnlPosition.Location = new global::System.Drawing.Point(22, 25);+ this.pnlPosition.Name = "pnlPosition";+ this.pnlPosition.Size = new global::System.Drawing.Size(228, 77);+ this.pnlPosition.TabIndex = 20;+ this.numSourcePositionX.Location = new global::System.Drawing.Point(146, 9);+ this.numSourcePositionX.Name = "numSourcePositionX";+ this.numSourcePositionX.Size = new global::System.Drawing.Size(65, 22);+ this.numSourcePositionX.TabIndex = 11;+ this.numSourcePositionX.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.Label36.AutoSize = true;+ this.Label36.Location = new global::System.Drawing.Point(123, 11);+ this.Label36.Name = "Label36";+ this.Label36.Size = new global::System.Drawing.Size(16, 16);+ this.Label36.TabIndex = 7;+ this.Label36.Text = "X";+ this.lblPosition.AutoSize = true;+ this.lblPosition.Location = new global::System.Drawing.Point(16, 6);+ this.lblPosition.Name = "lblPosition";+ this.lblPosition.Size = new global::System.Drawing.Size(97, 16);+ this.lblPosition.TabIndex = 12;+ this.lblPosition.Text = "Center position";+ this.btnPickSourcePosition.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 14.25f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnPickSourcePosition.Location = new global::System.Drawing.Point(15, 31);+ this.btnPickSourcePosition.Name = "btnPickSourcePosition";+ this.btnPickSourcePosition.Size = new global::System.Drawing.Size(102, 35);+ this.btnPickSourcePosition.TabIndex = 9;+ this.btnPickSourcePosition.Text = "Pick ";+ this.btnPickSourcePosition.UseVisualStyleBackColor = true;+ this.numSourcePositionY.Location = new global::System.Drawing.Point(146, 41);+ this.numSourcePositionY.Name = "numSourcePositionY";+ this.numSourcePositionY.Size = new global::System.Drawing.Size(65, 22);+ this.numSourcePositionY.TabIndex = 10;+ this.numSourcePositionY.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.Label35.AutoSize = true;+ this.Label35.Location = new global::System.Drawing.Point(123, 43);+ this.Label35.Name = "Label35";+ this.Label35.Size = new global::System.Drawing.Size(17, 16);+ this.Label35.TabIndex = 6;+ this.Label35.Text = "Y";+ this.btnDelete.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnDelete.Location = new global::System.Drawing.Point(1389, 245);+ this.btnDelete.Name = "btnDelete";+ this.btnDelete.Size = new global::System.Drawing.Size(70, 29);+ this.btnDelete.TabIndex = 2;+ this.btnDelete.Text = "Delete";+ this.btnDelete.UseVisualStyleBackColor = true;+ this.btnNew.BackColor = global::System.Drawing.Color.Azure;+ this.btnNew.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnNew.Location = new global::System.Drawing.Point(1189, 245);+ this.btnNew.Name = "btnNew";+ this.btnNew.Size = new global::System.Drawing.Size(70, 28);+ this.btnNew.TabIndex = 2;+ this.btnNew.Text = "New";+ this.btnNew.UseVisualStyleBackColor = false;+ this.btnCopy.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnCopy.Location = new global::System.Drawing.Point(1314, 244);+ this.btnCopy.Name = "btnCopy";+ this.btnCopy.Size = new global::System.Drawing.Size(70, 29);+ this.btnCopy.TabIndex = 2;+ this.btnCopy.Text = "Copy";+ this.btnCopy.UseVisualStyleBackColor = true;+ this.lstSources.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lstSources.FormattingEnabled = true;+ this.lstSources.ItemHeight = 16;+ this.lstSources.Location = new global::System.Drawing.Point(1187, 43);+ this.lstSources.Name = "lstSources";+ this.lstSources.Size = new global::System.Drawing.Size(273, 196);+ this.lstSources.TabIndex = 1;+ this.pnlSourceImage.Location = new global::System.Drawing.Point(16, 14);+ this.pnlSourceImage.Name = "pnlSourceImage";+ this.pnlSourceImage.Size = new global::System.Drawing.Size(1160, 653);+ this.pnlSourceImage.TabIndex = 0;+ this.grpSourceDetails.Controls.Add(this.txtDetachAfterSteps);+ this.grpSourceDetails.Controls.Add(this.btnSaveSource);+ this.grpSourceDetails.Controls.Add(this.Label47);+ this.grpSourceDetails.Controls.Add(this.chkDetachSource);+ this.grpSourceDetails.Controls.Add(this.lblLambdaIs);+ this.grpSourceDetails.Controls.Add(this.chkSourceOn);+ this.grpSourceDetails.Controls.Add(this.grpComposite);+ this.grpSourceDetails.Controls.Add(this.grpSingleSource);+ this.grpSourceDetails.Controls.Add(this.radModePulsed);+ this.grpSourceDetails.Controls.Add(this.radModeContinuous);+ this.grpSourceDetails.Controls.Add(this.txtName);+ this.grpSourceDetails.Controls.Add(this.cmbMainType);+ this.grpSourceDetails.Controls.Add(this.Label39);+ this.grpSourceDetails.Controls.Add(this.lblName);+ this.grpSourceDetails.Controls.Add(this.Label38);+ this.grpSourceDetails.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.grpSourceDetails.Location = new global::System.Drawing.Point(1471, 15);+ this.grpSourceDetails.Name = "grpSourceDetails";+ this.grpSourceDetails.Size = new global::System.Drawing.Size(254, 666);+ this.grpSourceDetails.TabIndex = 3;+ this.grpSourceDetails.TabStop = false;+ this.grpSourceDetails.Text = "Source ";+ this.txtDetachAfterSteps.BorderStyle = global::System.Windows.Forms.BorderStyle.FixedSingle;+ this.txtDetachAfterSteps.Location = new global::System.Drawing.Point(128, 591);+ this.txtDetachAfterSteps.Name = "txtDetachAfterSteps";+ this.txtDetachAfterSteps.Size = new global::System.Drawing.Size(65, 22);+ this.txtDetachAfterSteps.TabIndex = 23;+ this.btnSaveSource.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnSaveSource.Location = new global::System.Drawing.Point(12, 623);+ this.btnSaveSource.Name = "btnSaveSource";+ this.btnSaveSource.Size = new global::System.Drawing.Size(228, 30);+ this.btnSaveSource.TabIndex = 17;+ this.btnSaveSource.Text = "Save source data";+ this.btnSaveSource.UseVisualStyleBackColor = true;+ this.Label47.AutoSize = true;+ this.Label47.Location = new global::System.Drawing.Point(199, 594);+ this.Label47.Name = "Label47";+ this.Label47.Size = new global::System.Drawing.Size(41, 16);+ this.Label47.TabIndex = 22;+ this.Label47.Text = "steps";+ this.chkDetachSource.AutoSize = true;+ this.chkDetachSource.Location = new global::System.Drawing.Point(23, 592);+ this.chkDetachSource.Name = "chkDetachSource";+ this.chkDetachSource.Size = new global::System.Drawing.Size(99, 20);+ this.chkDetachSource.TabIndex = 21;+ this.chkDetachSource.Text = "Detach after";+ this.chkDetachSource.UseVisualStyleBackColor = true;+ this.lblLambdaIs.AutoSize = true;+ this.lblLambdaIs.BackColor = global::System.Drawing.Color.White;+ this.lblLambdaIs.Location = new global::System.Drawing.Point(162, 1);+ this.lblLambdaIs.Name = "lblLambdaIs";+ this.lblLambdaIs.Size = new global::System.Drawing.Size(52, 16);+ this.lblLambdaIs.TabIndex = 19;+ this.lblLambdaIs.Text = "λ= px";+ this.chkSourceOn.AutoSize = true;+ this.chkSourceOn.Location = new global::System.Drawing.Point(60, 0);+ this.chkSourceOn.Name = "chkSourceOn";+ this.chkSourceOn.Size = new global::System.Drawing.Size(42, 20);+ this.chkSourceOn.TabIndex = 18;+ this.chkSourceOn.Text = "on";+ this.chkSourceOn.UseVisualStyleBackColor = true;+ this.grpComposite.Controls.Add(this.Label59);+ this.grpComposite.Controls.Add(this.Label58);+ this.grpComposite.Controls.Add(this.numRandomizeOffWidth);+ this.grpComposite.Controls.Add(this.numRandomizePosition);+ this.grpComposite.Controls.Add(this.NumRandomizePhase);+ this.grpComposite.Controls.Add(this.numRandomizeFrequency);+ this.grpComposite.Controls.Add(this.chkRandomizePhase);+ this.grpComposite.Controls.Add(this.chkRandomizePosition);+ this.grpComposite.Controls.Add(this.chkOffWidth);+ this.grpComposite.Controls.Add(this.chkRandomizeFrequency);+ this.grpComposite.Controls.Add(this.numSpacingSizeY);+ this.grpComposite.Controls.Add(this.numSpacingSizeX);+ this.grpComposite.Controls.Add(this.numArraySizeY);+ this.grpComposite.Controls.Add(this.numArraySizeX);+ this.grpComposite.Controls.Add(this.Label50);+ this.grpComposite.Controls.Add(this.Label51);+ this.grpComposite.Controls.Add(this.Label52);+ this.grpComposite.Controls.Add(this.Label53);+ this.grpComposite.Controls.Add(this.cmbCompositeProperties);+ this.grpComposite.Location = new global::System.Drawing.Point(12, 344);+ this.grpComposite.Name = "grpComposite";+ this.grpComposite.Size = new global::System.Drawing.Size(230, 241);+ this.grpComposite.TabIndex = 16;+ this.grpComposite.TabStop = false;+ this.grpComposite.Text = "Composite source";+ this.Label59.AutoSize = true;+ this.Label59.Location = new global::System.Drawing.Point(181, 17);+ this.Label59.Name = "Label59";+ this.Label59.Size = new global::System.Drawing.Size(15, 16);+ this.Label59.TabIndex = 16;+ this.Label59.Text = "y";+ this.Label58.AutoSize = true;+ this.Label58.Location = new global::System.Drawing.Point(110, 17);+ this.Label58.Name = "Label58";+ this.Label58.Size = new global::System.Drawing.Size(14, 16);+ this.Label58.TabIndex = 16;+ this.Label58.Text = "x";+ this.numRandomizeOffWidth.Location = new global::System.Drawing.Point(17, 208);+ global::System.Windows.Forms.NumericUpDown numRandomizeOffWidth = this.numRandomizeOffWidth;+ int[] array16 = new int[4];+ array16[0] = 10000;+ numRandomizeOffWidth.Maximum = new decimal(array16);+ this.numRandomizeOffWidth.Name = "numRandomizeOffWidth";+ this.numRandomizeOffWidth.Size = new global::System.Drawing.Size(81, 22);+ this.numRandomizeOffWidth.TabIndex = 14;+ this.numRandomizeOffWidth.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.numRandomizePosition.Location = new global::System.Drawing.Point(129, 208);+ global::System.Windows.Forms.NumericUpDown numRandomizePosition = this.numRandomizePosition;+ int[] array17 = new int[4];+ array17[0] = 5;+ numRandomizePosition.Maximum = new decimal(array17);+ this.numRandomizePosition.Name = "numRandomizePosition";+ this.numRandomizePosition.Size = new global::System.Drawing.Size(80, 22);+ this.numRandomizePosition.TabIndex = 14;+ this.numRandomizePosition.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.NumRandomizePhase.Location = new global::System.Drawing.Point(129, 162);+ global::System.Windows.Forms.NumericUpDown numRandomizePhase = this.NumRandomizePhase;+ int[] array18 = new int[4];+ array18[0] = 180;+ numRandomizePhase.Maximum = new decimal(array18);+ this.NumRandomizePhase.Name = "NumRandomizePhase";+ this.NumRandomizePhase.Size = new global::System.Drawing.Size(80, 22);+ this.NumRandomizePhase.TabIndex = 14;+ this.NumRandomizePhase.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.numRandomizeFrequency.Location = new global::System.Drawing.Point(18, 163);+ global::System.Windows.Forms.NumericUpDown numRandomizeFrequency = this.numRandomizeFrequency;+ int[] array19 = new int[4];+ array19[0] = 50;+ numRandomizeFrequency.Maximum = new decimal(array19);+ this.numRandomizeFrequency.Name = "numRandomizeFrequency";+ this.numRandomizeFrequency.Size = new global::System.Drawing.Size(80, 22);+ this.numRandomizeFrequency.TabIndex = 14;+ this.numRandomizeFrequency.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.chkRandomizePhase.AutoSize = true;+ this.chkRandomizePhase.Location = new global::System.Drawing.Point(129, 144);+ this.chkRandomizePhase.Name = "chkRandomizePhase";+ this.chkRandomizePhase.Size = new global::System.Drawing.Size(66, 20);+ this.chkRandomizePhase.TabIndex = 15;+ this.chkRandomizePhase.Text = "Phase";+ this.chkRandomizePhase.UseVisualStyleBackColor = true;+ this.chkRandomizePosition.AutoSize = true;+ this.chkRandomizePosition.Location = new global::System.Drawing.Point(129, 190);+ this.chkRandomizePosition.Name = "chkRandomizePosition";+ this.chkRandomizePosition.Size = new global::System.Drawing.Size(75, 20);+ this.chkRandomizePosition.TabIndex = 15;+ this.chkRandomizePosition.Text = "Position";+ this.chkRandomizePosition.UseVisualStyleBackColor = true;+ this.chkOffWidth.AutoSize = true;+ this.chkOffWidth.Location = new global::System.Drawing.Point(17, 190);+ this.chkOffWidth.Name = "chkOffWidth";+ this.chkOffWidth.Size = new global::System.Drawing.Size(75, 20);+ this.chkOffWidth.TabIndex = 15;+ this.chkOffWidth.Text = "Off state";+ this.chkOffWidth.UseVisualStyleBackColor = true;+ this.chkRandomizeFrequency.AutoSize = true;+ this.chkRandomizeFrequency.Location = new global::System.Drawing.Point(19, 145);+ this.chkRandomizeFrequency.Name = "chkRandomizeFrequency";+ this.chkRandomizeFrequency.Size = new global::System.Drawing.Size(91, 20);+ this.chkRandomizeFrequency.TabIndex = 15;+ this.chkRandomizeFrequency.Text = "Frequency";+ this.chkRandomizeFrequency.UseVisualStyleBackColor = true;+ this.numSpacingSizeY.Location = new global::System.Drawing.Point(161, 64);+ this.numSpacingSizeY.Name = "numSpacingSizeY";+ this.numSpacingSizeY.Size = new global::System.Drawing.Size(55, 22);+ this.numSpacingSizeY.TabIndex = 14;+ this.numSpacingSizeY.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.numSpacingSizeX.Location = new global::System.Drawing.Point(94, 64);+ this.numSpacingSizeX.Name = "numSpacingSizeX";+ this.numSpacingSizeX.Size = new global::System.Drawing.Size(55, 22);+ this.numSpacingSizeX.TabIndex = 14;+ this.numSpacingSizeX.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numArraySizeY = this.numArraySizeY;+ int[] array20 = new int[4];+ array20[0] = 2;+ numArraySizeY.Increment = new decimal(array20);+ this.numArraySizeY.Location = new global::System.Drawing.Point(161, 36);+ global::System.Windows.Forms.NumericUpDown numArraySizeY2 = this.numArraySizeY;+ int[] array21 = new int[4];+ array21[0] = 101;+ numArraySizeY2.Maximum = new decimal(array21);+ global::System.Windows.Forms.NumericUpDown numArraySizeY3 = this.numArraySizeY;+ int[] array22 = new int[4];+ array22[0] = 1;+ numArraySizeY3.Minimum = new decimal(array22);+ this.numArraySizeY.Name = "numArraySizeY";+ this.numArraySizeY.Size = new global::System.Drawing.Size(55, 22);+ this.numArraySizeY.TabIndex = 14;+ this.numArraySizeY.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numArraySizeY4 = this.numArraySizeY;+ int[] array23 = new int[4];+ array23[0] = 1;+ numArraySizeY4.Value = new decimal(array23);+ global::System.Windows.Forms.NumericUpDown numArraySizeX = this.numArraySizeX;+ int[] array24 = new int[4];+ array24[0] = 2;+ numArraySizeX.Increment = new decimal(array24);+ this.numArraySizeX.Location = new global::System.Drawing.Point(93, 36);+ global::System.Windows.Forms.NumericUpDown numArraySizeX2 = this.numArraySizeX;+ int[] array25 = new int[4];+ array25[0] = 101;+ numArraySizeX2.Maximum = new decimal(array25);+ global::System.Windows.Forms.NumericUpDown numArraySizeX3 = this.numArraySizeX;+ int[] array26 = new int[4];+ array26[0] = 1;+ numArraySizeX3.Minimum = new decimal(array26);+ this.numArraySizeX.Name = "numArraySizeX";+ this.numArraySizeX.Size = new global::System.Drawing.Size(55, 22);+ this.numArraySizeX.TabIndex = 14;+ this.numArraySizeX.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numArraySizeX4 = this.numArraySizeX;+ int[] array27 = new int[4];+ array27[0] = 1;+ numArraySizeX4.Value = new decimal(array27);+ this.Label50.AutoSize = true;+ this.Label50.Location = new global::System.Drawing.Point(15, 124);+ this.Label50.Name = "Label50";+ this.Label50.Size = new global::System.Drawing.Size(77, 16);+ this.Label50.TabIndex = 0;+ this.Label50.Text = "Randomize";+ this.Label51.AutoSize = true;+ this.Label51.Location = new global::System.Drawing.Point(15, 96);+ this.Label51.Name = "Label51";+ this.Label51.Size = new global::System.Drawing.Size(70, 16);+ this.Label51.TabIndex = 0;+ this.Label51.Text = "Properties";+ this.Label52.AutoSize = true;+ this.Label52.Location = new global::System.Drawing.Point(15, 66);+ this.Label52.Name = "Label52";+ this.Label52.Size = new global::System.Drawing.Size(61, 16);+ this.Label52.TabIndex = 0;+ this.Label52.Text = "Spacing ";+ this.Label53.AutoSize = true;+ this.Label53.Location = new global::System.Drawing.Point(15, 36);+ this.Label53.Name = "Label53";+ this.Label53.Size = new global::System.Drawing.Size(67, 16);+ this.Label53.TabIndex = 0;+ this.Label53.Text = "Array size";+ this.cmbCompositeProperties.Enabled = false;+ this.cmbCompositeProperties.FormattingEnabled = true;+ this.cmbCompositeProperties.Items.AddRange(new object[] { "Inherit from single", "Inherit + randomize" });+ this.cmbCompositeProperties.Location = new global::System.Drawing.Point(88, 93);+ this.cmbCompositeProperties.Name = "cmbCompositeProperties";+ this.cmbCompositeProperties.Size = new global::System.Drawing.Size(134, 24);+ this.cmbCompositeProperties.TabIndex = 13;+ this.grpSingleSource.Controls.Add(this.numOffStateCycles);+ this.grpSingleSource.Controls.Add(this.numPhase);+ this.grpSingleSource.Controls.Add(this.numAmplitude);+ this.grpSingleSource.Controls.Add(this.numFrequency);+ this.grpSingleSource.Controls.Add(this.numPulseWidthCycles);+ this.grpSingleSource.Controls.Add(this.Label44);+ this.grpSingleSource.Controls.Add(this.Label46);+ this.grpSingleSource.Controls.Add(this.Label45);+ this.grpSingleSource.Controls.Add(this.Label43);+ this.grpSingleSource.Controls.Add(this.Label42);+ this.grpSingleSource.Controls.Add(this.Label54);+ this.grpSingleSource.Controls.Add(this.Label41);+ this.grpSingleSource.Controls.Add(this.Label40);+ this.grpSingleSource.Controls.Add(this.cmbPulseShape);+ this.grpSingleSource.Location = new global::System.Drawing.Point(12, 126);+ this.grpSingleSource.Name = "grpSingleSource";+ this.grpSingleSource.Size = new global::System.Drawing.Size(230, 213);+ this.grpSingleSource.TabIndex = 16;+ this.grpSingleSource.TabStop = false;+ this.grpSingleSource.Text = "Single source properties";+ this.numOffStateCycles.Location = new global::System.Drawing.Point(106, 179);+ global::System.Windows.Forms.NumericUpDown numOffStateCycles = this.numOffStateCycles;+ int[] array28 = new int[4];+ array28[0] = 100000;+ numOffStateCycles.Maximum = new decimal(array28);+ global::System.Windows.Forms.NumericUpDown numOffStateCycles2 = this.numOffStateCycles;+ int[] array29 = new int[4];+ array29[0] = 1;+ numOffStateCycles2.Minimum = new decimal(array29);+ this.numOffStateCycles.Name = "numOffStateCycles";+ this.numOffStateCycles.Size = new global::System.Drawing.Size(64, 22);+ this.numOffStateCycles.TabIndex = 14;+ this.numOffStateCycles.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numOffStateCycles3 = this.numOffStateCycles;+ int[] array30 = new int[4];+ array30[0] = 10;+ numOffStateCycles3.Value = new decimal(array30);+ this.numPhase.Location = new global::System.Drawing.Point(106, 87);+ global::System.Windows.Forms.NumericUpDown numPhase = this.numPhase;+ int[] array31 = new int[4];+ array31[0] = 180;+ numPhase.Maximum = new decimal(array31);+ this.numPhase.Minimum = new decimal(new int[] { 180, 0, 0, int.MinValue });+ this.numPhase.Name = "numPhase";+ this.numPhase.Size = new global::System.Drawing.Size(64, 22);+ this.numPhase.TabIndex = 14;+ this.numPhase.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.numAmplitude.Location = new global::System.Drawing.Point(106, 59);+ this.numAmplitude.Name = "numAmplitude";+ this.numAmplitude.Size = new global::System.Drawing.Size(64, 22);+ this.numAmplitude.TabIndex = 14;+ this.numAmplitude.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numAmplitude = this.numAmplitude;+ int[] array32 = new int[4];+ array32[0] = 100;+ numAmplitude.Value = new decimal(array32);+ this.numFrequency.Location = new global::System.Drawing.Point(106, 31);+ global::System.Windows.Forms.NumericUpDown numFrequency = this.numFrequency;+ int[] array33 = new int[4];+ array33[0] = 255;+ numFrequency.Maximum = new decimal(array33);+ global::System.Windows.Forms.NumericUpDown numFrequency2 = this.numFrequency;+ int[] array34 = new int[4];+ array34[0] = 1;+ numFrequency2.Minimum = new decimal(array34);+ this.numFrequency.Name = "numFrequency";+ this.numFrequency.Size = new global::System.Drawing.Size(64, 22);+ this.numFrequency.TabIndex = 14;+ this.numFrequency.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numFrequency3 = this.numFrequency;+ int[] array35 = new int[4];+ array35[0] = 100;+ numFrequency3.Value = new decimal(array35);+ this.numPulseWidthCycles.Location = new global::System.Drawing.Point(106, 151);+ this.numPulseWidthCycles.Name = "numPulseWidthCycles";+ this.numPulseWidthCycles.Size = new global::System.Drawing.Size(64, 22);+ this.numPulseWidthCycles.TabIndex = 14;+ this.numPulseWidthCycles.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numPulseWidthCycles = this.numPulseWidthCycles;+ int[] array36 = new int[4];+ array36[0] = 10;+ numPulseWidthCycles.Value = new decimal(array36);+ this.Label44.AutoSize = true;+ this.Label44.Location = new global::System.Drawing.Point(15, 182);+ this.Label44.Name = "Label44";+ this.Label44.Size = new global::System.Drawing.Size(56, 16);+ this.Label44.TabIndex = 0;+ this.Label44.Text = "Off state";+ this.Label46.AutoSize = true;+ this.Label46.Location = new global::System.Drawing.Point(176, 181);+ this.Label46.Name = "Label46";+ this.Label46.Size = new global::System.Drawing.Size(47, 16);+ this.Label46.TabIndex = 0;+ this.Label46.Text = "cycles";+ this.Label45.AutoSize = true;+ this.Label45.Location = new global::System.Drawing.Point(176, 153);+ this.Label45.Name = "Label45";+ this.Label45.Size = new global::System.Drawing.Size(47, 16);+ this.Label45.TabIndex = 0;+ this.Label45.Text = "cycles";+ this.Label43.AutoSize = true;+ this.Label43.Location = new global::System.Drawing.Point(15, 153);+ this.Label43.Name = "Label43";+ this.Label43.Size = new global::System.Drawing.Size(75, 16);+ this.Label43.TabIndex = 0;+ this.Label43.Text = "Pulse width";+ this.Label42.AutoSize = true;+ this.Label42.Location = new global::System.Drawing.Point(15, 121);+ this.Label42.Name = "Label42";+ this.Label42.Size = new global::System.Drawing.Size(83, 16);+ this.Label42.TabIndex = 0;+ this.Label42.Text = "Pulse shape";+ this.Label54.AutoSize = true;+ this.Label54.Location = new global::System.Drawing.Point(14, 89);+ this.Label54.Name = "Label54";+ this.Label54.Size = new global::System.Drawing.Size(47, 16);+ this.Label54.TabIndex = 0;+ this.Label54.Text = "Phase";+ this.Label41.AutoSize = true;+ this.Label41.Location = new global::System.Drawing.Point(14, 61);+ this.Label41.Name = "Label41";+ this.Label41.Size = new global::System.Drawing.Size(68, 16);+ this.Label41.TabIndex = 0;+ this.Label41.Text = "Amplitude";+ this.Label40.AutoSize = true;+ this.Label40.Location = new global::System.Drawing.Point(14, 33);+ this.Label40.Name = "Label40";+ this.Label40.Size = new global::System.Drawing.Size(72, 16);+ this.Label40.TabIndex = 0;+ this.Label40.Text = "Frequency";+ this.cmbPulseShape.Enabled = false;+ this.cmbPulseShape.FormattingEnabled = true;+ this.cmbPulseShape.Items.AddRange(new object[] { "Gaussian", "Smoothed square" });+ this.cmbPulseShape.Location = new global::System.Drawing.Point(106, 118);+ this.cmbPulseShape.Name = "cmbPulseShape";+ this.cmbPulseShape.Size = new global::System.Drawing.Size(110, 24);+ this.cmbPulseShape.TabIndex = 13;+ this.radModePulsed.AutoSize = true;+ this.radModePulsed.Location = new global::System.Drawing.Point(156, 97);+ this.radModePulsed.Name = "radModePulsed";+ this.radModePulsed.Size = new global::System.Drawing.Size(68, 20);+ this.radModePulsed.TabIndex = 15;+ this.radModePulsed.TabStop = true;+ this.radModePulsed.Text = "Pulsed";+ this.radModePulsed.UseVisualStyleBackColor = true;+ this.radModeContinuous.AutoSize = true;+ this.radModeContinuous.Location = new global::System.Drawing.Point(65, 97);+ this.radModeContinuous.Name = "radModeContinuous";+ this.radModeContinuous.Size = new global::System.Drawing.Size(92, 20);+ this.radModeContinuous.TabIndex = 15;+ this.radModeContinuous.TabStop = true;+ this.radModeContinuous.Text = "Continuous";+ this.radModeContinuous.UseVisualStyleBackColor = true;+ this.txtName.BorderStyle = global::System.Windows.Forms.BorderStyle.FixedSingle;+ this.txtName.Location = new global::System.Drawing.Point(92, 30);+ this.txtName.Name = "txtName";+ this.txtName.Size = new global::System.Drawing.Size(142, 22);+ this.txtName.TabIndex = 14;+ this.cmbMainType.FormattingEnabled = true;+ this.cmbMainType.Items.AddRange(new object[] { "Single point", "Composite" });+ this.cmbMainType.Location = new global::System.Drawing.Point(92, 61);+ this.cmbMainType.Name = "cmbMainType";+ this.cmbMainType.Size = new global::System.Drawing.Size(142, 24);+ this.cmbMainType.TabIndex = 13;+ this.Label39.AutoSize = true;+ this.Label39.Location = new global::System.Drawing.Point(20, 99);+ this.Label39.Name = "Label39";+ this.Label39.Size = new global::System.Drawing.Size(43, 16);+ this.Label39.TabIndex = 12;+ this.Label39.Text = "Mode";+ this.lblName.AutoSize = true;+ this.lblName.Location = new global::System.Drawing.Point(20, 33);+ this.lblName.Name = "lblName";+ this.lblName.Size = new global::System.Drawing.Size(45, 16);+ this.lblName.TabIndex = 12;+ this.lblName.Text = "Name";+ this.Label38.AutoSize = true;+ this.Label38.Location = new global::System.Drawing.Point(20, 64);+ this.Label38.Name = "Label38";+ this.Label38.Size = new global::System.Drawing.Size(66, 16);+ this.Label38.TabIndex = 12;+ this.Label38.Text = "Main type";+ this.tabProbeList.Controls.Add(this.GroupBox2);+ this.tabProbeList.Controls.Add(this.grpProbe2);+ this.tabProbeList.Controls.Add(this.grpProbe1);+ this.tabProbeList.Controls.Add(this.pnlProbeImage);+ this.tabProbeList.Location = new global::System.Drawing.Point(4, 34);+ this.tabProbeList.Name = "tabProbeList";+ this.tabProbeList.Size = new global::System.Drawing.Size(1742, 693);+ this.tabProbeList.TabIndex = 2;+ this.tabProbeList.Text = " Probes ";+ this.tabProbeList.UseVisualStyleBackColor = true;+ this.GroupBox2.Controls.Add(this.Label49);+ this.GroupBox2.Controls.Add(this.Label48);+ this.GroupBox2.Controls.Add(this.Label37);+ this.GroupBox2.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.GroupBox2.Location = new global::System.Drawing.Point(1201, 584);+ this.GroupBox2.Name = "GroupBox2";+ this.GroupBox2.Size = new global::System.Drawing.Size(504, 83);+ this.GroupBox2.TabIndex = 2;+ this.GroupBox2.TabStop = false;+ this.GroupBox2.Text = "How to use probes";+ this.Label49.AutoSize = true;+ this.Label49.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label49.Location = new global::System.Drawing.Point(15, 60);+ this.Label49.Name = "Label49";+ this.Label49.Size = new global::System.Drawing.Size(430, 16);+ this.Label49.TabIndex = 0;+ this.Label49.Text = "- Probe type \"Line\": Use 2 clicks to set line, then third click to place plot .";+ this.Label48.AutoSize = true;+ this.Label48.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label48.Location = new global::System.Drawing.Point(14, 42);+ this.Label48.Name = "Label48";+ this.Label48.Size = new global::System.Drawing.Size(461, 16);+ this.Label48.TabIndex = 0;+ this.Label48.Text = "- Probe type \"Point\": First click sets probe location, second sets data window";+ this.Label37.AutoSize = true;+ this.Label37.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label37.Location = new global::System.Drawing.Point(15, 22);+ this.Label37.Name = "Label37";+ this.Label37.Size = new global::System.Drawing.Size(442, 16);+ this.Label37.TabIndex = 0;+ this.Label37.Text = "Set all properties first and then use the \"Pick\" button to choose a location. ";+ this.grpProbe2.BackColor = global::System.Drawing.Color.Gainsboro;+ this.grpProbe2.Controls.Add(this.Label22);+ this.grpProbe2.Controls.Add(this.numRunningWindow2);+ this.grpProbe2.Controls.Add(this.chkProbeOn2);+ this.grpProbe2.Controls.Add(this.txtStartAfterStep2);+ this.grpProbe2.Controls.Add(this.chkStartAfterStep2);+ this.grpProbe2.Controls.Add(this.Label23);+ this.grpProbe2.Controls.Add(this.Label24);+ this.grpProbe2.Controls.Add(this.txtMaxScaleY2);+ this.grpProbe2.Controls.Add(this.txtMinScaleY2);+ this.grpProbe2.Controls.Add(this.radFullScale2);+ this.grpProbe2.Controls.Add(this.radRunningScale2);+ this.grpProbe2.Controls.Add(this.chkAutoScaleY2);+ this.grpProbe2.Controls.Add(this.chkAutoScaleX2);+ this.grpProbe2.Controls.Add(this.numBPosY2);+ this.grpProbe2.Controls.Add(this.numAPosY2);+ this.grpProbe2.Controls.Add(this.numBPosX2);+ this.grpProbe2.Controls.Add(this.numAPosX2);+ this.grpProbe2.Controls.Add(this.butPicPositions2);+ this.grpProbe2.Controls.Add(this.Label25);+ this.grpProbe2.Controls.Add(this.cmbPlaceOn2);+ this.grpProbe2.Controls.Add(this.cmbMeasurement2);+ this.grpProbe2.Controls.Add(this.Label26);+ this.grpProbe2.Controls.Add(this.Label27);+ this.grpProbe2.Controls.Add(this.cmbBoxSize2);+ this.grpProbe2.Controls.Add(this.cmbProbeType2);+ this.grpProbe2.Controls.Add(this.Label28);+ this.grpProbe2.Controls.Add(this.Label29);+ this.grpProbe2.Controls.Add(this.Label30);+ this.grpProbe2.Controls.Add(this.Label31);+ this.grpProbe2.Controls.Add(this.Label32);+ this.grpProbe2.Controls.Add(this.Label33);+ this.grpProbe2.Controls.Add(this.Label34);+ this.grpProbe2.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.grpProbe2.Location = new global::System.Drawing.Point(1202, 303);+ this.grpProbe2.Name = "grpProbe2";+ this.grpProbe2.Size = new global::System.Drawing.Size(506, 276);+ this.grpProbe2.TabIndex = 1;+ this.grpProbe2.TabStop = false;+ this.grpProbe2.Text = "Probe 2 ";+ this.Label22.AutoSize = true;+ this.Label22.Location = new global::System.Drawing.Point(259, 59);+ this.Label22.Name = "Label22";+ this.Label22.Size = new global::System.Drawing.Size(104, 16);+ this.Label22.TabIndex = 14;+ this.Label22.Text = "Running window";+ this.numRunningWindow2.Location = new global::System.Drawing.Point(371, 58);+ global::System.Windows.Forms.NumericUpDown numRunningWindow = this.numRunningWindow2;+ int[] array37 = new int[4];+ array37[0] = 1000000;+ numRunningWindow.Maximum = new decimal(array37);+ global::System.Windows.Forms.NumericUpDown numRunningWindow2 = this.numRunningWindow2;+ int[] array38 = new int[4];+ array38[0] = 10;+ numRunningWindow2.Minimum = new decimal(array38);+ this.numRunningWindow2.Name = "numRunningWindow2";+ this.numRunningWindow2.Size = new global::System.Drawing.Size(83, 22);+ this.numRunningWindow2.TabIndex = 13;+ this.numRunningWindow2.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numRunningWindow3 = this.numRunningWindow2;+ int[] array39 = new int[4];+ array39[0] = 500;+ numRunningWindow3.Value = new decimal(array39);+ this.chkProbeOn2.AutoSize = true;+ this.chkProbeOn2.Location = new global::System.Drawing.Point(66, -1);+ this.chkProbeOn2.Name = "chkProbeOn2";+ this.chkProbeOn2.Size = new global::System.Drawing.Size(44, 20);+ this.chkProbeOn2.TabIndex = 12;+ this.chkProbeOn2.Text = "On";+ this.chkProbeOn2.UseVisualStyleBackColor = true;+ this.txtStartAfterStep2.Location = new global::System.Drawing.Point(179, 163);+ this.txtStartAfterStep2.Name = "txtStartAfterStep2";+ this.txtStartAfterStep2.Size = new global::System.Drawing.Size(57, 22);+ this.txtStartAfterStep2.TabIndex = 11;+ this.txtStartAfterStep2.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Right;+ this.chkStartAfterStep2.AutoSize = true;+ this.chkStartAfterStep2.Location = new global::System.Drawing.Point(17, 165);+ this.chkStartAfterStep2.Name = "chkStartAfterStep2";+ this.chkStartAfterStep2.Size = new global::System.Drawing.Size(167, 20);+ this.chkStartAfterStep2.TabIndex = 10;+ this.chkStartAfterStep2.Text = "Start recording at step #";+ this.chkStartAfterStep2.UseVisualStyleBackColor = true;+ this.Label23.AutoSize = true;+ this.Label23.Location = new global::System.Drawing.Point(438, 111);+ this.Label23.Name = "Label23";+ this.Label23.Size = new global::System.Drawing.Size(33, 16);+ this.Label23.TabIndex = 2;+ this.Label23.Text = "Max";+ this.Label24.AutoSize = true;+ this.Label24.Location = new global::System.Drawing.Point(378, 111);+ this.Label24.Name = "Label24";+ this.Label24.Size = new global::System.Drawing.Size(29, 16);+ this.Label24.TabIndex = 2;+ this.Label24.Text = "Min";+ this.txtMaxScaleY2.Location = new global::System.Drawing.Point(431, 127);+ this.txtMaxScaleY2.Name = "txtMaxScaleY2";+ this.txtMaxScaleY2.Size = new global::System.Drawing.Size(52, 22);+ this.txtMaxScaleY2.TabIndex = 8;+ this.txtMaxScaleY2.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Right;+ this.txtMinScaleY2.Location = new global::System.Drawing.Point(371, 127);+ this.txtMinScaleY2.Name = "txtMinScaleY2";+ this.txtMinScaleY2.Size = new global::System.Drawing.Size(52, 22);+ this.txtMinScaleY2.TabIndex = 8;+ this.txtMinScaleY2.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Right;+ this.radFullScale2.AutoSize = true;+ this.radFullScale2.Location = new global::System.Drawing.Point(379, 24);+ this.radFullScale2.Name = "radFullScale2";+ this.radFullScale2.Size = new global::System.Drawing.Size(83, 20);+ this.radFullScale2.TabIndex = 7;+ this.radFullScale2.TabStop = true;+ this.radFullScale2.Text = "Full scale";+ this.radFullScale2.UseVisualStyleBackColor = true;+ this.radRunningScale2.AutoSize = true;+ this.radRunningScale2.Location = new global::System.Drawing.Point(262, 24);+ this.radRunningScale2.Name = "radRunningScale2";+ this.radRunningScale2.Size = new global::System.Drawing.Size(111, 20);+ this.radRunningScale2.TabIndex = 7;+ this.radRunningScale2.TabStop = true;+ this.radRunningScale2.Text = "Running scale";+ this.radRunningScale2.UseVisualStyleBackColor = true;+ this.chkAutoScaleY2.AutoSize = true;+ this.chkAutoScaleY2.Location = new global::System.Drawing.Point(262, 127);+ this.chkAutoScaleY2.Name = "chkAutoScaleY2";+ this.chkAutoScaleY2.Size = new global::System.Drawing.Size(110, 20);+ this.chkAutoScaleY2.TabIndex = 6;+ this.chkAutoScaleY2.Text = "Auto Scale Y";+ this.chkAutoScaleY2.UseVisualStyleBackColor = true;+ this.chkAutoScaleX2.AutoSize = true;+ this.chkAutoScaleX2.Location = new global::System.Drawing.Point(262, 91);+ this.chkAutoScaleX2.Name = "chkAutoScaleX2";+ this.chkAutoScaleX2.Size = new global::System.Drawing.Size(101, 20);+ this.chkAutoScaleX2.TabIndex = 6;+ this.chkAutoScaleX2.Text = "Auto scale X";+ this.chkAutoScaleX2.UseVisualStyleBackColor = true;+ this.numBPosY2.Location = new global::System.Drawing.Point(326, 234);+ this.numBPosY2.Name = "numBPosY2";+ this.numBPosY2.Size = new global::System.Drawing.Size(65, 22);+ this.numBPosY2.TabIndex = 5;+ this.numBPosY2.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.numAPosY2.Location = new global::System.Drawing.Point(126, 234);+ this.numAPosY2.Name = "numAPosY2";+ this.numAPosY2.Size = new global::System.Drawing.Size(65, 22);+ this.numAPosY2.TabIndex = 5;+ this.numAPosY2.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.numBPosX2.Location = new global::System.Drawing.Point(238, 234);+ this.numBPosX2.Name = "numBPosX2";+ this.numBPosX2.Size = new global::System.Drawing.Size(65, 22);+ this.numBPosX2.TabIndex = 5;+ this.numBPosX2.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.numAPosX2.Location = new global::System.Drawing.Point(38, 234);+ this.numAPosX2.Name = "numAPosX2";+ this.numAPosX2.Size = new global::System.Drawing.Size(65, 22);+ this.numAPosX2.TabIndex = 5;+ this.numAPosX2.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.butPicPositions2.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.butPicPositions2.Location = new global::System.Drawing.Point(402, 226);+ this.butPicPositions2.Name = "butPicPositions2";+ this.butPicPositions2.Size = new global::System.Drawing.Size(90, 34);+ this.butPicPositions2.TabIndex = 4;+ this.butPicPositions2.Text = "Pick ";+ this.butPicPositions2.UseVisualStyleBackColor = true;+ this.Label25.AutoSize = true;+ this.Label25.Location = new global::System.Drawing.Point(311, 236);+ this.Label25.Name = "Label25";+ this.Label25.Size = new global::System.Drawing.Size(17, 16);+ this.Label25.TabIndex = 2;+ this.Label25.Text = "Y";+ this.cmbPlaceOn2.FormattingEnabled = true;+ this.cmbPlaceOn2.Items.AddRange(new object[] { "Field", "Intensity" });+ this.cmbPlaceOn2.Location = new global::System.Drawing.Point(106, 24);+ this.cmbPlaceOn2.Name = "cmbPlaceOn2";+ this.cmbPlaceOn2.Size = new global::System.Drawing.Size(130, 24);+ this.cmbPlaceOn2.TabIndex = 3;+ this.cmbMeasurement2.FormattingEnabled = true;+ this.cmbMeasurement2.Items.AddRange(new object[] { "Amplitude", "Intensity", "Integrate Intensity" });+ this.cmbMeasurement2.Location = new global::System.Drawing.Point(106, 56);+ this.cmbMeasurement2.Name = "cmbMeasurement2";+ this.cmbMeasurement2.Size = new global::System.Drawing.Size(130, 24);+ this.cmbMeasurement2.TabIndex = 3;+ this.Label26.AutoSize = true;+ this.Label26.Location = new global::System.Drawing.Point(111, 236);+ this.Label26.Name = "Label26";+ this.Label26.Size = new global::System.Drawing.Size(17, 16);+ this.Label26.TabIndex = 2;+ this.Label26.Text = "Y";+ this.Label27.AutoSize = true;+ this.Label27.Location = new global::System.Drawing.Point(223, 236);+ this.Label27.Name = "Label27";+ this.Label27.Size = new global::System.Drawing.Size(16, 16);+ this.Label27.TabIndex = 2;+ this.Label27.Text = "X";+ this.cmbBoxSize2.FormattingEnabled = true;+ this.cmbBoxSize2.Items.AddRange(new object[] { "Tiny (200 x100)", "Small (300 x 150)", "Medium (400x200)", "Large (500x250)", "Extra Large (700x350)" });+ this.cmbBoxSize2.Location = new global::System.Drawing.Point(106, 124);+ this.cmbBoxSize2.Name = "cmbBoxSize2";+ this.cmbBoxSize2.Size = new global::System.Drawing.Size(130, 24);+ this.cmbBoxSize2.TabIndex = 3;+ this.cmbProbeType2.FormattingEnabled = true;+ this.cmbProbeType2.Items.AddRange(new object[] { "Point (A)", "Line (A-B)" });+ this.cmbProbeType2.Location = new global::System.Drawing.Point(106, 89);+ this.cmbProbeType2.Name = "cmbProbeType2";+ this.cmbProbeType2.Size = new global::System.Drawing.Size(130, 24);+ this.cmbProbeType2.TabIndex = 3;+ this.Label28.AutoSize = true;+ this.Label28.Location = new global::System.Drawing.Point(277, 209);+ this.Label28.Name = "Label28";+ this.Label28.Size = new global::System.Drawing.Size(68, 16);+ this.Label28.TabIndex = 2;+ this.Label28.Text = "Position B";+ this.Label29.AutoSize = true;+ this.Label29.Location = new global::System.Drawing.Point(23, 236);+ this.Label29.Name = "Label29";+ this.Label29.Size = new global::System.Drawing.Size(16, 16);+ this.Label29.TabIndex = 2;+ this.Label29.Text = "X";+ this.Label30.AutoSize = true;+ this.Label30.Location = new global::System.Drawing.Point(76, 209);+ this.Label30.Name = "Label30";+ this.Label30.Size = new global::System.Drawing.Size(68, 16);+ this.Label30.TabIndex = 2;+ this.Label30.Text = "Position A";+ this.Label31.AutoSize = true;+ this.Label31.Location = new global::System.Drawing.Point(14, 127);+ this.Label31.Name = "Label31";+ this.Label31.Size = new global::System.Drawing.Size(60, 16);+ this.Label31.TabIndex = 2;+ this.Label31.Text = "Box Size";+ this.Label32.AutoSize = true;+ this.Label32.Location = new global::System.Drawing.Point(14, 92);+ this.Label32.Name = "Label32";+ this.Label32.Size = new global::System.Drawing.Size(74, 16);+ this.Label32.TabIndex = 2;+ this.Label32.Text = "Probe type";+ this.Label33.AutoSize = true;+ this.Label33.Location = new global::System.Drawing.Point(12, 59);+ this.Label33.Name = "Label33";+ this.Label33.Size = new global::System.Drawing.Size(90, 16);+ this.Label33.TabIndex = 2;+ this.Label33.Text = "Measurement";+ this.Label34.AutoSize = true;+ this.Label34.Location = new global::System.Drawing.Point(14, 29);+ this.Label34.Name = "Label34";+ this.Label34.Size = new global::System.Drawing.Size(64, 16);+ this.Label34.TabIndex = 1;+ this.Label34.Text = "Place on:";+ this.grpProbe1.BackColor = global::System.Drawing.Color.Gainsboro;+ this.grpProbe1.Controls.Add(this.Label21);+ this.grpProbe1.Controls.Add(this.numRunningWindow);+ this.grpProbe1.Controls.Add(this.chkProbeOn1);+ this.grpProbe1.Controls.Add(this.txtStartAfterStep);+ this.grpProbe1.Controls.Add(this.chkStartAfterStep);+ this.grpProbe1.Controls.Add(this.Label19);+ this.grpProbe1.Controls.Add(this.Label18);+ this.grpProbe1.Controls.Add(this.txtMaxScaleY);+ this.grpProbe1.Controls.Add(this.txtMinScaleY);+ this.grpProbe1.Controls.Add(this.radFullScale);+ this.grpProbe1.Controls.Add(this.radRunningScale);+ this.grpProbe1.Controls.Add(this.chkAutoScaleY);+ this.grpProbe1.Controls.Add(this.chkAutoScaleX);+ this.grpProbe1.Controls.Add(this.numBPosY);+ this.grpProbe1.Controls.Add(this.numAPosY);+ this.grpProbe1.Controls.Add(this.numBPosX);+ this.grpProbe1.Controls.Add(this.numAPosX);+ this.grpProbe1.Controls.Add(this.butPicPositions);+ this.grpProbe1.Controls.Add(this.Label16);+ this.grpProbe1.Controls.Add(this.cmbPlaceOn);+ this.grpProbe1.Controls.Add(this.cmbMeasurement);+ this.grpProbe1.Controls.Add(this.Label13);+ this.grpProbe1.Controls.Add(this.Label15);+ this.grpProbe1.Controls.Add(this.cmbBoxSize);+ this.grpProbe1.Controls.Add(this.cmbProbeType);+ this.grpProbe1.Controls.Add(this.Label14);+ this.grpProbe1.Controls.Add(this.Label12);+ this.grpProbe1.Controls.Add(this.Label11);+ this.grpProbe1.Controls.Add(this.Label17);+ this.grpProbe1.Controls.Add(this.Label10);+ this.grpProbe1.Controls.Add(this.Label9);+ this.grpProbe1.Controls.Add(this.Label8);+ this.grpProbe1.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.grpProbe1.Location = new global::System.Drawing.Point(1202, 14);+ this.grpProbe1.Name = "grpProbe1";+ this.grpProbe1.Size = new global::System.Drawing.Size(506, 276);+ this.grpProbe1.TabIndex = 1;+ this.grpProbe1.TabStop = false;+ this.grpProbe1.Text = "Probe 1 ";+ this.Label21.AutoSize = true;+ this.Label21.Location = new global::System.Drawing.Point(259, 59);+ this.Label21.Name = "Label21";+ this.Label21.Size = new global::System.Drawing.Size(104, 16);+ this.Label21.TabIndex = 14;+ this.Label21.Text = "Running window";+ this.numRunningWindow.Location = new global::System.Drawing.Point(371, 58);+ global::System.Windows.Forms.NumericUpDown numRunningWindow4 = this.numRunningWindow;+ int[] array40 = new int[4];+ array40[0] = 1000000;+ numRunningWindow4.Maximum = new decimal(array40);+ global::System.Windows.Forms.NumericUpDown numRunningWindow5 = this.numRunningWindow;+ int[] array41 = new int[4];+ array41[0] = 10;+ numRunningWindow5.Minimum = new decimal(array41);+ this.numRunningWindow.Name = "numRunningWindow";+ this.numRunningWindow.Size = new global::System.Drawing.Size(83, 22);+ this.numRunningWindow.TabIndex = 13;+ this.numRunningWindow.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numRunningWindow6 = this.numRunningWindow;+ int[] array42 = new int[4];+ array42[0] = 500;+ numRunningWindow6.Value = new decimal(array42);+ this.chkProbeOn1.AutoSize = true;+ this.chkProbeOn1.Location = new global::System.Drawing.Point(66, -1);+ this.chkProbeOn1.Name = "chkProbeOn1";+ this.chkProbeOn1.Size = new global::System.Drawing.Size(44, 20);+ this.chkProbeOn1.TabIndex = 12;+ this.chkProbeOn1.Text = "On";+ this.chkProbeOn1.UseVisualStyleBackColor = true;+ this.txtStartAfterStep.Location = new global::System.Drawing.Point(179, 163);+ this.txtStartAfterStep.Name = "txtStartAfterStep";+ this.txtStartAfterStep.Size = new global::System.Drawing.Size(57, 22);+ this.txtStartAfterStep.TabIndex = 11;+ this.txtStartAfterStep.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Right;+ this.chkStartAfterStep.AutoSize = true;+ this.chkStartAfterStep.Location = new global::System.Drawing.Point(17, 165);+ this.chkStartAfterStep.Name = "chkStartAfterStep";+ this.chkStartAfterStep.Size = new global::System.Drawing.Size(167, 20);+ this.chkStartAfterStep.TabIndex = 10;+ this.chkStartAfterStep.Text = "Start recording at step #";+ this.chkStartAfterStep.UseVisualStyleBackColor = true;+ this.Label19.AutoSize = true;+ this.Label19.Location = new global::System.Drawing.Point(438, 111);+ this.Label19.Name = "Label19";+ this.Label19.Size = new global::System.Drawing.Size(33, 16);+ this.Label19.TabIndex = 2;+ this.Label19.Text = "Max";+ this.Label18.AutoSize = true;+ this.Label18.Location = new global::System.Drawing.Point(378, 111);+ this.Label18.Name = "Label18";+ this.Label18.Size = new global::System.Drawing.Size(29, 16);+ this.Label18.TabIndex = 2;+ this.Label18.Text = "Min";+ this.txtMaxScaleY.Location = new global::System.Drawing.Point(431, 127);+ this.txtMaxScaleY.Name = "txtMaxScaleY";+ this.txtMaxScaleY.Size = new global::System.Drawing.Size(52, 22);+ this.txtMaxScaleY.TabIndex = 8;+ this.txtMaxScaleY.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Right;+ this.txtMinScaleY.Location = new global::System.Drawing.Point(371, 127);+ this.txtMinScaleY.Name = "txtMinScaleY";+ this.txtMinScaleY.Size = new global::System.Drawing.Size(52, 22);+ this.txtMinScaleY.TabIndex = 8;+ this.txtMinScaleY.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Right;+ this.radFullScale.AutoSize = true;+ this.radFullScale.Location = new global::System.Drawing.Point(379, 24);+ this.radFullScale.Name = "radFullScale";+ this.radFullScale.Size = new global::System.Drawing.Size(83, 20);+ this.radFullScale.TabIndex = 7;+ this.radFullScale.TabStop = true;+ this.radFullScale.Text = "Full scale";+ this.radFullScale.UseVisualStyleBackColor = true;+ this.radRunningScale.AutoSize = true;+ this.radRunningScale.Location = new global::System.Drawing.Point(262, 24);+ this.radRunningScale.Name = "radRunningScale";+ this.radRunningScale.Size = new global::System.Drawing.Size(111, 20);+ this.radRunningScale.TabIndex = 7;+ this.radRunningScale.TabStop = true;+ this.radRunningScale.Text = "Running scale";+ this.radRunningScale.UseVisualStyleBackColor = true;+ this.chkAutoScaleY.AutoSize = true;+ this.chkAutoScaleY.Location = new global::System.Drawing.Point(262, 127);+ this.chkAutoScaleY.Name = "chkAutoScaleY";+ this.chkAutoScaleY.Size = new global::System.Drawing.Size(110, 20);+ this.chkAutoScaleY.TabIndex = 6;+ this.chkAutoScaleY.Text = "Auto Scale Y";+ this.chkAutoScaleY.UseVisualStyleBackColor = true;+ this.chkAutoScaleX.AutoSize = true;+ this.chkAutoScaleX.Location = new global::System.Drawing.Point(262, 91);+ this.chkAutoScaleX.Name = "chkAutoScaleX";+ this.chkAutoScaleX.Size = new global::System.Drawing.Size(101, 20);+ this.chkAutoScaleX.TabIndex = 6;+ this.chkAutoScaleX.Text = "Auto scale X";+ this.chkAutoScaleX.UseVisualStyleBackColor = true;+ this.numBPosY.Location = new global::System.Drawing.Point(326, 234);+ this.numBPosY.Name = "numBPosY";+ this.numBPosY.Size = new global::System.Drawing.Size(65, 22);+ this.numBPosY.TabIndex = 5;+ this.numBPosY.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.numAPosY.Location = new global::System.Drawing.Point(126, 234);+ this.numAPosY.Name = "numAPosY";+ this.numAPosY.Size = new global::System.Drawing.Size(65, 22);+ this.numAPosY.TabIndex = 5;+ this.numAPosY.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.numBPosX.Location = new global::System.Drawing.Point(238, 234);+ this.numBPosX.Name = "numBPosX";+ this.numBPosX.Size = new global::System.Drawing.Size(65, 22);+ this.numBPosX.TabIndex = 5;+ this.numBPosX.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.numAPosX.Location = new global::System.Drawing.Point(38, 234);+ this.numAPosX.Name = "numAPosX";+ this.numAPosX.Size = new global::System.Drawing.Size(65, 22);+ this.numAPosX.TabIndex = 5;+ this.numAPosX.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.butPicPositions.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.butPicPositions.Location = new global::System.Drawing.Point(402, 226);+ this.butPicPositions.Name = "butPicPositions";+ this.butPicPositions.Size = new global::System.Drawing.Size(90, 34);+ this.butPicPositions.TabIndex = 4;+ this.butPicPositions.Text = "Pick ";+ this.butPicPositions.UseVisualStyleBackColor = true;+ this.Label16.AutoSize = true;+ this.Label16.Location = new global::System.Drawing.Point(311, 236);+ this.Label16.Name = "Label16";+ this.Label16.Size = new global::System.Drawing.Size(17, 16);+ this.Label16.TabIndex = 2;+ this.Label16.Text = "Y";+ this.cmbPlaceOn.FormattingEnabled = true;+ this.cmbPlaceOn.Items.AddRange(new object[] { "Field", "Intensity" });+ this.cmbPlaceOn.Location = new global::System.Drawing.Point(106, 24);+ this.cmbPlaceOn.Name = "cmbPlaceOn";+ this.cmbPlaceOn.Size = new global::System.Drawing.Size(130, 24);+ this.cmbPlaceOn.TabIndex = 3;+ this.cmbMeasurement.FormattingEnabled = true;+ this.cmbMeasurement.Items.AddRange(new object[] { "Amplitude", "Intensity", "Integrate Intensity" });+ this.cmbMeasurement.Location = new global::System.Drawing.Point(106, 56);+ this.cmbMeasurement.Name = "cmbMeasurement";+ this.cmbMeasurement.Size = new global::System.Drawing.Size(130, 24);+ this.cmbMeasurement.TabIndex = 3;+ this.Label13.AutoSize = true;+ this.Label13.Location = new global::System.Drawing.Point(111, 236);+ this.Label13.Name = "Label13";+ this.Label13.Size = new global::System.Drawing.Size(17, 16);+ this.Label13.TabIndex = 2;+ this.Label13.Text = "Y";+ this.Label15.AutoSize = true;+ this.Label15.Location = new global::System.Drawing.Point(223, 236);+ this.Label15.Name = "Label15";+ this.Label15.Size = new global::System.Drawing.Size(16, 16);+ this.Label15.TabIndex = 2;+ this.Label15.Text = "X";+ this.cmbBoxSize.FormattingEnabled = true;+ this.cmbBoxSize.Items.AddRange(new object[] { "Tiny (200 x100)", "Small (300 x 150)", "Medium (400x200)", "Large (500x250)", "Extra Large (700x350)" });+ this.cmbBoxSize.Location = new global::System.Drawing.Point(106, 124);+ this.cmbBoxSize.Name = "cmbBoxSize";+ this.cmbBoxSize.Size = new global::System.Drawing.Size(130, 24);+ this.cmbBoxSize.TabIndex = 3;+ this.cmbProbeType.FormattingEnabled = true;+ this.cmbProbeType.Items.AddRange(new object[] { "Point (A)", "Line (A-B)" });+ this.cmbProbeType.Location = new global::System.Drawing.Point(106, 89);+ this.cmbProbeType.Name = "cmbProbeType";+ this.cmbProbeType.Size = new global::System.Drawing.Size(130, 24);+ this.cmbProbeType.TabIndex = 3;+ this.Label14.AutoSize = true;+ this.Label14.Location = new global::System.Drawing.Point(277, 209);+ this.Label14.Name = "Label14";+ this.Label14.Size = new global::System.Drawing.Size(68, 16);+ this.Label14.TabIndex = 2;+ this.Label14.Text = "Position B";+ this.Label12.AutoSize = true;+ this.Label12.Location = new global::System.Drawing.Point(23, 236);+ this.Label12.Name = "Label12";+ this.Label12.Size = new global::System.Drawing.Size(16, 16);+ this.Label12.TabIndex = 2;+ this.Label12.Text = "X";+ this.Label11.AutoSize = true;+ this.Label11.Location = new global::System.Drawing.Point(76, 209);+ this.Label11.Name = "Label11";+ this.Label11.Size = new global::System.Drawing.Size(68, 16);+ this.Label11.TabIndex = 2;+ this.Label11.Text = "Position A";+ this.Label17.AutoSize = true;+ this.Label17.Location = new global::System.Drawing.Point(14, 127);+ this.Label17.Name = "Label17";+ this.Label17.Size = new global::System.Drawing.Size(60, 16);+ this.Label17.TabIndex = 2;+ this.Label17.Text = "Box Size";+ this.Label10.AutoSize = true;+ this.Label10.Location = new global::System.Drawing.Point(14, 92);+ this.Label10.Name = "Label10";+ this.Label10.Size = new global::System.Drawing.Size(74, 16);+ this.Label10.TabIndex = 2;+ this.Label10.Text = "Probe type";+ this.Label9.AutoSize = true;+ this.Label9.Location = new global::System.Drawing.Point(12, 59);+ this.Label9.Name = "Label9";+ this.Label9.Size = new global::System.Drawing.Size(90, 16);+ this.Label9.TabIndex = 2;+ this.Label9.Text = "Measurement";+ this.Label8.AutoSize = true;+ this.Label8.Location = new global::System.Drawing.Point(14, 29);+ this.Label8.Name = "Label8";+ this.Label8.Size = new global::System.Drawing.Size(64, 16);+ this.Label8.TabIndex = 1;+ this.Label8.Text = "Place on:";+ this.pnlProbeImage.Location = new global::System.Drawing.Point(16, 14);+ this.pnlProbeImage.Name = "pnlProbeImage";+ this.pnlProbeImage.Size = new global::System.Drawing.Size(1160, 653);+ this.pnlProbeImage.TabIndex = 0;+ this.tabViewer.Controls.Add(this.pnlPreviewIntensityProps);+ this.tabViewer.Controls.Add(this.Panel3);+ this.tabViewer.Controls.Add(this.Label56);+ this.tabViewer.Controls.Add(this.Label55);+ this.tabViewer.Controls.Add(this.lblWarningIntensity);+ this.tabViewer.Controls.Add(this.lblWarningField);+ this.tabViewer.Controls.Add(this.btnExportIntensityFrame);+ this.tabViewer.Controls.Add(this.btnExportFieldFrame);+ this.tabViewer.Controls.Add(this.btnOpenImageFolder);+ this.tabViewer.Controls.Add(this.btnOpenVideoFolder);+ this.tabViewer.Controls.Add(this.btnViewIntensityVideo);+ this.tabViewer.Controls.Add(this.btnViewFieldVideo);+ this.tabViewer.Controls.Add(this.pnlPreviewIntensity);+ this.tabViewer.Controls.Add(this.pnlPreviewField);+ this.tabViewer.Location = new global::System.Drawing.Point(4, 34);+ this.tabViewer.Name = "tabViewer";+ this.tabViewer.Size = new global::System.Drawing.Size(1742, 693);+ this.tabViewer.TabIndex = 4;+ this.tabViewer.Text = " Preview ";+ this.tabViewer.UseVisualStyleBackColor = true;+ this.pnlPreviewIntensityProps.BackColor = global::System.Drawing.SystemColors.ButtonFace;+ this.pnlPreviewIntensityProps.Controls.Add(this.chkExportVideoIntensity2);+ this.pnlPreviewIntensityProps.Controls.Add(this.Label64);+ this.pnlPreviewIntensityProps.Controls.Add(this.numBrightnessIntensityOverlay);+ this.pnlPreviewIntensityProps.Controls.Add(this.numIntensityScaling2);+ this.pnlPreviewIntensityProps.Controls.Add(this.chkDiplayOverlayInIntensity);+ this.pnlPreviewIntensityProps.Controls.Add(this.Label66);+ this.pnlPreviewIntensityProps.Location = new global::System.Drawing.Point(1023, 12);+ this.pnlPreviewIntensityProps.Name = "pnlPreviewIntensityProps";+ this.pnlPreviewIntensityProps.Size = new global::System.Drawing.Size(700, 40);+ this.pnlPreviewIntensityProps.TabIndex = 14;+ this.chkExportVideoIntensity2.AutoSize = true;+ this.chkExportVideoIntensity2.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.chkExportVideoIntensity2.Location = new global::System.Drawing.Point(577, 8);+ this.chkExportVideoIntensity2.Name = "chkExportVideoIntensity2";+ this.chkExportVideoIntensity2.Size = new global::System.Drawing.Size(115, 24);+ this.chkExportVideoIntensity2.TabIndex = 12;+ this.chkExportVideoIntensity2.Text = "Export video";+ this.chkExportVideoIntensity2.UseVisualStyleBackColor = true;+ this.Label64.AutoSize = true;+ this.Label64.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label64.Location = new global::System.Drawing.Point(13, 9);+ this.Label64.Name = "Label64";+ this.Label64.Size = new global::System.Drawing.Size(129, 20);+ this.Label64.TabIndex = 9;+ this.Label64.Text = "Field scale factor";+ this.numBrightnessIntensityOverlay.DecimalPlaces = 2;+ this.numBrightnessIntensityOverlay.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.numBrightnessIntensityOverlay.Increment = new decimal(new int[] { 5, 0, 0, 131072 });+ this.numBrightnessIntensityOverlay.Location = new global::System.Drawing.Point(473, 7);+ global::System.Windows.Forms.NumericUpDown numBrightnessIntensityOverlay = this.numBrightnessIntensityOverlay;+ int[] array43 = new int[4];+ array43[0] = 5;+ numBrightnessIntensityOverlay.Maximum = new decimal(array43);+ this.numBrightnessIntensityOverlay.Name = "numBrightnessIntensityOverlay";+ this.numBrightnessIntensityOverlay.Size = new global::System.Drawing.Size(67, 26);+ this.numBrightnessIntensityOverlay.TabIndex = 11;+ this.numBrightnessIntensityOverlay.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numBrightnessIntensityOverlay2 = this.numBrightnessIntensityOverlay;+ int[] array44 = new int[4];+ array44[0] = 1;+ numBrightnessIntensityOverlay2.Value = new decimal(array44);+ this.numIntensityScaling2.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.numIntensityScaling2.Location = new global::System.Drawing.Point(151, 7);+ global::System.Windows.Forms.NumericUpDown numIntensityScaling2 = this.numIntensityScaling2;+ int[] array45 = new int[4];+ array45[0] = 1000;+ numIntensityScaling2.Maximum = new decimal(array45);+ this.numIntensityScaling2.Name = "numIntensityScaling2";+ this.numIntensityScaling2.Size = new global::System.Drawing.Size(74, 26);+ this.numIntensityScaling2.TabIndex = 8;+ this.numIntensityScaling2.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.chkDiplayOverlayInIntensity.AutoSize = true;+ this.chkDiplayOverlayInIntensity.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.chkDiplayOverlayInIntensity.Location = new global::System.Drawing.Point(253, 9);+ this.chkDiplayOverlayInIntensity.Name = "chkDiplayOverlayInIntensity";+ this.chkDiplayOverlayInIntensity.Size = new global::System.Drawing.Size(132, 24);+ this.chkDiplayOverlayInIntensity.TabIndex = 10;+ this.chkDiplayOverlayInIntensity.Text = "Display overlay";+ this.chkDiplayOverlayInIntensity.UseVisualStyleBackColor = true;+ this.Label66.AutoSize = true;+ this.Label66.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label66.Location = new global::System.Drawing.Point(382, 10);+ this.Label66.Name = "Label66";+ this.Label66.Size = new global::System.Drawing.Size(91, 20);+ this.Label66.TabIndex = 9;+ this.Label66.Text = "/ brightness";+ this.Panel3.BackColor = global::System.Drawing.SystemColors.ButtonFace;+ this.Panel3.Controls.Add(this.Label63);+ this.Panel3.Controls.Add(this.chkExportVideoField2);+ this.Panel3.Controls.Add(this.numFieldScaling2);+ this.Panel3.Controls.Add(this.Label65);+ this.Panel3.Controls.Add(this.numBrightnessFieldOverlay);+ this.Panel3.Controls.Add(this.chkDiplayOverlayInField);+ this.Panel3.Location = new global::System.Drawing.Point(170, 11);+ this.Panel3.Name = "Panel3";+ this.Panel3.Size = new global::System.Drawing.Size(697, 40);+ this.Panel3.TabIndex = 13;+ this.Label63.AutoSize = true;+ this.Label63.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label63.Location = new global::System.Drawing.Point(9, 10);+ this.Label63.Name = "Label63";+ this.Label63.Size = new global::System.Drawing.Size(129, 20);+ this.Label63.TabIndex = 9;+ this.Label63.Text = "Field scale factor";+ this.chkExportVideoField2.AutoSize = true;+ this.chkExportVideoField2.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.chkExportVideoField2.Location = new global::System.Drawing.Point(571, 9);+ this.chkExportVideoField2.Name = "chkExportVideoField2";+ this.chkExportVideoField2.Size = new global::System.Drawing.Size(115, 24);+ this.chkExportVideoField2.TabIndex = 12;+ this.chkExportVideoField2.Text = "Export video";+ this.chkExportVideoField2.UseVisualStyleBackColor = true;+ this.numFieldScaling2.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.numFieldScaling2.Location = new global::System.Drawing.Point(144, 8);+ global::System.Windows.Forms.NumericUpDown numFieldScaling2 = this.numFieldScaling2;+ int[] array46 = new int[4];+ array46[0] = 1000;+ numFieldScaling2.Maximum = new decimal(array46);+ this.numFieldScaling2.Name = "numFieldScaling2";+ this.numFieldScaling2.Size = new global::System.Drawing.Size(75, 26);+ this.numFieldScaling2.TabIndex = 8;+ this.numFieldScaling2.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ this.Label65.AutoSize = true;+ this.Label65.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label65.Location = new global::System.Drawing.Point(380, 10);+ this.Label65.Name = "Label65";+ this.Label65.Size = new global::System.Drawing.Size(91, 20);+ this.Label65.TabIndex = 9;+ this.Label65.Text = "/ brightness";+ this.numBrightnessFieldOverlay.DecimalPlaces = 2;+ this.numBrightnessFieldOverlay.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.numBrightnessFieldOverlay.Increment = new decimal(new int[] { 5, 0, 0, 131072 });+ this.numBrightnessFieldOverlay.Location = new global::System.Drawing.Point(474, 8);+ global::System.Windows.Forms.NumericUpDown numBrightnessFieldOverlay = this.numBrightnessFieldOverlay;+ int[] array47 = new int[4];+ array47[0] = 5;+ numBrightnessFieldOverlay.Maximum = new decimal(array47);+ this.numBrightnessFieldOverlay.Name = "numBrightnessFieldOverlay";+ this.numBrightnessFieldOverlay.Size = new global::System.Drawing.Size(67, 26);+ this.numBrightnessFieldOverlay.TabIndex = 11;+ this.numBrightnessFieldOverlay.TextAlign = global::System.Windows.Forms.HorizontalAlignment.Center;+ global::System.Windows.Forms.NumericUpDown numBrightnessFieldOverlay2 = this.numBrightnessFieldOverlay;+ int[] array48 = new int[4];+ array48[0] = 1;+ numBrightnessFieldOverlay2.Value = new decimal(array48);+ this.chkDiplayOverlayInField.AutoSize = true;+ this.chkDiplayOverlayInField.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.chkDiplayOverlayInField.Location = new global::System.Drawing.Point(254, 9);+ this.chkDiplayOverlayInField.Name = "chkDiplayOverlayInField";+ this.chkDiplayOverlayInField.Size = new global::System.Drawing.Size(132, 24);+ this.chkDiplayOverlayInField.TabIndex = 10;+ this.chkDiplayOverlayInField.Text = "Display overlay";+ this.chkDiplayOverlayInField.UseVisualStyleBackColor = true;+ this.Label56.AutoSize = true;+ this.Label56.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 20.25f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label56.Location = new global::System.Drawing.Point(881, 16);+ this.Label56.Name = "Label56";+ this.Label56.Size = new global::System.Drawing.Size(126, 31);+ this.Label56.TabIndex = 7;+ this.Label56.Text = "Intensity";+ this.Label55.AutoSize = true;+ this.Label55.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 20.25f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Label55.Location = new global::System.Drawing.Point(53, 16);+ this.Label55.Name = "Label55";+ this.Label55.Size = new global::System.Drawing.Size(78, 31);+ this.Label55.TabIndex = 7;+ this.Label55.Text = "Field";+ this.lblWarningIntensity.AutoSize = true;+ this.lblWarningIntensity.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblWarningIntensity.Location = new global::System.Drawing.Point(1201, 550);+ this.lblWarningIntensity.Name = "lblWarningIntensity";+ this.lblWarningIntensity.Size = new global::System.Drawing.Size(183, 20);+ this.lblWarningIntensity.TabIndex = 6;+ this.lblWarningIntensity.Text = "Intensity video is created";+ this.lblWarningField.AutoSize = true;+ this.lblWarningField.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblWarningField.Location = new global::System.Drawing.Point(335, 551);+ this.lblWarningField.Name = "lblWarningField";+ this.lblWarningField.Size = new global::System.Drawing.Size(157, 20);+ this.lblWarningField.TabIndex = 6;+ this.lblWarningField.Text = "Field video is created";+ this.btnExportIntensityFrame.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnExportIntensityFrame.Location = new global::System.Drawing.Point(1410, 545);+ this.btnExportIntensityFrame.Name = "btnExportIntensityFrame";+ this.btnExportIntensityFrame.Size = new global::System.Drawing.Size(247, 31);+ this.btnExportIntensityFrame.TabIndex = 5;+ this.btnExportIntensityFrame.Text = "Export frame as image";+ this.btnExportIntensityFrame.UseVisualStyleBackColor = true;+ this.btnExportFieldFrame.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnExportFieldFrame.Location = new global::System.Drawing.Point(536, 547);+ this.btnExportFieldFrame.Name = "btnExportFieldFrame";+ this.btnExportFieldFrame.Size = new global::System.Drawing.Size(243, 29);+ this.btnExportFieldFrame.TabIndex = 4;+ this.btnExportFieldFrame.Text = "Export frame as Image";+ this.btnExportFieldFrame.UseVisualStyleBackColor = true;+ this.btnOpenImageFolder.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnOpenImageFolder.Location = new global::System.Drawing.Point(1524, 650);+ this.btnOpenImageFolder.Name = "btnOpenImageFolder";+ this.btnOpenImageFolder.Size = new global::System.Drawing.Size(207, 33);+ this.btnOpenImageFolder.TabIndex = 2;+ this.btnOpenImageFolder.Text = "Open Image folder";+ this.btnOpenImageFolder.UseVisualStyleBackColor = true;+ this.btnOpenVideoFolder.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnOpenVideoFolder.Location = new global::System.Drawing.Point(1311, 650);+ this.btnOpenVideoFolder.Name = "btnOpenVideoFolder";+ this.btnOpenVideoFolder.Size = new global::System.Drawing.Size(207, 33);+ this.btnOpenVideoFolder.TabIndex = 2;+ this.btnOpenVideoFolder.Text = "Open video folder";+ this.btnOpenVideoFolder.UseVisualStyleBackColor = true;+ this.btnViewIntensityVideo.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnViewIntensityVideo.Location = new global::System.Drawing.Point(929, 546);+ this.btnViewIntensityVideo.Name = "btnViewIntensityVideo";+ this.btnViewIntensityVideo.Size = new global::System.Drawing.Size(247, 29);+ this.btnViewIntensityVideo.TabIndex = 1;+ this.btnViewIntensityVideo.Text = "View video in media player";+ this.btnViewIntensityVideo.UseVisualStyleBackColor = true;+ this.btnViewFieldVideo.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnViewFieldVideo.Location = new global::System.Drawing.Point(79, 547);+ this.btnViewFieldVideo.Name = "btnViewFieldVideo";+ this.btnViewFieldVideo.Size = new global::System.Drawing.Size(216, 29);+ this.btnViewFieldVideo.TabIndex = 1;+ this.btnViewFieldVideo.Text = "View video in media player";+ this.btnViewFieldVideo.UseVisualStyleBackColor = true;+ this.pnlPreviewIntensity.Location = new global::System.Drawing.Point(873, 57);+ this.pnlPreviewIntensity.Name = "pnlPreviewIntensity";+ this.pnlPreviewIntensity.Size = new global::System.Drawing.Size(850, 478);+ this.pnlPreviewIntensity.TabIndex = 0;+ this.pnlPreviewField.Location = new global::System.Drawing.Point(17, 56);+ this.pnlPreviewField.Name = "pnlPreviewField";+ this.pnlPreviewField.Size = new global::System.Drawing.Size(850, 478);+ this.pnlPreviewField.TabIndex = 0;+ this.tabOutput.Controls.Add(this.btnRenameVideo);+ this.tabOutput.Controls.Add(this.btnShareWithEditors);+ this.tabOutput.Controls.Add(this.btnCopyToClipboard);+ this.tabOutput.Controls.Add(this.btnOpenImageFolder2);+ this.tabOutput.Controls.Add(this.btnViewVIdeoInPlayer2);+ this.tabOutput.Controls.Add(this.btnOpenVIdeoFolder2);+ this.tabOutput.Controls.Add(this.lblPreview);+ this.tabOutput.Controls.Add(this.btnDeleteVideos);+ this.tabOutput.Controls.Add(this.btnDeleteImages);+ this.tabOutput.Controls.Add(this.btnDeleteScene);+ this.tabOutput.Controls.Add(this.btnLoadExternal);+ this.tabOutput.Controls.Add(this.pnlPreview);+ this.tabOutput.Controls.Add(this.Label57);+ this.tabOutput.Controls.Add(this.lstScenes);+ this.tabOutput.Controls.Add(this.lstImages);+ this.tabOutput.Controls.Add(this.lstVideo);+ this.tabOutput.Controls.Add(this.lstAllProjects3);+ this.tabOutput.Location = new global::System.Drawing.Point(4, 34);+ this.tabOutput.Name = "tabOutput";+ this.tabOutput.Size = new global::System.Drawing.Size(1742, 693);+ this.tabOutput.TabIndex = 3;+ this.tabOutput.Text = " Manage output ";+ this.tabOutput.UseVisualStyleBackColor = true;+ this.btnRenameVideo.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnRenameVideo.Location = new global::System.Drawing.Point(566, 631);+ this.btnRenameVideo.Name = "btnRenameVideo";+ this.btnRenameVideo.Size = new global::System.Drawing.Size(75, 31);+ this.btnRenameVideo.TabIndex = 20;+ this.btnRenameVideo.Text = "Rename";+ this.btnRenameVideo.UseVisualStyleBackColor = true;+ this.btnShareWithEditors.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnShareWithEditors.Location = new global::System.Drawing.Point(1517, 635);+ this.btnShareWithEditors.Name = "btnShareWithEditors";+ this.btnShareWithEditors.Size = new global::System.Drawing.Size(193, 27);+ this.btnShareWithEditors.TabIndex = 19;+ this.btnShareWithEditors.Text = "Share this image with tabs";+ this.btnShareWithEditors.UseVisualStyleBackColor = true;+ this.btnCopyToClipboard.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnCopyToClipboard.Location = new global::System.Drawing.Point(594, 407);+ this.btnCopyToClipboard.Name = "btnCopyToClipboard";+ this.btnCopyToClipboard.Size = new global::System.Drawing.Size(129, 30);+ this.btnCopyToClipboard.TabIndex = 18;+ this.btnCopyToClipboard.Text = "Copy to clipboard";+ this.btnCopyToClipboard.UseVisualStyleBackColor = true;+ this.btnOpenImageFolder2.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnOpenImageFolder2.Location = new global::System.Drawing.Point(759, 407);+ this.btnOpenImageFolder2.Name = "btnOpenImageFolder2";+ this.btnOpenImageFolder2.Size = new global::System.Drawing.Size(132, 30);+ this.btnOpenImageFolder2.TabIndex = 17;+ this.btnOpenImageFolder2.Text = "Open image folder";+ this.btnOpenImageFolder2.UseVisualStyleBackColor = true;+ this.btnViewVIdeoInPlayer2.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnViewVIdeoInPlayer2.Location = new global::System.Drawing.Point(677, 630);+ this.btnViewVIdeoInPlayer2.Name = "btnViewVIdeoInPlayer2";+ this.btnViewVIdeoInPlayer2.Size = new global::System.Drawing.Size(114, 33);+ this.btnViewVIdeoInPlayer2.TabIndex = 16;+ this.btnViewVIdeoInPlayer2.Text = "View in player";+ this.btnViewVIdeoInPlayer2.UseVisualStyleBackColor = true;+ this.btnOpenVIdeoFolder2.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnOpenVIdeoFolder2.Location = new global::System.Drawing.Point(799, 630);+ this.btnOpenVIdeoFolder2.Name = "btnOpenVIdeoFolder2";+ this.btnOpenVIdeoFolder2.Size = new global::System.Drawing.Size(93, 34);+ this.btnOpenVIdeoFolder2.TabIndex = 15;+ this.btnOpenVIdeoFolder2.Text = "Open folder";+ this.btnOpenVIdeoFolder2.UseVisualStyleBackColor = true;+ this.lblPreview.AutoSize = true;+ this.lblPreview.Location = new global::System.Drawing.Point(911, 25);+ this.lblPreview.Name = "lblPreview";+ this.lblPreview.Size = new global::System.Drawing.Size(88, 25);+ this.lblPreview.TabIndex = 14;+ this.lblPreview.Text = "Preview";+ this.btnDeleteVideos.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnDeleteVideos.Location = new global::System.Drawing.Point(456, 631);+ this.btnDeleteVideos.Name = "btnDeleteVideos";+ this.btnDeleteVideos.Size = new global::System.Drawing.Size(101, 31);+ this.btnDeleteVideos.TabIndex = 13;+ this.btnDeleteVideos.Text = "Delete video";+ this.btnDeleteVideos.UseVisualStyleBackColor = true;+ this.btnDeleteImages.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnDeleteImages.Location = new global::System.Drawing.Point(458, 405);+ this.btnDeleteImages.Name = "btnDeleteImages";+ this.btnDeleteImages.Size = new global::System.Drawing.Size(99, 32);+ this.btnDeleteImages.TabIndex = 13;+ this.btnDeleteImages.Text = "Delete image";+ this.btnDeleteImages.UseVisualStyleBackColor = true;+ this.btnDeleteScene.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnDeleteScene.Location = new global::System.Drawing.Point(459, 177);+ this.btnDeleteScene.Name = "btnDeleteScene";+ this.btnDeleteScene.Size = new global::System.Drawing.Size(111, 32);+ this.btnDeleteScene.TabIndex = 13;+ this.btnDeleteScene.Text = "Delete scene";+ this.btnDeleteScene.UseVisualStyleBackColor = true;+ this.btnLoadExternal.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnLoadExternal.Location = new global::System.Drawing.Point(785, 177);+ this.btnLoadExternal.Name = "btnLoadExternal";+ this.btnLoadExternal.Size = new global::System.Drawing.Size(104, 32);+ this.btnLoadExternal.TabIndex = 13;+ this.btnLoadExternal.Text = "Load external";+ this.btnLoadExternal.UseVisualStyleBackColor = true;+ this.pnlPreview.BackColor = global::System.Drawing.Color.Gainsboro;+ this.pnlPreview.Location = new global::System.Drawing.Point(908, 52);+ this.pnlPreview.Name = "pnlPreview";+ this.pnlPreview.Size = new global::System.Drawing.Size(806, 573);+ this.pnlPreview.TabIndex = 12;+ this.Label57.AutoSize = true;+ this.Label57.Location = new global::System.Drawing.Point(20, 16);+ this.Label57.Name = "Label57";+ this.Label57.Size = new global::System.Drawing.Size(227, 25);+ this.Label57.TabIndex = 11;+ this.Label57.Text = "Manage project output";+ this.lstScenes.BackColor = global::System.Drawing.SystemColors.MenuBar;+ this.lstScenes.Columns.AddRange(new global::System.Windows.Forms.ColumnHeader[] { this.colSceneName, this.colSceneCreated });+ this.lstScenes.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lstScenes.FullRowSelect = true;+ this.lstScenes.HideSelection = false;+ this.lstScenes.Location = new global::System.Drawing.Point(460, 51);+ this.lstScenes.Name = "lstScenes";+ this.lstScenes.Size = new global::System.Drawing.Size(432, 126);+ this.lstScenes.TabIndex = 10;+ this.lstScenes.UseCompatibleStateImageBehavior = false;+ this.lstScenes.View = global::System.Windows.Forms.View.Details;+ this.colSceneName.Text = "Scene file name";+ this.colSceneName.Width = 262;+ this.colSceneCreated.Text = "Created on";+ this.colSceneCreated.Width = 138;+ this.lstImages.BackColor = global::System.Drawing.SystemColors.Menu;+ this.lstImages.Columns.AddRange(new global::System.Windows.Forms.ColumnHeader[] { this.colImageName, this.colCreatedOn });+ this.lstImages.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lstImages.FullRowSelect = true;+ this.lstImages.HideSelection = false;+ this.lstImages.Location = new global::System.Drawing.Point(460, 221);+ this.lstImages.Name = "lstImages";+ this.lstImages.Size = new global::System.Drawing.Size(432, 183);+ this.lstImages.TabIndex = 9;+ this.lstImages.UseCompatibleStateImageBehavior = false;+ this.lstImages.View = global::System.Windows.Forms.View.Details;+ this.colImageName.Text = "Image file name";+ this.colImageName.Width = 258;+ this.colCreatedOn.Text = "Created on";+ this.colCreatedOn.Width = 141;+ this.lstVideo.BackColor = global::System.Drawing.SystemColors.Menu;+ this.lstVideo.Columns.AddRange(new global::System.Windows.Forms.ColumnHeader[] { this.colVideoName, this.colCreatedOn2 });+ this.lstVideo.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lstVideo.FullRowSelect = true;+ this.lstVideo.HideSelection = false;+ this.lstVideo.Location = new global::System.Drawing.Point(457, 452);+ this.lstVideo.Name = "lstVideo";+ this.lstVideo.Size = new global::System.Drawing.Size(435, 173);+ this.lstVideo.TabIndex = 9;+ this.lstVideo.UseCompatibleStateImageBehavior = false;+ this.lstVideo.View = global::System.Windows.Forms.View.Details;+ this.colVideoName.Text = "Video file name";+ this.colVideoName.Width = 255;+ this.colCreatedOn2.Text = "Created on";+ this.colCreatedOn2.Width = 145;+ this.lstAllProjects3.BackColor = global::System.Drawing.SystemColors.Menu;+ this.lstAllProjects3.Columns.AddRange(new global::System.Windows.Forms.ColumnHeader[] { this.colProjectName2, this.colLastEdited2 });+ this.lstAllProjects3.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lstAllProjects3.FullRowSelect = true;+ this.lstAllProjects3.HideSelection = false;+ this.lstAllProjects3.Location = new global::System.Drawing.Point(18, 51);+ this.lstAllProjects3.MultiSelect = false;+ this.lstAllProjects3.Name = "lstAllProjects3";+ this.lstAllProjects3.Size = new global::System.Drawing.Size(427, 611);+ this.lstAllProjects3.TabIndex = 9;+ this.lstAllProjects3.UseCompatibleStateImageBehavior = false;+ this.lstAllProjects3.View = global::System.Windows.Forms.View.Details;+ this.colProjectName2.Text = "Project name";+ this.colProjectName2.Width = 280;+ this.colLastEdited2.Text = "Last edited";+ this.colLastEdited2.Width = 160;+ this.tabColorScheme.Controls.Add(this.lblType);+ this.tabColorScheme.Controls.Add(this.radSchemeTypeIntensity);+ this.tabColorScheme.Controls.Add(this.radSchemeTypeField);+ this.tabColorScheme.Controls.Add(this.btnLoadScheme);+ this.tabColorScheme.Controls.Add(this.btbChooseFFolder);+ this.tabColorScheme.Controls.Add(this.lblSchemeFolder);+ this.tabColorScheme.Controls.Add(this.ListView1);+ this.tabColorScheme.Controls.Add(this.txtSchemeFolder);+ this.tabColorScheme.Controls.Add(this.txtCurrentColorScheme);+ this.tabColorScheme.Controls.Add(this.lblCurrentCOlorScheme);+ this.tabColorScheme.Controls.Add(this.lblColorSchemeEditor);+ this.tabColorScheme.Controls.Add(this.btnColor9);+ this.tabColorScheme.Controls.Add(this.btnColor8);+ this.tabColorScheme.Controls.Add(this.btnColor7);+ this.tabColorScheme.Controls.Add(this.btnColor6);+ this.tabColorScheme.Controls.Add(this.btnColor5);+ this.tabColorScheme.Controls.Add(this.btnColor4);+ this.tabColorScheme.Controls.Add(this.btnColor3);+ this.tabColorScheme.Controls.Add(this.btnCOlor2);+ this.tabColorScheme.Controls.Add(this.btnColor1);+ this.tabColorScheme.Controls.Add(this.lblColorPicker);+ this.tabColorScheme.Controls.Add(this.Panel2);+ this.tabColorScheme.Controls.Add(this.pnlScheme);+ this.tabColorScheme.Controls.Add(this.btnDeleteColorScheme);+ this.tabColorScheme.Controls.Add(this.btnRenameColorScheme);+ this.tabColorScheme.Controls.Add(this.btnSaveAsColorScheme);+ this.tabColorScheme.Controls.Add(this.btnSaveCurrentScheme);+ this.tabColorScheme.Location = new global::System.Drawing.Point(4, 34);+ this.tabColorScheme.Name = "tabColorScheme";+ this.tabColorScheme.Padding = new global::System.Windows.Forms.Padding(3);+ this.tabColorScheme.Size = new global::System.Drawing.Size(1742, 693);+ this.tabColorScheme.TabIndex = 0;+ this.tabColorScheme.Text = " Colors ";+ this.tabColorScheme.UseVisualStyleBackColor = true;+ this.lblType.AutoSize = true;+ this.lblType.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblType.Location = new global::System.Drawing.Point(23, 93);+ this.lblType.Name = "lblType";+ this.lblType.Size = new global::System.Drawing.Size(98, 18);+ this.lblType.TabIndex = 19;+ this.lblType.Text = "Scheme type:";+ this.radSchemeTypeIntensity.AutoSize = true;+ this.radSchemeTypeIntensity.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.radSchemeTypeIntensity.Location = new global::System.Drawing.Point(197, 91);+ this.radSchemeTypeIntensity.Name = "radSchemeTypeIntensity";+ this.radSchemeTypeIntensity.Size = new global::System.Drawing.Size(79, 22);+ this.radSchemeTypeIntensity.TabIndex = 18;+ this.radSchemeTypeIntensity.Text = "Intensity";+ this.radSchemeTypeIntensity.UseVisualStyleBackColor = true;+ this.radSchemeTypeField.AutoSize = true;+ this.radSchemeTypeField.Checked = true;+ this.radSchemeTypeField.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.radSchemeTypeField.Location = new global::System.Drawing.Point(134, 91);+ this.radSchemeTypeField.Name = "radSchemeTypeField";+ this.radSchemeTypeField.Size = new global::System.Drawing.Size(57, 22);+ this.radSchemeTypeField.TabIndex = 18;+ this.radSchemeTypeField.TabStop = true;+ this.radSchemeTypeField.Text = "Field";+ this.radSchemeTypeField.UseVisualStyleBackColor = true;+ this.btnLoadScheme.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnLoadScheme.Location = new global::System.Drawing.Point(27, 528);+ this.btnLoadScheme.Name = "btnLoadScheme";+ this.btnLoadScheme.Size = new global::System.Drawing.Size(88, 28);+ this.btnLoadScheme.TabIndex = 11;+ this.btnLoadScheme.Text = "Load ";+ this.btnLoadScheme.UseVisualStyleBackColor = true;+ this.btbChooseFFolder.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btbChooseFFolder.Location = new global::System.Drawing.Point(470, 125);+ this.btbChooseFFolder.Name = "btbChooseFFolder";+ this.btbChooseFFolder.Size = new global::System.Drawing.Size(89, 25);+ this.btbChooseFFolder.TabIndex = 10;+ this.btbChooseFFolder.Text = "Choose...";+ this.btbChooseFFolder.UseVisualStyleBackColor = true;+ this.lblSchemeFolder.AutoSize = true;+ this.lblSchemeFolder.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblSchemeFolder.Location = new global::System.Drawing.Point(24, 128);+ this.lblSchemeFolder.Name = "lblSchemeFolder";+ this.lblSchemeFolder.Size = new global::System.Drawing.Size(104, 18);+ this.lblSchemeFolder.TabIndex = 9;+ this.lblSchemeFolder.Text = "Scheme folder";+ this.ListView1.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.ListView1.HideSelection = false;+ this.ListView1.Location = new global::System.Drawing.Point(27, 157);+ this.ListView1.Name = "ListView1";+ this.ListView1.Size = new global::System.Drawing.Size(531, 365);+ this.ListView1.TabIndex = 8;+ this.ListView1.UseCompatibleStateImageBehavior = false;+ this.txtSchemeFolder.BorderStyle = global::System.Windows.Forms.BorderStyle.FixedSingle;+ this.txtSchemeFolder.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.txtSchemeFolder.Location = new global::System.Drawing.Point(134, 125);+ this.txtSchemeFolder.Name = "txtSchemeFolder";+ this.txtSchemeFolder.Size = new global::System.Drawing.Size(330, 22);+ this.txtSchemeFolder.TabIndex = 7;+ this.txtCurrentColorScheme.BorderStyle = global::System.Windows.Forms.BorderStyle.FixedSingle;+ this.txtCurrentColorScheme.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.txtCurrentColorScheme.Location = new global::System.Drawing.Point(135, 56);+ this.txtCurrentColorScheme.Name = "txtCurrentColorScheme";+ this.txtCurrentColorScheme.Size = new global::System.Drawing.Size(299, 24);+ this.txtCurrentColorScheme.TabIndex = 7;+ this.lblCurrentCOlorScheme.AutoSize = true;+ this.lblCurrentCOlorScheme.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblCurrentCOlorScheme.Location = new global::System.Drawing.Point(23, 58);+ this.lblCurrentCOlorScheme.Name = "lblCurrentCOlorScheme";+ this.lblCurrentCOlorScheme.Size = new global::System.Drawing.Size(108, 18);+ this.lblCurrentCOlorScheme.TabIndex = 6;+ this.lblCurrentCOlorScheme.Text = "Color Scheme:";+ this.lblColorSchemeEditor.AutoSize = true;+ this.lblColorSchemeEditor.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 14.25f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblColorSchemeEditor.Location = new global::System.Drawing.Point(22, 12);+ this.lblColorSchemeEditor.Name = "lblColorSchemeEditor";+ this.lblColorSchemeEditor.Size = new global::System.Drawing.Size(204, 24);+ this.lblColorSchemeEditor.TabIndex = 5;+ this.lblColorSchemeEditor.Text = "Color Scheme Editor";+ this.btnColor9.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnColor9.Location = new global::System.Drawing.Point(1054, 514);+ this.btnColor9.Name = "btnColor9";+ this.btnColor9.Size = new global::System.Drawing.Size(78, 34);+ this.btnColor9.TabIndex = 4;+ this.btnColor9.Text = "Color 9 ->";+ this.btnColor9.UseVisualStyleBackColor = true;+ this.btnColor8.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnColor8.Location = new global::System.Drawing.Point(1055, 465);+ this.btnColor8.Name = "btnColor8";+ this.btnColor8.Size = new global::System.Drawing.Size(78, 34);+ this.btnColor8.TabIndex = 4;+ this.btnColor8.Text = "Color 8 ->";+ this.btnColor8.UseVisualStyleBackColor = true;+ this.btnColor7.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnColor7.Location = new global::System.Drawing.Point(1055, 416);+ this.btnColor7.Name = "btnColor7";+ this.btnColor7.Size = new global::System.Drawing.Size(78, 34);+ this.btnColor7.TabIndex = 4;+ this.btnColor7.Text = "Color 7 ->";+ this.btnColor7.UseVisualStyleBackColor = true;+ this.btnColor6.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnColor6.Location = new global::System.Drawing.Point(1055, 368);+ this.btnColor6.Name = "btnColor6";+ this.btnColor6.Size = new global::System.Drawing.Size(78, 34);+ this.btnColor6.TabIndex = 4;+ this.btnColor6.Text = "Color 6 ->";+ this.btnColor6.UseVisualStyleBackColor = true;+ this.btnColor5.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnColor5.Location = new global::System.Drawing.Point(1055, 322);+ this.btnColor5.Name = "btnColor5";+ this.btnColor5.Size = new global::System.Drawing.Size(78, 34);+ this.btnColor5.TabIndex = 4;+ this.btnColor5.Text = "Color 5 ->";+ this.btnColor5.UseVisualStyleBackColor = true;+ this.btnColor4.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnColor4.Location = new global::System.Drawing.Point(1054, 273);+ this.btnColor4.Name = "btnColor4";+ this.btnColor4.Size = new global::System.Drawing.Size(78, 34);+ this.btnColor4.TabIndex = 4;+ this.btnColor4.Text = "Color 4 ->";+ this.btnColor4.UseVisualStyleBackColor = true;+ this.btnColor3.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnColor3.Location = new global::System.Drawing.Point(1054, 225);+ this.btnColor3.Name = "btnColor3";+ this.btnColor3.Size = new global::System.Drawing.Size(78, 34);+ this.btnColor3.TabIndex = 4;+ this.btnColor3.Text = "Color 3 ->";+ this.btnColor3.UseVisualStyleBackColor = true;+ this.btnCOlor2.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnCOlor2.Location = new global::System.Drawing.Point(1055, 176);+ this.btnCOlor2.Name = "btnCOlor2";+ this.btnCOlor2.Size = new global::System.Drawing.Size(78, 34);+ this.btnCOlor2.TabIndex = 4;+ this.btnCOlor2.Text = "Color 2 ->";+ this.btnCOlor2.UseVisualStyleBackColor = true;+ this.btnColor1.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnColor1.Location = new global::System.Drawing.Point(1055, 128);+ this.btnColor1.Name = "btnColor1";+ this.btnColor1.Size = new global::System.Drawing.Size(78, 34);+ this.btnColor1.TabIndex = 4;+ this.btnColor1.Text = "Color 1 ->";+ this.btnColor1.UseVisualStyleBackColor = true;+ this.lblColorPicker.AutoSize = true;+ this.lblColorPicker.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblColorPicker.Location = new global::System.Drawing.Point(596, 101);+ this.lblColorPicker.Name = "lblColorPicker";+ this.lblColorPicker.Size = new global::System.Drawing.Size(93, 20);+ this.lblColorPicker.TabIndex = 2;+ this.lblColorPicker.Text = "Color Picker";+ this.Panel2.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.Panel2.Location = new global::System.Drawing.Point(598, 125);+ this.Panel2.Name = "Panel2";+ this.Panel2.Size = new global::System.Drawing.Size(445, 425);+ this.Panel2.TabIndex = 1;+ this.pnlScheme.Location = new global::System.Drawing.Point(1139, 139);+ this.pnlScheme.Name = "pnlScheme";+ this.pnlScheme.Size = new global::System.Drawing.Size(55, 399);+ this.pnlScheme.TabIndex = 1;+ this.btnDeleteColorScheme.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnDeleteColorScheme.Location = new global::System.Drawing.Point(470, 528);+ this.btnDeleteColorScheme.Name = "btnDeleteColorScheme";+ this.btnDeleteColorScheme.Size = new global::System.Drawing.Size(89, 28);+ this.btnDeleteColorScheme.TabIndex = 0;+ this.btnDeleteColorScheme.Text = "Delete";+ this.btnDeleteColorScheme.UseVisualStyleBackColor = true;+ this.btnRenameColorScheme.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnRenameColorScheme.Location = new global::System.Drawing.Point(376, 528);+ this.btnRenameColorScheme.Name = "btnRenameColorScheme";+ this.btnRenameColorScheme.Size = new global::System.Drawing.Size(88, 28);+ this.btnRenameColorScheme.TabIndex = 0;+ this.btnRenameColorScheme.Text = "Rename";+ this.btnRenameColorScheme.UseVisualStyleBackColor = true;+ this.btnSaveAsColorScheme.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnSaveAsColorScheme.Location = new global::System.Drawing.Point(215, 528);+ this.btnSaveAsColorScheme.Name = "btnSaveAsColorScheme";+ this.btnSaveAsColorScheme.Size = new global::System.Drawing.Size(88, 28);+ this.btnSaveAsColorScheme.TabIndex = 0;+ this.btnSaveAsColorScheme.Text = "Save As";+ this.btnSaveAsColorScheme.UseVisualStyleBackColor = true;+ this.btnSaveCurrentScheme.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnSaveCurrentScheme.Location = new global::System.Drawing.Point(121, 528);+ this.btnSaveCurrentScheme.Name = "btnSaveCurrentScheme";+ this.btnSaveCurrentScheme.Size = new global::System.Drawing.Size(88, 28);+ this.btnSaveCurrentScheme.TabIndex = 0;+ this.btnSaveCurrentScheme.Text = "Save ";+ this.btnSaveCurrentScheme.UseVisualStyleBackColor = true;+ this.btnSaveConfiguration.BackColor = global::System.Drawing.Color.Azure;+ this.btnSaveConfiguration.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Bold, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnSaveConfiguration.Location = new global::System.Drawing.Point(1503, 840);+ this.btnSaveConfiguration.Name = "btnSaveConfiguration";+ this.btnSaveConfiguration.Size = new global::System.Drawing.Size(259, 53);+ this.btnSaveConfiguration.TabIndex = 2;+ this.btnSaveConfiguration.Text = "Save changes to project";+ this.btnSaveConfiguration.UseVisualStyleBackColor = false;+ this.btnStartSimulation.BackColor = global::System.Drawing.Color.Azure;+ this.btnStartSimulation.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 15.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnStartSimulation.Location = new global::System.Drawing.Point(18, 23);+ this.btnStartSimulation.Name = "btnStartSimulation";+ this.btnStartSimulation.Size = new global::System.Drawing.Size(216, 42);+ this.btnStartSimulation.TabIndex = 7;+ this.btnStartSimulation.Text = "Start Simulation";+ this.btnStartSimulation.UseVisualStyleBackColor = false;+ this.btnPauzeResume.BackColor = global::System.Drawing.Color.Azure;+ this.btnPauzeResume.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 15.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnPauzeResume.Location = new global::System.Drawing.Point(18, 71);+ this.btnPauzeResume.Name = "btnPauzeResume";+ this.btnPauzeResume.Size = new global::System.Drawing.Size(215, 46);+ this.btnPauzeResume.TabIndex = 2;+ this.btnPauzeResume.Text = "Pauze simulation";+ this.btnPauzeResume.UseVisualStyleBackColor = false;+ this.MenuStrip1.Items.AddRange(new global::System.Windows.Forms.ToolStripItem[] { this.itemFile, this.InfoToolStripMenuItem });+ this.MenuStrip1.Location = new global::System.Drawing.Point(0, 0);+ this.MenuStrip1.Name = "MenuStrip1";+ this.MenuStrip1.Size = new global::System.Drawing.Size(1781, 28);+ this.MenuStrip1.TabIndex = 1;+ this.MenuStrip1.Text = "MenuStrip1";+ this.itemFile.DropDownItems.AddRange(new global::System.Windows.Forms.ToolStripItem[] { this.NewToolStripMenuItem, this.OpenToolStripMenuItem, this.ChooseProjectRootToolStripMenuItem, this.SetCValueToolStripMenuItem, this.SaveToolStripMenuItem, this.ExitToolStripMenuItem });+ this.itemFile.Font = new global::System.Drawing.Font("Segoe UI", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.itemFile.Name = "itemFile";+ this.itemFile.Size = new global::System.Drawing.Size(44, 24);+ this.itemFile.Text = "File";+ this.NewToolStripMenuItem.Name = "NewToolStripMenuItem";+ this.NewToolStripMenuItem.Size = new global::System.Drawing.Size(210, 24);+ this.NewToolStripMenuItem.Text = "New";+ this.OpenToolStripMenuItem.Name = "OpenToolStripMenuItem";+ this.OpenToolStripMenuItem.Size = new global::System.Drawing.Size(210, 24);+ this.OpenToolStripMenuItem.Text = "Open";+ this.ChooseProjectRootToolStripMenuItem.Name = "ChooseProjectRootToolStripMenuItem";+ this.ChooseProjectRootToolStripMenuItem.Size = new global::System.Drawing.Size(210, 24);+ this.ChooseProjectRootToolStripMenuItem.Text = "Choose project root";+ this.SetCValueToolStripMenuItem.Name = "SetCValueToolStripMenuItem";+ this.SetCValueToolStripMenuItem.Size = new global::System.Drawing.Size(210, 24);+ this.SetCValueToolStripMenuItem.Text = "Set c-value";+ this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";+ this.SaveToolStripMenuItem.Size = new global::System.Drawing.Size(210, 24);+ this.SaveToolStripMenuItem.Text = "Save";+ this.ExitToolStripMenuItem.Name = "ExitToolStripMenuItem";+ this.ExitToolStripMenuItem.Size = new global::System.Drawing.Size(210, 24);+ this.ExitToolStripMenuItem.Text = "Exit";+ this.InfoToolStripMenuItem.DropDownItems.AddRange(new global::System.Windows.Forms.ToolStripItem[] { this.HelpToolStripMenuItem, this.AboutToolStripMenuItem });+ this.InfoToolStripMenuItem.Font = new global::System.Drawing.Font("Segoe UI", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.InfoToolStripMenuItem.Name = "InfoToolStripMenuItem";+ this.InfoToolStripMenuItem.Size = new global::System.Drawing.Size(47, 24);+ this.InfoToolStripMenuItem.Text = "Info";+ this.HelpToolStripMenuItem.Name = "HelpToolStripMenuItem";+ this.HelpToolStripMenuItem.Size = new global::System.Drawing.Size(119, 24);+ this.HelpToolStripMenuItem.Text = "Help";+ this.AboutToolStripMenuItem.Name = "AboutToolStripMenuItem";+ this.AboutToolStripMenuItem.Size = new global::System.Drawing.Size(119, 24);+ this.AboutToolStripMenuItem.Text = "About";+ this.lblProjectName.AutoSize = true;+ this.lblProjectName.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblProjectName.Location = new global::System.Drawing.Point(1101, 13);+ this.lblProjectName.Name = "lblProjectName";+ this.lblProjectName.Size = new global::System.Drawing.Size(96, 18);+ this.lblProjectName.TabIndex = 2;+ this.lblProjectName.Text = "Project name";+ this.txtProjectName.BorderStyle = global::System.Windows.Forms.BorderStyle.FixedSingle;+ this.txtProjectName.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.txtProjectName.Location = new global::System.Drawing.Point(1203, 11);+ this.txtProjectName.Name = "txtProjectName";+ this.txtProjectName.ReadOnly = true;+ this.txtProjectName.Size = new global::System.Drawing.Size(292, 24);+ this.txtProjectName.TabIndex = 3;+ this.txtRootFolder.BorderStyle = global::System.Windows.Forms.BorderStyle.FixedSingle;+ this.txtRootFolder.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.txtRootFolder.Location = new global::System.Drawing.Point(145, 11);+ this.txtRootFolder.Name = "txtRootFolder";+ this.txtRootFolder.ReadOnly = true;+ this.txtRootFolder.Size = new global::System.Drawing.Size(810, 24);+ this.txtRootFolder.TabIndex = 3;+ this.lblRootFolder.AutoSize = true;+ this.lblRootFolder.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.lblRootFolder.Location = new global::System.Drawing.Point(12, 13);+ this.lblRootFolder.Name = "lblRootFolder";+ this.lblRootFolder.Size = new global::System.Drawing.Size(127, 18);+ this.lblRootFolder.TabIndex = 2;+ this.lblRootFolder.Text = "Project root folder";+ this.btnBrowseRoot.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnBrowseRoot.Location = new global::System.Drawing.Point(966, 8);+ this.btnBrowseRoot.Name = "btnBrowseRoot";+ this.btnBrowseRoot.Size = new global::System.Drawing.Size(124, 29);+ this.btnBrowseRoot.TabIndex = 4;+ this.btnBrowseRoot.TabStop = false;+ this.btnBrowseRoot.Text = "Browse root";+ this.btnBrowseRoot.UseVisualStyleBackColor = true;+ this.StatusStrip1.Items.AddRange(new global::System.Windows.Forms.ToolStripItem[] { this.ToolStripStatusLabel1 });+ this.StatusStrip1.Location = new global::System.Drawing.Point(0, 967);+ this.StatusStrip1.Name = "StatusStrip1";+ this.StatusStrip1.Size = new global::System.Drawing.Size(1781, 22);+ this.StatusStrip1.TabIndex = 5;+ this.StatusStrip1.Text = "StatusStrip1";+ this.ToolStripStatusLabel1.Name = "ToolStripStatusLabel1";+ this.ToolStripStatusLabel1.Size = new global::System.Drawing.Size(120, 17);+ this.ToolStripStatusLabel1.Text = "ToolStripStatusLabel1";+ this.grpNavigateTabs.Controls.Add(this.btnGotoPreview);+ this.grpNavigateTabs.Controls.Add(this.btnGotoProbes);+ this.grpNavigateTabs.Controls.Add(this.btnGotoSources);+ this.grpNavigateTabs.Controls.Add(this.btnGotoConfiguration);+ this.grpNavigateTabs.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.grpNavigateTabs.Location = new global::System.Drawing.Point(511, 827);+ this.grpNavigateTabs.Name = "grpNavigateTabs";+ this.grpNavigateTabs.Size = new global::System.Drawing.Size(858, 76);+ this.grpNavigateTabs.TabIndex = 8;+ this.grpNavigateTabs.TabStop = false;+ this.grpNavigateTabs.Text = "Quick navigate to";+ this.btnGotoPreview.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnGotoPreview.Location = new global::System.Drawing.Point(635, 27);+ this.btnGotoPreview.Name = "btnGotoPreview";+ this.btnGotoPreview.Size = new global::System.Drawing.Size(194, 31);+ this.btnGotoPreview.TabIndex = 0;+ this.btnGotoPreview.Text = "Preview";+ this.btnGotoPreview.UseVisualStyleBackColor = true;+ this.btnGotoProbes.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnGotoProbes.Location = new global::System.Drawing.Point(431, 27);+ this.btnGotoProbes.Name = "btnGotoProbes";+ this.btnGotoProbes.Size = new global::System.Drawing.Size(198, 31);+ this.btnGotoProbes.TabIndex = 0;+ this.btnGotoProbes.Text = "Probes";+ this.btnGotoProbes.UseVisualStyleBackColor = true;+ this.btnGotoSources.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnGotoSources.Location = new global::System.Drawing.Point(228, 27);+ this.btnGotoSources.Name = "btnGotoSources";+ this.btnGotoSources.Size = new global::System.Drawing.Size(197, 31);+ this.btnGotoSources.TabIndex = 0;+ this.btnGotoSources.Text = "Sources";+ this.btnGotoSources.UseVisualStyleBackColor = true;+ this.btnGotoConfiguration.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnGotoConfiguration.Location = new global::System.Drawing.Point(25, 27);+ this.btnGotoConfiguration.Name = "btnGotoConfiguration";+ this.btnGotoConfiguration.Size = new global::System.Drawing.Size(197, 31);+ this.btnGotoConfiguration.TabIndex = 0;+ this.btnGotoConfiguration.Text = "Settings";+ this.btnGotoConfiguration.UseVisualStyleBackColor = true;+ this.grpSimulationControlButtons.BackColor = global::System.Drawing.SystemColors.Control;+ this.grpSimulationControlButtons.Controls.Add(this.btnPauzeResume);+ this.grpSimulationControlButtons.Controls.Add(this.btnStartSimulation);+ this.grpSimulationControlButtons.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.grpSimulationControlButtons.Location = new global::System.Drawing.Point(16, 827);+ this.grpSimulationControlButtons.Name = "grpSimulationControlButtons";+ this.grpSimulationControlButtons.Size = new global::System.Drawing.Size(262, 127);+ this.grpSimulationControlButtons.TabIndex = 9;+ this.grpSimulationControlButtons.TabStop = false;+ this.grpSimulationControlButtons.Text = "Simulation Control";+ this.Panel1.BackColor = global::System.Drawing.Color.Azure;+ this.Panel1.Controls.Add(this.btnDescription);+ this.Panel1.Controls.Add(this.txtRootFolder);+ this.Panel1.Controls.Add(this.txtProjectName);+ this.Panel1.Controls.Add(this.lblRootFolder);+ this.Panel1.Controls.Add(this.lblProjectName);+ this.Panel1.Controls.Add(this.btnBrowseRoot);+ this.Panel1.Location = new global::System.Drawing.Point(19, 33);+ this.Panel1.Name = "Panel1";+ this.Panel1.Size = new global::System.Drawing.Size(1734, 43);+ this.Panel1.TabIndex = 10;+ this.btnDescription.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnDescription.Location = new global::System.Drawing.Point(1536, 8);+ this.btnDescription.Name = "btnDescription";+ this.btnDescription.Size = new global::System.Drawing.Size(168, 29);+ this.btnDescription.TabIndex = 5;+ this.btnDescription.Text = "Edit description";+ this.btnDescription.UseVisualStyleBackColor = true;+ this.grpShareImage.Controls.Add(this.btnShareIntensityImage);+ this.grpShareImage.Controls.Add(this.btnShareFieldImage);+ this.grpShareImage.Controls.Add(this.btnShareSceneImage);+ this.grpShareImage.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 9.75f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.grpShareImage.Location = new global::System.Drawing.Point(295, 827);+ this.grpShareImage.Name = "grpShareImage";+ this.grpShareImage.Size = new global::System.Drawing.Size(199, 125);+ this.grpShareImage.TabIndex = 11;+ this.grpShareImage.TabStop = false;+ this.grpShareImage.Text = "Share with source / probe";+ this.btnShareIntensityImage.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnShareIntensityImage.Location = new global::System.Drawing.Point(14, 86);+ this.btnShareIntensityImage.Name = "btnShareIntensityImage";+ this.btnShareIntensityImage.Size = new global::System.Drawing.Size(154, 27);+ this.btnShareIntensityImage.TabIndex = 0;+ this.btnShareIntensityImage.Text = "Intensity image";+ this.btnShareIntensityImage.UseVisualStyleBackColor = true;+ this.btnShareFieldImage.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnShareFieldImage.Location = new global::System.Drawing.Point(16, 53);+ this.btnShareFieldImage.Name = "btnShareFieldImage";+ this.btnShareFieldImage.Size = new global::System.Drawing.Size(154, 27);+ this.btnShareFieldImage.TabIndex = 0;+ this.btnShareFieldImage.Text = "Field image";+ this.btnShareFieldImage.UseVisualStyleBackColor = true;+ this.btnShareSceneImage.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnShareSceneImage.Location = new global::System.Drawing.Point(15, 21);+ this.btnShareSceneImage.Name = "btnShareSceneImage";+ this.btnShareSceneImage.Size = new global::System.Drawing.Size(155, 27);+ this.btnShareSceneImage.TabIndex = 0;+ this.btnShareSceneImage.Text = "Scene image";+ this.btnShareSceneImage.UseVisualStyleBackColor = true;+ // event wiring (was VB WithEvents/Handles)+ this.tabMainFunctions.Selecting += new TabControlCancelEventHandler(this.tabMainFunctions_Selecting);+ this.tabMainFunctions.DrawItem += new DrawItemEventHandler(this.tabMainFunctions_DrawItem);+ this.tabMainFunctions.SelectedIndexChanged += new EventHandler(this.tabMainFunctions_SelectedIndexChanged);+ this.tabMainFunctions.SelectedIndexChanged += new EventHandler(this.ProbeTabChanged);+ this.tabMainFunctions.SelectedIndexChanged += new EventHandler(this.SourceTabChanged);+ this.btnColor5.Click += new EventHandler(this.StopButton_Click);+ this.btnColor4.Click += new EventHandler(this.StopButton_Click);+ this.btnColor3.Click += new EventHandler(this.StopButton_Click);+ this.btnCOlor2.Click += new EventHandler(this.StopButton_Click);+ this.btnColor1.Click += new EventHandler(this.StopButton_Click);+ this.pnlScheme.Paint += new PaintEventHandler(this.pnlScheme_Paint);+ this.btnSaveAsColorScheme.Click += new EventHandler(this.btnSaveAsColorScheme_Click);+ this.btnSaveCurrentScheme.Click += new EventHandler(this.btnSaveCurrentScheme_Click);+ this.ListView1.ColumnClick += new ColumnClickEventHandler(this.ListView1_ColumnClick);+ this.ListView1.SelectedIndexChanged += new EventHandler(this.ListView1_SelectedIndexChanged);+ this.ListView1.DoubleClick += new EventHandler(this.ListView1_DoubleClick);+ this.ListView1.KeyDown += new KeyEventHandler(this.ListView1_KeyDown);+ this.NewToolStripMenuItem.Click += new EventHandler(this.btnNewProject2_Click);+ this.OpenToolStripMenuItem.Click += new EventHandler(this.OpenProject_Click);+ this.SaveToolStripMenuItem.Click += new EventHandler(this.SaveProject_Click);+ this.ExitToolStripMenuItem.Click += new EventHandler(this.ExitProgram_Click);+ this.btnLoadScheme.Click += new EventHandler(this.btnLoadScheme_Click);+ this.radSchemeTypeIntensity.CheckedChanged += new EventHandler(this.SchemeType_CheckedChanged);+ this.radSchemeTypeField.CheckedChanged += new EventHandler(this.SchemeType_CheckedChanged);+ this.btbChooseFFolder.Click += new EventHandler(this.btbChooseFFolder_Click);+ this.txtSchemeFolder.KeyDown += new KeyEventHandler(this.txtSchemeFolder_KeyDown);+ this.btnColor7.Click += new EventHandler(this.StopButton_Click);+ this.btnColor6.Click += new EventHandler(this.StopButton_Click);+ this.txtRootFolder.DoubleClick += new EventHandler(this.ChooseProjectRootToolStripMenuItem_Click);+ this.btnBrowseRoot.Click += new EventHandler(this.ChooseProjectRootToolStripMenuItem_Click);+ this.btnSaveAs.Click += new EventHandler(this.SaveAs_Click);+ this.txtDampingEdgeSize.TextChanged += new EventHandler(this.DampingSize_TextChanged);+ this.txtDampingEdgeSize.Leave += new EventHandler(this.SceneText_Leave);+ this.chkUseImageSources.CheckedChanged += new EventHandler(this.chkUseSources_CheckedChanged);+ this.chkDampingEdge.CheckedChanged += new EventHandler(this.chkDampingEdge_CheckedChanged);+ this.btnLoadSceneImage.Click += new EventHandler(this.btnLOadSceneImage_Click);+ this.txtYsize.TextChanged += new EventHandler(this.CanvasSize_TextChanged);+ this.txtYsize.Leave += new EventHandler(this.SceneText_Leave);+ this.txtXSize.TextChanged += new EventHandler(this.CanvasSize_TextChanged);+ this.txtXSize.Leave += new EventHandler(this.SceneText_Leave);+ this.radUserDefinedScene.CheckedChanged += new EventHandler(this.SceneMode_CheckedChanged);+ this.radUseSceneImage.CheckedChanged += new EventHandler(this.SceneMode_CheckedChanged);+ this.btnSaveConfiguration.Click += new EventHandler(this.SaveProject_Click);+ this.numVisualizeEvery.ValueChanged += new EventHandler(this.numVisualizeEvery_ValueChanged);+ this.chkPreviewVideoIntensity.CheckedChanged += new EventHandler(this.SimulationOption_CheckedChanged);+ this.chkExportVideoIntensity.CheckedChanged += new EventHandler(this.SimulationOption_CheckedChanged);+ this.chkPreviewVideoField.CheckedChanged += new EventHandler(this.SimulationOption_CheckedChanged);+ this.chkExportVideoField.CheckedChanged += new EventHandler(this.SimulationOption_CheckedChanged);+ this.cmbFieldColorScheme.SelectedIndexChanged += new EventHandler(this.SchemeCombo_SelectedIndexChanged);+ this.cmbIntensityColorScheme.SelectedIndexChanged += new EventHandler(this.SchemeCombo_SelectedIndexChanged);+ this.btnStartSimulation.Click += new EventHandler(this.btnStartSimulation_Click);+ this.numFieldScaling.ValueChanged += new EventHandler(this.numScaleFieldValues_ValueChanged);+ this.numIntensityScaling.ValueChanged += new EventHandler(this.numScaleIntensity_ValueChanged);+ this.btnEditObjectSourceList.Click += new EventHandler(this.btnEditSourceList_Click);+ this.chkUseObjectSources.CheckedChanged += new EventHandler(this.chkUseObjectSources_CheckedChanged);+ this.numScaleImageSource.ValueChanged += new EventHandler(this.ImageSourceScale_ValueChanged);+ this.numOffsetIntensity.ValueChanged += new EventHandler(this.numOffsetIntensity_ValueChanged);+ this.numOffsetField.ValueChanged += new EventHandler(this.numOffsetField_ValueChanged);+ this.btnViewIntensityVideo.Click += new EventHandler(this.btnViewIntensityVideo_Click);+ this.btnViewFieldVideo.Click += new EventHandler(this.btnViewFieldVideo_Click);+ this.lblVideoQuality.Click += new EventHandler(this.lblVideoQuality_Click);+ this.numQuality.ValueChanged += new EventHandler(this.numQuality_ValueChanged);+ this.chkUseGPU.CheckedChanged += new EventHandler(this.chkUseGPU_CheckedChanged);+ this.btnPauzeResume.Click += new EventHandler(this.btnPauzeResume_Click);+ this.grpProbe1.Enter += new EventHandler(this.grpProbe1_Enter);+ this.radFullScale.CheckedChanged += new EventHandler(this.ProbeScaleMode_CheckedChanged);+ this.radRunningScale.CheckedChanged += new EventHandler(this.ProbeScaleMode_CheckedChanged);+ this.chkAutoScaleY.CheckedChanged += new EventHandler(this.ProbeAutoScale_CheckedChanged);+ this.chkAutoScaleX.CheckedChanged += new EventHandler(this.ProbeAutoScale_CheckedChanged);+ this.numBPosY.ValueChanged += new EventHandler(this.ProbePosition_ValueChanged);+ this.numAPosY.ValueChanged += new EventHandler(this.ProbePosition_ValueChanged);+ this.numBPosX.ValueChanged += new EventHandler(this.ProbePosition_ValueChanged);+ this.numAPosX.ValueChanged += new EventHandler(this.ProbePosition_ValueChanged);+ this.butPicPositions.Click += new EventHandler(this.butPicPositions_Click);+ this.cmbPlaceOn.SelectedIndexChanged += new EventHandler(this.ProbeCombo_SelectedIndexChanged);+ this.cmbMeasurement.SelectedIndexChanged += new EventHandler(this.ProbeCombo_SelectedIndexChanged);+ this.cmbBoxSize.SelectedIndexChanged += new EventHandler(this.ProbeCombo_SelectedIndexChanged);+ this.cmbProbeType.SelectedIndexChanged += new EventHandler(this.ProbeCombo_SelectedIndexChanged);+ this.txtStartAfterStep.KeyDown += new KeyEventHandler(this.ProbeTextBox_KeyDown);+ this.txtStartAfterStep.Validated += new EventHandler(this.ProbeStartAfterStep_Validated);+ this.chkStartAfterStep.CheckedChanged += new EventHandler(this.ProbeStartAfterStep_CheckedChanged);+ this.txtMaxScaleY.KeyDown += new KeyEventHandler(this.ProbeTextBox_KeyDown);+ this.txtMaxScaleY.Validated += new EventHandler(this.ProbeYRange_Validated);+ this.txtMinScaleY.KeyDown += new KeyEventHandler(this.ProbeTextBox_KeyDown);+ this.txtMinScaleY.Validated += new EventHandler(this.ProbeYRange_Validated);+ this.numRefractiveIndex.ValueChanged += new EventHandler(this.RefractiveIndex_ValueChanged);+ this.chkProbeOn1.CheckedChanged += new EventHandler(this.ProbeOn_CheckedChanged);+ this.Label21.Click += new EventHandler(this.Label21_Click);+ this.numRunningWindow.ValueChanged += new EventHandler(this.ProbeRunningWindow_ValueChanged);+ this.grpProbe2.Enter += new EventHandler(this.grpProbe1_Enter);+ this.Label22.Click += new EventHandler(this.Label21_Click);+ this.numRunningWindow2.ValueChanged += new EventHandler(this.ProbeRunningWindow2_ValueChanged);+ this.chkProbeOn2.CheckedChanged += new EventHandler(this.ProbeOn2_CheckedChanged);+ this.txtStartAfterStep2.KeyDown += new KeyEventHandler(this.ProbeTextBox2_KeyDown);+ this.txtStartAfterStep2.Validated += new EventHandler(this.ProbeStartAfterStep2_Validated);+ this.chkStartAfterStep2.CheckedChanged += new EventHandler(this.ProbeStartAfterStep2_CheckedChanged);+ this.txtMaxScaleY2.KeyDown += new KeyEventHandler(this.ProbeTextBox2_KeyDown);+ this.txtMaxScaleY2.Validated += new EventHandler(this.ProbeYRange2_Validated);+ this.txtMinScaleY2.KeyDown += new KeyEventHandler(this.ProbeTextBox2_KeyDown);+ this.txtMinScaleY2.Validated += new EventHandler(this.ProbeYRange2_Validated);+ this.radFullScale2.CheckedChanged += new EventHandler(this.ProbeScaleMode2_CheckedChanged);+ this.radRunningScale2.CheckedChanged += new EventHandler(this.ProbeScaleMode2_CheckedChanged);+ this.chkAutoScaleY2.CheckedChanged += new EventHandler(this.ProbeAutoScale2_CheckedChanged);+ this.chkAutoScaleX2.CheckedChanged += new EventHandler(this.ProbeAutoScale2_CheckedChanged);+ this.numBPosY2.ValueChanged += new EventHandler(this.ProbePosition2_ValueChanged);+ this.numAPosY2.ValueChanged += new EventHandler(this.ProbePosition2_ValueChanged);+ this.numBPosX2.ValueChanged += new EventHandler(this.ProbePosition2_ValueChanged);+ this.numAPosX2.ValueChanged += new EventHandler(this.ProbePosition2_ValueChanged);+ this.butPicPositions2.Click += new EventHandler(this.butPicPositions2_Click);+ this.cmbPlaceOn2.SelectedIndexChanged += new EventHandler(this.ProbeCombo2_SelectedIndexChanged);+ this.cmbMeasurement2.SelectedIndexChanged += new EventHandler(this.ProbeCombo2_SelectedIndexChanged);+ this.cmbBoxSize2.SelectedIndexChanged += new EventHandler(this.ProbeCombo2_SelectedIndexChanged);+ this.cmbProbeType2.SelectedIndexChanged += new EventHandler(this.ProbeCombo2_SelectedIndexChanged);+ this.btnDelete.Click += new EventHandler(this.btnDelete_Click);+ this.lstSources.DrawItem += new DrawItemEventHandler(this.lstSources_DrawItem);+ this.lstSources.SelectedIndexChanged += new EventHandler(this.lstSources_SelectedIndexChanged);+ this.numSourcePositionY.ValueChanged += new EventHandler(this.SourcePosition_ValueChanged);+ this.numSourcePositionX.ValueChanged += new EventHandler(this.SourcePosition_ValueChanged);+ this.btnPickSourcePosition.Click += new EventHandler(this.PickSourcePosition_Click);+ this.btnCopy.Click += new EventHandler(this.btnCopy_Click);+ this.radModePulsed.CheckedChanged += new EventHandler(this.SourceMode_CheckedChanged);+ this.radModeContinuous.CheckedChanged += new EventHandler(this.SourceMode_CheckedChanged);+ this.cmbMainType.SelectedIndexChanged += new EventHandler(this.SourceMainType_SelectedIndexChanged);+ this.numOffStateCycles.ValueChanged += new EventHandler(this.SourceRandomizeLimitInput_ValueChanged);+ this.numFrequency.ValueChanged += new EventHandler(this.SourceFrequency_ValueChanged);+ this.numFrequency.ValueChanged += new EventHandler(this.SourceRandomizeLimitInput_ValueChanged);+ this.numSpacingSizeX.ValueChanged += new EventHandler(this.SourceRandomizeLimitInput_ValueChanged);+ this.numArraySizeX.ValueChanged += new EventHandler(this.SourceRandomizeLimitInput_ValueChanged);+ this.numArraySizeX.Validating += new CancelEventHandler(this.ArraySize_Validating);+ this.cmbCompositeProperties.SelectedIndexChanged += new EventHandler(this.SourceMainType_SelectedIndexChanged);+ this.numSpacingSizeY.ValueChanged += new EventHandler(this.SourceRandomizeLimitInput_ValueChanged);+ this.numArraySizeY.ValueChanged += new EventHandler(this.SourceRandomizeLimitInput_ValueChanged);+ this.numArraySizeY.Validating += new CancelEventHandler(this.ArraySize_Validating);+ this.btnSaveSource.Click += new EventHandler(this.btnSaveSource_Click);+ this.chkRandomizePhase.CheckedChanged += new EventHandler(this.SourceRandomizeCheck_CheckedChanged);+ this.chkRandomizePosition.CheckedChanged += new EventHandler(this.SourceRandomizeCheck_CheckedChanged);+ this.chkOffWidth.CheckedChanged += new EventHandler(this.SourceRandomizeCheck_CheckedChanged);+ this.chkRandomizeFrequency.CheckedChanged += new EventHandler(this.SourceRandomizeCheck_CheckedChanged);+ this.btnOpenVideoFolder.Click += new EventHandler(this.btnOpenVideoFolder_Click);+ this.chkDetachSource.CheckedChanged += new EventHandler(this.SourceDetach_CheckedChanged);+ this.btnRenameProject.Click += new EventHandler(this.btnRenameProject_Click);+ this.btnDeleteProject.Click += new EventHandler(this.btnDeleteProject_Click);+ this.btnLoadProject.Click += new EventHandler(this.btnLoadProject_Click);+ this.ChooseProjectRootToolStripMenuItem.Click += new EventHandler(this.ChooseProjectRootToolStripMenuItem_Click);+ this.SetCValueToolStripMenuItem.Click += new EventHandler(this.SetCValueToolStripMenuItem_Click);+ this.btnExportIntensityFrame.Click += new EventHandler(this.btnExportIntensityFrame_Click);+ this.btnExportFieldFrame.Click += new EventHandler(this.btnExportFieldFrame_Click);+ this.btnOpenImageFolder.Click += new EventHandler(this.btnOpenImageFolder_Click);+ this.btnNew.Click += new EventHandler(this.btnNew_Click);+ this.btnGotoPreview.Click += new EventHandler(this.btnGotoPreview_Click);+ this.btnGotoProbes.Click += new EventHandler(this.btnGotoProbes_Click);+ this.btnGotoSources.Click += new EventHandler(this.btnGotoSources_Click);+ this.btnGotoConfiguration.Click += new EventHandler(this.btnGotoConfiguration_Click);+ this.btnShareIntensityImage.Click += new EventHandler(this.btnShareIntensityImage_Click);+ this.btnShareFieldImage.Click += new EventHandler(this.btnShareFieldImage_Click);+ this.btnShareSceneImage.Click += new EventHandler(this.btnShareSceneImage_Click);+ this.btnNewProject.Click += new EventHandler(this.btnNewProject2_Click);+ this.btnColor9.Click += new EventHandler(this.StopButton_Click);+ this.btnColor8.Click += new EventHandler(this.StopButton_Click);+ this.btnDeleteColorScheme.Click += new EventHandler(this.btnDeleteColorScheme_Click);+ this.btnRenameColorScheme.Click += new EventHandler(this.btnRenameColorScheme_Click);+ this.lstAllProjects.ColumnClick += new ColumnClickEventHandler(this.lstAllProjects_ColumnClick);+ this.lstAllProjects.SelectedIndexChanged += new EventHandler(this.lstAllProjects_SelectedIndexChanged);+ this.lstAllProjects.DoubleClick += new EventHandler(this.lstAllProjects_DoubleClick);+ this.lstImages.ColumnClick += new ColumnClickEventHandler(this.lstImages_ColumnClick);+ this.lstImages.SelectedIndexChanged += new EventHandler(this.lstImages_SelectedIndexChanged);+ this.lstImages.KeyDown += new KeyEventHandler(this.lstImages_KeyDown);+ this.lstVideo.ColumnClick += new ColumnClickEventHandler(this.lstVideo_ColumnClick);+ this.lstVideo.SelectedIndexChanged += new EventHandler(this.lstVideo_SelectedIndexChanged);+ this.lstVideo.KeyDown += new KeyEventHandler(this.lstVideo_KeyDown);+ this.lstVideo.DoubleClick += new EventHandler(this.lstVideo_DoubleClick);+ this.lstAllProjects3.ColumnClick += new ColumnClickEventHandler(this.lstAllProjects3_ColumnClick);+ this.lstAllProjects3.SelectedIndexChanged += new EventHandler(this.lstAllProjects3_SelectedIndexChanged);+ this.btnDeleteScene.Click += new EventHandler(this.btnDeleteScene_Click);+ this.btnLoadExternal.Click += new EventHandler(this.btnLoadExternal_Click);+ this.lstScenes.ColumnClick += new ColumnClickEventHandler(this.lstScenes_ColumnClick);+ this.lstScenes.SelectedIndexChanged += new EventHandler(this.lstScenes_SelectedIndexChanged);+ this.btnOpenImageFolder2.Click += new EventHandler(this.btnOpenImageFolder2_Click);+ this.btnViewVIdeoInPlayer2.Click += new EventHandler(this.btnViewVIdeoInPlayer2_Click);+ this.btnOpenVIdeoFolder2.Click += new EventHandler(this.btnOpenVIdeoFolder2_Click);+ this.btnDeleteVideos.Click += new EventHandler(this.btnDeleteVideos_Click);+ this.btnDeleteImages.Click += new EventHandler(this.btnDeleteImages_Click);+ this.btnCopyToClipboard.Click += new EventHandler(this.btnCopyToClipboard_Click);+ this.btnShareWithEditors.Click += new EventHandler(this.btnShareWithEditors_Click);+ this.chkUse4thOrderLaplacian.CheckedChanged += new EventHandler(this.chkUse4thOrderLaplacian_CheckedChanged);+ this.lblInfo.Click += new EventHandler(this.lblInfo_Click);+ this.btnRenameVideo.Click += new EventHandler(this.btnRenameVideo_Click);+ this.picPreviewSource.Paint += new PaintEventHandler(this.picPreviewSource_Paint);+ this.picPreviewSource.SizeChanged += new EventHandler(this.picPreviewSource_SizeChanged);+ this.chkAutoRescaleSourceOn.CheckedChanged += new EventHandler(this.chkAutoRescaleSourceOn_CheckedChanged);+ this.numSimulationSteps.ValueChanged += new EventHandler(this.numSimulationSteps_ValueChanged);+ this.numTimeDecayFactor.ValueChanged += new EventHandler(this.numTimeDecayFactor_ValueChanged);+ this.numFieldScaling2.ValueChanged += new EventHandler(this.numScaleFieldValues2_ValueChanged);+ this.chkDiplayOverlayInField.CheckedChanged += new EventHandler(this.chkDiplayOverlayInField_CheckedChanged);+ this.numIntensityScaling2.ValueChanged += new EventHandler(this.numScaleIntensity2_ValueChanged);+ this.chkDiplayOverlayInIntensity.CheckedChanged += new EventHandler(this.chkDiplayOverlayInIntensity_CheckedChanged);+ this.numBrightnessIntensityOverlay.ValueChanged += new EventHandler(this.numBrightnessIntensityOverlay_ValueChanged);+ this.numBrightnessFieldOverlay.ValueChanged += new EventHandler(this.numBrightnessFieldOverlay_ValueChanged);+ this.chkExportVideoIntensity2.CheckedChanged += new EventHandler(this.chkExportVideoIntensity2_CheckedChanged);+ this.chkExportVideoField2.CheckedChanged += new EventHandler(this.chkExportVideoField2_CheckedChanged);+ this.HelpToolStripMenuItem.Click += new EventHandler(this.HelpToolStripMenuItem_Click);+ this.AboutToolStripMenuItem.Click += new EventHandler(this.AboutToolStripMenuItem_Click);+ this.btnSaveConfiguration2.Click += new EventHandler(this.btnSaveConfiguration2_Click);+ this.btnDescription.Click += new EventHandler(this.btnDescription_Click);+ this.btnPickRoot.Click += new EventHandler(this.ChooseProjectRootToolStripMenuItem_Click);+ base.AutoScaleDimensions = new global::System.Drawing.SizeF(6f, 13f);+ base.AutoScaleMode = global::System.Windows.Forms.AutoScaleMode.Font;+ base.ClientSize = new global::System.Drawing.Size(1781, 989);+ base.Controls.Add(this.grpShareImage);+ base.Controls.Add(this.Panel1);+ base.Controls.Add(this.grpSimulationControlButtons);+ base.Controls.Add(this.grpNavigateTabs);+ base.Controls.Add(this.StatusStrip1);+ base.Controls.Add(this.tabMainFunctions);+ base.Controls.Add(this.MenuStrip1);+ base.Controls.Add(this.btnSaveConfiguration);+ base.Icon = (global::System.Drawing.Icon)componentResourceManager.GetObject("$this.Icon");+ base.MainMenuStrip = this.MenuStrip1;+ base.Name = "Form1";+ this.Text = "Wave Dude 2D V0.29";+ this.tabMainFunctions.ResumeLayout(false);+ this.tabConfiguration.ResumeLayout(false);+ this.grpProjects.ResumeLayout(false);+ this.grpSimulationSettings.ResumeLayout(false);+ this.grpSimulationSettings.PerformLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numTimeDecayFactor).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numSimulationSteps).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numQuality).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numIntensityScaling).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numOffsetIntensity).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numOffsetField).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numFieldScaling).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numVisualizeEvery).EndInit();+ this.grpSceneProperties.ResumeLayout(false);+ this.grpSceneProperties.PerformLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numRefractiveIndex).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.picImagePreview).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numScaleImageSource).EndInit();+ this.tabSourceList.ResumeLayout(false);+ this.tabSourceList.PerformLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.picPreviewSource).EndInit();+ this.grpPlaceSource.ResumeLayout(false);+ this.pnlPosition.ResumeLayout(false);+ this.pnlPosition.PerformLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numSourcePositionX).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numSourcePositionY).EndInit();+ this.grpSourceDetails.ResumeLayout(false);+ this.grpSourceDetails.PerformLayout();+ this.grpComposite.ResumeLayout(false);+ this.grpComposite.PerformLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numRandomizeOffWidth).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numRandomizePosition).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.NumRandomizePhase).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numRandomizeFrequency).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numSpacingSizeY).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numSpacingSizeX).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numArraySizeY).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numArraySizeX).EndInit();+ this.grpSingleSource.ResumeLayout(false);+ this.grpSingleSource.PerformLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numOffStateCycles).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numPhase).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numAmplitude).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numFrequency).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numPulseWidthCycles).EndInit();+ this.tabProbeList.ResumeLayout(false);+ this.GroupBox2.ResumeLayout(false);+ this.GroupBox2.PerformLayout();+ this.grpProbe2.ResumeLayout(false);+ this.grpProbe2.PerformLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numRunningWindow2).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numBPosY2).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numAPosY2).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numBPosX2).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numAPosX2).EndInit();+ this.grpProbe1.ResumeLayout(false);+ this.grpProbe1.PerformLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numRunningWindow).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numBPosY).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numAPosY).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numBPosX).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numAPosX).EndInit();+ this.tabViewer.ResumeLayout(false);+ this.tabViewer.PerformLayout();+ this.pnlPreviewIntensityProps.ResumeLayout(false);+ this.pnlPreviewIntensityProps.PerformLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numBrightnessIntensityOverlay).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numIntensityScaling2).EndInit();+ this.Panel3.ResumeLayout(false);+ this.Panel3.PerformLayout();+ ((global::System.ComponentModel.ISupportInitialize)this.numFieldScaling2).EndInit();+ ((global::System.ComponentModel.ISupportInitialize)this.numBrightnessFieldOverlay).EndInit();+ this.tabOutput.ResumeLayout(false);+ this.tabOutput.PerformLayout();+ this.tabColorScheme.ResumeLayout(false);+ this.tabColorScheme.PerformLayout();+ this.MenuStrip1.ResumeLayout(false);+ this.MenuStrip1.PerformLayout();+ this.StatusStrip1.ResumeLayout(false);+ this.StatusStrip1.PerformLayout();+ this.grpNavigateTabs.ResumeLayout(false);+ this.grpSimulationControlButtons.ResumeLayout(false);+ this.Panel1.ResumeLayout(false);+ this.Panel1.PerformLayout();+ this.grpShareImage.ResumeLayout(false);+ base.ResumeLayout(false);+ base.PerformLayout();+ }++ private TabControl tabMainFunctions;+ private TabPage tabColorScheme;+ private TextBox txtCurrentColorScheme;+ private Label lblCurrentCOlorScheme;+ private Label lblColorSchemeEditor;+ private Button btnColor5;+ private Button btnColor4;+ private Button btnColor3;+ private Button btnCOlor2;+ private Button btnColor1;+ private Label lblColorPicker;+ private Panel Panel2;+ private Panel pnlScheme;+ private Button btnSaveAsColorScheme;+ private Button btnSaveCurrentScheme;+ private TabPage tabConfiguration;+ private TabPage tabProbeList;+ private TabPage tabOutput;+ private TabPage tabViewer;+ private ListView ListView1;+ private MenuStrip MenuStrip1;+ private ToolStripMenuItem itemFile;+ private ToolStripMenuItem NewToolStripMenuItem;+ private ToolStripMenuItem OpenToolStripMenuItem;+ private ToolStripMenuItem SaveToolStripMenuItem;+ private ToolStripMenuItem ExitToolStripMenuItem;+ private Label lblSchemeFolder;+ private Button btnLoadScheme;+ private Label lblType;+ private RadioButton radSchemeTypeIntensity;+ private RadioButton radSchemeTypeField;+ private Button btbChooseFFolder;+ private TextBox txtSchemeFolder;+ private Button btnColor7;+ private Button btnColor6;+ private Label lblProjectName;+ private TextBox txtProjectName;+ private TextBox txtRootFolder;+ private Label lblRootFolder;+ private Button btnBrowseRoot;+ private Button btnSaveAs;+ private GroupBox grpSceneProperties;+ private TextBox txtDampingEdgeSize;+ private CheckBox chkUseImageSources;+ private CheckBox chkDampingEdge;+ private Button btnLoadSceneImage;+ private Label lblImageNameAndSize;+ private Label Label1;+ private Label lblPix;+ private Label lblX;+ private TextBox txtYsize;+ private TextBox txtXSize;+ private RadioButton radUserDefinedScene;+ private PictureBox picImagePreview;+ private RadioButton radUseSceneImage;+ private TabPage tabSourceList;+ private Button btnSaveConfiguration;+ private GroupBox grpSimulationSettings;+ private NumericUpDown numVisualizeEvery;+ private Label Label4;+ private Label lblVisualizeEvery;+ private Label lblSimulationSteps;+ private CheckBox chkPreviewVideoIntensity;+ private CheckBox chkExportVideoIntensity;+ private CheckBox chkPreviewVideoField;+ private CheckBox chkExportVideoField;+ private Label lblPreviewVideo;+ private Label lblExportVideo;+ private Panel pnlPreviewIntensity;+ private Panel pnlPreviewField;+ private ComboBox cmbFieldColorScheme;+ private Label Label3;+ private Label Label2;+ private ComboBox cmbIntensityColorScheme;+ private Button btnStartSimulation;+ private NumericUpDown numFieldScaling;+ private Label Label5;+ private NumericUpDown numIntensityScaling;+ private Label numScaleIntensityValues;+ private Button btnEditObjectSourceList;+ private CheckBox chkUseObjectSources;+ private Label lblScaleImgSourceIntensity;+ private NumericUpDown numScaleImageSource;+ private NumericUpDown numOffsetIntensity;+ private NumericUpDown numOffsetField;+ private Label Label6;+ private Label lblOffsetField;+ private Button btnViewIntensityVideo;+ private Button btnViewFieldVideo;+ private Label lblVideoQuality;+ private NumericUpDown numQuality;+ private CheckBox chkUseGPU;+ private Label Label7;+ private StatusStrip StatusStrip1;+ private ToolStripStatusLabel ToolStripStatusLabel1;+ private Button btnPauzeResume;+ private Panel pnlSourceImage;+ private Panel pnlProbeImage;+ private GroupBox grpProbe1;+ private RadioButton radFullScale;+ private RadioButton radRunningScale;+ private CheckBox chkAutoScaleY;+ private CheckBox chkAutoScaleX;+ private NumericUpDown numBPosY;+ private NumericUpDown numAPosY;+ private NumericUpDown numBPosX;+ private NumericUpDown numAPosX;+ private Button butPicPositions;+ private Label Label16;+ private ComboBox cmbPlaceOn;+ private ComboBox cmbMeasurement;+ private Label Label13;+ private Label Label15;+ private ComboBox cmbBoxSize;+ private ComboBox cmbProbeType;+ private Label Label14;+ private Label Label12;+ private Label Label11;+ private Label Label17;+ private Label Label10;+ private Label Label9;+ private Label Label8;+ private TextBox txtStartAfterStep;+ private CheckBox chkStartAfterStep;+ private Label Label19;+ private Label Label18;+ private TextBox txtMaxScaleY;+ private TextBox txtMinScaleY;+ private Label Label20;+ private NumericUpDown numRefractiveIndex;+ private CheckBox chkProbeOn1;+ private Label Label21;+ private NumericUpDown numRunningWindow;+ private GroupBox grpProbe2;+ private Label Label22;+ private NumericUpDown numRunningWindow2;+ private CheckBox chkProbeOn2;+ private TextBox txtStartAfterStep2;+ private CheckBox chkStartAfterStep2;+ private Label Label23;+ private Label Label24;+ private TextBox txtMaxScaleY2;+ private TextBox txtMinScaleY2;+ private RadioButton radFullScale2;+ private RadioButton radRunningScale2;+ private CheckBox chkAutoScaleY2;+ private CheckBox chkAutoScaleX2;+ private NumericUpDown numBPosY2;+ private NumericUpDown numAPosY2;+ private NumericUpDown numBPosX2;+ private NumericUpDown numAPosX2;+ private Button butPicPositions2;+ private Label Label25;+ private ComboBox cmbPlaceOn2;+ private ComboBox cmbMeasurement2;+ private Label Label26;+ private Label Label27;+ private ComboBox cmbBoxSize2;+ private ComboBox cmbProbeType2;+ private Label Label28;+ private Label Label29;+ private Label Label30;+ private Label Label31;+ private Label Label32;+ private Label Label33;+ private Label Label34;+ private Button btnDelete;+ private ListBox lstSources;+ private GroupBox grpSourceDetails;+ private Label lblPosition;+ private NumericUpDown numSourcePositionY;+ private NumericUpDown numSourcePositionX;+ private Button btnPickSourcePosition;+ private Label Label36;+ private Label Label35;+ private Button btnCopy;+ private GroupBox grpSingleSource;+ private Label Label43;+ private Label Label42;+ private Label Label41;+ private Label Label40;+ private RadioButton radModePulsed;+ private RadioButton radModeContinuous;+ private TextBox txtName;+ private ComboBox cmbMainType;+ private Label Label39;+ private Label lblName;+ private Label Label38;+ private NumericUpDown numOffStateCycles;+ private NumericUpDown numAmplitude;+ private NumericUpDown numFrequency;+ private NumericUpDown numPulseWidthCycles;+ private Label Label44;+ private Label Label46;+ private Label Label45;+ private ComboBox cmbPulseShape;+ private GroupBox grpComposite;+ private NumericUpDown numSpacingSizeX;+ private NumericUpDown numArraySizeX;+ private NumericUpDown numRandomizeFrequency;+ private Label Label50;+ private Label Label51;+ private Label Label52;+ private Label Label53;+ private ComboBox cmbCompositeProperties;+ private NumericUpDown numPhase;+ private Label Label54;+ private NumericUpDown numSpacingSizeY;+ private NumericUpDown numArraySizeY;+ private Button btnSaveSource;+ private NumericUpDown numRandomizeOffWidth;+ private NumericUpDown numRandomizePosition;+ private NumericUpDown NumRandomizePhase;+ private CheckBox chkRandomizePhase;+ private CheckBox chkRandomizePosition;+ private CheckBox chkOffWidth;+ private CheckBox chkRandomizeFrequency;+ private Button btnOpenVideoFolder;+ private TextBox txtDetachAfterSteps;+ private Label Label47;+ private CheckBox chkDetachSource;+ private Panel pnlPosition;+ private Label lblLambdaIs;+ private CheckBox chkSourceOn;+ private Button btnRenameProject;+ private Button btnDeleteProject;+ private Button btnLoadProject;+ private ToolStripMenuItem ChooseProjectRootToolStripMenuItem;+ private ToolStripMenuItem SetCValueToolStripMenuItem;+ private Button btnExportIntensityFrame;+ private Button btnExportFieldFrame;+ private Button btnOpenImageFolder;+ private Button btnNew;+ private Label lblWarningIntensity;+ private Label lblWarningField;+ private GroupBox grpNavigateTabs;+ private GroupBox grpSimulationControlButtons;+ private Button btnGotoPreview;+ private Button btnGotoProbes;+ private Button btnGotoSources;+ private Button btnGotoConfiguration;+ private Panel Panel1;+ private GroupBox grpShareImage;+ private Button btnShareIntensityImage;+ private Button btnShareFieldImage;+ private Button btnShareSceneImage;+ private Button btnNewProject;+ private Button btnColor9;+ private Button btnColor8;+ private GroupBox grpProjects;+ private GroupBox grpPlaceSource;+ private GroupBox GroupBox2;+ private Label Label49;+ private Label Label48;+ private Label Label37;+ private Button btnDeleteColorScheme;+ private Button btnRenameColorScheme;+ private Label Label56;+ private Label Label55;+ private ListView lstAllProjects;+ private ColumnHeader colProjectName;+ private ColumnHeader colLastEdit;+ private ListView lstImages;+ private ColumnHeader colImageName;+ private ColumnHeader colCreatedOn;+ private ListView lstVideo;+ private ColumnHeader colVideoName;+ private ListView lstAllProjects3;+ private ColumnHeader colProjectName2;+ private ColumnHeader colLastEdited2;+ private Button btnDeleteScene;+ private Button btnLoadExternal;+ private Panel pnlPreview;+ private Label Label57;+ private ListView lstScenes;+ private ColumnHeader colSceneName;+ private ColumnHeader colSceneCreated;+ private Button btnOpenImageFolder2;+ private Button btnViewVIdeoInPlayer2;+ private Button btnOpenVIdeoFolder2;+ private Label lblPreview;+ private Button btnDeleteVideos;+ private Button btnDeleteImages;+ private Button btnCopyToClipboard;+ private Button btnShareWithEditors;+ private CheckBox chkUse4thOrderLaplacian;+ private Label lblInfo;+ private Button btnRenameVideo;+ private PictureBox picPreviewSource;+ private CheckBox chkAutoRescaleSourceOn;+ private NumericUpDown numSimulationSteps;+ private Label Label59;+ private Label Label58;+ private Label Label60;+ private Label Label61;+ private NumericUpDown numTimeDecayFactor;+ private Label Label62;+ private Label Label63;+ private NumericUpDown numFieldScaling2;+ private CheckBox chkDiplayOverlayInField;+ private Label Label64;+ private NumericUpDown numIntensityScaling2;+ private CheckBox chkDiplayOverlayInIntensity;+ private NumericUpDown numBrightnessIntensityOverlay;+ private NumericUpDown numBrightnessFieldOverlay;+ private Label Label66;+ private Label Label65;+ private Panel pnlPreviewIntensityProps;+ private CheckBox chkExportVideoIntensity2;+ private Panel Panel3;+ private CheckBox chkExportVideoField2;+ private ToolStripMenuItem InfoToolStripMenuItem;+ private ToolStripMenuItem HelpToolStripMenuItem;+ private ToolStripMenuItem AboutToolStripMenuItem;+ private Button btnSaveConfiguration2;+ private Button btnDescription;+ private Button btnPickRoot;+ private global::System.ComponentModel.IContainer components;+ }+}diff --git a/Wave_Dude_2D/Form1.Output.cs b/Wave_Dude_2D/Form1.Output.csnew file mode 100644index 0000000..9e9e15a--- /dev/null+++ b/Wave_Dude_2D/Form1.Output.cs@@ -0,0 +1,783 @@+using System;+using System.Collections.Generic;+using System.Drawing;+using System.Globalization;+using System.IO;+using System.Linq;+using System.Runtime.InteropServices;+using System.Windows.Forms;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Outputs tab: a second project list (<c>lstAllProjects3</c>) and, for the project selected+ /// there, three file lists (scene images, rendered frames, videos) with a shared preview box+ /// and delete/rename/open/copy commands. Only one of the three file lists has a selection at+ /// a time; selecting in one clears the other two. The lists show files on disk, not the open+ /// project's state, so they are refreshed from disk after every change. Everything here runs+ /// on the UI thread.+ /// </summary>+ public partial class Form1+ {+ /// <summary>+ /// Creates the preview <see cref="PictureBox"/> (zoom-to-fit, docked in <c>pnlPreview</c>),+ /// fills the Outputs-tab project list and sets the initial button state. Called once from+ /// <c>Form1_Load</c>.+ /// </summary>+ private void InitializeOutputsTab()+ {+ this._outputPreviewPic = new PictureBox();+ this._outputPreviewPic.Dock = DockStyle.Fill;+ this._outputPreviewPic.SizeMode = PictureBoxSizeMode.Zoom;+ this.pnlPreview.Controls.Add(this._outputPreviewPic);+ this.RefreshOutputProjectList("");+ this.UpdateShareWithEditorsButton();+ }++ /// <summary>+ /// Rebuilds the Outputs-tab project list from disk with its own sort state and selects+ /// <paramref name="preferredName"/>, or the previously selected project when that is "".+ /// Selecting an entry triggers <see cref="lstAllProjects3_SelectedIndexChanged"/>, which+ /// reloads the file lists.+ /// </summary>+ private void RefreshOutputProjectList(string preferredName = "")+ {+ string selectedName = (preferredName.Length > 0) ? preferredName : this.SelectedProjectName(this.lstAllProjects3);+ List<Form1.ProjectListEntry> entries = this.BuildProjectEntries();+ this.SortProjectEntries(entries, this._outputProjectSortColumn, this._outputProjectSortAscending);+ this.PopulateProjectListView(this.lstAllProjects3, entries);+ this.UpdateOutputProjectSortHeaders();+ this.SelectProjectInList(this.lstAllProjects3, selectedName);+ }++ /// <summary>Clicking a column header sorts the Outputs-tab project list by it; clicking the current sort column again flips the direction.</summary>+ private void lstAllProjects3_ColumnClick(object sender, ColumnClickEventArgs e)+ {+ if (e.Column == this._outputProjectSortColumn)+ {+ this._outputProjectSortAscending = !this._outputProjectSortAscending;+ }+ else+ {+ this._outputProjectSortColumn = e.Column;+ this._outputProjectSortAscending = true;+ }+ this.RefreshOutputProjectList("");+ }++ /// <summary>Appends " ^" (ascending) or " v" (descending) to the header of the column the Outputs-tab project list is sorted by.</summary>+ private void UpdateOutputProjectSortHeaders()+ {+ string arrow = this._outputProjectSortAscending ? " ^" : " v";+ this.colProjectName2.Text = "Project name" + ((this._outputProjectSortColumn == 0) ? arrow : "");+ this.colLastEdited2.Text = "Last edited" + ((this._outputProjectSortColumn == 1) ? arrow : "");+ }++ /// <summary>Full folder path of the project selected in the Outputs-tab list, or "" when none is selected.</summary>+ private string SelectedOutputProjectFolder()+ {+ string name = this.SelectedProjectName(this.lstAllProjects3);+ return (name.Length == 0) ? "" : ProjectStore.FolderPathFor(this._settings.ProjectRoot, name);+ }++ /// <summary>Selecting a project reloads the three file lists for it.</summary>+ private void lstAllProjects3_SelectedIndexChanged(object sender, EventArgs e)+ {+ this.RefreshOutputFileLists();+ }++ /// <summary>+ /// Refills the scene, image and video lists from the selected Outputs-tab project (empties+ /// them when none is selected), updates their sort headers, clears the preview and the+ /// copy-button state. Previous file selections are dropped; the <c>Refill*List</c> methods+ /// are the variants that keep them.+ /// </summary>+ private void RefreshOutputFileLists()+ {+ string projectFolder = this.SelectedOutputProjectFolder();+ this.FillFileList(this.lstScenes, projectFolder, ProjectStore.SceneImageFolderName, Form1.SceneImageExtensions, this._sceneSortColumn, this._sceneSortAscending);+ this.FillFileList(this.lstImages, projectFolder, ProjectStore.OutputFramesFolderName, Form1.OutputImageExtensions, this._imageSortColumn, this._imageSortAscending);+ this.FillFileList(this.lstVideo, projectFolder, ProjectStore.OutputVideoFolderName, Form1.OutputVideoExtensions, this._videoSortColumn, this._videoSortAscending);+ this.UpdateFileListSortHeaders(this.colSceneName, "Scene file name", this.colSceneCreated, "Created on", this._sceneSortColumn, this._sceneSortAscending);+ this.UpdateFileListSortHeaders(this.colImageName, "Image file name", this.colCreatedOn, "Created on", this._imageSortColumn, this._imageSortAscending);+ this.UpdateFileListSortHeaders(this.colVideoName, "Video file name", this.colCreatedOn2, "Created on", this._videoSortColumn, this._videoSortAscending);+ this.ClearOutputPreview();+ this.UpdateCopyToClipboardButton();+ }++ /// <summary>+ /// Replaces the items of <paramref name="list"/> with the files in+ /// <c>projectFolder\subfolderName</c> whose lower-cased extension (including the dot) is in+ /// <paramref name="extensions"/>. Sorted by file name, or by creation time when the list has+ /// a date column and <paramref name="sortColumn"/> is 1. Each item's <c>Tag</c> is the full+ /// path; the optional second column shows the local creation time as "yyyy-MM-dd HH:mm".+ /// The list is left empty when <paramref name="projectFolder"/> is "" or the sub-folder does+ /// not exist.+ /// </summary>+ private void FillFileList(ListView list, string projectFolder, string subfolderName, string[] extensions, int sortColumn, bool sortAscending)+ {+ list.BeginUpdate();+ try+ {+ list.Items.Clear();+ if (projectFolder.Length == 0)+ {+ return;+ }+ string folder = Path.Combine(projectFolder, subfolderName);+ if (!Directory.Exists(folder))+ {+ return;+ }+ List<string> files = new List<string>(Directory.GetFiles(folder));+ files.RemoveAll(f => Array.IndexOf(extensions, Path.GetExtension(f).ToLowerInvariant()) < 0);+ bool byCreatedDate = list.Columns.Count > 1 && sortColumn == 1;+ files.Sort((a, b) => CompareFileEntries(a, b, byCreatedDate, sortAscending));+ foreach (string file in files)+ {+ ListViewItem item = new ListViewItem(Path.GetFileName(file));+ if (list.Columns.Count > 1)+ {+ item.SubItems.Add(File.GetCreationTime(file).ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture));+ }+ item.Tag = file;+ list.Items.Add(item);+ }+ }+ finally+ {+ list.EndUpdate();+ }+ }++ /// <summary>Sort comparison for two full file paths: by creation time (read from disk on every call) or by file name, case-insensitive; negated for descending order.</summary>+ private static int CompareFileEntries(string a, string b, bool byCreatedDate, bool ascending)+ {+ int order = byCreatedDate+ ? File.GetCreationTime(a).CompareTo(File.GetCreationTime(b))+ : string.Compare(Path.GetFileName(a), Path.GetFileName(b), StringComparison.OrdinalIgnoreCase);+ return ascending ? order : -order;+ }++ /// <summary>Writes the two header labels of a file list, appending " ^" or " v" to the column (0 = name, 1 = date) the list is sorted by.</summary>+ private void UpdateFileListSortHeaders(ColumnHeader nameColumn, string nameLabel, ColumnHeader dateColumn, string dateLabel, int sortColumn, bool ascending)+ {+ string arrow = ascending ? " ^" : " v";+ nameColumn.Text = nameLabel + ((sortColumn == 0) ? arrow : "");+ dateColumn.Text = dateLabel + ((sortColumn == 1) ? arrow : "");+ }++ /// <summary>Full paths (item tags) of the selected items in a file list; items without a path tag are skipped.</summary>+ private List<string> SelectedFilePaths(ListView list)+ {+ List<string> paths = new List<string>();+ foreach (ListViewItem item in list.SelectedItems)+ {+ string path = item.Tag as string;+ if (!string.IsNullOrEmpty(path))+ {+ paths.Add(path);+ }+ }+ return paths;+ }++ /// <summary>Re-selects every item of <paramref name="list"/> whose path is in <paramref name="paths"/> (case-insensitive); used to keep the selection across a refill.</summary>+ private void ReselectFiles(ListView list, List<string> paths)+ {+ if (paths.Count == 0)+ {+ return;+ }+ foreach (ListViewItem item in list.Items)+ {+ string path = item.Tag as string;+ if (path != null && paths.Contains(path, StringComparer.OrdinalIgnoreCase))+ {+ item.Selected = true;+ }+ }+ }++ /// <summary>Reloads and re-sorts the scene-image list, keeping the selected files selected; used after a header click.</summary>+ private void RefillSceneList()+ {+ List<string> selected = this.SelectedFilePaths(this.lstScenes);+ this.FillFileList(this.lstScenes, this.SelectedOutputProjectFolder(), ProjectStore.SceneImageFolderName, Form1.SceneImageExtensions, this._sceneSortColumn, this._sceneSortAscending);+ this.UpdateFileListSortHeaders(this.colSceneName, "Scene file name", this.colSceneCreated, "Created on", this._sceneSortColumn, this._sceneSortAscending);+ this.ReselectFiles(this.lstScenes, selected);+ }++ /// <summary>Reloads and re-sorts the output-frame list, keeping the selected files selected; used after a header click.</summary>+ private void RefillImageList()+ {+ List<string> selected = this.SelectedFilePaths(this.lstImages);+ this.FillFileList(this.lstImages, this.SelectedOutputProjectFolder(), ProjectStore.OutputFramesFolderName, Form1.OutputImageExtensions, this._imageSortColumn, this._imageSortAscending);+ this.UpdateFileListSortHeaders(this.colImageName, "Image file name", this.colCreatedOn, "Created on", this._imageSortColumn, this._imageSortAscending);+ this.ReselectFiles(this.lstImages, selected);+ }++ /// <summary>Reloads and re-sorts the video list, keeping the selected files selected; used after a header click.</summary>+ private void RefillVideoList()+ {+ List<string> selected = this.SelectedFilePaths(this.lstVideo);+ this.FillFileList(this.lstVideo, this.SelectedOutputProjectFolder(), ProjectStore.OutputVideoFolderName, Form1.OutputVideoExtensions, this._videoSortColumn, this._videoSortAscending);+ this.UpdateFileListSortHeaders(this.colVideoName, "Video file name", this.colCreatedOn2, "Created on", this._videoSortColumn, this._videoSortAscending);+ this.ReselectFiles(this.lstVideo, selected);+ }++ /// <summary>Clicking a header sorts the scene-image list by that column (toggling direction on a repeat click).</summary>+ private void lstScenes_ColumnClick(object sender, ColumnClickEventArgs e)+ {+ Form1.ToggleFileSort(ref this._sceneSortColumn, ref this._sceneSortAscending, e.Column);+ this.RefillSceneList();+ }++ /// <summary>Clicking a header sorts the output-frame list by that column (toggling direction on a repeat click).</summary>+ private void lstImages_ColumnClick(object sender, ColumnClickEventArgs e)+ {+ Form1.ToggleFileSort(ref this._imageSortColumn, ref this._imageSortAscending, e.Column);+ this.RefillImageList();+ }++ /// <summary>Clicking a header sorts the video list by that column (toggling direction on a repeat click).</summary>+ private void lstVideo_ColumnClick(object sender, ColumnClickEventArgs e)+ {+ Form1.ToggleFileSort(ref this._videoSortColumn, ref this._videoSortAscending, e.Column);+ this.RefillVideoList();+ }++ /// <summary>Applies a header click to a sort column/direction pair: the same column flips the direction, a different column becomes the sort column in ascending order.</summary>+ private static void ToggleFileSort(ref int sortColumn, ref bool sortAscending, int clickedColumn)+ {+ if (clickedColumn == sortColumn)+ {+ sortAscending = !sortAscending;+ }+ else+ {+ sortColumn = clickedColumn;+ sortAscending = true;+ }+ }++ /// <summary>+ /// Clears the selection of the two file lists other than <paramref name="active"/>. Sets+ /// <c>_clearingFileListSelection</c> while doing so, so that their+ /// <c>SelectedIndexChanged</c> handlers ignore the change and do not clear the preview.+ /// </summary>+ private void ClearOtherFileListSelections(ListView active)+ {+ this._clearingFileListSelection = true;+ try+ {+ if (active != this.lstScenes)+ {+ this.lstScenes.SelectedItems.Clear();+ }+ if (active != this.lstImages)+ {+ this.lstImages.SelectedItems.Clear();+ }+ if (active != this.lstVideo)+ {+ this.lstVideo.SelectedItems.Clear();+ }+ }+ finally+ {+ this._clearingFileListSelection = false;+ }+ }++ /// <summary>Selecting a scene image makes it the only selection across the three lists and shows it in the preview; ignored while another list is clearing selections.</summary>+ private void lstScenes_SelectedIndexChanged(object sender, EventArgs e)+ {+ if (this._clearingFileListSelection)+ {+ return;+ }+ this.ClearOtherFileListSelections(this.lstScenes);+ this.ShowOutputPreview(this.lstScenes);+ }++ /// <summary>Selecting output frames makes them the only selection across the three lists, previews the first one and updates the copy button; ignored while another list is clearing selections.</summary>+ private void lstImages_SelectedIndexChanged(object sender, EventArgs e)+ {+ if (this._clearingFileListSelection)+ {+ return;+ }+ this.ClearOtherFileListSelections(this.lstImages);+ this.ShowOutputPreview(this.lstImages);+ this.UpdateCopyToClipboardButton();+ }++ /// <summary>+ /// Shows the first selected file of <paramref name="list"/> in the preview as a still image+ /// (an in-memory copy, so the file is not locked). Clears the preview when the file is+ /// missing or cannot be decoded; leaves it untouched when nothing is selected.+ /// </summary>+ private void ShowOutputPreview(ListView list)+ {+ if (list.SelectedItems.Count == 0)+ {+ return;+ }+ string path = list.SelectedItems[0].Tag as string;+ if (string.IsNullOrEmpty(path) || !File.Exists(path))+ {+ this.ClearOutputPreview();+ return;+ }+ try+ {+ this.SetOutputPreviewImage(Form1.LoadImageCopy(path), false);+ }+ catch (Exception)+ {+ this.ClearOutputPreview();+ }+ }++ /// <summary>+ /// Selecting exactly one video makes it the only selection across the three lists and shows+ /// the shell thumbnail for it, requested at the preview box's current size (at least 64x64+ /// pixels). Any other selection count, a missing file or a shell failure clears the preview.+ /// Ignored while another list is clearing selections.+ /// </summary>+ private void lstVideo_SelectedIndexChanged(object sender, EventArgs e)+ {+ if (this._clearingFileListSelection)+ {+ return;+ }+ this.ClearOtherFileListSelections(this.lstVideo);+ if (this.lstVideo.SelectedItems.Count != 1)+ {+ this.ClearOutputPreview();+ return;+ }+ string path = this.lstVideo.SelectedItems[0].Tag as string;+ if (string.IsNullOrEmpty(path) || !File.Exists(path))+ {+ this.ClearOutputPreview();+ return;+ }+ try+ {+ int width = Math.Max(64, this._outputPreviewPic.ClientSize.Width);+ int height = Math.Max(64, this._outputPreviewPic.ClientSize.Height);+ this.SetOutputPreviewImage(Form1.GetShellThumbnail(path, width, height), true);+ }+ catch (Exception)+ {+ this.ClearOutputPreview();+ }+ }++ /// <summary>+ /// Puts <paramref name="image"/> (may be null) into the preview box, disposing the image that+ /// was there before (the preview box owns its image), remembers whether it is a video+ /// thumbnail and updates the "share with editors" button accordingly.+ /// </summary>+ private void SetOutputPreviewImage(Image image, bool isVideo = false)+ {+ Image previous = this._outputPreviewPic.Image;+ this._outputPreviewPic.Image = image;+ if (previous != null)+ {+ previous.Dispose();+ }+ this._outputPreviewIsVideo = isVideo;+ this.UpdateShareWithEditorsButton();+ }++ /// <summary>Removes and disposes the preview image; safe to call before <see cref="InitializeOutputsTab"/> has created the preview box.</summary>+ private void ClearOutputPreview()+ {+ if (this._outputPreviewPic != null)+ {+ this.SetOutputPreviewImage(null, false);+ }+ }++ /// <summary>+ /// Permanently deletes the selected scene image files after confirmation. If the list shows+ /// the open project and one of the files is the scene image it currently uses, the question+ /// says so and the scene is switched to "User defined" after deleting. Files that could not+ /// be deleted are reported together at the end.+ /// </summary>+ private void btnDeleteScene_Click(object sender, EventArgs e)+ {+ if (this.lstScenes.SelectedItems.Count == 0)+ {+ MessageBox.Show(this, "Select a scene image in the list first.", "Delete scene", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ List<string> paths = this.SelectedFilePaths(this.lstScenes);++ bool listShowsOpenProject = this._project != null && string.Equals(this._project.FolderPath, this.SelectedOutputProjectFolder(), StringComparison.OrdinalIgnoreCase);+ string currentImagePath = (listShowsOpenProject && this._scene.UseImage) ? SceneSettings.ToFullPath(this._project.FolderPath, this._scene.ImageFile) : "";+ bool deletesCurrentImage = currentImagePath.Length > 0 && paths.Exists(p => string.Equals(p, currentImagePath, StringComparison.OrdinalIgnoreCase));++ string question = (paths.Count == 1)+ ? "Permanently delete '" + Path.GetFileName(paths[0]) + "'?"+ : "Permanently delete these " + paths.Count.ToString(CultureInfo.InvariantCulture) + " scene images?";+ if (deletesCurrentImage)+ {+ question += "\r\n\r\nThis is the scene image currently used by the open project. Deleting it will switch the scene to \"User defined\" instead.";+ }+ if (MessageBox.Show(this, question, "Delete scene", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)+ {+ return;+ }++ List<string> errors = new List<string>();+ foreach (string path in paths)+ {+ try+ {+ File.Delete(path);+ }+ catch (Exception ex)+ {+ errors.Add(Path.GetFileName(path) + ": " + ex.Message);+ }+ }+ if (deletesCurrentImage)+ {+ this.radUserDefinedScene.Checked = true;+ }+ this.RefreshOutputFileLists();+ this.ShowDeleteErrorsIfAny(errors, "Delete scene");+ }++ /// <summary>+ /// Runs the Scene tab's "load scene image" dialog (which copies an outside image into the+ /// open project's scene_images folder and makes it the scene image), then refreshes the+ /// file lists if the Outputs tab currently shows the open project.+ /// </summary>+ private void btnLoadExternal_Click(object sender, EventArgs e)+ {+ this.btnLOadSceneImage_Click(sender, e);+ if (this._project != null && string.Equals(this._project.FolderPath, this.SelectedOutputProjectFolder(), StringComparison.OrdinalIgnoreCase))+ {+ this.RefreshOutputFileLists();+ }+ }++ /// <summary>Deletes the selected output frames (see <see cref="DeleteSelectedImages"/>).</summary>+ private void btnDeleteImages_Click(object sender, EventArgs e)+ {+ this.DeleteSelectedImages();+ }++ /// <summary>Pressing Delete in the output-frame list deletes the selected frames.</summary>+ private void lstImages_KeyDown(object sender, KeyEventArgs e)+ {+ if (e.KeyCode == Keys.Delete)+ {+ e.Handled = true;+ this.DeleteSelectedImages();+ }+ }++ /// <summary>Permanently deletes the selected output frame files after confirmation; files that could not be deleted are reported together at the end.</summary>+ private void DeleteSelectedImages()+ {+ if (this.lstImages.SelectedItems.Count == 0)+ {+ MessageBox.Show(this, "Select one or more images in the list first.", "Delete images", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ int count = this.lstImages.SelectedItems.Count;+ string question = (count == 1)+ ? "Permanently delete '" + this.lstImages.SelectedItems[0].Text + "'?"+ : "Permanently delete these " + count.ToString(CultureInfo.InvariantCulture) + " images?";+ if (MessageBox.Show(this, question, "Delete images", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)+ {+ return;+ }+ List<string> errors = new List<string>();+ foreach (ListViewItem item in this.lstImages.SelectedItems)+ {+ string path = (string)item.Tag;+ try+ {+ File.Delete(path);+ }+ catch (Exception ex)+ {+ errors.Add(item.Text + ": " + ex.Message);+ }+ }+ this.RefreshOutputFileLists();+ this.ShowDeleteErrorsIfAny(errors, "Delete images");+ }++ /// <summary>Copies the single selected output frame to the clipboard as a bitmap (the clipboard takes its own copy, so the loaded bitmap is disposed immediately).</summary>+ private void btnCopyToClipboard_Click(object sender, EventArgs e)+ {+ if (this.lstImages.SelectedItems.Count != 1)+ {+ return;+ }+ string path = this.lstImages.SelectedItems[0].Tag as string;+ if (string.IsNullOrEmpty(path) || !File.Exists(path))+ {+ return;+ }+ try+ {+ using (Bitmap bitmap = Form1.LoadImageCopy(path))+ {+ Clipboard.SetImage(bitmap);+ }+ this.ToolStripStatusLabel1.Text = "Copied '" + Path.GetFileName(path) + "' to the clipboard.";+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The image could not be copied to the clipboard:\r\n\r\n" + ex.Message, "Copy to clipboard", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ }+ }++ /// <summary>Enables "Copy to clipboard" only when exactly one output frame is selected.</summary>+ private void UpdateCopyToClipboardButton()+ {+ this.btnCopyToClipboard.Enabled = this.lstImages.SelectedItems.Count == 1;+ }++ /// <summary>Opens the selected project's output_frames folder in Explorer (icon view; the folder is created if missing).</summary>+ private void btnOpenImageFolder2_Click(object sender, EventArgs e)+ {+ string folder = this.SelectedOutputProjectFolder();+ if (folder.Length == 0)+ {+ MessageBox.Show(this, "Select a project in the list first.", "Open image folder", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ try+ {+ this.OpenFolderInExplorer(Path.Combine(folder, ProjectStore.OutputFramesFolderName), 1);+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The image folder could not be opened:\r\n\r\n" + ex.Message, "Open image folder", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ }+ }++ /// <summary>Deletes the selected videos (see <see cref="DeleteSelectedVideos"/>).</summary>+ private void btnDeleteVideos_Click(object sender, EventArgs e)+ {+ this.DeleteSelectedVideos();+ }++ /// <summary>Pressing Delete in the video list deletes the selected videos.</summary>+ private void lstVideo_KeyDown(object sender, KeyEventArgs e)+ {+ if (e.KeyCode == Keys.Delete)+ {+ e.Handled = true;+ this.DeleteSelectedVideos();+ }+ }++ /// <summary>Permanently deletes the selected video files after confirmation; files that could not be deleted are reported together at the end.</summary>+ private void DeleteSelectedVideos()+ {+ if (this.lstVideo.SelectedItems.Count == 0)+ {+ MessageBox.Show(this, "Select one or more videos in the list first.", "Delete videos", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ int count = this.lstVideo.SelectedItems.Count;+ string question = (count == 1)+ ? "Permanently delete '" + this.lstVideo.SelectedItems[0].Text + "'?"+ : "Permanently delete these " + count.ToString(CultureInfo.InvariantCulture) + " videos?";+ if (MessageBox.Show(this, question, "Delete videos", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)+ {+ return;+ }+ List<string> errors = new List<string>();+ foreach (ListViewItem item in this.lstVideo.SelectedItems)+ {+ string path = (string)item.Tag;+ try+ {+ File.Delete(path);+ }+ catch (Exception ex)+ {+ errors.Add(item.Text + ": " + ex.Message);+ }+ }+ this.RefreshOutputFileLists();+ this.ShowDeleteErrorsIfAny(errors, "Delete videos");+ }++ /// <summary>Opens the first selected video in the system's default player.</summary>+ private void btnViewVIdeoInPlayer2_Click(object sender, EventArgs e)+ {+ if (this.lstVideo.SelectedItems.Count == 0)+ {+ MessageBox.Show(this, "Select a video in the list first.", "View in player", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ this.OpenVideo((string)this.lstVideo.SelectedItems[0].Tag);+ }++ /// <summary>Double-clicking a video opens it in the system's default player.</summary>+ private void lstVideo_DoubleClick(object sender, EventArgs e)+ {+ if (this.lstVideo.SelectedItems.Count > 0)+ {+ this.OpenVideo((string)this.lstVideo.SelectedItems[0].Tag);+ }+ }++ /// <summary>+ /// Renames the single selected video file inside its folder after prompting for a new file+ /// name; an empty or unchanged name is a no-op, invalid characters and an existing target+ /// are refused. The extension is not enforced, so a file renamed to a non-video extension+ /// disappears from the list.+ /// </summary>+ private void btnRenameVideo_Click(object sender, EventArgs e)+ {+ if (this.lstVideo.SelectedItems.Count != 1)+ {+ MessageBox.Show(this, "Select a single video in the list first.", "Rename video", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ string oldPath = (string)this.lstVideo.SelectedItems[0].Tag;+ string fileName = Path.GetFileName(oldPath);+ string newName = fileName;+ if (!this.PromptForText("Rename video", "New name for '" + fileName + "':", fileName, ref newName))+ {+ return;+ }+ newName = newName.Trim();+ if (newName.Length == 0 || newName == fileName)+ {+ return;+ }+ if (newName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)+ {+ MessageBox.Show(this, "That name contains characters that are not allowed in a file name.", "Rename video", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ return;+ }+ string newPath = Path.Combine(Path.GetDirectoryName(oldPath), newName);+ if (File.Exists(newPath))+ {+ MessageBox.Show(this, "A file named '" + newName + "' already exists.", "Rename video", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ return;+ }+ try+ {+ File.Move(oldPath, newPath);+ this.RefreshOutputFileLists();+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The video could not be renamed:\r\n\r\n" + ex.Message, "Rename video", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ }+ }++ /// <summary>Opens the selected project's output_video folder in Explorer (details view; the folder is created if missing).</summary>+ private void btnOpenVIdeoFolder2_Click(object sender, EventArgs e)+ {+ string folder = this.SelectedOutputProjectFolder();+ if (folder.Length == 0)+ {+ MessageBox.Show(this, "Select a project in the list first.", "Open video folder", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ try+ {+ this.OpenFolderInExplorer(Path.Combine(folder, ProjectStore.OutputVideoFolderName), 4);+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The video folder could not be opened:\r\n\r\n" + ex.Message, "Open video folder", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ }+ }++ /// <summary>Copies the previewed still image into the Sources and Probes tab preview boxes.</summary>+ private void btnShareWithEditors_Click(object sender, EventArgs e)+ {+ this.CopyPreviewToTabs(this._outputPreviewPic);+ }++ /// <summary>Enables "Share with editors" only while the preview shows a still image (not a video thumbnail).</summary>+ private void UpdateShareWithEditorsButton()+ {+ this.btnShareWithEditors.Enabled = !this._outputPreviewIsVideo && this._outputPreviewPic != null && this._outputPreviewPic.Image != null;+ }++ /// <summary>Shows one message box listing <paramref name="errors"/> (one per line) under <paramref name="title"/>; does nothing for an empty list.</summary>+ private void ShowDeleteErrorsIfAny(List<string> errors, string title)+ {+ if (errors.Count > 0)+ {+ MessageBox.Show(this, "Some files could not be deleted:\r\n\r\n" + string.Join("\r\n", errors), title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ }+ }++ /// <summary>+ /// shell32: creates the shell item for a file system path and returns the interface+ /// identified by <paramref name="riid"/>. <c>PreserveSig = false</c> turns a failing HRESULT+ /// into a <see cref="COMException"/>.+ /// </summary>+ [DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]+ private static extern void SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string path, IntPtr pbc, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppv);++ /// <summary>gdi32: frees a GDI object; used for the HBITMAP the shell hands back in <see cref="GetShellThumbnail"/>.</summary>+ [DllImport("gdi32.dll")]+ private static extern bool DeleteObject(IntPtr hObject);++ /// <summary>+ /// Asks the Windows shell (<c>IShellItemImageFactory</c>) for the thumbnail it would show for+ /// a file, requesting <paramref name="width"/> x <paramref name="height"/> pixels but+ /// accepting a larger one. Used for video previews. The returned bitmap is an independent+ /// managed copy; the shell's HBITMAP and the COM object are released before returning.+ /// </summary>+ /// <returns>The thumbnail, or null when the shell does not provide one for the file.</returns>+ /// <exception cref="COMException">The shell could not create the item or extract the thumbnail.</exception>+ private static Bitmap GetShellThumbnail(string filePath, int width, int height)+ {+ Guid factoryGuid = typeof(Form1.IShellItemImageFactory).GUID;+ object shellItem;+ Form1.SHCreateItemFromParsingName(filePath, IntPtr.Zero, ref factoryGuid, out shellItem);+ Form1.IShellItemImageFactory factory = shellItem as Form1.IShellItemImageFactory;+ if (factory == null)+ {+ return null;+ }+ IntPtr bitmapHandle = IntPtr.Zero;+ try+ {+ factory.GetImage(new Form1.NativeSize+ {+ cx = width,+ cy = height+ }, Form1.ThumbnailOptions.BiggerSizeOk | Form1.ThumbnailOptions.ThumbnailOnly, out bitmapHandle);+ if (bitmapHandle == IntPtr.Zero)+ {+ return null;+ }+ using (Bitmap wrapper = Image.FromHbitmap(bitmapHandle))+ {+ return new Bitmap(wrapper);+ }+ }+ finally+ {+ if (bitmapHandle != IntPtr.Zero)+ {+ Form1.DeleteObject(bitmapHandle);+ }+ Marshal.ReleaseComObject(factory);+ }+ }+ }+}diff --git a/Wave_Dude_2D/Form1.Probes.cs b/Wave_Dude_2D/Form1.Probes.csnew file mode 100644index 0000000..fec1002--- /dev/null+++ b/Wave_Dude_2D/Form1.Probes.cs@@ -0,0 +1,1096 @@+using System;+using System.Collections.Generic;+using System.Drawing;+using System.Drawing.Drawing2D;+using System.Globalization;+using System.Windows.Forms;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Probes tab: editing the two <see cref="ProbeSettings"/> in <c>_probes</c> through the+ /// per-probe control sets in <c>_probeUi</c>, picking positions with the mouse on the probe+ /// picture, and overlaying probe markers and live graphs on the preview pictures.+ /// Everything here runs on the UI thread; <see cref="ShowProbeSamples"/> is the only entry point+ /// fed by the simulation worker, and it arrives already marshalled through <c>PostToUi</c>.+ /// </summary>+ /// <remarks>+ /// Two coordinate systems are used throughout. Canvas pixels are 0-based cells of the+ /// simulation grid (size from <c>EffectiveCanvas()</c> while editing, <c>_runCanvas</c> for the+ /// current/last run); picture-box pixels are client coordinates of a <see cref="PictureBox"/>+ /// in Zoom mode, where the image is scaled uniformly and centred. <see cref="ZoomedImageRectangle"/>+ /// gives the image's rectangle in picture-box pixels; <see cref="TryPictureToCanvas"/> and+ /// <see cref="ToScreen"/> convert between the two.+ /// </remarks>+ public partial class Form1+ {+ /// <summary>The control set for probe <paramref name="index"/>, or null before <see cref="InitializeProbeControls"/> has run (designer-wired handlers can fire that early).</summary>+ private Form1.ProbeControlSet ProbeUi(int index)+ {+ return this._probeUi == null ? null : this._probeUi[index];+ }++ /// <summary>Creates the default probe list: <see cref="ProbeCount"/> fresh, inactive probes.</summary>+ private static List<ProbeSettings> NewProbeList()+ {+ List<ProbeSettings> probes = new List<ProbeSettings>();+ for (int i = 0; i < Form1.ProbeCount; i++)+ {+ probes.Add(new ProbeSettings());+ }+ return probes;+ }++ /// <summary>Pads or truncates <c>_probes</c> to exactly <see cref="ProbeCount"/> entries after loading a project (the config may hold any count).</summary>+ private void NormalizeProbeCount()+ {+ while (this._probes.Count < Form1.ProbeCount)+ {+ this._probes.Add(new ProbeSettings());+ }+ while (this._probes.Count > Form1.ProbeCount)+ {+ this._probes.RemoveAt(this._probes.Count - 1);+ }+ }++ /// <summary>+ /// One-time setup from the constructor: binds the designer controls of both probe panels into+ /// <c>_probeUi</c>, fills the fixed combo boxes (item order mirrors the enum order because the+ /// selected index is cast straight to the enum), sets spinner ranges, hooks the paint and mouse+ /// handlers of the probe and preview pictures (which must already exist) and shows the current probes.+ /// </summary>+ private void InitializeProbeControls()+ {+ this._probeUi = new Form1.ProbeControlSet[]+ {+ new Form1.ProbeControlSet(0, "Probe 1", this.chkProbeOn1, this.cmbPlaceOn, this.cmbMeasurement, this.cmbProbeType, this.cmbBoxSize, this.numAPosX, this.numAPosY, this.numBPosX, this.numBPosY, this.butPicPositions, this.radRunningScale, this.radFullScale, this.chkAutoScaleX, this.chkAutoScaleY, this.txtMinScaleY, this.txtMaxScaleY, this.chkStartAfterStep, this.txtStartAfterStep, this.numRunningWindow, new Control[] { this.numBPosX, this.numBPosY, this.Label14, this.Label15, this.Label16 }),+ new Form1.ProbeControlSet(1, "Probe 2", this.chkProbeOn2, this.cmbPlaceOn2, this.cmbMeasurement2, this.cmbProbeType2, this.cmbBoxSize2, this.numAPosX2, this.numAPosY2, this.numBPosX2, this.numBPosY2, this.butPicPositions2, this.radRunningScale2, this.radFullScale2, this.chkAutoScaleX2, this.chkAutoScaleY2, this.txtMinScaleY2, this.txtMaxScaleY2, this.chkStartAfterStep2, this.txtStartAfterStep2, this.numRunningWindow2, new Control[] { this.numBPosX2, this.numBPosY2, this.Label28, this.Label27, this.Label25 })+ };+ foreach (Form1.ProbeControlSet ui in this._probeUi)+ {+ foreach (ComboBox combo in new ComboBox[] { ui.CmbPlaceOn, ui.CmbMeasurement, ui.CmbProbeType, ui.CmbBoxSize })+ {+ combo.DropDownStyle = ComboBoxStyle.DropDownList;+ }+ ui.CmbPlaceOn.Items.Clear();+ ui.CmbPlaceOn.Items.AddRange(new object[] { "Field", "Intensity" });+ ui.CmbProbeType.Items.Clear();+ ui.CmbProbeType.Items.AddRange(new object[] { "Point (A)", "Line (A-B)" });+ ui.CmbBoxSize.Items.Clear();+ ui.CmbBoxSize.Items.AddRange(new object[] { "Tiny (200 x 100)", "Small (300 x 150)", "Medium (400 x 200)", "Large (500 x 250)", "Extra Large (700 x 350)" });+ foreach (NumericUpDown position in new NumericUpDown[] { ui.NumAPosX, ui.NumAPosY, ui.NumBPosX, ui.NumBPosY })+ {+ position.DecimalPlaces = 0;+ position.Minimum = 0m;+ // Placeholder until SetProbeRanges knows the canvas size.+ position.Maximum = 16383m;+ }+ ui.NumRunningWindow.DecimalPlaces = 0;+ ui.NumRunningWindow.Minimum = 10m;+ ui.NumRunningWindow.Maximum = ProbeSettings.MaxRunningWindow;+ }+ this._picField.Paint += this.PreviewPicture_Paint;+ this._picIntensity.Paint += this.PreviewPicture_Paint;+ this._picProbe.Paint += this.ProbePicture_Paint;+ this._picProbe.MouseClick += this.ProbePicture_MouseClick;+ this._picProbe.MouseMove += this.ProbePicture_MouseMove;+ this._picProbe.MouseLeave += this.ProbePicture_MouseLeave;+ this.ShowProbesInControls();+ }++ /// <summary>Cancels any position pick in progress and pushes every probe in <c>_probes</c> into its controls.</summary>+ private void ShowProbesInControls()+ {+ this.EndPick();+ foreach (Form1.ProbeControlSet ui in this._probeUi)+ {+ this.ShowProbeInControls(ui);+ }+ }++ /// <summary>+ /// Normalizes the probe and writes all of its values into the controls of <paramref name="ui"/>.+ /// <c>_loadingProbe</c> is set meanwhile so the change handlers do not write back or mark the+ /// project dirty. Positions are clamped to the spinner ranges; the Y range is shown with "G6"+ /// in the invariant culture. Ends by refreshing the enabled states and repainting the pictures.+ /// </summary>+ private void ShowProbeInControls(Form1.ProbeControlSet ui)+ {+ ProbeSettings probe = this._probes[ui.Index];+ probe.Normalize();+ this._loadingProbe = true;+ try+ {+ this.SetProbeRanges(ui);+ ui.ChkOn.Checked = probe.Active;+ ui.CmbPlaceOn.SelectedIndex = (int)probe.PlaceOn;+ this.FillMeasurementCombo(ui, probe);+ ui.CmbProbeType.SelectedIndex = (int)probe.Kind;+ ui.CmbBoxSize.SelectedIndex = (int)probe.BoxSize;+ ui.NumAPosX.Value = Form1.ClampToRange(ui.NumAPosX, probe.PosAX);+ ui.NumAPosY.Value = Form1.ClampToRange(ui.NumAPosY, probe.PosAY);+ ui.NumBPosX.Value = Form1.ClampToRange(ui.NumBPosX, probe.PosBX);+ ui.NumBPosY.Value = Form1.ClampToRange(ui.NumBPosY, probe.PosBY);+ ui.RadRunning.Checked = probe.ScaleMode == ProbeScaleMode.Running;+ ui.RadFull.Checked = probe.ScaleMode == ProbeScaleMode.Full;+ ui.ChkAutoX.Checked = probe.AutoScaleX;+ ui.ChkAutoY.Checked = probe.AutoScaleY;+ ui.TxtMinY.Text = probe.YMin.ToString("G6", CultureInfo.InvariantCulture);+ ui.TxtMaxY.Text = probe.YMax.ToString("G6", CultureInfo.InvariantCulture);+ ui.ChkStartAfter.Checked = probe.UseStartAfterStep;+ ui.TxtStartAfter.Text = probe.StartAfterStep.ToString(CultureInfo.InvariantCulture);+ ui.NumRunningWindow.Value = Form1.ClampToRange(ui.NumRunningWindow, probe.RunningWindow);+ }+ finally+ {+ this._loadingProbe = false;+ }+ this.UpdateProbeControlState(ui);+ this.InvalidateProbePictures();+ }++ /// <summary>+ /// Rebuilds the measurement combo for the probe's <see cref="ProbeSettings.PlaceOn"/>: the field+ /// offers only "Amplitude", the intensity output "Intensity" and "Integrated intensity".+ /// Selects the entry matching <paramref name="p"/>'s measurement (index 1 = integrated).+ /// </summary>+ private void FillMeasurementCombo(Form1.ProbeControlSet ui, ProbeSettings p)+ {+ ui.CmbMeasurement.Items.Clear();+ if (p.PlaceOn == ProbePlaceOn.Field)+ {+ ui.CmbMeasurement.Items.Add("Amplitude");+ ui.CmbMeasurement.SelectedIndex = 0;+ }+ else+ {+ ui.CmbMeasurement.Items.Add("Intensity");+ ui.CmbMeasurement.Items.Add("Integrated intensity");+ ui.CmbMeasurement.SelectedIndex = ((p.Measurement == ProbeMeasurement.IntegratedIntensity) ? 1 : 0);+ }+ }++ /// <summary>Maps a measurement combo index back to the enum for the given surface (inverse of <see cref="FillMeasurementCombo"/>); the field always yields amplitude.</summary>+ private static ProbeMeasurement MeasurementFromIndex(ProbePlaceOn placeOn, int index)+ {+ if (placeOn == ProbePlaceOn.Field)+ {+ return ProbeMeasurement.Amplitude;+ }+ return index == 1 ? ProbeMeasurement.IntegratedIntensity : ProbeMeasurement.Intensity;+ }++ /// <summary>+ /// Enables/disables controls to match the probe: B position only for line probes; scale mode,+ /// auto X and running window only for point probes (a profile has a fixed X axis); the Y range+ /// boxes only when auto Y is off; the start-after step box only when its check box is on.+ /// </summary>+ private void UpdateProbeControlState(Form1.ProbeControlSet ui)+ {+ bool isLine = this._probes[ui.Index].Kind == ProbeKind.Line;+ foreach (Control control in ui.BOnlyControls)+ {+ control.Enabled = isLine;+ }+ foreach (Control control in new Control[] { ui.RadRunning, ui.RadFull, ui.ChkAutoX, ui.NumRunningWindow })+ {+ control.Enabled = !isLine;+ }+ ui.TxtMinY.Enabled = !ui.ChkAutoY.Checked;+ ui.TxtMaxY.Enabled = !ui.ChkAutoY.Checked;+ ui.TxtStartAfter.Enabled = ui.ChkStartAfter.Checked;+ }++ /// <summary>Applies <see cref="SetProbeRanges(Form1.ProbeControlSet)"/> to both probes; no-op before the controls are initialized.</summary>+ private void SetProbeRanges()+ {+ if (this._probeUi == null)+ {+ return;+ }+ foreach (Form1.ProbeControlSet ui in this._probeUi)+ {+ this.SetProbeRanges(ui);+ }+ }++ /// <summary>+ /// Limits the position spinners to the current canvas size (width-1 / height-1 in canvas pixels,+ /// or 16383 when the size is unknown). Lowering a maximum can clamp the value and fire+ /// ValueChanged, so <c>_loadingProbe</c> is raised meanwhile (and restored to its previous state,+ /// since this is also called from inside <see cref="ShowProbeInControls"/>).+ /// </summary>+ private void SetProbeRanges(Form1.ProbeControlSet ui)+ {+ Size canvas = this.EffectiveCanvas();+ decimal maxX = new decimal((canvas.Width > 0) ? (canvas.Width - 1) : 16383);+ decimal maxY = new decimal((canvas.Height > 0) ? (canvas.Height - 1) : 16383);+ bool wasLoading = this._loadingProbe;+ this._loadingProbe = true;+ try+ {+ ui.NumAPosX.Maximum = maxX;+ ui.NumBPosX.Maximum = maxX;+ ui.NumAPosY.Maximum = maxY;+ ui.NumBPosY.Maximum = maxY;+ }+ finally+ {+ this._loadingProbe = wasLoading;+ }+ }++ /// <summary>+ /// Copies every control of <paramref name="ui"/> into its <see cref="ProbeSettings"/>. Spinners are+ /// validated first so typed-but-uncommitted text counts. The Y range is parsed (invariant culture)+ /// only when auto Y is off, and unparsable text leaves the old value; same for the start-after step.+ /// Ends with <see cref="ProbeSettings.Normalize"/>. Does not mark the project dirty or repaint.+ /// </summary>+ private void ReadProbeControls(Form1.ProbeControlSet ui)+ {+ ProbeSettings probe = this._probes[ui.Index];+ probe.Active = ui.ChkOn.Checked;+ if (ui.CmbPlaceOn.SelectedIndex >= 0)+ {+ probe.PlaceOn = (ProbePlaceOn)ui.CmbPlaceOn.SelectedIndex;+ }+ if (ui.CmbMeasurement.SelectedIndex >= 0)+ {+ probe.Measurement = Form1.MeasurementFromIndex(probe.PlaceOn, ui.CmbMeasurement.SelectedIndex);+ }+ if (ui.CmbProbeType.SelectedIndex >= 0)+ {+ probe.Kind = (ProbeKind)ui.CmbProbeType.SelectedIndex;+ }+ if (ui.CmbBoxSize.SelectedIndex >= 0)+ {+ probe.BoxSize = (ProbeBoxSize)ui.CmbBoxSize.SelectedIndex;+ }+ ui.NumAPosX.Validate();+ ui.NumAPosY.Validate();+ ui.NumBPosX.Validate();+ ui.NumBPosY.Validate();+ probe.PosAX = Convert.ToInt32(ui.NumAPosX.Value);+ probe.PosAY = Convert.ToInt32(ui.NumAPosY.Value);+ probe.PosBX = Convert.ToInt32(ui.NumBPosX.Value);+ probe.PosBY = Convert.ToInt32(ui.NumBPosY.Value);+ probe.ScaleMode = (ui.RadFull.Checked ? ProbeScaleMode.Full : ProbeScaleMode.Running);+ probe.AutoScaleX = ui.ChkAutoX.Checked;+ probe.AutoScaleY = ui.ChkAutoY.Checked;+ if (!ui.ChkAutoY.Checked)+ {+ double yMin;+ if (double.TryParse(ui.TxtMinY.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out yMin))+ {+ probe.YMin = yMin;+ }+ double yMax;+ if (double.TryParse(ui.TxtMaxY.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out yMax))+ {+ probe.YMax = yMax;+ }+ }+ probe.UseStartAfterStep = ui.ChkStartAfter.Checked;+ int startAfter;+ if (int.TryParse(ui.TxtStartAfter.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out startAfter))+ {+ probe.StartAfterStep = startAfter;+ }+ ui.NumRunningWindow.Validate();+ probe.RunningWindow = Convert.ToInt32(ui.NumRunningWindow.Value);+ probe.Normalize();+ }++ /// <summary>Probe 1: a combo box (place on / measurement / type / box size) changed; see <see cref="HandleProbeComboChanged"/>.</summary>+ private void ProbeCombo_SelectedIndexChanged(object sender, EventArgs e)+ {+ this.HandleProbeComboChanged(this.ProbeUi(0), sender);+ }++ /// <summary>Probe 1: an A/B position spinner changed; the new canvas position is stored.</summary>+ private void ProbePosition_ValueChanged(object sender, EventArgs e)+ {+ this.HandleProbePositionChanged(this.ProbeUi(0));+ }++ /// <summary>Probe 1: the "on" check box toggled the probe's active flag.</summary>+ private void ProbeOn_CheckedChanged(object sender, EventArgs e)+ {+ this.HandleProbeOnChanged(this.ProbeUi(0));+ }++ /// <summary>Probe 1: Enter in a Y-range or start-after text box applies all controls.</summary>+ private void ProbeTextBox_KeyDown(object sender, KeyEventArgs e)+ {+ this.HandleProbeTextBoxKeyDown(this.ProbeUi(0), e);+ }++ /// <summary>Probe 1: running/full scale radio button changed.</summary>+ private void ProbeScaleMode_CheckedChanged(object sender, EventArgs e)+ {+ this.HandleProbeScaleModeChanged(this.ProbeUi(0));+ }++ /// <summary>Probe 1: auto X / auto Y check box changed.</summary>+ private void ProbeAutoScale_CheckedChanged(object sender, EventArgs e)+ {+ this.HandleProbeAutoScaleChanged(this.ProbeUi(0));+ }++ /// <summary>Probe 1: a Y-range text box lost focus; all controls are applied.</summary>+ private void ProbeYRange_Validated(object sender, EventArgs e)+ {+ this.HandleProbeControlApplied(this.ProbeUi(0));+ }++ /// <summary>Probe 1: the "start after step" check box toggled.</summary>+ private void ProbeStartAfterStep_CheckedChanged(object sender, EventArgs e)+ {+ this.HandleProbeStartAfterStepChanged(this.ProbeUi(0));+ }++ /// <summary>Probe 1: the start-after step text box lost focus; all controls are applied.</summary>+ private void ProbeStartAfterStep_Validated(object sender, EventArgs e)+ {+ this.HandleProbeControlApplied(this.ProbeUi(0));+ }++ /// <summary>Probe 1: the running window spinner changed; all controls are applied.</summary>+ private void ProbeRunningWindow_ValueChanged(object sender, EventArgs e)+ {+ this.HandleProbeControlApplied(this.ProbeUi(0));+ }++ /// <summary>Probe 2: a combo box changed; see <see cref="HandleProbeComboChanged"/>.</summary>+ private void ProbeCombo2_SelectedIndexChanged(object sender, EventArgs e)+ {+ this.HandleProbeComboChanged(this.ProbeUi(1), sender);+ }++ /// <summary>Probe 2: an A/B position spinner changed; the new canvas position is stored.</summary>+ private void ProbePosition2_ValueChanged(object sender, EventArgs e)+ {+ this.HandleProbePositionChanged(this.ProbeUi(1));+ }++ /// <summary>Probe 2: the "on" check box toggled the probe's active flag.</summary>+ private void ProbeOn2_CheckedChanged(object sender, EventArgs e)+ {+ this.HandleProbeOnChanged(this.ProbeUi(1));+ }++ /// <summary>Probe 2: Enter in a Y-range or start-after text box applies all controls.</summary>+ private void ProbeTextBox2_KeyDown(object sender, KeyEventArgs e)+ {+ this.HandleProbeTextBoxKeyDown(this.ProbeUi(1), e);+ }++ /// <summary>Probe 2: running/full scale radio button changed.</summary>+ private void ProbeScaleMode2_CheckedChanged(object sender, EventArgs e)+ {+ this.HandleProbeScaleModeChanged(this.ProbeUi(1));+ }++ /// <summary>Probe 2: auto X / auto Y check box changed.</summary>+ private void ProbeAutoScale2_CheckedChanged(object sender, EventArgs e)+ {+ this.HandleProbeAutoScaleChanged(this.ProbeUi(1));+ }++ /// <summary>Probe 2: a Y-range text box lost focus; all controls are applied.</summary>+ private void ProbeYRange2_Validated(object sender, EventArgs e)+ {+ this.HandleProbeControlApplied(this.ProbeUi(1));+ }++ /// <summary>Probe 2: the "start after step" check box toggled.</summary>+ private void ProbeStartAfterStep2_CheckedChanged(object sender, EventArgs e)+ {+ this.HandleProbeStartAfterStepChanged(this.ProbeUi(1));+ }++ /// <summary>Probe 2: the start-after step text box lost focus; all controls are applied.</summary>+ private void ProbeStartAfterStep2_Validated(object sender, EventArgs e)+ {+ this.HandleProbeControlApplied(this.ProbeUi(1));+ }++ /// <summary>Probe 2: the running window spinner changed; all controls are applied.</summary>+ private void ProbeRunningWindow2_ValueChanged(object sender, EventArgs e)+ {+ this.HandleProbeControlApplied(this.ProbeUi(1));+ }++ /// <summary>+ /// Shared handler for the four combo boxes of a probe. Ignored while loading. Changing the probe+ /// type cancels a pick in progress for that probe; changing "place on" first updates the probe and+ /// refills the measurement combo (under the loading guard, so the refill does not recurse). Then+ /// all controls are read back, enabled states refreshed, and the project marked dirty.+ /// </summary>+ /// <param name="ui">Control set of the probe whose combo box changed; null before <see cref="InitializeProbeControls"/> has run.</param>+ /// <param name="sender">The combo box that raised the event.</param>+ private void HandleProbeComboChanged(Form1.ProbeControlSet ui, object sender)+ {+ if (ui == null || this._loadingProbe)+ {+ return;+ }+ if (sender == ui.CmbProbeType && this._pickStep != 0 && this._pickIndex == ui.Index)+ {+ this.EndPick();+ }+ if (sender == ui.CmbPlaceOn && ui.CmbPlaceOn.SelectedIndex >= 0)+ {+ ProbeSettings probe = this._probes[ui.Index];+ probe.PlaceOn = (ProbePlaceOn)ui.CmbPlaceOn.SelectedIndex;+ probe.Normalize();+ this._loadingProbe = true;+ try+ {+ this.FillMeasurementCombo(ui, probe);+ }+ finally+ {+ this._loadingProbe = false;+ }+ }+ this.ReadProbeControls(ui);+ this.UpdateProbeControlState(ui);+ this.ProbeSettingsChanged();+ }++ /// <summary>Stores the four position spinners (canvas pixels) into the probe and marks the project dirty; ignored while loading.</summary>+ private void HandleProbePositionChanged(Form1.ProbeControlSet ui)+ {+ if (ui == null || this._loadingProbe)+ {+ return;+ }+ ProbeSettings probe = this._probes[ui.Index];+ probe.PosAX = Convert.ToInt32(ui.NumAPosX.Value);+ probe.PosAY = Convert.ToInt32(ui.NumAPosY.Value);+ probe.PosBX = Convert.ToInt32(ui.NumBPosX.Value);+ probe.PosBY = Convert.ToInt32(ui.NumBPosY.Value);+ this.ProbeSettingsChanged();+ }++ /// <summary>Stores the "on" check box into <see cref="ProbeSettings.Active"/> and marks the project dirty; ignored while loading.</summary>+ private void HandleProbeOnChanged(Form1.ProbeControlSet ui)+ {+ if (ui == null || this._loadingProbe)+ {+ return;+ }+ this._probes[ui.Index].Active = ui.ChkOn.Checked;+ this.ProbeSettingsChanged();+ }++ /// <summary>On Enter (and only then): swallows the key so the text box does not beep, then applies all controls of the probe; ignored while loading.</summary>+ private void HandleProbeTextBoxKeyDown(Form1.ProbeControlSet ui, KeyEventArgs e)+ {+ if (e.KeyCode != Keys.Return)+ {+ return;+ }+ e.SuppressKeyPress = true;+ e.Handled = true;+ if (ui == null || this._loadingProbe)+ {+ return;+ }+ this.ReadProbeControls(ui);+ this.ProbeSettingsChanged();+ }++ /// <summary>Stores the scale mode radio buttons into the probe and marks the project dirty; ignored while loading.</summary>+ private void HandleProbeScaleModeChanged(Form1.ProbeControlSet ui)+ {+ if (ui == null || this._loadingProbe)+ {+ return;+ }+ this._probes[ui.Index].ScaleMode = (ui.RadFull.Checked ? ProbeScaleMode.Full : ProbeScaleMode.Running);+ this.ProbeSettingsChanged();+ }++ /// <summary>+ /// Stores the auto X / auto Y check boxes. When auto Y has just been switched off, the Y range the+ /// running graph currently shows is frozen into the probe (<see cref="FreezeValueRange"/>) and+ /// written into the min/max text boxes, so the user starts from the displayed range rather than+ /// the stale stored one. Ignored while loading.+ /// </summary>+ private void HandleProbeAutoScaleChanged(Form1.ProbeControlSet ui)+ {+ if (ui == null || this._loadingProbe)+ {+ return;+ }+ ProbeSettings probe = this._probes[ui.Index];+ bool wasAutoY = probe.AutoScaleY;+ probe.AutoScaleX = ui.ChkAutoX.Checked;+ probe.AutoScaleY = ui.ChkAutoY.Checked;+ if (wasAutoY && !probe.AutoScaleY)+ {+ this.FreezeValueRange(ui, probe);+ this._loadingProbe = true;+ try+ {+ ui.TxtMinY.Text = probe.YMin.ToString("G6", CultureInfo.InvariantCulture);+ ui.TxtMaxY.Text = probe.YMax.ToString("G6", CultureInfo.InvariantCulture);+ }+ finally+ {+ this._loadingProbe = false;+ }+ }+ this.UpdateProbeControlState(ui);+ this.ProbeSettingsChanged();+ }++ /// <summary>Generic "commit" used by Validated and ValueChanged events: reads all controls back and marks the project dirty; ignored while loading.</summary>+ private void HandleProbeControlApplied(Form1.ProbeControlSet ui)+ {+ if (ui == null || this._loadingProbe)+ {+ return;+ }+ this.ReadProbeControls(ui);+ this.ProbeSettingsChanged();+ }++ /// <summary>Stores the "start after step" check box, enables/disables its text box and marks the project dirty; ignored while loading.</summary>+ private void HandleProbeStartAfterStepChanged(Form1.ProbeControlSet ui)+ {+ if (ui == null || this._loadingProbe)+ {+ return;+ }+ this._probes[ui.Index].UseStartAfterStep = ui.ChkStartAfter.Checked;+ this.UpdateProbeControlState(ui);+ this.ProbeSettingsChanged();+ }++ /// <summary>+ /// When auto Y scaling is switched off, keeps the Y range the running graph currently shows:+ /// recomputes the auto-scaled range from the trace of the current/last run (via+ /// <see cref="ProbeGraphPainter.ComputeRanges"/> on an auto-Y clone) and stores it in+ /// <paramref name="p"/>. Does nothing when there is no run trace for this probe, when the run+ /// used a different probe kind, when a line probe has no profile yet (or is still gated by+ /// its start-after step), when a point probe has no samples, or when the computed range is empty.+ /// </summary>+ private void FreezeValueRange(Form1.ProbeControlSet ui, ProbeSettings p)+ {+ int index = ui.Index;+ if (this._probeTraces.Count <= index || this._runProbes == null || this._runProbes.Count <= index)+ {+ return;+ }+ if (this._runProbes[index].Kind != p.Kind)+ {+ return;+ }+ ProbeTrace trace = this._probeTraces[index];+ if (p.Kind == ProbeKind.Line)+ {+ if (p.UseStartAfterStep && trace.StepsSampled < p.StartAfterStep)+ {+ return;+ }+ if (trace.Profile == null)+ {+ return;+ }+ }+ else if (trace.Series.Count == 0)+ {+ return;+ }+ ProbeSettings autoScaled = p.Clone();+ autoScaled.AutoScaleY = true;+ double xMin = 0.0;+ double xMax = 0.0;+ double yMin = 0.0;+ double yMax = 0.0;+ ProbeGraphPainter.ComputeRanges(autoScaled, trace, this._runSteps, ref xMin, ref xMax, ref yMin, ref yMax);+ if (yMax > yMin)+ {+ p.YMin = yMin;+ p.YMax = yMax;+ }+ }++ /// <summary>Marks the project dirty (unless a loading flag is set) and repaints all three probe-related pictures.</summary>+ private void ProbeSettingsChanged()+ {+ this.MarkProjectChanged();+ this.InvalidateProbePictures();+ }++ /// <summary>Invalidates the probe picture and the field/intensity previews so markers and graph boxes are redrawn; safe before the pictures exist.</summary>+ private void InvalidateProbePictures()+ {+ if (this._picProbe != null)+ {+ this._picProbe.Invalidate();+ }+ if (this._picField != null)+ {+ this._picField.Invalidate();+ }+ if (this._picIntensity != null)+ {+ this._picIntensity.Invalidate();+ }+ }++ /// <summary>+ /// Any main tab switch cancels a pick in progress and refreshes the spinner ranges (the canvas+ /// size may have changed on the Configuration tab); switching to the Probes tab additionally+ /// loads the scene image (or a black canvas) into the probe picture if it is still empty.+ /// </summary>+ private void ProbeTabChanged(object sender, EventArgs e)+ {+ this.EndPick();+ this.SetProbeRanges();+ if (this.tabMainFunctions.SelectedTab == this.tabProbeList)+ {+ this.AutoLoadSceneImageIfEmpty(this._picProbe);+ }+ }++ /// <summary>Probe 1 "pick positions" button: starts picking in the probe picture, or cancels it when already picking.</summary>+ private void butPicPositions_Click(object sender, EventArgs e)+ {+ this.StartOrCancelPick(this.ProbeUi(0));+ }++ /// <summary>Probe 2 "pick positions" button: starts picking in the probe picture, or cancels it when already picking.</summary>+ private void butPicPositions2_Click(object sender, EventArgs e)+ {+ this.StartOrCancelPick(this.ProbeUi(1));+ }++ /// <summary>Toggles pick mode for one probe: cancels a pick in progress (for any probe) and, unless that pick was this probe's, starts a new one.</summary>+ private void StartOrCancelPick(Form1.ProbeControlSet ui)+ {+ if (ui == null)+ {+ return;+ }+ bool wasPicking = this._pickStep != 0 && this._pickIndex == ui.Index;+ this.EndPick();+ if (!wasPicking)+ {+ this.StartPick(ui);+ }+ }++ /// <summary>Gives the probe picture a black bitmap of the canvas size so positions can be picked without a scene image; does nothing when the canvas size is unknown. The bitmap is owned by the picture box.</summary>+ private void EnsureProbePicture()+ {+ Size canvas = this.EffectiveCanvas();+ if (canvas.Width <= 0 || canvas.Height <= 0)+ {+ return;+ }+ Bitmap bitmap = new Bitmap(canvas.Width, canvas.Height);+ using (Graphics g = Graphics.FromImage(bitmap))+ {+ g.Clear(Color.Black);+ }+ this._picProbe.Image = bitmap;+ }++ /// <summary>+ /// Enters pick mode for <paramref name="ui"/>'s probe: makes sure the probe picture has an image+ /// (otherwise shows a message and gives up), sets <c>_pickIndex</c>/<c>_pickStep</c> to step 1,+ /// switches to a cross cursor, relabels the pick button "Cancel" and shows the first instruction+ /// in the status bar. Clicks are then handled by <see cref="ProbePicture_MouseClick"/>.+ /// </summary>+ private void StartPick(Form1.ProbeControlSet ui)+ {+ if (this._picProbe.Image == null)+ {+ this.EnsureProbePicture();+ }+ if (this._picProbe.Image == null)+ {+ MessageBox.Show(this, "There is no picture to pick from yet, and the canvas size is not known either\r\n(choose a scene image, or a user defined width and height, on the Configuration tab first).", "Probe positions", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ this._pickIndex = ui.Index;+ this._pickStep = 1;+ this._pickHover = null;+ this._picProbe.Cursor = Cursors.Cross;+ ui.ButPick.Text = "Cancel";+ this.ShowPickInstruction();+ }++ /// <summary>Writes the status-bar instruction for the current pick step (1: position A / the point, 2: position B, 3: top-left corner of the graph box).</summary>+ private void ShowPickInstruction()+ {+ Form1.ProbeControlSet ui = this._probeUi[this._pickIndex];+ switch (this._pickStep)+ {+ case 1:+ this.ToolStripStatusLabel1.Text = ((this._probes[this._pickIndex].Kind == ProbeKind.Line) ? (ui.Title + ": click in the picture for position A, the start of the line (press Cancel to stop picking).") : (ui.Title + ": click in the picture for the position of the probe (press Cancel to stop picking)."));+ break;+ case 2:+ this.ToolStripStatusLabel1.Text = ui.Title + ": click in the picture for position B, the end of the line.";+ break;+ case 3:+ this.ToolStripStatusLabel1.Text = ui.Title + ": click in the picture for the top left corner of the graph box.";+ break;+ default:+ this.ToolStripStatusLabel1.Text = "";+ break;+ }+ }++ /// <summary>Leaves pick mode: restores the pick button text, clears step and hover, resets the cursor, repaints, and clears the status bar if a pick was active. Safe to call when nothing is being picked or before the probe picture exists.</summary>+ private void EndPick()+ {+ bool wasPicking = this._pickStep != 0;+ if (wasPicking)+ {+ this._probeUi[this._pickIndex].ButPick.Text = this._probeUi[this._pickIndex].PickButtonText;+ }+ this._pickStep = 0;+ this._pickHover = null;+ if (this._picProbe != null)+ {+ this._picProbe.Cursor = Cursors.Default;+ this._picProbe.Invalidate();+ }+ if (wasPicking)+ {+ this.ToolStripStatusLabel1.Text = "";+ }+ }++ /// <summary>+ /// Left click on the probe picture while picking: the click (picture-box pixels) is converted to a+ /// canvas pixel and, depending on the step, written into the A spinners (their ValueChanged stores+ /// it in the probe), the B spinners, or directly into <see cref="ProbeSettings.BoxX"/>/<c>BoxY</c>.+ /// Point probes skip step 2. Clicks outside the image area are ignored.+ /// </summary>+ private void ProbePicture_MouseClick(object sender, MouseEventArgs e)+ {+ if (this._pickStep == 0 || e.Button != MouseButtons.Left)+ {+ return;+ }+ Form1.ProbeControlSet ui = this._probeUi[this._pickIndex];+ int x = 0;+ int y = 0;+ if (!this.TryPictureToCanvas(this._picProbe, e.Location, ref x, ref y))+ {+ return;+ }+ switch (this._pickStep)+ {+ case 1:+ ui.NumAPosX.Value = Form1.ClampToRange(ui.NumAPosX, x);+ ui.NumAPosY.Value = Form1.ClampToRange(ui.NumAPosY, y);+ this._pickStep = ((this._probes[this._pickIndex].Kind == ProbeKind.Line) ? 2 : 3);+ this.ShowPickInstruction();+ break;+ case 2:+ ui.NumBPosX.Value = Form1.ClampToRange(ui.NumBPosX, x);+ ui.NumBPosY.Value = Form1.ClampToRange(ui.NumBPosY, y);+ this._pickStep = 3;+ this.ShowPickInstruction();+ break;+ default:+ this._probes[this._pickIndex].BoxX = x;+ this._probes[this._pickIndex].BoxY = y;+ this.ProbeSettingsChanged();+ this.EndPick();+ break;+ }+ this._picProbe.Invalidate();+ }++ /// <summary>During step 3 (graph box placement) remembers the mouse position in picture-box pixels so <see cref="ProbePicture_Paint"/> can preview the box there.</summary>+ private void ProbePicture_MouseMove(object sender, MouseEventArgs e)+ {+ if (this._pickStep == 3)+ {+ this._pickHover = new Point?(e.Location);+ this._picProbe.Invalidate();+ }+ }++ /// <summary>Drops the box preview position when the mouse leaves the probe picture.</summary>+ private void ProbePicture_MouseLeave(object sender, EventArgs e)+ {+ if (this._pickHover != null)+ {+ this._pickHover = null;+ this._picProbe.Invalidate();+ }+ }++ /// <summary>+ /// Maps a point in picture-box pixels to canvas pixel coordinates; false when the box has no+ /// image or the point lies outside the zoomed image area. The canvas size is+ /// <c>EffectiveCanvas()</c>, falling back to the image size when unknown. The result is floored+ /// and clamped to 0..width-1 / 0..height-1.+ /// </summary>+ private bool TryPictureToCanvas(PictureBox box, Point point, ref int x, ref int y)+ {+ if (box.Image == null)+ {+ return false;+ }+ RectangleF area = Form1.ZoomedImageRectangle(box);+ if (area.Width <= 0f || area.Height <= 0f || !area.Contains(point.X, point.Y))+ {+ return false;+ }+ Size canvas = this.EffectiveCanvas();+ if (canvas.Width <= 0)+ {+ canvas = box.Image.Size;+ }+ x = (int)Math.Floor((point.X - area.X) / area.Width * canvas.Width);+ y = (int)Math.Floor((point.Y - area.Y) / area.Height * canvas.Height);+ x = Math.Max(0, Math.Min(canvas.Width - 1, x));+ y = Math.Max(0, Math.Min(canvas.Height - 1, y));+ return true;+ }++ /// <summary>+ /// The rectangle (picture-box pixels) the image occupies inside a picture box in Zoom size mode:+ /// uniformly scaled to fit and centred. Empty when there is no image. All preview boxes are+ /// created with <c>SizeMode = Zoom</c>, so this matches what WinForms draws.+ /// </summary>+ private static RectangleF ZoomedImageRectangle(PictureBox box)+ {+ Image image = box.Image;+ if (image == null || image.Width <= 0 || image.Height <= 0)+ {+ return RectangleF.Empty;+ }+ float boxWidth = box.ClientSize.Width;+ float boxHeight = box.ClientSize.Height;+ float scale = Math.Min(boxWidth / image.Width, boxHeight / image.Height);+ float width = image.Width * scale;+ float height = image.Height * scale;+ return new RectangleF((boxWidth - width) / 2f, (boxHeight - height) / 2f, width, height);+ }++ /// <summary>+ /// Converts a rectangle in canvas pixels to picture-box pixels (despite the name, not screen+ /// coordinates): offsets by the image area's origin and scales by <paramref name="sx"/>/<paramref name="sy"/>+ /// (picture-box pixels per canvas pixel), rounding each edge.+ /// </summary>+ private static Rectangle ToScreen(Rectangle r, RectangleF area, float sx, float sy)+ {+ return new Rectangle((int)Math.Round(area.X + r.X * sx), (int)Math.Round(area.Y + r.Y * sy), (int)Math.Round(r.Width * sx), (int)Math.Round(r.Height * sy));+ }++ /// <summary>+ /// Paint overlay for the field and intensity preview pictures: draws markers and live graphs for+ /// the probes of the current/last run (<c>_runProbes</c>, scaled by <c>_runCanvas</c> because the+ /// picture shows run output) whose <see cref="ProbeSettings.PlaceOn"/> matches the picture.+ /// Position, kind and measurement come from the run copy, but display settings are taken from+ /// the probe being edited (<see cref="ProbeSettings.CopyDisplayFrom"/>) so box moves, scaling and+ /// the active flag apply immediately. Nothing is drawn before the first run.+ /// </summary>+ private void PreviewPicture_Paint(object sender, PaintEventArgs e)+ {+ PictureBox picture = (PictureBox)sender;+ if (picture.Image == null || this._runProbes == null || this._runCanvas.Width <= 0)+ {+ return;+ }+ ProbePlaceOn placeOn = ((picture == this._picField) ? ProbePlaceOn.Field : ProbePlaceOn.Intensity);+ RectangleF area = Form1.ZoomedImageRectangle(picture);+ if (area.Width <= 0f)+ {+ return;+ }+ float sx = area.Width / this._runCanvas.Width;+ float sy = area.Height / this._runCanvas.Height;+ for (int i = 0; i < this._runProbes.Count; i++)+ {+ ProbeSettings probe = this._runProbes[i].Clone();+ if (i < this._probes.Count)+ {+ probe.CopyDisplayFrom(this._probes[i]);+ }+ if (probe.PlaceOn != placeOn || !probe.Active)+ {+ continue;+ }+ ProbeGraphPainter.DrawMarkers(e.Graphics, probe, i, area.X, area.Y, sx, sy);+ ProbeTrace trace = null;+ if (i < this._probeTraces.Count)+ {+ trace = this._probeTraces[i];+ }+ Rectangle box = Form1.ToScreen(ProbeGraphPainter.BoxInCanvas(probe, this._runCanvas.Width, this._runCanvas.Height), area, sx, sy);+ ProbeGraphPainter.DrawGraph(e.Graphics, box, probe.Title(i), probe, trace, this._runSteps);+ }+ }++ /// <summary>+ /// Paint overlay for the probe picture on the Probes tab (scaled by <c>EffectiveCanvas()</c>,+ /// falling back to the image size): for every active probe, and for the probe currently being+ /// picked even if inactive, draws the position markers and a translucent dashed yellow placeholder+ /// where the graph box will be, labelled with the probe title. During pick step 3 the placeholder+ /// follows the hovered mouse position instead of the stored box position.+ /// </summary>+ private void ProbePicture_Paint(object sender, PaintEventArgs e)+ {+ if (this._picProbe.Image == null)+ {+ return;+ }+ Size canvas = this.EffectiveCanvas();+ if (canvas.Width <= 0)+ {+ canvas = this._picProbe.Image.Size;+ }+ RectangleF area = Form1.ZoomedImageRectangle(this._picProbe);+ if (area.Width <= 0f)+ {+ return;+ }+ float sx = area.Width / canvas.Width;+ float sy = area.Height / canvas.Height;+ for (int i = 0; i < this._probes.Count; i++)+ {+ ProbeSettings probe = this._probes[i];+ bool picking = this._pickStep != 0 && this._pickIndex == i;+ if (!probe.Active && !picking)+ {+ continue;+ }+ ProbeGraphPainter.DrawMarkers(e.Graphics, probe, i, area.X, area.Y, sx, sy);+ ProbeSettings shown = probe;+ if (this._pickStep == 3 && this._pickIndex == i && this._pickHover != null)+ {+ int hoverX = 0;+ int hoverY = 0;+ if (this.TryPictureToCanvas(this._picProbe, this._pickHover.Value, ref hoverX, ref hoverY))+ {+ shown = probe.Clone();+ shown.BoxX = hoverX;+ shown.BoxY = hoverY;+ }+ }+ Rectangle box = Form1.ToScreen(ProbeGraphPainter.BoxInCanvas(shown, canvas.Width, canvas.Height), area, sx, sy);+ using (SolidBrush fill = new SolidBrush(Color.FromArgb(40, 255, 208, 64)))+ {+ e.Graphics.FillRectangle(fill, box);+ }+ using (Pen outline = new Pen(Color.FromArgb(230, 255, 208, 64), 1.5f))+ {+ outline.DashStyle = DashStyle.Dash;+ e.Graphics.DrawRectangle(outline, box);+ }+ using (Font font = new Font("Segoe UI", 12f, FontStyle.Bold, GraphicsUnit.Pixel))+ {+ using (SolidBrush textBrush = new SolidBrush(Color.FromArgb(240, 255, 208, 64)))+ {+ e.Graphics.DrawString(probe.Title(i), font, textBrush, box.X + 4, box.Y + 3);+ }+ }+ }+ }++ /// <summary>Replaces <c>_probes</c> with the list from the current project's config (padded/truncated to <see cref="ProbeCount"/>) and shows it; no-op without a project.</summary>+ private void LoadProbesFromProject()+ {+ if (this._project == null)+ {+ return;+ }+ this._probes = ProbeSettings.ListFromConfig(this._project.Config);+ this.NormalizeProbeCount();+ this.ShowProbesInControls();+ }++ /// <summary>Replaces <c>_probes</c> with defaults (new project) and shows them.</summary>+ private void ResetProbes()+ {+ this._probes = Form1.NewProbeList();+ this.ShowProbesInControls();+ }++ /// <summary>Commits every control to <c>_probes</c> and returns independent copies for the <c>SimulationJob</c>, so the worker thread never reads the instances the user keeps editing.</summary>+ private List<ProbeSettings> ProbesForRun()+ {+ foreach (Form1.ProbeControlSet ui in this._probeUi)+ {+ this.ReadProbeControls(ui);+ }+ List<ProbeSettings> copies = new List<ProbeSettings>();+ foreach (ProbeSettings probe in this._probes)+ {+ copies.Add(probe.Clone());+ }+ return copies;+ }++ /// <summary>+ /// Called when a simulation starts: records the run's probe copies, canvas size (canvas pixels)+ /// and total step count for the paint handlers, replaces the traces with one empty+ /// <see cref="ProbeTrace"/> per probe, and repaints.+ /// </summary>+ /// <param name="probes">The copies from <see cref="ProbesForRun"/>; may be null.</param>+ /// <param name="canvas">Canvas size of the run in canvas pixels; the previews scale probe positions by it.</param>+ /// <param name="steps">Total steps of the run, used for the full-scale X axis.</param>+ private void BeginProbeRun(List<ProbeSettings> probes, Size canvas, int steps)+ {+ this._runProbes = probes;+ this._runCanvas = canvas;+ this._runSteps = steps;+ this._probeTraces.Clear();+ if (probes != null)+ {+ for (int i = 0; i < probes.Count; i++)+ {+ this._probeTraces.Add(new ProbeTrace());+ }+ }+ this.InvalidateProbePictures();+ }++ /// <summary>+ /// Receives a batch of probe results from <see cref="SimulationRunner.ProbesUpdated"/>; runs on the+ /// UI thread because the subscription wraps it in <c>PostToUi</c>. Batches from a runner that is no+ /// longer <c>_runner</c> (or arriving after dispose) are dropped. Appends the new samples to each+ /// trace's series, replaces the profile when the batch carries one, updates the sampled step count+ /// and repaints the field/intensity previews (the probe picture shows no live data).+ /// </summary>+ private void ShowProbeSamples(SimulationRunner runner, ProbeUpdate update)+ {+ if (runner != this._runner || base.IsDisposed)+ {+ return;+ }+ int count = Math.Min(update.Samples.Length, this._probeTraces.Count);+ for (int i = 0; i < count; i++)+ {+ this._probeTraces[i].Series.Add(update.Samples[i]);+ if (update.Profiles[i] != null)+ {+ this._probeTraces[i].SetProfile(update.Profiles[i], update.Lengths[i]);+ }+ this._probeTraces[i].StepsSampled = update.StepsDone;+ }+ if (this._picField != null)+ {+ this._picField.Invalidate();+ }+ if (this._picIntensity != null)+ {+ this._picIntensity.Invalidate();+ }+ }+ }+}diff --git a/Wave_Dude_2D/Form1.Projects.cs b/Wave_Dude_2D/Form1.Projects.csnew file mode 100644index 0000000..513292b--- /dev/null+++ b/Wave_Dude_2D/Form1.Projects.cs@@ -0,0 +1,385 @@+using System;+using System.Collections.Generic;+using System.Globalization;+using System.IO;+using System.Windows.Forms;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Projects tab: the sortable list of every project folder found under the configured project+ /// root (<see cref="AppSettings.ProjectRoot"/>) and the new/load/delete/rename commands that act+ /// on the selected entry. The list-building helpers here (<see cref="BuildProjectEntries"/>,+ /// <see cref="SortProjectEntries"/>, <see cref="PopulateProjectListView"/>,+ /// <see cref="SelectedProjectName"/>, <see cref="SelectProjectInList"/>) are shared with the+ /// second project list on the Outputs tab (<c>Form1.Output.cs</c>). Everything here runs on+ /// the UI thread.+ /// </summary>+ public partial class Form1+ {+ /// <summary>+ /// Scans the project root for project folders and returns one unsorted entry per project.+ /// The "last modified" time is the write time of the project's configuration.json, or of+ /// the folder itself when that file is missing (legacy folders).+ /// </summary>+ /// <returns>An empty list when no project root is configured or it cannot be read.</returns>+ private List<Form1.ProjectListEntry> BuildProjectEntries()+ {+ List<Form1.ProjectListEntry> entries = new List<Form1.ProjectListEntry>();+ foreach (string name in ProjectStore.ListProjects(this._settings.ProjectRoot))+ {+ string folder = ProjectStore.FolderPathFor(this._settings.ProjectRoot, name);+ string configPath = Path.Combine(folder, ProjectConfig.FileName);+ DateTime lastModified = File.Exists(configPath) ? File.GetLastWriteTime(configPath) : Directory.GetLastWriteTime(folder);+ entries.Add(new Form1.ProjectListEntry(name, lastModified));+ }+ return entries;+ }++ /// <summary>+ /// Sorts <paramref name="entries"/> in place: column 0 by name (case-insensitive), any other+ /// column by last-modified time; the list is reversed afterwards for descending order.+ /// </summary>+ private void SortProjectEntries(List<Form1.ProjectListEntry> entries, int sortColumn, bool ascending)+ {+ if (sortColumn == 0)+ {+ entries.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));+ }+ else+ {+ entries.Sort((a, b) => DateTime.Compare(a.LastModified, b.LastModified));+ }+ if (!ascending)+ {+ entries.Reverse();+ }+ }++ /// <summary>+ /// Replaces the items of <paramref name="list"/> with one row per entry: the name and the+ /// last-modified time as local "yyyy-MM-dd HH:mm". Each item's <c>Tag</c> holds its+ /// <see cref="ProjectListEntry"/>.+ /// </summary>+ private void PopulateProjectListView(ListView list, List<Form1.ProjectListEntry> entries)+ {+ list.BeginUpdate();+ try+ {+ list.Items.Clear();+ foreach (Form1.ProjectListEntry entry in entries)+ {+ ListViewItem item = new ListViewItem(entry.Name);+ item.SubItems.Add(entry.LastModified.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture));+ item.Tag = entry;+ list.Items.Add(item);+ }+ }+ finally+ {+ list.EndUpdate();+ }+ }++ /// <summary>Name of the first selected project in <paramref name="list"/>, or "" when nothing is selected.</summary>+ private string SelectedProjectName(ListView list)+ {+ if (list.SelectedItems.Count == 0)+ {+ return "";+ }+ Form1.ProjectListEntry entry = list.SelectedItems[0].Tag as Form1.ProjectListEntry;+ return (entry != null) ? entry.Name : "";+ }++ /// <summary>+ /// Adds the entry named <paramref name="name"/> (case-insensitive) to the selection of+ /// <paramref name="list"/> and scrolls it into view; does nothing for "" or an unknown name.+ /// </summary>+ private void SelectProjectInList(ListView list, string name)+ {+ if (name.Length == 0)+ {+ return;+ }+ foreach (ListViewItem item in list.Items)+ {+ Form1.ProjectListEntry entry = (Form1.ProjectListEntry)item.Tag;+ if (string.Equals(entry.Name, name, StringComparison.OrdinalIgnoreCase))+ {+ item.Selected = true;+ item.EnsureVisible();+ break;+ }+ }+ }++ /// <summary>+ /// Rebuilds the Projects-tab list from disk with the current sort, keeps the previously+ /// selected project selected when it still exists, and refreshes the sort arrows and buttons.+ /// Called after every project command and whenever the root folder changes.+ /// </summary>+ private void RefreshProjectList()+ {+ string selectedName = this.SelectedProjectName(this.lstAllProjects);+ List<Form1.ProjectListEntry> entries = this.BuildProjectEntries();+ this.SortProjectEntries(entries, this._projectSortColumn, this._projectSortAscending);+ this.PopulateProjectListView(this.lstAllProjects, entries);+ this.UpdateProjectListSortHeaders();+ this.SelectProjectInList(this.lstAllProjects, selectedName);+ this.UpdateProjectListButtons();+ }++ /// <summary>Clicking a column header sorts the project list by it; clicking the current sort column again flips the direction.</summary>+ private void lstAllProjects_ColumnClick(object sender, ColumnClickEventArgs e)+ {+ if (e.Column == this._projectSortColumn)+ {+ this._projectSortAscending = !this._projectSortAscending;+ }+ else+ {+ this._projectSortColumn = e.Column;+ this._projectSortAscending = true;+ }+ this.RefreshProjectList();+ }++ /// <summary>Appends " ^" (ascending) or " v" (descending) to the header text of the column the project list is sorted by.</summary>+ private void UpdateProjectListSortHeaders()+ {+ string arrow = this._projectSortAscending ? " ^" : " v";+ this.colProjectName.Text = "Project name" + ((this._projectSortColumn == 0) ? arrow : "");+ this.colLastEdit.Text = "Last edited" + ((this._projectSortColumn == 1) ? arrow : "");+ }++ /// <summary>Enables "New" only when a project root is configured, and Load/Delete/Rename only when a project is selected.</summary>+ private void UpdateProjectListButtons()+ {+ bool hasSelection = this.lstAllProjects.SelectedItems.Count > 0;+ this.btnNewProject.Enabled = this._settings != null && this._settings.ProjectRoot.Length > 0;+ this.btnLoadProject.Enabled = hasSelection;+ this.btnDeleteProject.Enabled = hasSelection;+ this.btnRenameProject.Enabled = hasSelection;+ }++ /// <summary>+ /// Creates a new project (wired to both the "New project" button and File > New): offers+ /// to save the open project, then asks for a name until it is valid and unused or the prompt+ /// is cancelled. On success the editor is reset to defaults, those defaults are written into+ /// the new project's configuration.json, and the project becomes the current one.+ /// </summary>+ private void btnNewProject2_Click(object sender, EventArgs e)+ {+ if (this._settings.ProjectRoot.Length == 0)+ {+ MessageBox.Show(this, "Choose a project root folder first (File > Choose project root).", "New project", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ if (!this.ConfirmSaveProject())+ {+ return;+ }+ string name = "";+ while (this.PromptForText("New project", "Name for the new project:", name, ref name))+ {+ name = name.Trim();+ string error = ProjectStore.ValidateName(name);+ if (error.Length > 0)+ {+ MessageBox.Show(this, error, "New project", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ continue;+ }+ if (ProjectStore.IsProjectFolder(ProjectStore.FolderPathFor(this._settings.ProjectRoot, name)))+ {+ MessageBox.Show(this, "A project named '" + name + "' already exists in this root folder. Choose a different name.", "New project", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ continue;+ }+ try+ {+ Project project = ProjectStore.Create(this._settings.ProjectRoot, name);+ this.StartNewProject();+ this._scene.ToConfig(project.Config);+ this._simulation.ToConfig(project.Config);+ ProbeSettings.ListToConfig(this._probes, project.Config);+ SourceSettings.ListToConfig(this._sources, project.Config);+ project.Save();+ this.SetCurrentProject(project);+ this.ToolStripStatusLabel1.Text = "Project '" + name + "' created.";+ break;+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The project could not be created:\r\n\r\n" + ex.Message, "New project", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ }+ }+ }++ /// <summary>Changing the selection updates which project buttons are enabled.</summary>+ private void lstAllProjects_SelectedIndexChanged(object sender, EventArgs e)+ {+ this.UpdateProjectListButtons();+ }++ /// <summary>Double-clicking a project loads it, exactly like the Load button.</summary>+ private void lstAllProjects_DoubleClick(object sender, EventArgs e)+ {+ this.btnLoadProject_Click(sender, e);+ }++ /// <summary>Full folder path of the project selected in the Projects-tab list, or "" when none is selected.</summary>+ private string SelectedProjectFolder()+ {+ string name = this.SelectedProjectName(this.lstAllProjects);+ return (name.Length == 0) ? "" : ProjectStore.FolderPathFor(this._settings.ProjectRoot, name);+ }++ /// <summary>+ /// True when <paramref name="folder"/> is the open project's folder and a+ /// <see cref="SimulationRunner"/> still exists for it (a run is in progress), in which case+ /// the folder must not be deleted or renamed.+ /// </summary>+ private bool IsOpenProjectRunning(string folder)+ {+ return this._project != null && this._runner != null && string.Equals(this._project.FolderPath, folder, StringComparison.OrdinalIgnoreCase);+ }++ /// <summary>Loads the selected project into the editor after offering to save unsaved changes; read errors are shown in a message box.</summary>+ private void btnLoadProject_Click(object sender, EventArgs e)+ {+ string folder = this.SelectedProjectFolder();+ if (folder.Length == 0)+ {+ return;+ }+ try+ {+ if (this.ConfirmSaveProject())+ {+ this.SetCurrentProject(ProjectStore.Open(folder));+ }+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The project could not be opened:\r\n\r\n" + ex.Message, "Load project", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ }+ }++ /// <summary>+ /// Permanently deletes the selected project folder after a confirmation that also mentions+ /// how many files its assets folder holds. Refused while a simulation is running for that+ /// project. If the deleted project was the open one, the editor is reset to a new, unsaved+ /// project.+ /// </summary>+ private void btnDeleteProject_Click(object sender, EventArgs e)+ {+ string name = this.SelectedProjectName(this.lstAllProjects);+ string folder = this.SelectedProjectFolder();+ if (folder.Length == 0)+ {+ return;+ }+ if (this.IsOpenProjectRunning(folder))+ {+ MessageBox.Show(this, "A simulation is running for this project. Stop it first.", "Delete project", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ string question = "Permanently delete the project '" + name + "' and everything in its folder?\r\n\r\n" + folder;+ int assetCount = Form1.CountFilesIn(Path.Combine(folder, ProjectStore.AssetsFolderName));+ if (assetCount > 0)+ {+ question += "\r\n\r\nThis includes " + assetCount.ToString(CultureInfo.InvariantCulture) + " file(s) in its assets folder - copy them elsewhere first if you want to keep them.";+ }+ if (MessageBox.Show(this, question, "Delete project", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)+ {+ return;+ }+ bool deletesOpenProject = this._project != null && string.Equals(this._project.FolderPath, folder, StringComparison.OrdinalIgnoreCase);+ try+ {+ ProjectStore.Delete(folder);+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The project could not be deleted:\r\n\r\n" + ex.Message, "Delete project", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ this.RefreshProjectList();+ return;+ }+ if (deletesOpenProject)+ {+ this.StartNewProject();+ this.UpdateProjectAccess();+ }+ this.RefreshProjectList();+ this.ToolStripStatusLabel1.Text = "Project '" + name + "' deleted.";+ }++ /// <summary>Number of files anywhere below <paramref name="folderPath"/>; 0 when the folder is missing or unreadable.</summary>+ private static int CountFilesIn(string folderPath)+ {+ if (!Directory.Exists(folderPath))+ {+ return 0;+ }+ try+ {+ return Directory.GetFiles(folderPath, "*", SearchOption.AllDirectories).Length;+ }+ catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)+ {+ return 0;+ }+ }++ /// <summary>+ /// Renames the selected project folder after prompting for a new name (validated by+ /// <see cref="ProjectStore.Rename"/>). Refused while a simulation is running for it; an+ /// unchanged name is a no-op.+ /// </summary>+ /// <remarks>+ /// When the renamed project is the open one it is re-opened from the new folder so that all+ /// project-relative paths stay valid. That re-reads configuration.json, so unsaved edits to+ /// the open project are discarded without asking.+ /// </remarks>+ private void btnRenameProject_Click(object sender, EventArgs e)+ {+ string oldName = this.SelectedProjectName(this.lstAllProjects);+ string folder = this.SelectedProjectFolder();+ if (folder.Length == 0)+ {+ return;+ }+ if (this.IsOpenProjectRunning(folder))+ {+ MessageBox.Show(this, "A simulation is running for this project. Stop it first.", "Rename project", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ string newName = oldName;+ if (!this.PromptForText("Rename project", "New name for '" + oldName + "':", oldName, ref newName))+ {+ return;+ }+ newName = newName.Trim();+ if (newName == oldName)+ {+ return;+ }+ bool renamesOpenProject = this._project != null && string.Equals(this._project.FolderPath, folder, StringComparison.OrdinalIgnoreCase);+ try+ {+ string newFolder = ProjectStore.Rename(folder, newName);+ if (renamesOpenProject)+ {+ this.SetCurrentProject(ProjectStore.Open(newFolder));+ }+ this.RefreshProjectList();+ this.SelectProjectInList(this.lstAllProjects, newName);+ this.ToolStripStatusLabel1.Text = "Project '" + oldName + "' renamed to '" + newName + "'.";+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The project could not be renamed:\r\n\r\n" + ex.Message, "Rename project", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ }+ }+ }+}diff --git a/Wave_Dude_2D/Form1.Scene.cs b/Wave_Dude_2D/Form1.Scene.csnew file mode 100644index 0000000..ca8e891--- /dev/null+++ b/Wave_Dude_2D/Form1.Scene.cs@@ -0,0 +1,909 @@+using System;+using System.Drawing;+using System.Drawing.Drawing2D;+using System.Drawing.Imaging;+using System.Globalization;+using System.IO;+using System.Runtime.InteropServices;+using System.Windows.Forms;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Scene tab: scene image / user-defined canvas, damping edge, image sources,+ /// and the glowing-edges overlay drawn on top of the field / intensity previews.+ /// The model is <c>_scene</c> (a <see cref="SceneSettings"/>), the loaded bitmap is+ /// <c>_sceneImage</c> (owned by the form, replaced through <see cref="ReplaceSceneImage"/>),+ /// and <c>_loadingScene</c> is the re-entrancy guard that makes the change handlers ignore+ /// programmatic control updates. Everything here runs on the UI thread.+ /// </summary>+ public partial class Form1+ {+ /// <summary>+ /// Applies the Scene tab control settings that are not in the designer (preview zoom mode,+ /// label ellipsis, text lengths, image-source scale range). Called once from the constructor.+ /// </summary>+ private void InitializeSceneControls()+ {+ this.picImagePreview.BorderStyle = BorderStyle.FixedSingle;+ this.picImagePreview.BackColor = SystemColors.ControlLight;+ this.picImagePreview.SizeMode = PictureBoxSizeMode.Zoom;+ this.lblImageNameAndSize.AutoSize = false;+ this.lblImageNameAndSize.AutoEllipsis = true;+ this.lblImageNameAndSize.Size = new Size(470, 20);+ this.txtXSize.MaxLength = 5;+ this.txtYsize.MaxLength = 5;+ this.txtDampingEdgeSize.MaxLength = 4;+ this.numScaleImageSource.Minimum = 0m;+ this.numScaleImageSource.Maximum = 1000m;+ }++ /// <summary>+ /// Replaces <c>_scene</c> with the scene section of the open project's config, loads the+ /// referenced image as the scene image (silently leaving it unloaded when the file is missing+ /// or unreadable) and shows everything in the controls. Does nothing when no project is open.+ /// </summary>+ private void LoadSceneFromProject()+ {+ if (this._project == null)+ {+ return;+ }+ this._scene = SceneSettings.FromConfig(this._project.Config);+ this.ReplaceSceneImage(null);+ if (this._scene.ImageFile.Length > 0)+ {+ string imagePath = SceneSettings.ToFullPath(this._project.FolderPath, this._scene.ImageFile);+ if (File.Exists(imagePath))+ {+ try+ {+ this.ReplaceSceneImage(Form1.LoadImageCopy(imagePath));+ }+ catch (Exception)+ {+ }+ }+ }+ this.ShowSceneInControls();+ }++ /// <summary>+ /// Copies <c>_scene</c> into the Scene tab controls with <c>_loadingScene</c> set so the change+ /// handlers neither write back nor mark the project dirty, then refreshes control enabling,+ /// the preview and the damping-edge validation colour.+ /// </summary>+ private void ShowSceneInControls()+ {+ this._loadingScene = true;+ try+ {+ this.radUseSceneImage.Checked = this._scene.UseImage;+ this.radUserDefinedScene.Checked = !this._scene.UseImage;+ this.txtXSize.Text = this._scene.UserWidth.ToString(CultureInfo.InvariantCulture);+ this.txtYsize.Text = this._scene.UserHeight.ToString(CultureInfo.InvariantCulture);+ this.chkDampingEdge.Checked = this._scene.DampingEdgeEnabled;+ this.txtDampingEdgeSize.Text = this._scene.DampingEdgeSize.ToString(CultureInfo.InvariantCulture);+ this.chkUseImageSources.Checked = this._scene.UseSources;+ this.numScaleImageSource.Value = Form1.ClampToRange(this.numScaleImageSource, this._scene.ImageSourceScale);+ this.chkUseObjectSources.Checked = this._scene.UseObjectSources;+ this.numRefractiveIndex.Value = Form1.ClampToRange(this.numRefractiveIndex, this._scene.BackgroundRefractiveIndex);+ this.txtXSize.ForeColor = SystemColors.WindowText;+ this.txtYsize.ForeColor = SystemColors.WindowText;+ }+ finally+ {+ this._loadingScene = false;+ }+ this.UpdateSceneControlState();+ this.UpdateScenePreview();+ this.ShowDampingValidity();+ }++ /// <summary>Enables or disables the Scene tab controls according to the scene mode (image vs. user-defined size), the damping-edge checkbox and the image-sources checkbox.</summary>+ private void UpdateSceneControlState()+ {+ bool useImage = this._scene.UseImage;+ this.btnLoadSceneImage.Enabled = useImage;+ this.lblImageNameAndSize.Enabled = useImage;+ this.txtXSize.Enabled = !useImage;+ this.txtYsize.Enabled = !useImage;+ this.lblX.Enabled = !useImage;+ this.lblPix.Enabled = !useImage;+ this.numRefractiveIndex.Enabled = !useImage;+ this.Label20.Enabled = !useImage;+ this.txtDampingEdgeSize.Enabled = this._scene.DampingEdgeEnabled;+ this.Label1.Enabled = this._scene.DampingEdgeEnabled;+ this.numScaleImageSource.Enabled = this._scene.UseSources;+ this.lblScaleImgSourceIntensity.Enabled = this._scene.UseSources;+ }++ /// <summary>+ /// Shows either the scene image (zoomed) or a generated placeholder for the user-defined canvas+ /// size in <c>picImagePreview</c>, disposing the previous placeholder. The scene image itself+ /// is not disposed here (see <see cref="ReplaceSceneImage"/>).+ /// </summary>+ private void UpdateScenePreview()+ {+ this.UpdateImageLabel();+ if (this._scene.UseImage)+ {+ this.picImagePreview.SizeMode = PictureBoxSizeMode.Zoom;+ this.picImagePreview.Image = this._sceneImage;+ this.DisposeEmptyPreview();+ }+ else+ {+ this.picImagePreview.SizeMode = PictureBoxSizeMode.CenterImage;+ Bitmap preview = this.MakeEmptyCanvasPreview(this._scene.UserWidth, this._scene.UserHeight);+ this.picImagePreview.Image = preview;+ this.DisposeEmptyPreview();+ this._emptyPreview = preview;+ }+ }++ /// <summary>Sets the image name/size label: no image, image configured but not loadable, or file name with pixel size.</summary>+ private void UpdateImageLabel()+ {+ if (this._scene.ImageFile.Length == 0)+ {+ this.lblImageNameAndSize.Text = "(no image loaded)";+ }+ else if (this._sceneImage == null)+ {+ this.lblImageNameAndSize.Text = "(image not found or not readable: " + Path.GetFileName(this._scene.ImageFile) + ")";+ }+ else+ {+ this.lblImageNameAndSize.Text = Path.GetFileName(this._scene.ImageFile) + " (" + this._sceneImage.Width.ToString(CultureInfo.InvariantCulture) + " x " + this._sceneImage.Height.ToString(CultureInfo.InvariantCulture) + " px)";+ }+ }++ /// <summary>+ /// Draws a white placeholder bitmap with a grey frame and a "W x H px (empty scene)" caption,+ /// scaled with preserved aspect ratio to fit the preview box client area minus an 8 px margin+ /// (at least 2 x 2 px).+ /// </summary>+ /// <param name="canvasWidth">Canvas width in simulation pixels.</param>+ /// <param name="canvasHeight">Canvas height in simulation pixels.</param>+ /// <returns>A new bitmap; the caller stores it in <c>_emptyPreview</c> and disposes it.</returns>+ private Bitmap MakeEmptyCanvasPreview(int canvasWidth, int canvasHeight)+ {+ int maxWidth = Math.Max(16, this.picImagePreview.ClientSize.Width - 8);+ int maxHeight = Math.Max(16, this.picImagePreview.ClientSize.Height - 8);+ double scale = Math.Min((double)maxWidth / canvasWidth, (double)maxHeight / canvasHeight);+ int previewWidth = Math.Max(2, (int)Math.Round(canvasWidth * scale));+ int previewHeight = Math.Max(2, (int)Math.Round(canvasHeight * scale));+ Bitmap preview = new Bitmap(previewWidth, previewHeight, PixelFormat.Format32bppArgb);+ using (Graphics g = Graphics.FromImage(preview))+ {+ g.Clear(Color.White);+ using (Pen pen = new Pen(Color.Gray))+ {+ g.DrawRectangle(pen, 0, 0, previewWidth - 1, previewHeight - 1);+ }+ using (Font font = new Font("Microsoft Sans Serif", 9f))+ using (StringFormat format = new StringFormat())+ {+ format.Alignment = StringAlignment.Center;+ format.LineAlignment = StringAlignment.Center;+ g.DrawString(canvasWidth.ToString(CultureInfo.InvariantCulture) + " x " + canvasHeight.ToString(CultureInfo.InvariantCulture) + " px (empty scene)", font, Brushes.Gray, new RectangleF(0f, 0f, previewWidth, previewHeight), format);+ }+ }+ return preview;+ }++ /// <summary>Disposes the placeholder preview bitmap, if any. Callers assign a new preview image first.</summary>+ private void DisposeEmptyPreview()+ {+ if (this._emptyPreview != null)+ {+ this._emptyPreview.Dispose();+ this._emptyPreview = null;+ }+ }++ /// <summary>+ /// Makes <paramref name="newImage"/> the current scene image, taking ownership. The previous+ /// image is detached from the preview box if it is shown there and disposed, and the glow-edges+ /// overlay is recomputed for the new image.+ /// </summary>+ /// <param name="newImage">The new scene image, or null to unload.</param>+ private void ReplaceSceneImage(Bitmap newImage)+ {+ Bitmap oldImage = this._sceneImage;+ this._sceneImage = newImage;+ if (oldImage != null)+ {+ if (object.ReferenceEquals(this.picImagePreview.Image, oldImage))+ {+ this.picImagePreview.Image = null;+ }+ oldImage.Dispose();+ }+ this.UpdateGlowEdgesImage();+ }++ /// <summary>Disposes the Sobel edge image and its resized cache.</summary>+ private void ClearGlowEdgesImage()+ {+ if (this._glowEdgesImage != null)+ {+ this._glowEdgesImage.Dispose();+ this._glowEdgesImage = null;+ }+ if (this._glowOverlayCache != null)+ {+ this._glowOverlayCache.Dispose();+ this._glowOverlayCache = null;+ }+ }++ /// <summary>+ /// Recomputes the Sobel edge image from <c>_sceneImage</c> (none when no image is loaded) and+ /// re-composes the field and intensity previews so the overlay follows the new scene.+ /// </summary>+ private void UpdateGlowEdgesImage()+ {+ this.ClearGlowEdgesImage();+ if (this._sceneImage != null)+ {+ this._glowEdgesImage = Form1.ComputeGlowingEdges(this._sceneImage);+ }+ this.RefreshPreviewOverlay(this._picField, this.FieldOverlayGain());+ this.RefreshPreviewOverlay(this._picIntensity, this.IntensityOverlayGain());+ }++ /// <summary>Overlay gain for the field preview: the brightness box value when the overlay checkbox is on, otherwise 0 (overlay off).</summary>+ private double FieldOverlayGain()+ {+ return this.chkDiplayOverlayInField.Checked ? Convert.ToDouble(this.numBrightnessFieldOverlay.Value) : 0.0;+ }++ /// <summary>Overlay gain for the intensity preview: the brightness box value when the overlay checkbox is on, otherwise 0 (overlay off).</summary>+ private double IntensityOverlayGain()+ {+ return this.chkDiplayOverlayInIntensity.Checked ? Convert.ToDouble(this.numBrightnessIntensityOverlay.Value) : 0.0;+ }++ /// <summary>+ /// Computes a per-channel 3x3 Sobel gradient magnitude (scaled by 0.25, clamped to 255) of+ /// <paramref name="source"/> on a black background, used as the glowing-edges preview overlay.+ /// The source is first drawn into a 24bpp copy so any pixel format works. The outermost pixel+ /// ring is always black, and images smaller than 3 x 3 give an all-black result.+ /// </summary>+ /// <returns>A new 24bpp bitmap of the source size, owned by the caller.</returns>+ private static Bitmap ComputeGlowingEdges(Bitmap source)+ {+ int width = source.Width;+ int height = source.Height;+ Bitmap edges = new Bitmap(width, height, PixelFormat.Format24bppRgb);+ using (Graphics g = Graphics.FromImage(edges))+ {+ g.Clear(Color.Black);+ }+ if (width < 3 || height < 3)+ {+ return edges;+ }+ using (Bitmap sourceCopy = new Bitmap(width, height, PixelFormat.Format24bppRgb))+ {+ using (Graphics g = Graphics.FromImage(sourceCopy))+ {+ g.DrawImageUnscaled(source, 0, 0);+ }+ Rectangle bounds = new Rectangle(0, 0, width, height);+ BitmapData sourceData = sourceCopy.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);+ BitmapData edgesData = edges.LockBits(bounds, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);+ try+ {+ int sourceStride = sourceData.Stride;+ int edgesStride = edgesData.Stride;+ byte[] sourcePixels = new byte[sourceStride * height];+ byte[] edgePixels = new byte[edgesStride * height];+ Marshal.Copy(sourceData.Scan0, sourcePixels, 0, sourcePixels.Length);+ for (int y = 1; y < height - 1; y++)+ {+ int rowAbove = (y - 1) * sourceStride;+ int row = y * sourceStride;+ int rowBelow = (y + 1) * sourceStride;+ int edgeRow = y * edgesStride;+ for (int x = 1; x < width - 1; x++)+ {+ int above = rowAbove + (x - 1) * 3;+ int center = row + (x - 1) * 3;+ int below = rowBelow + (x - 1) * 3;+ int target = edgeRow + x * 3;+ for (int channel = 0; channel < 3; channel++)+ {+ int topLeft = sourcePixels[above + channel];+ int top = sourcePixels[above + 3 + channel];+ int topRight = sourcePixels[above + 6 + channel];+ int left = sourcePixels[center + channel];+ int right = sourcePixels[center + 6 + channel];+ int bottomLeft = sourcePixels[below + channel];+ int bottom = sourcePixels[below + 3 + channel];+ int bottomRight = sourcePixels[below + 6 + channel];+ int gx = topRight + 2 * right + bottomRight - (topLeft + 2 * left + bottomLeft);+ int gy = bottomLeft + 2 * bottom + bottomRight - (topLeft + 2 * top + topRight);+ // 0.25 keeps a full-contrast step edge (gradient 4 * 255) just within the byte range.+ double magnitude = Math.Sqrt((double)gx * gx + (double)gy * gy) * 0.25;+ edgePixels[target + channel] = (byte)Math.Round(Math.Min(255.0, magnitude));+ }+ }+ }+ Marshal.Copy(edgePixels, 0, edgesData.Scan0, edgePixels.Length);+ }+ finally+ {+ sourceCopy.UnlockBits(sourceData);+ edges.UnlockBits(edgesData);+ }+ }+ return edges;+ }++ /// <summary>+ /// Returns the edge image scaled (bilinear) to <paramref name="targetSize"/>, the preview+ /// frame size in picture-box pixels. The result is cached in <c>_glowOverlayCache</c> until a+ /// different size is requested or the scene image changes.+ /// </summary>+ /// <returns>The cached 24bpp bitmap (owned by the form; do not dispose), or null when there is no scene image.</returns>+ private Bitmap GetGlowOverlayResized(Size targetSize)+ {+ if (this._glowEdgesImage == null)+ {+ return null;+ }+ if (this._glowOverlayCache != null && this._glowOverlayCacheSize.Equals(targetSize))+ {+ return this._glowOverlayCache;+ }+ if (this._glowOverlayCache != null)+ {+ this._glowOverlayCache.Dispose();+ }+ Bitmap resized = new Bitmap(Math.Max(1, targetSize.Width), Math.Max(1, targetSize.Height), PixelFormat.Format24bppRgb);+ using (Graphics g = Graphics.FromImage(resized))+ {+ g.Clear(Color.Black);+ g.InterpolationMode = InterpolationMode.HighQualityBilinear;+ g.DrawImage(this._glowEdgesImage, new Rectangle(Point.Empty, targetSize));+ }+ this._glowOverlayCache = resized;+ this._glowOverlayCacheSize = targetSize;+ return resized;+ }++ /// <summary>+ /// Returns a copy of <paramref name="frame"/> with the glow overlay (resized to the frame)+ /// multiplied by <paramref name="gain"/> and added to each RGB channel, saturating at 255.+ /// Alpha is left untouched. Frames with fewer than 3 bytes per pixel, or no overlay, give a plain copy.+ /// </summary>+ /// <param name="frame">The raw preview frame; not modified.</param>+ /// <param name="gain">Overlay brightness multiplier; negative values count as 0.</param>+ /// <returns>A new bitmap owned by the caller.</returns>+ private Bitmap ComposeGlowOverlay(Bitmap frame, double gain)+ {+ Bitmap overlay = this.GetGlowOverlayResized(frame.Size);+ Bitmap result = new Bitmap(frame);+ if (overlay == null)+ {+ return result;+ }+ double overlayGain = Math.Max(0.0, gain);+ int bytesPerPixel = Image.GetPixelFormatSize(result.PixelFormat) / 8;+ if (bytesPerPixel < 3)+ {+ return result;+ }+ Rectangle bounds = new Rectangle(0, 0, frame.Width, frame.Height);+ BitmapData resultData = result.LockBits(bounds, ImageLockMode.ReadWrite, result.PixelFormat);+ BitmapData overlayData = overlay.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);+ try+ {+ int resultStride = resultData.Stride;+ int overlayStride = overlayData.Stride;+ int height = frame.Height;+ int width = frame.Width;+ byte[] resultPixels = new byte[resultStride * height];+ byte[] overlayPixels = new byte[overlayStride * height];+ Marshal.Copy(resultData.Scan0, resultPixels, 0, resultPixels.Length);+ Marshal.Copy(overlayData.Scan0, overlayPixels, 0, overlayPixels.Length);+ for (int y = 0; y < height; y++)+ {+ int resultRow = y * resultStride;+ int overlayRow = y * overlayStride;+ for (int x = 0; x < width; x++)+ {+ int resultOffset = resultRow + x * bytesPerPixel;+ int overlayOffset = overlayRow + x * 3;+ resultPixels[resultOffset] = (byte)Math.Round(Math.Min(255.0, resultPixels[resultOffset] + overlayPixels[overlayOffset] * overlayGain));+ resultPixels[resultOffset + 1] = (byte)Math.Round(Math.Min(255.0, resultPixels[resultOffset + 1] + overlayPixels[overlayOffset + 1] * overlayGain));+ resultPixels[resultOffset + 2] = (byte)Math.Round(Math.Min(255.0, resultPixels[resultOffset + 2] + overlayPixels[overlayOffset + 2] * overlayGain));+ }+ }+ Marshal.Copy(resultPixels, 0, resultData.Scan0, resultPixels.Length);+ }+ finally+ {+ result.UnlockBits(resultData);+ overlay.UnlockBits(overlayData);+ }+ return result;+ }++ /// <summary>+ /// Shows <paramref name="frame"/> in <paramref name="box"/>, taking ownership of it. The raw+ /// frame is kept in <c>box.Tag</c> and <c>box.Image</c> receives either the same object or,+ /// when <paramref name="gain"/> > 0 and an overlay exists, a composed copy. The previous raw+ /// frame and previous composed image (when distinct) are disposed. Called on the UI thread+ /// from <c>ShowPreview</c>, which <c>SimulationRunner</c> reaches through <c>PostToUi</c>.+ /// </summary>+ private void SetPreviewFrame(PictureBox box, Bitmap frame, double gain)+ {+ Image oldImage = box.Image;+ Bitmap oldFrame = box.Tag as Bitmap;+ box.Tag = frame;+ box.Image = ((gain > 0.0 && this._glowEdgesImage != null) ? this.ComposeGlowOverlay(frame, gain) : frame);+ if (oldImage != null && !object.ReferenceEquals(oldImage, oldFrame))+ {+ oldImage.Dispose();+ }+ if (oldFrame != null)+ {+ oldFrame.Dispose();+ }+ }++ /// <summary>+ /// Re-composes the overlay for a preview box from the raw frame kept in <c>box.Tag</c>+ /// (no-op when the box is null or holds no frame), disposing the previously composed image.+ /// Used when the overlay checkbox / brightness or the scene image changes.+ /// </summary>+ private void RefreshPreviewOverlay(PictureBox box, double gain)+ {+ if (box == null)+ {+ return;+ }+ Bitmap frame = box.Tag as Bitmap;+ if (frame == null)+ {+ return;+ }+ Image oldImage = box.Image;+ box.Image = ((gain > 0.0 && this._glowEdgesImage != null) ? this.ComposeGlowOverlay(frame, gain) : frame);+ if (oldImage != null && !object.ReferenceEquals(oldImage, frame))+ {+ oldImage.Dispose();+ }+ }++ /// <summary>Toggling the field overlay re-composes the field preview.</summary>+ private void chkDiplayOverlayInField_CheckedChanged(object sender, EventArgs e)+ {+ this.RefreshPreviewOverlay(this._picField, this.FieldOverlayGain());+ }++ /// <summary>Toggling the intensity overlay re-composes the intensity preview.</summary>+ private void chkDiplayOverlayInIntensity_CheckedChanged(object sender, EventArgs e)+ {+ this.RefreshPreviewOverlay(this._picIntensity, this.IntensityOverlayGain());+ }++ /// <summary>Changing the field overlay brightness re-composes the field preview.</summary>+ private void numBrightnessFieldOverlay_ValueChanged(object sender, EventArgs e)+ {+ this.RefreshPreviewOverlay(this._picField, this.FieldOverlayGain());+ }++ /// <summary>Changing the intensity overlay brightness re-composes the intensity preview.</summary>+ private void numBrightnessIntensityOverlay_ValueChanged(object sender, EventArgs e)+ {+ this.RefreshPreviewOverlay(this._picIntensity, this.IntensityOverlayGain());+ }++ /// <summary>+ /// Loads an image file into a new memory-backed 32bpp ARGB <see cref="Bitmap"/> so GDI+ does+ /// not keep the file locked. Unreadable files throw the usual IO / GDI+ exceptions.+ /// </summary>+ private static Bitmap LoadImageCopy(string fullPath)+ {+ using (FileStream stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))+ using (Image image = Image.FromStream(stream))+ {+ return new Bitmap(image);+ }+ }++ /// <summary>+ /// Size of the simulation canvas in canvas pixels: the scene image size in image mode+ /// (<see cref="Size.Empty"/> when no image is loaded), otherwise the user-defined width and height.+ /// </summary>+ private Size EffectiveCanvas()+ {+ if (this._scene.UseImage)+ {+ return (this._sceneImage == null) ? Size.Empty : this._sceneImage.Size;+ }+ return new Size(this._scene.UserWidth, this._scene.UserHeight);+ }++ /// <summary>+ /// Replaces the image in <paramref name="pic"/> (the source / probe placement boxes) with a copy+ /// of the scene image, or with a black canvas of the effective size in user-defined mode, and+ /// disposes the previous image. When the canvas size is not known yet a message is shown and+ /// the box is left unchanged.+ /// </summary>+ private void ImportSceneImageInto(PictureBox pic)+ {+ Image oldImage = pic.Image;+ Bitmap canvas;+ if (this._scene.UseImage && this._sceneImage != null)+ {+ canvas = new Bitmap(this._sceneImage);+ }+ else+ {+ Size size = this.EffectiveCanvas();+ if (size.Width <= 0 || size.Height <= 0)+ {+ MessageBox.Show(this, "The canvas size is not known yet\r\n(choose a scene image, or a user defined width and height, on the Configuration tab first).", "Import scene image", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ canvas = new Bitmap(size.Width, size.Height);+ using (Graphics g = Graphics.FromImage(canvas))+ {+ g.Clear(Color.Black);+ }+ }+ pic.Image = canvas;+ pic.Invalidate();+ if (oldImage != null)+ {+ oldImage.Dispose();+ }+ }++ /// <summary>+ /// Like <see cref="ImportSceneImageInto"/> but only when <paramref name="pic"/> has no image yet,+ /// and silently does nothing when the canvas size is unknown. Called when the Sources / Probes+ /// tabs are shown.+ /// </summary>+ private void AutoLoadSceneImageIfEmpty(PictureBox pic)+ {+ if (pic == null || pic.Image != null)+ {+ return;+ }+ if (this._scene.UseImage && this._sceneImage != null)+ {+ pic.Image = new Bitmap(this._sceneImage);+ pic.Invalidate();+ }+ else+ {+ Size size = this.EffectiveCanvas();+ if (size.Width <= 0 || size.Height <= 0)+ {+ return;+ }+ Bitmap canvas = new Bitmap(size.Width, size.Height);+ using (Graphics g = Graphics.FromImage(canvas))+ {+ g.Clear(Color.Black);+ }+ pic.Image = canvas;+ pic.Invalidate();+ }+ }++ /// <summary>+ /// Parses <paramref name="text"/> as an unsigned decimal integer (invariant culture, digits only+ /// after trimming) and checks it lies in <paramref name="minValue"/>..<paramref name="maxValue"/>.+ /// </summary>+ /// <param name="text">Text box content; leading / trailing whitespace is trimmed.</param>+ /// <param name="minValue">Smallest accepted value, inclusive.</param>+ /// <param name="maxValue">Largest accepted value, inclusive.</param>+ /// <param name="value">Receives the parsed number (0 when parsing fails), even when the range check fails.</param>+ /// <returns>True when the text parsed and is within range.</returns>+ private static bool TryParseInt(string text, int minValue, int maxValue, ref int value)+ {+ return int.TryParse(text.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out value) && value >= minValue && value <= maxValue;+ }++ /// <summary>+ /// Validates the damping-edge text: it must be a whole number 1..8192 and, when the canvas+ /// size is known, less than half of the smaller canvas side.+ /// </summary>+ /// <param name="text">Content of the damping-edge text box.</param>+ /// <param name="value">Receives the parsed number.</param>+ /// <returns>An empty string when acceptable, otherwise the message to show the user.</returns>+ private string DampingProblem(string text, ref int value)+ {+ if (!Form1.TryParseInt(text, 1, 8192, ref value))+ {+ return "Enter a whole number of pixels, 1 or more.";+ }+ Size size = this.EffectiveCanvas();+ int smallerSide = Math.Min(size.Width, size.Height);+ if (size.Width > 0 && 2 * value >= smallerSide)+ {+ return "The damping edge must be less than half of the smaller canvas side (" + smallerSide.ToString(CultureInfo.InvariantCulture) + " px).";+ }+ return "";+ }++ /// <summary>Colours the damping-edge text box red when its text is not acceptable for the current canvas size, without changing the stored value.</summary>+ private void ShowDampingValidity()+ {+ int value = 0;+ bool valid = this.DampingProblem(this.txtDampingEdgeSize.Text, ref value).Length == 0;+ this.txtDampingEdgeSize.ForeColor = valid ? SystemColors.WindowText : Color.Red;+ }++ /// <summary>+ /// Switching between "use scene image" and "user defined" stores the mode, rebuilds or clears+ /// the glow overlay, updates control enabling, the preview and the damping validation, and+ /// marks the project changed. Ignored for the radio being unchecked and while <c>_loadingScene</c> is set.+ /// </summary>+ private void SceneMode_CheckedChanged(object sender, EventArgs e)+ {+ if (this._loadingScene)+ {+ return;+ }+ RadioButton radio = (RadioButton)sender;+ if (!radio.Checked)+ {+ return;+ }+ this._scene.UseImage = object.ReferenceEquals(radio, this.radUseSceneImage);+ if (this._scene.UseImage)+ {+ this.UpdateGlowEdgesImage();+ }+ else+ {+ this.ClearGlowEdgesImage();+ this.RefreshPreviewOverlay(this._picField, this.FieldOverlayGain());+ this.RefreshPreviewOverlay(this._picIntensity, this.IntensityOverlayGain());+ }+ this.UpdateSceneControlState();+ this.UpdateScenePreview();+ this.ShowDampingValidity();+ this.MarkProjectChanged();+ }++ /// <summary>+ /// Lets the user pick an image file, loads it as the scene image, copies it into the project's+ /// scene-image folder when it lies outside the project folder, stores the project-relative path,+ /// switches to image mode and marks the project changed. Unreadable files are reported and nothing+ /// changes. Also invoked from the Output tab's "load external" button.+ /// </summary>+ private void btnLOadSceneImage_Click(object sender, EventArgs e)+ {+ string projectFolder = ((this._project == null) ? "" : this._project.FolderPath);+ using (OpenFileDialog dialog = new OpenFileDialog())+ {+ dialog.Title = "Choose the scene image";+ dialog.Filter = "Images (*.png;*.jpg;*.jpeg;*.bmp;*.tif;*.tiff;*.gif)|*.png;*.jpg;*.jpeg;*.bmp;*.tif;*.tiff;*.gif|All files (*.*)|*.*";+ if (this._project != null)+ {+ if (Directory.Exists(this._project.SceneImageFolder))+ {+ dialog.InitialDirectory = this._project.SceneImageFolder;+ }+ else+ {+ dialog.InitialDirectory = this._project.FolderPath;+ }+ }+ if (dialog.ShowDialog(this) != DialogResult.OK)+ {+ return;+ }+ Bitmap image;+ try+ {+ image = Form1.LoadImageCopy(dialog.FileName);+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The file could not be read as an image:\r\n\r\n" + ex.Message, "Scene image", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ return;+ }+ this.ReplaceSceneImage(image);+ string imagePath = dialog.FileName;+ if (this._project != null && !Form1.IsInsideFolder(imagePath, this._project.FolderPath))+ {+ imagePath = Form1.CopyIntoSceneImageFolder(this._project, imagePath);+ }+ this._scene.ImageFile = SceneSettings.ToStoredPath(projectFolder, imagePath);+ this._scene.UseImage = true;+ }+ this._loadingScene = true;+ try+ {+ this.radUseSceneImage.Checked = true;+ }+ finally+ {+ this._loadingScene = false;+ }+ this.UpdateSceneControlState();+ this.UpdateScenePreview();+ this.ShowDampingValidity();+ this.MarkProjectChanged();+ }++ /// <summary>+ /// Typing a user-defined width or height (8..16384) stores it, refreshes the preview and damping+ /// validation and marks the project changed; invalid text turns the box red and shows a tooltip+ /// without changing the stored value.+ /// </summary>+ private void CanvasSize_TextChanged(object sender, EventArgs e)+ {+ if (this._loadingScene)+ {+ return;+ }+ TextBox box = (TextBox)sender;+ int size = 0;+ if (Form1.TryParseInt(box.Text, 8, 16384, ref size))+ {+ box.ForeColor = SystemColors.WindowText;+ this._sceneTip.Hide(box);+ if (object.ReferenceEquals(box, this.txtXSize))+ {+ this._scene.UserWidth = size;+ }+ else+ {+ this._scene.UserHeight = size;+ }+ this.UpdateScenePreview();+ this.ShowDampingValidity();+ this.MarkProjectChanged();+ }+ else+ {+ box.ForeColor = Color.Red;+ this._sceneTip.Show("Enter a whole number of pixels from 8 to 16384.", box, 0, box.Height + 2, 3000);+ }+ }++ /// <summary>Stores the damping-edge on/off flag, enables or disables the size box and marks the project changed.</summary>+ private void chkDampingEdge_CheckedChanged(object sender, EventArgs e)+ {+ if (this._loadingScene)+ {+ return;+ }+ this._scene.DampingEdgeEnabled = this.chkDampingEdge.Checked;+ this.UpdateSceneControlState();+ this.MarkProjectChanged();+ }++ /// <summary>+ /// Stores the damping-edge size when <see cref="DampingProblem"/> accepts the text and marks the+ /// project changed; otherwise turns the box red and shows the problem as a tooltip.+ /// </summary>+ private void DampingSize_TextChanged(object sender, EventArgs e)+ {+ if (this._loadingScene)+ {+ return;+ }+ int value = 0;+ string problem = this.DampingProblem(this.txtDampingEdgeSize.Text, ref value);+ if (problem.Length == 0)+ {+ this._scene.DampingEdgeSize = value;+ this.txtDampingEdgeSize.ForeColor = SystemColors.WindowText;+ this._sceneTip.Hide(this.txtDampingEdgeSize);+ this.MarkProjectChanged();+ }+ else+ {+ this.txtDampingEdgeSize.ForeColor = Color.Red;+ this._sceneTip.Show(problem, this.txtDampingEdgeSize, 0, this.txtDampingEdgeSize.Height + 2, 3000);+ }+ }++ /// <summary>+ /// Leaving a canvas-size or damping-size text box restores the last accepted value from+ /// <c>_scene</c> (under <c>_loadingScene</c> so no change handler runs), resets the text colour+ /// and re-validates the damping edge.+ /// </summary>+ private void SceneText_Leave(object sender, EventArgs e)+ {+ TextBox box = (TextBox)sender;+ this._sceneTip.Hide(box);+ this._loadingScene = true;+ try+ {+ if (object.ReferenceEquals(box, this.txtXSize))+ {+ box.Text = this._scene.UserWidth.ToString(CultureInfo.InvariantCulture);+ }+ else if (object.ReferenceEquals(box, this.txtYsize))+ {+ box.Text = this._scene.UserHeight.ToString(CultureInfo.InvariantCulture);+ }+ else+ {+ box.Text = this._scene.DampingEdgeSize.ToString(CultureInfo.InvariantCulture);+ }+ box.ForeColor = SystemColors.WindowText;+ }+ finally+ {+ this._loadingScene = false;+ }+ this.ShowDampingValidity();+ }++ /// <summary>Stores whether green pixels of the scene image act as sources, enables or disables the scale box and marks the project changed.</summary>+ private void chkUseSources_CheckedChanged(object sender, EventArgs e)+ {+ if (this._loadingScene)+ {+ return;+ }+ this._scene.UseSources = this.chkUseImageSources.Checked;+ this.UpdateSceneControlState();+ this.MarkProjectChanged();+ }++ /// <summary>Stores whether the object sources from the source list are used and marks the project changed.</summary>+ private void chkUseObjectSources_CheckedChanged(object sender, EventArgs e)+ {+ if (this._loadingScene)+ {+ return;+ }+ this._scene.UseObjectSources = this.chkUseObjectSources.Checked;+ this.MarkProjectChanged();+ }++ /// <summary>Stores the image-source intensity scale (0..1000) and marks the project changed.</summary>+ private void ImageSourceScale_ValueChanged(object sender, EventArgs e)+ {+ if (this._loadingScene)+ {+ return;+ }+ this._scene.ImageSourceScale = Convert.ToDouble(this.numScaleImageSource.Value);+ this.MarkProjectChanged();+ }++ /// <summary>Stores the background refractive index of the user-defined (empty) scene and marks the project changed.</summary>+ private void RefractiveIndex_ValueChanged(object sender, EventArgs e)+ {+ if (this._loadingScene)+ {+ return;+ }+ this._scene.BackgroundRefractiveIndex = Convert.ToDouble(this.numRefractiveIndex.Value);+ this.MarkProjectChanged();+ }++ /// <summary>+ /// Converts <paramref name="value"/> to a decimal clamped to the <see cref="NumericUpDown.Minimum"/>..+ /// <see cref="NumericUpDown.Maximum"/> range of <paramref name="box"/>, so that assigning it to+ /// <see cref="NumericUpDown.Value"/> cannot throw. Used by all tabs when loading settings.+ /// </summary>+ private static decimal ClampToRange(NumericUpDown box, double value)+ {+ return (value < Convert.ToDouble(box.Minimum)) ? box.Minimum : ((value > Convert.ToDouble(box.Maximum)) ? box.Maximum : new decimal(value));+ }++ /// <summary>Jumps to the source list tab.</summary>+ private void btnEditSourceList_Click(object sender, EventArgs e)+ {+ this.tabMainFunctions.SelectedTab = this.tabSourceList;+ }+ }+}diff --git a/Wave_Dude_2D/Form1.Simulation.cs b/Wave_Dude_2D/Form1.Simulation.csnew file mode 100644index 0000000..3c7098f--- /dev/null+++ b/Wave_Dude_2D/Form1.Simulation.cs@@ -0,0 +1,1368 @@+using System;+using System.Collections.Generic;+using System.Diagnostics;+using System.Drawing;+using System.Drawing.Imaging;+using System.Globalization;+using System.IO;+using System.Reflection;+using System.Runtime.InteropServices;+using System.Threading;+using System.Windows.Forms;++namespace _2D_wave_sim_V01+{+ public partial class Form1+ {+ /// <summary>+ /// Called once from <c>Form1_Load</c>: sets the ranges of the simulation NumericUpDowns (the viewer-tab scaling boxes copy+ /// the configuration-tab ones), creates the four black preview boxes and puts the buttons, labels and status bar in their idle state.+ /// </summary>+ private void InitializeSimulationControls()+ {+ this.numVisualizeEvery.Minimum = 1m;+ this.numFieldScaling.Minimum = 0.1m;+ this.numFieldScaling.Maximum = 1000m;+ this.numIntensityScaling.Minimum = 0.1m;+ this.numIntensityScaling.Maximum = 1000m;+ this.numFieldScaling2.Minimum = this.numFieldScaling.Minimum;+ this.numFieldScaling2.Maximum = this.numFieldScaling.Maximum;+ this.numFieldScaling2.DecimalPlaces = this.numFieldScaling.DecimalPlaces;+ this.numFieldScaling2.Increment = this.numFieldScaling.Increment;+ this.numIntensityScaling2.Minimum = this.numIntensityScaling.Minimum;+ this.numIntensityScaling2.Maximum = this.numIntensityScaling.Maximum;+ this.numIntensityScaling2.DecimalPlaces = this.numIntensityScaling.DecimalPlaces;+ this.numIntensityScaling2.Increment = this.numIntensityScaling.Increment;+ foreach (NumericUpDown offsetBox in new NumericUpDown[] { this.numOffsetField, this.numOffsetIntensity })+ {+ offsetBox.DecimalPlaces = 2;+ offsetBox.Minimum = -1m;+ offsetBox.Maximum = 1m;+ offsetBox.Increment = 0.01m;+ }+ this.numQuality.Minimum = 1m;+ this.numQuality.Maximum = 100m;+ this.numQuality.DecimalPlaces = 0;+ this.StatusStrip1.ShowItemToolTips = true;+ this.ToolStripStatusLabel1.Spring = true;+ this.ToolStripStatusLabel1.TextAlign = ContentAlignment.MiddleLeft;+ this.ToolStripStatusLabel1.Text = "";+ this.UpdateRunButtons();+ this.btnViewIntensityVideo.Text = "View intensity video in media player";+ this.UpdateVideoButtons();+ this.cmbFieldColorScheme.DropDownStyle = ComboBoxStyle.DropDownList;+ this.cmbIntensityColorScheme.DropDownStyle = ComboBoxStyle.DropDownList;+ this._picField = Form1.MakePreviewBox(this.pnlPreviewField);+ this._picIntensity = Form1.MakePreviewBox(this.pnlPreviewIntensity);+ this._picSource = Form1.MakePreviewBox(this.pnlSourceImage);+ this._picProbe = Form1.MakePreviewBox(this.pnlProbeImage);+ this.UpdateCopyButtons();+ this.lblWarningField.Text = "Field video not exported";+ this.lblWarningField.ForeColor = Color.DarkBlue;+ this.lblWarningIntensity.Text = "Intensity video not exported";+ this.lblWarningIntensity.ForeColor = Color.DarkBlue;+ }++ /// <summary>Creates a black, zoom-to-fit <see cref="PictureBox"/> that fills <paramref name="host"/>.</summary>+ private static PictureBox MakePreviewBox(Panel host)+ {+ host.BackColor = Color.Black;+ PictureBox pictureBox = new PictureBox();+ pictureBox.Dock = DockStyle.Fill;+ pictureBox.SizeMode = PictureBoxSizeMode.Zoom;+ pictureBox.BackColor = Color.Black;+ host.Controls.Add(pictureBox);+ return pictureBox;+ }++ /// <summary>+ /// Copies <c>_simulation</c> into the controls, clamping every value to its box's range (the clamped+ /// <c>VisualizeEvery</c> is written back into the settings). <c>_loadingSim</c> is set meanwhile so the+ /// ValueChanged handlers neither write back nor mark the project dirty.+ /// </summary>+ private void ShowSimulationInControls()+ {+ this._loadingSim = true;+ try+ {+ int visualizeEvery = Math.Max(Convert.ToInt32(this.numVisualizeEvery.Minimum), Math.Min(Convert.ToInt32(this.numVisualizeEvery.Maximum), this._simulation.VisualizeEvery));+ this._simulation.VisualizeEvery = visualizeEvery;+ this.numSimulationSteps.Value = Form1.ClampToRange(this.numSimulationSteps, this._simulation.Steps);+ this.numVisualizeEvery.Value = visualizeEvery;+ this.numFieldScaling.Value = Form1.ClampToRange(this.numFieldScaling, this._simulation.FieldBrightness);+ this.numIntensityScaling.Value = Form1.ClampToRange(this.numIntensityScaling, this._simulation.IntensityBrightness);+ this.numFieldScaling2.Value = Form1.ClampToRange(this.numFieldScaling2, this._simulation.FieldBrightness);+ this.numIntensityScaling2.Value = Form1.ClampToRange(this.numIntensityScaling2, this._simulation.IntensityBrightness);+ this.numQuality.Value = Form1.ClampToRange(this.numQuality, this._simulation.VideoQuality);+ this.numOffsetField.Value = Form1.ClampToRange(this.numOffsetField, this._simulation.FieldBlackLevel);+ this.numOffsetIntensity.Value = Form1.ClampToRange(this.numOffsetIntensity, this._simulation.IntensityBlackLevel);+ this.numTimeDecayFactor.Value = Form1.ClampToRange(this.numTimeDecayFactor, this._simulation.TimeDecayFactor);+ this.chkExportVideoField.Checked = this._simulation.ExportField;+ this.chkExportVideoIntensity.Checked = this._simulation.ExportIntensity;+ this.chkExportVideoField2.Checked = this._simulation.ExportField;+ this.chkExportVideoIntensity2.Checked = this._simulation.ExportIntensity;+ this.chkPreviewVideoField.Checked = this._simulation.PreviewField;+ this.chkPreviewVideoIntensity.Checked = this._simulation.PreviewIntensity;+ this.chkUseGPU.Checked = this._simulation.UseGpu;+ this.chkUse4thOrderLaplacian.Checked = this._simulation.Use4thOrderLaplacian;+ this.FillSchemeCombo(this.cmbFieldColorScheme, "field", this._simulation.FieldColorScheme);+ this.FillSchemeCombo(this.cmbIntensityColorScheme, "intensity", this._simulation.IntensityColorScheme);+ }+ finally+ {+ this._loadingSim = false;+ }+ this.UpdateSimulationControlState();+ }++ /// <summary>Enables the scheme combos, the quality box and the "not exported" warnings according to the export / preview check boxes.</summary>+ private void UpdateSimulationControlState()+ {+ this.cmbFieldColorScheme.Enabled = this.chkExportVideoField.Checked || this.chkPreviewVideoField.Checked;+ this.cmbIntensityColorScheme.Enabled = this.chkExportVideoIntensity.Checked || this.chkPreviewVideoIntensity.Checked;+ bool exporting = this.chkExportVideoField.Checked || this.chkExportVideoIntensity.Checked;+ this.numQuality.Enabled = exporting;+ this.lblVideoQuality.Enabled = exporting;+ this.lblWarningField.Visible = !this.chkExportVideoField.Checked;+ this.lblWarningIntensity.Visible = !this.chkExportVideoIntensity.Checked;+ }++ /// <summary>+ /// Refills both scheme combos from <c>_schemes</c> (after the scheme list was reloaded) keeping the stored selections,+ /// without dirtying the project. Saves and restores <c>_loadingSim</c> so it can be called while a load is in progress.+ /// </summary>+ private void RefreshSchemeCombos()+ {+ bool loadingSim = this._loadingSim;+ this._loadingSim = true;+ try+ {+ this.FillSchemeCombo(this.cmbFieldColorScheme, "field", this._simulation.FieldColorScheme);+ this.FillSchemeCombo(this.cmbIntensityColorScheme, "intensity", this._simulation.IntensityColorScheme);+ }+ finally+ {+ this._loadingSim = loadingSim;+ }+ }++ /// <summary>Fills <paramref name="combo"/> with the schemes of one type and selects the one named <paramref name="selectedName"/> (case-insensitive), or nothing.</summary>+ /// <param name="combo">The field or intensity scheme combo; its items become <see cref="ColorScheme"/> objects.</param>+ /// <param name="schemeType">"field" or "intensity".</param>+ /// <param name="selectedName">Name of the scheme to select; no selection when it is not in the list.</param>+ private void FillSchemeCombo(ComboBox combo, string schemeType, string selectedName)+ {+ combo.BeginUpdate();+ try+ {+ combo.Items.Clear();+ ColorScheme selected = null;+ foreach (ColorScheme scheme in this._schemes)+ {+ if (string.Equals(scheme.SchemeType, schemeType, StringComparison.OrdinalIgnoreCase))+ {+ combo.Items.Add(scheme);+ if (string.Equals(scheme.Name, selectedName, StringComparison.OrdinalIgnoreCase))+ {+ selected = scheme;+ }+ }+ }+ if (selected != null)+ {+ combo.SelectedItem = selected;+ }+ else+ {+ combo.SelectedIndex = -1;+ }+ }+ finally+ {+ combo.EndUpdate();+ }+ }++ /// <summary>Looks up a loaded scheme by name and type (both case-insensitive).</summary>+ /// <returns>The scheme, or null when no such scheme is loaded.</returns>+ private ColorScheme FindScheme(string name, string schemeType)+ {+ foreach (ColorScheme scheme in this._schemes)+ {+ if (string.Equals(scheme.Name, name, StringComparison.OrdinalIgnoreCase) && string.Equals(scheme.SchemeType, schemeType, StringComparison.OrdinalIgnoreCase))+ {+ return scheme;+ }+ }+ return null;+ }++ /// <summary>+ /// Switching to the Configuration tab reloads the scheme list from the scheme folder (or just refills the combos when the+ /// folder does not exist); switching to the Output tab refreshes its project list, preferring the current project.+ /// </summary>+ private void tabMainFunctions_SelectedIndexChanged(object sender, EventArgs e)+ {+ if (this.tabMainFunctions.SelectedTab == this.tabConfiguration)+ {+ string schemeFolder = this.txtSchemeFolder.Text.Trim();+ if (Directory.Exists(schemeFolder))+ {+ this.LoadSchemeList();+ }+ else+ {+ this.RefreshSchemeCombos();+ }+ }+ if (this.tabMainFunctions.SelectedTab == this.tabOutput)+ {+ this.RefreshOutputProjectList((this._project != null) ? this._project.Name : "");+ }+ }++ /// <summary>Stores the number of steps and marks the project dirty.</summary>+ private void numSimulationSteps_ValueChanged(object sender, EventArgs e)+ {+ if (!this._loadingSim)+ {+ this._simulation.Steps = Convert.ToInt32(this.numSimulationSteps.Value);+ this.MarkProjectChanged();+ }+ }++ /// <summary>Stores how many steps go by between two rendered frames.</summary>+ private void numVisualizeEvery_ValueChanged(object sender, EventArgs e)+ {+ if (!this._loadingSim)+ {+ this._simulation.VisualizeEvery = Convert.ToInt32(this.numVisualizeEvery.Value);+ this.MarkProjectChanged();+ }+ }++ /// <summary>Mirrors a scaling value into the linked box on the other tab without raising the change handlers.</summary>+ private void SetLinkedScalingValue(NumericUpDown box, decimal value)+ {+ decimal clamped = (value < box.Minimum) ? box.Minimum : ((value > box.Maximum) ? box.Maximum : value);+ if (box.Value != clamped)+ {+ bool loadingSim = this._loadingSim;+ this._loadingSim = true;+ try+ {+ box.Value = clamped;+ }+ finally+ {+ this._loadingSim = loadingSim;+ }+ }+ }++ /// <summary>Mirrors a check state into the linked box on the other tab without raising its CheckedChanged handler.</summary>+ private void SetLinkedCheckedValue(CheckBox box, bool value)+ {+ if (box.Checked != value)+ {+ bool loadingSim = this._loadingSim;+ this._loadingSim = true;+ try+ {+ box.Checked = value;+ }+ finally+ {+ this._loadingSim = loadingSim;+ }+ }+ }++ /// <summary>Stores the field brightness and mirrors it into the viewer-tab box.</summary>+ private void numScaleFieldValues_ValueChanged(object sender, EventArgs e)+ {+ if (!this._loadingSim)+ {+ this._simulation.FieldBrightness = Convert.ToDouble(this.numFieldScaling.Value);+ this.SetLinkedScalingValue(this.numFieldScaling2, this.numFieldScaling.Value);+ this.MarkProjectChanged();+ }+ }++ /// <summary>Viewer-tab copy: stores the field brightness and mirrors it back into the configuration-tab box.</summary>+ private void numScaleFieldValues2_ValueChanged(object sender, EventArgs e)+ {+ if (!this._loadingSim)+ {+ this._simulation.FieldBrightness = Convert.ToDouble(this.numFieldScaling2.Value);+ this.SetLinkedScalingValue(this.numFieldScaling, this.numFieldScaling2.Value);+ this.MarkProjectChanged();+ }+ }++ /// <summary>Stores the video quality (1..100).</summary>+ private void numQuality_ValueChanged(object sender, EventArgs e)+ {+ if (!this._loadingSim)+ {+ this._simulation.VideoQuality = Convert.ToInt32(this.numQuality.Value);+ this.MarkProjectChanged();+ }+ }++ /// <summary>Stores the field black level (-1..1 palette offset).</summary>+ private void numOffsetField_ValueChanged(object sender, EventArgs e)+ {+ if (!this._loadingSim)+ {+ this._simulation.FieldBlackLevel = Convert.ToDouble(this.numOffsetField.Value);+ this.MarkProjectChanged();+ }+ }++ /// <summary>Stores the intensity black level (-1..1 palette offset).</summary>+ private void numOffsetIntensity_ValueChanged(object sender, EventArgs e)+ {+ if (!this._loadingSim)+ {+ this._simulation.IntensityBlackLevel = Convert.ToDouble(this.numOffsetIntensity.Value);+ this.MarkProjectChanged();+ }+ }++ /// <summary>Stores the time decay factor.</summary>+ private void numTimeDecayFactor_ValueChanged(object sender, EventArgs e)+ {+ if (!this._loadingSim)+ {+ this._simulation.TimeDecayFactor = Convert.ToDouble(this.numTimeDecayFactor.Value);+ this.MarkProjectChanged();+ }+ }++ /// <summary>Stores the intensity brightness and mirrors it into the viewer-tab box.</summary>+ private void numScaleIntensity_ValueChanged(object sender, EventArgs e)+ {+ if (!this._loadingSim)+ {+ this._simulation.IntensityBrightness = Convert.ToDouble(this.numIntensityScaling.Value);+ this.SetLinkedScalingValue(this.numIntensityScaling2, this.numIntensityScaling.Value);+ this.MarkProjectChanged();+ }+ }++ /// <summary>Viewer-tab copy: stores the intensity brightness and mirrors it back into the configuration-tab box.</summary>+ private void numScaleIntensity2_ValueChanged(object sender, EventArgs e)+ {+ if (!this._loadingSim)+ {+ this._simulation.IntensityBrightness = Convert.ToDouble(this.numIntensityScaling2.Value);+ this.SetLinkedScalingValue(this.numIntensityScaling, this.numIntensityScaling2.Value);+ this.MarkProjectChanged();+ }+ }++ /// <summary>+ /// Shared handler of the four export / preview boxes on the configuration tab: stores all four flags, mirrors the two+ /// export flags into the viewer tab and updates the dependent controls.+ /// </summary>+ private void SimulationOption_CheckedChanged(object sender, EventArgs e)+ {+ if (!this._loadingSim)+ {+ this._simulation.ExportField = this.chkExportVideoField.Checked;+ this._simulation.ExportIntensity = this.chkExportVideoIntensity.Checked;+ this._simulation.PreviewField = this.chkPreviewVideoField.Checked;+ this._simulation.PreviewIntensity = this.chkPreviewVideoIntensity.Checked;+ this.SetLinkedCheckedValue(this.chkExportVideoField2, this.chkExportVideoField.Checked);+ this.SetLinkedCheckedValue(this.chkExportVideoIntensity2, this.chkExportVideoIntensity.Checked);+ this.UpdateSimulationControlState();+ this.MarkProjectChanged();+ }+ }++ /// <summary>Viewer-tab copy of the field export box: stores the flag and mirrors it back.</summary>+ private void chkExportVideoField2_CheckedChanged(object sender, EventArgs e)+ {+ if (!this._loadingSim)+ {+ this._simulation.ExportField = this.chkExportVideoField2.Checked;+ this.SetLinkedCheckedValue(this.chkExportVideoField, this.chkExportVideoField2.Checked);+ this.UpdateSimulationControlState();+ this.MarkProjectChanged();+ }+ }++ /// <summary>Viewer-tab copy of the intensity export box: stores the flag and mirrors it back.</summary>+ private void chkExportVideoIntensity2_CheckedChanged(object sender, EventArgs e)+ {+ if (!this._loadingSim)+ {+ this._simulation.ExportIntensity = this.chkExportVideoIntensity2.Checked;+ this.SetLinkedCheckedValue(this.chkExportVideoIntensity, this.chkExportVideoIntensity2.Checked);+ this.UpdateSimulationControlState();+ this.MarkProjectChanged();+ }+ }++ /// <summary>Stores whether the OpenCL engine is tried first.</summary>+ private void chkUseGPU_CheckedChanged(object sender, EventArgs e)+ {+ if (!this._loadingSim)+ {+ this._simulation.UseGpu = this.chkUseGPU.Checked;+ this.MarkProjectChanged();+ }+ }++ /// <summary>Stores the Laplacian order choice.</summary>+ private void chkUse4thOrderLaplacian_CheckedChanged(object sender, EventArgs e)+ {+ if (!this._loadingSim)+ {+ this._simulation.Use4thOrderLaplacian = this.chkUse4thOrderLaplacian.Checked;+ this.MarkProjectChanged();+ }+ }++ /// <summary>Shared handler of both scheme combos: stores the chosen scheme name in the field or intensity setting, depending on which combo raised it.</summary>+ private void SchemeCombo_SelectedIndexChanged(object sender, EventArgs e)+ {+ if (this._loadingSim)+ {+ return;+ }+ ComboBox combo = (ComboBox)sender;+ ColorScheme scheme = combo.SelectedItem as ColorScheme;+ if (scheme == null)+ {+ return;+ }+ if (combo == this.cmbFieldColorScheme)+ {+ this._simulation.FieldColorScheme = scheme.Name;+ }+ else+ {+ this._simulation.IntensityColorScheme = scheme.Name;+ }+ this.MarkProjectChanged();+ }++ /// <summary>Starts a run, or asks the running one to stop (the button doubles as Stop while a run is active).</summary>+ private void btnStartSimulation_Click(object sender, EventArgs e)+ {+ if (this._runner != null)+ {+ this.RequestStop();+ }+ else+ {+ this.StartSimulation();+ }+ }++ /// <summary>Loads the scene image into the Sources and Probes picture boxes.</summary>+ private void btnShareSceneImage_Click(object sender, EventArgs e)+ {+ this.ImportSceneImageInto(this._picSource);+ this.ImportSceneImageInto(this._picProbe);+ }++ /// <summary>Copies the field preview into the Sources and Probes picture boxes.</summary>+ private void btnShareFieldImage_Click(object sender, EventArgs e)+ {+ this.CopyPreviewToTabs(this._picField);+ }++ /// <summary>Copies the intensity preview into the Sources and Probes picture boxes.</summary>+ private void btnShareIntensityImage_Click(object sender, EventArgs e)+ {+ this.CopyPreviewToTabs(this._picIntensity);+ }++ /// <summary>Gives <c>_picSource</c> and <c>_picProbe</c> each their own copy of the image in <paramref name="source"/>, disposing what they showed before. Does nothing when there is no image.</summary>+ private void CopyPreviewToTabs(PictureBox source)+ {+ Image image = source.Image;+ if (image == null)+ {+ return;+ }+ foreach (PictureBox target in new PictureBox[] { this._picSource, this._picProbe })+ {+ Bitmap copy = new Bitmap(image);+ Image previous = target.Image;+ target.Image = copy;+ if (previous != null)+ {+ previous.Dispose();+ }+ }+ }++ /// <summary>Enables the share buttons when the matching preview box has an image; also refreshes the export buttons.</summary>+ private void UpdateCopyButtons()+ {+ this.btnShareFieldImage.Enabled = this._picField != null && this._picField.Image != null;+ this.btnShareIntensityImage.Enabled = this._picIntensity != null && this._picIntensity.Image != null;+ this.UpdateExportButtons();+ }++ /// <summary>Enables the frame export buttons when no run is active or it is paused, and a full-size or preview frame exists to export.</summary>+ private void UpdateExportButtons()+ {+ bool canExport = this._paused || this._runner == null;+ this.btnExportFieldFrame.Enabled = canExport && (this._lastFullFieldFrame != null || (this._picField != null && this._picField.Image != null));+ this.btnExportIntensityFrame.Enabled = canExport && (this._lastFullIntensityFrame != null || (this._picIntensity != null && this._picIntensity.Image != null));+ }++ /// <summary>+ /// Toggles pause: blocks or releases the runner's gate, switches the status texts and shows the viewer tab on resume.+ /// Ignored when nothing runs or a stop is already pending.+ /// </summary>+ private void btnPauzeResume_Click(object sender, EventArgs e)+ {+ if (this._runner == null || this._stopRequested)+ {+ return;+ }+ if (this._paused)+ {+ this._paused = false;+ this._simStatus = this._progressText;+ this.ToolStripStatusLabel1.Text = "Simulation running...";+ this._runner.ResumeRun();+ this.tabMainFunctions.SelectedTab = this.tabViewer;+ }+ else+ {+ this._paused = true;+ this._simStatus = "paused - " + this._progressText;+ this.ToolStripStatusLabel1.Text = "Simulation paused (press Resume to continue, or Stop to finish and save the videos)";+ this._runner.PauseRun();+ }+ this.UpdateRunButtons();+ this.UpdateTitle();+ }++ /// <summary>Shows the Configuration tab.</summary>+ private void btnGotoConfiguration_Click(object sender, EventArgs e)+ {+ this.tabMainFunctions.SelectedTab = this.tabConfiguration;+ }++ /// <summary>Shows the Sources tab.</summary>+ private void btnGotoSources_Click(object sender, EventArgs e)+ {+ this.tabMainFunctions.SelectedTab = this.tabSourceList;+ }++ /// <summary>Shows the Probes tab.</summary>+ private void btnGotoProbes_Click(object sender, EventArgs e)+ {+ this.tabMainFunctions.SelectedTab = this.tabProbeList;+ }++ /// <summary>Shows the viewer tab.</summary>+ private void btnGotoPreview_Click(object sender, EventArgs e)+ {+ this.tabMainFunctions.SelectedTab = this.tabViewer;+ }++ /// <summary>+ /// Asks the runner to cancel (it finishes the current step, closes the video files and raises <c>Finished</c>) and puts the+ /// UI into the "stopping" state; the Start button is disabled until <see cref="OnSimulationFinished"/> re-enables it.+ /// </summary>+ private void RequestStop()+ {+ if (this._runner == null || this._stopRequested)+ {+ return;+ }+ this._stopRequested = true;+ this._paused = false;+ this._runner.Cancel();+ this.btnStartSimulation.Enabled = false;+ this.btnStartSimulation.Text = "Stopping...";+ this._simStatus = "stopping...";+ this.ToolStripStatusLabel1.Text = "Stopping the simulation and closing the video files...";+ this.UpdateRunButtons();+ this.UpdateTitle();+ }++ /// <summary>Greys the pause button when it cannot be used, sets its Pause / Resume caption and refreshes the export buttons.</summary>+ private void UpdateRunButtons()+ {+ bool canPause = this._runner != null && !this._stopRequested;+ this.btnPauzeResume.ForeColor = (canPause ? SystemColors.ControlText : Color.Gray);+ this.btnPauzeResume.Text = (this._paused ? "Resume simulation" : "Pause simulation");+ this.UpdateExportButtons();+ }++ /// <summary>Shows <paramref name="message"/> in a "Start simulation" message box.</summary>+ private void ShowSimulationProblem(string message)+ {+ MessageBox.Show(this, message, "Start simulation", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ }++ /// <summary>+ /// Validates every simulation control and copies it into <c>_simulation</c> (and the image source scale into+ /// <c>_scene</c>) just before a run, regardless of <c>_loadingSim</c>.+ /// </summary>+ private void ReadSimulationControls()+ {+ this.numVisualizeEvery.Validate();+ this.numFieldScaling.Validate();+ this.numIntensityScaling.Validate();+ this.numFieldScaling2.Validate();+ this.numIntensityScaling2.Validate();+ this.numOffsetField.Validate();+ this.numOffsetIntensity.Validate();+ this.numQuality.Validate();+ this.numScaleImageSource.Validate();+ this.numTimeDecayFactor.Validate();+ this._simulation.VisualizeEvery = Convert.ToInt32(this.numVisualizeEvery.Value);+ this._simulation.FieldBrightness = Convert.ToDouble(this.numFieldScaling.Value);+ this._simulation.IntensityBrightness = Convert.ToDouble(this.numIntensityScaling.Value);+ this._simulation.FieldBlackLevel = Convert.ToDouble(this.numOffsetField.Value);+ this._simulation.IntensityBlackLevel = Convert.ToDouble(this.numOffsetIntensity.Value);+ this._simulation.VideoQuality = Convert.ToInt32(this.numQuality.Value);+ this._simulation.TimeDecayFactor = Convert.ToDouble(this.numTimeDecayFactor.Value);+ this._simulation.ExportField = this.chkExportVideoField.Checked;+ this._simulation.ExportIntensity = this.chkExportVideoIntensity.Checked;+ this._simulation.PreviewField = this.chkPreviewVideoField.Checked;+ this._simulation.PreviewIntensity = this.chkPreviewVideoIntensity.Checked;+ this._simulation.UseGpu = this.chkUseGPU.Checked;+ this._simulation.Use4thOrderLaplacian = this.chkUse4thOrderLaplacian.Checked;+ this._scene.ImageSourceScale = Convert.ToDouble(this.numScaleImageSource.Value);+ }++ /// <summary>+ /// UI thread. Validates the scene and settings (asks to save the project first when exporting, warns when the scene has no+ /// sources), builds a <see cref="SimulationJob"/> with cloned settings, palettes, probes, sources and numbered output file+ /// names, wires every <see cref="SimulationRunner"/> event through <see cref="PostToUi"/> and starts the worker thread.+ /// </summary>+ private void StartSimulation()+ {+ this.ReadSimulationControls();+ SimulationSettings settings = this._simulation;+ bool wantField = settings.ExportField || settings.PreviewField;+ bool wantIntensity = settings.ExportIntensity || settings.PreviewIntensity;+ bool exporting = settings.ExportField || settings.ExportIntensity;+ bool previewing = settings.PreviewField || settings.PreviewIntensity;+ if (!wantField && !wantIntensity)+ {+ this.ShowSimulationProblem("Nothing to do: tick at least one of the export or preview options.");+ return;+ }+ settings.Steps = Convert.ToInt32(this.numSimulationSteps.Value);+ if (exporting && this._project == null)+ {+ DialogResult saveAnswer = MessageBox.Show(this, "The videos are saved in the output folder of the project, so the project must be saved first.\r\n\r\nSave the project now?", "Start simulation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);+ if (saveAnswer != DialogResult.Yes)+ {+ return;+ }+ if (!this.SaveProject())+ {+ return;+ }+ // Saving replaces _simulation (SetCurrentProject reloads it from the config), so re-fetch it.+ settings = this._simulation;+ }+ Size canvas = this.EffectiveCanvas();+ if (canvas.Width <= 0)+ {+ this.ShowSimulationProblem("There is no scene yet: load a scene image in the Scene properties, or define a canvas size.");+ return;+ }+ int dampingEdge = 0;+ if (this._scene.DampingEdgeEnabled)+ {+ string dampingProblem = this.DampingProblem(this.txtDampingEdgeSize.Text, ref dampingEdge);+ if (dampingProblem.Length > 0)+ {+ this.ShowSimulationProblem("The damping edge cannot be used: " + dampingProblem);+ this.txtDampingEdgeSize.Focus();+ return;+ }+ }+ bool useSources = this._scene.UseSources;+ bool hasImageSources = this._scene.UseImage && useSources && SceneData.CountSources(this._sceneImage) > 0;+ bool hasObjectSources = this._scene.UseObjectSources && this._sources.Count > 0;+ string noSourcesWarning = "";+ if (!hasImageSources && !hasObjectSources)+ {+ List<string> reasons = new List<string>();+ if (this._scene.UseImage)+ {+ if (!useSources)+ {+ reasons.Add("image sources are switched off in the Scene properties");+ }+ else if (SceneData.CountSources(this._sceneImage) == 0)+ {+ reasons.Add("the scene image has no sources (no pixels with a green value above 0)");+ }+ }+ if (!this._scene.UseObjectSources)+ {+ reasons.Add("object sources are switched off in the Scene properties");+ }+ else if (this._sources.Count == 0)+ {+ reasons.Add("there are no object sources yet (add one on the Sources tab)");+ }+ noSourcesWarning = "This scene has no sources yet: " + string.Join("; ", reasons) + ". The field will stay empty.";+ }+ if (noSourcesWarning.Length > 0)+ {+ DialogResult runAnyway = MessageBox.Show(this, noSourcesWarning + "\r\n\r\nRun the simulation anyway?", "Start simulation", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);+ if (runAnyway != DialogResult.Yes)+ {+ return;+ }+ }+ int[] fieldLut = null;+ int[] intensityLut = null;+ if (wantField)+ {+ ColorScheme fieldScheme = this.FindScheme(settings.FieldColorScheme, "field");+ if (fieldScheme == null)+ {+ this.ShowSimulationProblem("Choose a color scheme for the field first.");+ this.cmbFieldColorScheme.Focus();+ return;+ }+ fieldLut = ColorLut.Build(fieldScheme, false, settings.FieldBlackLevel, false, false).Argb;+ }+ if (wantIntensity)+ {+ ColorScheme intensityScheme = this.FindScheme(settings.IntensityColorScheme, "intensity");+ if (intensityScheme == null)+ {+ this.ShowSimulationProblem("Choose a color scheme for the intensity first.");+ this.cmbIntensityColorScheme.Focus();+ return;+ }+ intensityLut = ColorLut.Build(intensityScheme, false, settings.IntensityBlackLevel, false, false).Argb;+ }+ SimulationJob job = new SimulationJob();+ if (this._scene.UseImage)+ {+ job.Image = new Bitmap(this._sceneImage);+ }+ else+ {+ job.Width = canvas.Width;+ job.Height = canvas.Height;+ job.BackgroundRefractiveIndex = this._scene.BackgroundRefractiveIndex;+ }+ job.UseSources = useSources;+ job.SourceAmplitude = this._scene.ImageSourceScale;+ job.DampingEdge = dampingEdge;+ job.Settings = settings.Clone();+ job.FieldLut = fieldLut;+ job.IntensityLut = intensityLut;+ this._lastFieldLut = fieldLut;+ this._lastIntensityLut = intensityLut;+ job.PreviewWidth = Math.Max(16, Math.Min(this.pnlPreviewField.ClientSize.Width, this.pnlPreviewIntensity.ClientSize.Width));+ job.PreviewHeight = Math.Max(16, Math.Min(this.pnlPreviewField.ClientSize.Height, this.pnlPreviewIntensity.ClientSize.Height));+ job.Probes = this.ProbesForRun();+ job.ObjectSources = this.SourcesForRun();+ job.FieldOverlayGain = this.FieldOverlayGain();+ job.IntensityOverlayGain = this.IntensityOverlayGain();+ if (exporting && this._glowEdgesImage != null && (job.FieldOverlayGain > 0.0 || job.IntensityOverlayGain > 0.0))+ {+ job.GlowOverlay = new Bitmap(this._glowEdgesImage);+ }+ if (exporting)+ {+ try+ {+ Directory.CreateDirectory(this._project.OutputVideoFolder);+ }+ catch (Exception ex)+ {+ if (job.Image != null)+ {+ job.Image.Dispose();+ }+ if (job.GlowOverlay != null)+ {+ job.GlowOverlay.Dispose();+ }+ this.ShowSimulationProblem("The output folder could not be created:\r\n" + this._project.OutputVideoFolder + "\r\n\r\n" + ex.Message);+ return;+ }+ string suffix = this.NextNumericSuffix(this._project.OutputVideoFolder).ToString("D4", CultureInfo.InvariantCulture);+ if (settings.ExportField)+ {+ job.FieldVideoPath = Path.Combine(this._project.OutputVideoFolder, this._project.Name + "_field_" + suffix + ".mp4");+ }+ if (settings.ExportIntensity)+ {+ job.IntensityVideoPath = Path.Combine(this._project.OutputVideoFolder, this._project.Name + "_intensity_" + suffix + ".mp4");+ }+ }+ this.ClearPreviews();+ this.BeginProbeRun(job.Probes, canvas, settings.Steps);+ this._fieldVideoFile = "";+ this._intensityVideoFile = "";+ this.UpdateVideoButtons();+ this._runInfo = "Field: brightness " + settings.FieldBrightness.ToString("0.0#", CultureInfo.CurrentCulture)+ + ", offset " + settings.FieldBlackLevel.ToString("0.0#", CultureInfo.CurrentCulture)+ + "\r\nIntensity: brightness " + settings.IntensityBrightness.ToString("0.0#", CultureInfo.CurrentCulture)+ + ", offset " + settings.IntensityBlackLevel.ToString("0.0#", CultureInfo.CurrentCulture)+ + "\r\nImage source scale: " + this._scene.ImageSourceScale.ToString("0.0#", CultureInfo.CurrentCulture);+ if (previewing)+ {+ this.tabMainFunctions.SelectedTab = this.tabViewer;+ }+ SimulationRunner runner = new SimulationRunner(job);+ runner.ProgressChanged += (done, total) => this.PostToUi(() => this.ShowProgress(runner, done, total));+ runner.EngineReady += (description, note) => this.PostToUi(() => this.ShowEngine(runner, description, note));+ runner.ProbesUpdated += update => this.PostToUi(() => this.ShowProbeSamples(runner, update));+ runner.PreviewReady += (isField, frame) => this.PostToUi(() => this.ShowPreview(runner, isField, frame));+ runner.Finished += result => this.PostToUi(() => this.OnSimulationFinished(runner, result));+ this._runner = runner;+ this.btnStartSimulation.Text = "Stop Simulation";+ this._simStatus = "starting...";+ this._progressText = "starting...";+ this._paused = false;+ this._stopRequested = false;+ this.UpdateRunButtons();+ this.ToolStripStatusLabel1.Text = "Simulation running...";+ this.ToolStripStatusLabel1.ToolTipText = "";+ this.UpdateTitle();+ runner.Start();+ }++ /// <summary>+ /// Queues <paramref name="work"/> on the UI thread with <c>BeginInvoke</c>. Called from the runner's worker thread;+ /// the work is dropped silently when the form is disposed or its handle is gone (including the+ /// <see cref="InvalidOperationException"/> thrown while the handle is being destroyed).+ /// </summary>+ private void PostToUi(Action work)+ {+ if (base.IsDisposed || !base.IsHandleCreated)+ {+ return;+ }+ try+ {+ base.BeginInvoke(work);+ }+ catch (InvalidOperationException)+ {+ }+ }++ /// <summary>+ /// UI thread (via <see cref="PostToUi"/>): updates the progress text and window title. Ignored for a stale runner and while+ /// stopping, so "stopping..." is not overwritten by a late progress event.+ /// </summary>+ private void ShowProgress(SimulationRunner runner, int done, int total)+ {+ // A late progress event from the worker must not overwrite the "stopping..." status set by RequestStop.+ if (runner != this._runner || string.CompareOrdinal(this._simStatus, "stopping...") == 0)+ {+ return;+ }+ this._lastStepsDone = done;+ int percent = (int)(100L * done / Math.Max(1, total)); // long: 100 * steps can exceed int.MaxValue+ this._progressText = "step " + done.ToString("N0", CultureInfo.CurrentCulture) + " of " + total.ToString("N0", CultureInfo.CurrentCulture) + " (" + percent.ToString(CultureInfo.InvariantCulture) + "%)";+ this._simStatus = (this._paused ? "paused - " : "") + this._progressText;+ this.UpdateTitle();+ }++ /// <summary>UI thread (via <see cref="PostToUi"/>): shows which engine the runner picked, plus the fallback note, in the status bar.</summary>+ private void ShowEngine(SimulationRunner runner, string description, string note)+ {+ if (runner != this._runner || base.IsDisposed)+ {+ return;+ }+ string status = "Simulation running on " + description;+ if (note.Length > 0)+ {+ status = status + " - " + note;+ }+ this.ToolStripStatusLabel1.Text = status;+ this.ToolStripStatusLabel1.ToolTipText = status;+ }++ /// <summary>+ /// UI thread (via <see cref="PostToUi"/>): shows the downscaled preview frame in the field or intensity box (composed with the+ /// glow overlay when enabled) and takes ownership of <paramref name="frame"/>; a frame for a stale runner is disposed instead.+ /// Always acknowledges with <see cref="SimulationRunner.PreviewShown"/> so the worker may render the next preview.+ /// </summary>+ private void ShowPreview(SimulationRunner runner, bool isField, Bitmap frame)+ {+ if (runner != this._runner || base.IsDisposed)+ {+ frame.Dispose();+ runner.PreviewShown();+ return;+ }+ PictureBox target = (isField ? this._picField : this._picIntensity);+ double overlayGain = (isField ? this.FieldOverlayGain() : this.IntensityOverlayGain());+ this.SetPreviewFrame(target, frame, overlayGain);+ this.UpdateCopyButtons();+ runner.PreviewShown();+ }++ /// <summary>+ /// UI thread (via <see cref="PostToUi"/>): clears the runner, takes ownership of the result's full-size frames, enables the+ /// video buttons and builds the status-bar summary (steps, elapsed, steps/s, engine, files) with the details in its tooltip;+ /// a failed run is also reported in a message box.+ /// </summary>+ private void OnSimulationFinished(SimulationRunner runner, SimulationResult result)+ {+ if (runner != this._runner || base.IsDisposed)+ {+ return;+ }+ this._runner = null;+ this._hasRun = true;+ this._paused = false;+ this._stopRequested = false;+ this._lastStepsDone = result.StepsDone;+ this.UpdateRunButtons();+ this._simStatus = "";+ this.btnStartSimulation.Text = "Start Simulation";+ this.btnStartSimulation.Enabled = true;+ this.UpdateTitle();+ this._fieldVideoFile = result.FieldFile;+ this._intensityVideoFile = result.IntensityFile;+ this.UpdateVideoButtons();+ Bitmap previousFieldFrame = this._lastFullFieldFrame;+ this._lastFullFieldFrame = result.LastFieldFrame;+ if (previousFieldFrame != null)+ {+ previousFieldFrame.Dispose();+ }+ Bitmap previousIntensityFrame = this._lastFullIntensityFrame;+ this._lastFullIntensityFrame = result.LastIntensityFrame;+ if (previousIntensityFrame != null)+ {+ previousIntensityFrame.Dispose();+ }+ this.UpdateExportButtons();+ string elapsed = result.Elapsed.ToString("hh\\:mm\\:ss", CultureInfo.InvariantCulture);+ string details = "";+ if (result.Files.Count > 0)+ {+ details = "\r\n\r\nVideos (in " + Path.GetDirectoryName(result.Files[0]) + "):";+ foreach (string file in result.Files)+ {+ details = details + "\r\n" + Path.GetFileName(file);+ }+ }+ if (result.Status != SimulationStatus.Failed && result.Message.Length > 0)+ {+ details = details + "\r\n\r\n" + result.Message;+ }+ if (result.Engine.Length > 0)+ {+ details = details + "\r\n\r\nEngine: " + result.Engine;+ if (result.EngineNote.Length > 0)+ {+ details = details + "\r\n" + result.EngineNote;+ }+ }+ details = details + "\r\n\r\n" + this._runInfo;+ string stepsText = result.StepsDone.ToString("N0", CultureInfo.CurrentCulture);+ string summary;+ switch (result.Status)+ {+ case SimulationStatus.Completed:+ summary = "Simulation completed: " + stepsText + " steps in " + elapsed;+ break;+ case SimulationStatus.Cancelled:+ summary = "Simulation stopped after " + stepsText + " steps (" + elapsed + ")";+ break;+ default:+ summary = "Simulation failed after " + stepsText + " steps";+ break;+ }+ if (result.Elapsed.TotalSeconds > 0.5 && result.StepsDone > 0)+ {+ summary = summary + " - " + ((double)result.StepsDone / result.Elapsed.TotalSeconds).ToString("0.0", CultureInfo.CurrentCulture) + " steps/s";+ }+ if (result.Engine.Length > 0)+ {+ summary = summary + " - " + result.Engine;+ if (result.EngineNote.Length > 0)+ {+ summary = summary + " (" + result.EngineNote + ")";+ }+ }+ if (result.Files.Count > 0)+ {+ List<string> fileNames = new List<string>();+ foreach (string file in result.Files)+ {+ fileNames.Add(Path.GetFileName(file));+ }+ summary = summary + " - video: " + string.Join(", ", fileNames);+ }+ if (result.Status != SimulationStatus.Failed && result.Message.Length > 0)+ {+ summary += " - MP4 (H.264) was not available, the videos are .avi files";+ }+ this.ToolStripStatusLabel1.Text = summary;+ this.ToolStripStatusLabel1.ToolTipText = summary + details;+ if (result.Status == SimulationStatus.Failed)+ {+ MessageBox.Show(this, "The simulation failed after " + stepsText + " steps:\r\n\r\n" + result.Message + details, "Simulation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ }+ }++ /// <summary>Enables the "view video" buttons when the last run's video files still exist.</summary>+ private void UpdateVideoButtons()+ {+ this.btnViewFieldVideo.Enabled = this._fieldVideoFile.Length > 0 && File.Exists(this._fieldVideoFile);+ this.btnViewIntensityVideo.Enabled = this._intensityVideoFile.Length > 0 && File.Exists(this._intensityVideoFile);+ }++ /// <summary>Opens the last field video in the default media player.</summary>+ private void btnViewFieldVideo_Click(object sender, EventArgs e)+ {+ this.OpenVideo(this._fieldVideoFile);+ }++ /// <summary>Opens the last intensity video in the default media player.</summary>+ private void btnViewIntensityVideo_Click(object sender, EventArgs e)+ {+ this.OpenVideo(this._intensityVideoFile);+ }++ /// <summary>Launches <paramref name="videoFile"/> with the shell's default player; tells the user when the file has gone or cannot be opened.</summary>+ private void OpenVideo(string videoFile)+ {+ if (videoFile.Length == 0 || !File.Exists(videoFile))+ {+ MessageBox.Show(this, "The video file does not exist (any more):\r\n" + videoFile, "Video", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ this.UpdateVideoButtons();+ return;+ }+ try+ {+ Process.Start(new ProcessStartInfo(videoFile)+ {+ UseShellExecute = true+ });+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The video could not be opened:\r\n\r\n" + ex.Message, "Video", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ }+ }++ /// <summary>Opens the project's video folder in Explorer.</summary>+ private void btnOpenVideoFolder_Click(object sender, EventArgs e)+ {+ this.OpenVideoFolder();+ }++ /// <summary>Opens the project's exported-frames folder in Explorer.</summary>+ private void btnOpenImageFolder_Click(object sender, EventArgs e)+ {+ this.OpenFramesFolder();+ }++ /// <summary>Saves the current or last field frame as a PNG.</summary>+ private void btnExportFieldFrame_Click(object sender, EventArgs e)+ {+ this.ExportFrame(true);+ }++ /// <summary>Saves the current or last intensity frame as a PNG.</summary>+ private void btnExportIntensityFrame_Click(object sender, EventArgs e)+ {+ this.ExportFrame(false);+ }++ /// <summary>+ /// Saves a full-size frame as PNG in the project's frames folder. While the run is paused the runner renders the live+ /// field / intensity with the palette of the current run (that bitmap is owned and disposed here); otherwise the last frame+ /// of the previous run is used. The glow overlay is composed in when enabled. The file name carries the step count and a+ /// 4-digit sequence number.+ /// </summary>+ private void ExportFrame(bool isField)+ {+ Bitmap frame = null;+ bool ownsFrame = false;+ if (this._runner != null && this._paused)+ {+ int[] lut = (isField ? this._lastFieldLut : this._lastIntensityLut);+ float brightness = (float)(isField ? this._simulation.FieldBrightness : this._simulation.IntensityBrightness);+ frame = this._runner.RenderCurrentFrame(isField, lut, brightness);+ ownsFrame = true;+ }+ if (frame == null)+ {+ frame = (isField ? this._lastFullFieldFrame : this._lastFullIntensityFrame);+ }+ if (frame == null)+ {+ MessageBox.Show(this, "There is no picture to export yet.", "Export frame", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ try+ {+ Directory.CreateDirectory(this._project.OutputFramesFolder);+ }+ catch (Exception ex)+ {+ if (ownsFrame)+ {+ frame.Dispose();+ }+ MessageBox.Show(this, "The output folder could not be created:\r\n" + this._project.OutputFramesFolder + "\r\n\r\n" + ex.Message, "Export frame", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ return;+ }+ string kind = (isField ? "field" : "intensity");+ double overlayGain = (isField ? this.FieldOverlayGain() : this.IntensityOverlayGain());+ Bitmap output = frame;+ bool ownsOutput = false;+ if (overlayGain > 0.0 && this._glowEdgesImage != null)+ {+ output = this.ComposeGlowOverlay(frame, overlayGain);+ ownsOutput = true;+ }+ string suffix = this.NextNumericSuffix(this._project.OutputFramesFolder).ToString("D4", CultureInfo.InvariantCulture);+ string fileName = this._project.Name + "_" + kind + "_frame" + this._lastStepsDone.ToString(CultureInfo.InvariantCulture) + "_" + suffix + ".png";+ string path = Path.Combine(this._project.OutputFramesFolder, fileName);+ try+ {+ output.Save(path, ImageFormat.Png);+ this.ToolStripStatusLabel1.Text = "Frame exported: " + fileName;+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The frame could not be saved:\r\n\r\n" + ex.Message, "Export frame", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ }+ finally+ {+ if (ownsOutput)+ {+ output.Dispose();+ }+ if (ownsFrame)+ {+ frame.Dispose();+ }+ }+ }++ /// <summary>Returns one more than the highest 4-digit numeric suffix among the file names in <paramref name="folder"/>.</summary>+ private int NextNumericSuffix(string folder)+ {+ int highest = 0;+ if (Directory.Exists(folder))+ {+ foreach (string file in Directory.GetFiles(folder))+ {+ string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);+ if (fileNameWithoutExtension.Length >= 4)+ {+ string tail = fileNameWithoutExtension.Substring(fileNameWithoutExtension.Length - 4);+ int value;+ if (int.TryParse(tail, NumberStyles.None, CultureInfo.InvariantCulture, out value) && value > highest)+ {+ highest = value;+ }+ }+ }+ }+ return highest + 1;+ }++ /// <summary>Opens the project's video folder in Explorer (details view); reports when there is no project.</summary>+ private void OpenVideoFolder()+ {+ string folder = ((this._project == null) ? "" : this._project.OutputVideoFolder);+ if (folder.Length == 0)+ {+ MessageBox.Show(this, "There is no project open yet.", "Open video folder", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ try+ {+ this.OpenFolderInExplorer(folder, 4);+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The video folder could not be opened:\r\n\r\n" + ex.Message, "Open video folder", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ }+ }++ /// <summary>Opens the project's exported-frames folder in Explorer (icon view); reports when there is no project.</summary>+ private void OpenFramesFolder()+ {+ string folder = ((this._project == null) ? "" : this._project.OutputFramesFolder);+ if (folder.Length == 0)+ {+ MessageBox.Show(this, "There is no project open yet.", "Open image folder", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ try+ {+ this.OpenFolderInExplorer(folder, 1);+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The image folder could not be opened:\r\n\r\n" + ex.Message, "Open image folder", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ }+ }++ /// <summary>Creates <paramref name="folder"/> if needed, opens it in Explorer and tries to apply <paramref name="viewMode"/>; view-mode failures are ignored.</summary>+ /// <param name="folder">Folder to open; created when missing (that may throw, unlike the view-mode step).</param>+ /// <param name="viewMode">Explorer FOLDERVIEWMODE value: 1 = icons, 4 = details.</param>+ private void OpenFolderInExplorer(string folder, int viewMode)+ {+ Directory.CreateDirectory(folder);+ Process.Start(new ProcessStartInfo("explorer.exe", "\"" + folder + "\"")+ {+ UseShellExecute = true+ });+ try+ {+ this.SetExplorerWindowViewMode(folder, viewMode);+ }+ catch (Exception)+ {+ }+ }++ /// <summary>+ /// Finds the Explorer window that was just opened on <paramref name="folder"/> (polling up to 8 times)+ /// through the Shell.Application COM automation object (late bound) and sets its view mode (e.g. 1 = icons, 4 = details).+ /// Runs on the UI thread and sleeps 120 ms between polls, so it can block the UI for about a second when the window never shows up.+ /// </summary>+ private void SetExplorerWindowViewMode(string folder, int viewMode)+ {+ string target = Path.GetFullPath(folder).TrimEnd(new char[] { Path.DirectorySeparatorChar });+ Type shellType = Type.GetTypeFromProgID("Shell.Application");+ if (shellType == null)+ {+ return;+ }+ object shell = Activator.CreateInstance(shellType);+ try+ {+ for (int attempt = 1; attempt <= 8; attempt++)+ {+ object windows = shellType.InvokeMember("Windows", BindingFlags.InvokeMethod | BindingFlags.GetProperty, null, shell, null);+ Type windowsType = windows.GetType();+ int count = Convert.ToInt32(windowsType.InvokeMember("Count", BindingFlags.InvokeMethod | BindingFlags.GetProperty, null, windows, null));+ for (int i = 0; i < count; i++)+ {+ object window = windowsType.InvokeMember("Item", BindingFlags.InvokeMethod | BindingFlags.GetProperty, null, windows, new object[] { i });+ if (window == null)+ {+ continue;+ }+ Type windowType = window.GetType();+ string locationUrl = windowType.InvokeMember("LocationURL", BindingFlags.InvokeMethod | BindingFlags.GetProperty, null, window, null) as string;+ if (string.IsNullOrEmpty(locationUrl))+ {+ continue;+ }+ string windowPath;+ try+ {+ windowPath = new Uri(locationUrl).LocalPath.TrimEnd(new char[] { Path.DirectorySeparatorChar });+ }+ catch (Exception)+ {+ continue;+ }+ if (string.Equals(windowPath, target, StringComparison.OrdinalIgnoreCase))+ {+ object document = windowType.InvokeMember("Document", BindingFlags.InvokeMethod | BindingFlags.GetProperty, null, window, null);+ if (document != null)+ {+ document.GetType().InvokeMember("CurrentViewMode", BindingFlags.SetProperty, null, document, new object[] { viewMode });+ }+ return;+ }+ }+ Thread.Sleep(120); // give Explorer time to register the new window+ }+ }+ finally+ {+ Marshal.ReleaseComObject(shell);+ }+ }++ /// <summary>+ /// Empties both preview boxes, disposing the shown image and the raw frame kept in <c>Tag</c> (they differ when the glow+ /// overlay was composed in), and drops the last full-size frames.+ /// </summary>+ private void ClearPreviews()+ {+ foreach (PictureBox pictureBox in new PictureBox[] { this._picField, this._picIntensity })+ {+ if (pictureBox == null)+ {+ continue;+ }+ Image image = pictureBox.Image;+ Bitmap tagged = pictureBox.Tag as Bitmap;+ pictureBox.Image = null;+ pictureBox.Tag = null;+ if (image != null && !object.ReferenceEquals(image, tagged))+ {+ image.Dispose();+ }+ if (tagged != null)+ {+ tagged.Dispose();+ }+ }+ if (this._lastFullFieldFrame != null)+ {+ this._lastFullFieldFrame.Dispose();+ }+ this._lastFullFieldFrame = null;+ if (this._lastFullIntensityFrame != null)+ {+ this._lastFullIntensityFrame.Dispose();+ }+ this._lastFullIntensityFrame = null;+ this.UpdateCopyButtons();+ }++ /// <summary>Wired by the designer to both probe group boxes; intentionally does nothing.</summary>+ private void grpProbe1_Enter(object sender, EventArgs e)+ {+ }++ /// <summary>Wired by the designer to two labels; intentionally does nothing.</summary>+ private void Label21_Click(object sender, EventArgs e)+ {+ }++ /// <summary>Wired by the designer; intentionally does nothing.</summary>+ private void lblVideoQuality_Click(object sender, EventArgs e)+ {+ }++ /// <summary>Saves the project (viewer-tab copy of the Save button).</summary>+ private void btnSaveConfiguration2_Click(object sender, EventArgs e)+ {+ this.SaveProject();+ }++ /// <summary>+ /// "Created on" column header of the video list on the Output tab. Created and assigned by the designer; declared as a+ /// property (VB.NET WithEvents style) and placed in this file by the decompiler.+ /// </summary>+ protected internal virtual ColumnHeader colCreatedOn2 { get; set; }+ }+}diff --git a/Wave_Dude_2D/Form1.Sources.cs b/Wave_Dude_2D/Form1.Sources.csnew file mode 100644index 0000000..8b2d95d--- /dev/null+++ b/Wave_Dude_2D/Form1.Sources.cs@@ -0,0 +1,1016 @@+using System;+using System.Collections.Generic;+using System.ComponentModel;+using System.Drawing;+using System.Globalization;+using System.Windows.Forms;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Source list tab: editing, saving and previewing the wave sources of the project.+ /// The list of saved sources lives in <c>_sources</c>; the editor controls always show+ /// <c>_editing</c>, which is a clone of the selected entry (or a fresh source when nothing+ /// is selected) until the user presses "Save source". <c>_loadingSource</c> guards the+ /// control change handlers while the editor is being filled, <c>_syncingSourceList</c>+ /// guards the list selection handler while the list is rebuilt. Everything here runs on+ /// the UI thread.+ /// </summary>+ public partial class Form1+ {+ /// <summary>+ /// One-time set-up at form load: remembers the "Pick" button text and the save button+ /// colour, sets the numeric input limits (positions 0..16383 canvas px, array sizes+ /// 1..999 stepping by 2, spacings 0..16384 px), wires dirty tracking and the scene+ /// picture events, switches the list to owner drawing and shows the initial source.+ /// </summary>+ private void InitializeSourceControls()+ {+ this._pickSourceButtonText = this.btnPickSourcePosition.Text;+ this._sourceSaveButtonDefaultBackColor = this.btnSaveSource.BackColor;+ this.WireSourceDirtyTracking(this.grpSourceDetails);+ this.numSourcePositionX.DecimalPlaces = 0;+ this.numSourcePositionX.Minimum = 0m;+ this.numSourcePositionX.Maximum = 16383m;+ this.numSourcePositionY.DecimalPlaces = 0;+ this.numSourcePositionY.Minimum = 0m;+ this.numSourcePositionY.Maximum = 16383m;+ this.numArraySizeX.DecimalPlaces = 0;+ this.numArraySizeX.Minimum = 1m;+ this.numArraySizeX.Maximum = 999m;+ this.numArraySizeX.Increment = 2m;+ this.numArraySizeY.DecimalPlaces = 0;+ this.numArraySizeY.Minimum = 1m;+ this.numArraySizeY.Maximum = 999m;+ this.numArraySizeY.Increment = 2m;+ this.numSpacingSizeX.DecimalPlaces = 0;+ this.numSpacingSizeX.Minimum = 0m;+ this.numSpacingSizeX.Maximum = 16384m;+ this.numSpacingSizeY.DecimalPlaces = 0;+ this.numSpacingSizeY.Minimum = 0m;+ this.numSpacingSizeY.Maximum = 16384m;+ this.numAmplitude.DecimalPlaces = 0;+ this.numPulseWidthCycles.DecimalPlaces = 0;+ if (this.numPulseWidthCycles.Minimum < 1m)+ {+ this.numPulseWidthCycles.Minimum = 1m;+ }+ // Designer limit is too small for long pulses; widen it without touching the Designer.+ if (this.numPulseWidthCycles.Maximum < 100m)+ {+ this.numPulseWidthCycles.Maximum = 1000000m;+ }+ this.numOffStateCycles.DecimalPlaces = 0;+ this.numRandomizeFrequency.DecimalPlaces = 0;+ this.numRandomizeOffWidth.DecimalPlaces = 0;+ this.numRandomizePosition.DecimalPlaces = 0;+ this.NumRandomizePhase.DecimalPlaces = 0;+ this._picSource.Paint += this.SourcePicture_Paint;+ this._picSource.MouseClick += this.SourcePicture_MouseClick;+ this.lstSources.DrawMode = DrawMode.OwnerDrawFixed;+ this.RefreshSourceList();+ this.ShowSourceInControls(this._editing);+ this.ClearSourceDirty();+ this.UpdateListButtonState();+ }++ /// <summary>+ /// Replaces the source list with the sources stored in the open project and selects+ /// the first one (or an empty editor when the project has none). No-op without a project.+ /// </summary>+ private void LoadSourcesFromProject()+ {+ if (this._project == null)+ {+ return;+ }+ this._sources = SourceSettings.ListFromConfig(this._project.Config);+ if (this._sources.Count > 0)+ {+ this._currentSourceIndex = 0;+ this._editing = this._sources[0].Clone();+ }+ else+ {+ this._currentSourceIndex = -1;+ this._editing = new SourceSettings();+ }+ this.RefreshSourceList();+ this._syncingSourceList = true;+ try+ {+ this.lstSources.SelectedIndex = this._currentSourceIndex;+ }+ finally+ {+ this._syncingSourceList = false;+ }+ this.ShowSourceInControls(this._editing);+ this.ClearSourceDirty();+ this.UpdateListButtonState();+ }++ /// <summary>+ /// Empties the source list and the editor for a new project. The editor is only+ /// refreshed once the source picture box exists, i.e. after the form has been built.+ /// </summary>+ private void ResetSources()+ {+ this._sources = new List<SourceSettings>();+ this._currentSourceIndex = -1;+ this._editing = new SourceSettings();+ this.RefreshSourceList();+ if (this._picSource != null)+ {+ this.ShowSourceInControls(this._editing);+ this.ClearSourceDirty();+ }+ this.UpdateListButtonState();+ }++ /// <summary>+ /// Collects the elements of all enabled sources for a simulation run, or null when+ /// object sources are not in use (scene flag off, or no sources at all). Sources whose+ /// element list is still empty are generated on the spot. The returned list holds the+ /// sources' own <see cref="SourceElement"/> instances, not copies; the engines only+ /// read them from the worker thread.+ /// </summary>+ private List<SourceElement> SourcesForRun()+ {+ if (this._scene == null || !this._scene.UseObjectSources || this._sources.Count == 0)+ {+ return null;+ }+ List<SourceElement> elements = new List<SourceElement>();+ foreach (SourceSettings source in this._sources)+ {+ if (!source.SourceOn)+ {+ continue;+ }+ if (source.Elements == null || source.Elements.Count == 0)+ {+ source.GenerateElements(this._sourceRandom);+ }+ elements.AddRange(source.Elements);+ }+ return elements;+ }++ /// <summary>Rebuilds the list box items from <c>_sources</c>, keeping the current selection index when it is still valid; the selection handler is suppressed meanwhile.</summary>+ private void RefreshSourceList()+ {+ int selectedIndex = this.lstSources.SelectedIndex;+ this._syncingSourceList = true;+ try+ {+ this.lstSources.Items.Clear();+ foreach (SourceSettings source in this._sources)+ {+ this.lstSources.Items.Add(Form1.SourceListText(source));+ }+ if (selectedIndex >= 0 && selectedIndex < this.lstSources.Items.Count)+ {+ this.lstSources.SelectedIndex = selectedIndex;+ }+ }+ finally+ {+ this._syncingSourceList = false;+ }+ }++ /// <summary>List box caption for a source: the name followed by "(single)" or "(composite, X x Y)".</summary>+ private static string SourceListText(SourceSettings s)+ {+ if (s.MainType == SourceMainType.Composite)+ {+ return s.Name + " (composite, " + s.ArraySizeX.ToString(CultureInfo.InvariantCulture) + " x " + s.ArraySizeY.ToString(CultureInfo.InvariantCulture) + ")";+ }+ return s.Name + " (single)";+ }++ /// <summary>Owner-draws a list entry, in grey when the source is switched off.</summary>+ private void lstSources_DrawItem(object sender, DrawItemEventArgs e)+ {+ if (e.Index < 0 || e.Index >= this.lstSources.Items.Count)+ {+ return;+ }+ e.DrawBackground();+ Color textColor = ((e.Index < this._sources.Count && !this._sources[e.Index].SourceOn) ? Color.Gray : e.ForeColor);+ using (SolidBrush brush = new SolidBrush(textColor))+ {+ e.Graphics.DrawString(this.lstSources.Items[e.Index].ToString(), e.Font, brush, e.Bounds);+ }+ e.DrawFocusRectangle();+ }++ /// <summary>+ /// Selecting a list entry cancels any position pick and loads a clone of that source into+ /// the editor (unsaved edits of the previous source are discarded); deselecting loads an+ /// empty source. Ignored while the list is being synchronised programmatically.+ /// </summary>+ private void lstSources_SelectedIndexChanged(object sender, EventArgs e)+ {+ this.UpdateListButtonState();+ if (this._syncingSourceList)+ {+ return;+ }+ this.EndSourcePick();+ if (this.lstSources.SelectedIndex < 0)+ {+ this._currentSourceIndex = -1;+ this._editing = new SourceSettings();+ }+ else+ {+ this._currentSourceIndex = this.lstSources.SelectedIndex;+ this._editing = this._sources[this._currentSourceIndex].Clone();+ }+ this.ShowSourceInControls(this._editing);+ this.ClearSourceDirty();+ if (this._picSource != null)+ {+ this._picSource.Invalidate();+ }+ this.picPreviewSource.Invalidate();+ this.ToolStripStatusLabel1.Text = ((this._currentSourceIndex >= 0) ? ("Editing '" + this._editing.Name + "': press Save source to keep the changes.") : "");+ }++ /// <summary>Enables Copy and Delete only while a list entry is selected.</summary>+ private void UpdateListButtonState()+ {+ bool hasSelection = this.lstSources.SelectedIndex >= 0;+ this.btnCopy.Enabled = hasSelection;+ this.btnDelete.Enabled = hasSelection;+ }++ /// <summary>Starts a new, unsaved source named "Source N" in the editor, deselects the list and focuses the name box.</summary>+ private void btnNew_Click(object sender, EventArgs e)+ {+ this.EndSourcePick();+ this._syncingSourceList = true;+ try+ {+ this.lstSources.SelectedIndex = -1;+ }+ finally+ {+ this._syncingSourceList = false;+ }+ this._currentSourceIndex = -1;+ this._editing = new SourceSettings();+ this._editing.Name = "Source " + (this._sources.Count + 1).ToString(CultureInfo.InvariantCulture);+ this.ShowSourceInControls(this._editing);+ this.MarkSourceDirty();+ this.UpdateListButtonState();+ if (this._picSource != null)+ {+ this._picSource.Invalidate();+ }+ this.picPreviewSource.Invalidate();+ this.ToolStripStatusLabel1.Text = "New source: fill in its properties, then press Save source.";+ this.txtName.Focus();+ this.txtName.SelectAll();+ }++ /// <summary>Loads a clone of the selected source, named "... copy", into the editor as a new unsaved source (it is only added to the list on save).</summary>+ private void btnCopy_Click(object sender, EventArgs e)+ {+ if (this.lstSources.SelectedIndex < 0)+ {+ return;+ }+ this.EndSourcePick();+ string originalName = this._sources[this.lstSources.SelectedIndex].Name;+ this._editing = this._sources[this.lstSources.SelectedIndex].Clone();+ this._editing.Name = this._editing.Name + " copy";+ this._syncingSourceList = true;+ try+ {+ this.lstSources.SelectedIndex = -1;+ }+ finally+ {+ this._syncingSourceList = false;+ }+ this._currentSourceIndex = -1;+ this.ShowSourceInControls(this._editing);+ this.MarkSourceDirty();+ this.UpdateListButtonState();+ if (this._picSource != null)+ {+ this._picSource.Invalidate();+ }+ this.picPreviewSource.Invalidate();+ this.ToolStripStatusLabel1.Text = "Copy of '" + originalName + "': change it and press Save source to add it as a new source.";+ this.txtName.Focus();+ this.txtName.SelectAll();+ }++ /// <summary>After confirmation, removes the selected source from the list and marks the project dirty; clears the editor if that source was being edited.</summary>+ private void btnDelete_Click(object sender, EventArgs e)+ {+ if (this.lstSources.SelectedIndex < 0)+ {+ return;+ }+ int selectedIndex = this.lstSources.SelectedIndex;+ string name = this._sources[selectedIndex].Name;+ if (MessageBox.Show(this, "Delete the source '" + name + "'?", "Delete source", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)+ {+ return;+ }+ this._sources.RemoveAt(selectedIndex);+ if (this._currentSourceIndex == selectedIndex)+ {+ this._currentSourceIndex = -1;+ this._editing = new SourceSettings();+ this.ShowSourceInControls(this._editing);+ this.ClearSourceDirty();+ }+ else if (this._currentSourceIndex > selectedIndex)+ {+ this._currentSourceIndex--;+ }+ this.RefreshSourceList();+ this.UpdateListButtonState();+ this.MarkProjectChanged();+ if (this._picSource != null)+ {+ this._picSource.Invalidate();+ }+ this.picPreviewSource.Invalidate();+ this.ToolStripStatusLabel1.Text = "Source '" + name + "' deleted.";+ }++ /// <summary>Saves the editor contents into the list (see <see cref="CommitSourceEdits"/>).</summary>+ private void btnSaveSource_Click(object sender, EventArgs e)+ {+ this.CommitSourceEdits();+ }++ /// <summary>+ /// Reads the editor controls into the source being edited, regenerates its elements+ /// (re-rolling any randomisation) and stores it in the list, replacing the selected entry+ /// or appending a new one. Marks the project dirty and leaves the editor on a fresh clone+ /// of the saved source. Returns false, without saving, if the source has no name.+ /// </summary>+ private bool CommitSourceEdits()+ {+ this.ReadSourceControls(this._editing);+ if (this._editing.Name.Trim().Length == 0)+ {+ MessageBox.Show(this, "Give the source a name first.", "Save source", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ this.txtName.Focus();+ return false;+ }+ this._editing.GenerateElements(this._sourceRandom);+ if (this._currentSourceIndex >= 0 && this._currentSourceIndex < this._sources.Count)+ {+ this._sources[this._currentSourceIndex] = this._editing;+ }+ else+ {+ this._sources.Add(this._editing);+ this._currentSourceIndex = this._sources.Count - 1;+ }+ this.RefreshSourceList();+ this._syncingSourceList = true;+ try+ {+ this.lstSources.SelectedIndex = this._currentSourceIndex;+ }+ finally+ {+ this._syncingSourceList = false;+ }+ this.UpdateListButtonState();+ this.MarkProjectChanged();+ if (this._picSource != null)+ {+ this._picSource.Invalidate();+ }+ this.picPreviewSource.Invalidate();+ this.ToolStripStatusLabel1.Text = "Source '" + this._editing.Name + "' saved (" + this._editing.Elements.Count.ToString(CultureInfo.InvariantCulture) + " element(s)).";+ this._editing = this._editing.Clone();+ this.ClearSourceDirty();+ return true;+ }++ /// <summary>+ /// Fills the editor controls from a source (after normalising it), with+ /// <c>_loadingSource</c> set so the change handlers neither mark the editor dirty nor+ /// write back into <c>_editing</c>. Values outside a control's range are clamped for+ /// display. The randomise limits are refreshed before the randomise amounts are set so+ /// they are not clipped by stale maxima; finally the enabled states and the wavelength+ /// label are updated.+ /// </summary>+ private void ShowSourceInControls(SourceSettings s)+ {+ s.Normalize();+ this._loadingSource = true;+ try+ {+ this.txtName.Text = s.Name;+ this.cmbMainType.SelectedIndex = (int)s.MainType;+ this.chkSourceOn.Checked = s.SourceOn;+ this.chkDetachSource.Checked = s.DetachSource;+ this.txtDetachAfterSteps.Text = s.DetachAfterSteps.ToString(CultureInfo.InvariantCulture);+ this.numSourcePositionX.Value = Form1.ClampToRange(this.numSourcePositionX, s.PosX);+ this.numSourcePositionY.Value = Form1.ClampToRange(this.numSourcePositionY, s.PosY);+ this.numFrequency.Value = Form1.ClampToRange(this.numFrequency, s.Frequency);+ this.numAmplitude.Value = Form1.ClampToRange(this.numAmplitude, s.Amplitude);+ this.numPhase.Value = Form1.ClampToRange(this.numPhase, s.PhaseDeg);+ this.radModePulsed.Checked = s.Mode == SourceMode.Pulsed;+ this.radModeContinuous.Checked = s.Mode == SourceMode.Continuous;+ this.cmbPulseShape.SelectedIndex = (int)s.PulseShape;+ this.numPulseWidthCycles.Value = Form1.ClampToRange(this.numPulseWidthCycles, s.PulseWidthCycles);+ this.numOffStateCycles.Value = Form1.ClampToRange(this.numOffStateCycles, s.OffStateCycles);+ this.numArraySizeX.Value = Form1.ClampToRange(this.numArraySizeX, s.ArraySizeX);+ this.numArraySizeY.Value = Form1.ClampToRange(this.numArraySizeY, s.ArraySizeY);+ this.numSpacingSizeX.Value = Form1.ClampToRange(this.numSpacingSizeX, s.SpacingX);+ this.numSpacingSizeY.Value = Form1.ClampToRange(this.numSpacingSizeY, s.SpacingY);+ this.UpdateRandomizeLimits();+ this.cmbCompositeProperties.SelectedIndex = (int)s.CompositeMode;+ this.chkRandomizeFrequency.Checked = s.RandomizeFrequency;+ this.numRandomizeFrequency.Value = Form1.ClampToRange(this.numRandomizeFrequency, s.RandomizeFrequencyAmount);+ this.chkRandomizePhase.Checked = s.RandomizePhase;+ this.NumRandomizePhase.Value = Form1.ClampToRange(this.NumRandomizePhase, s.RandomizePhaseAmount);+ this.chkOffWidth.Checked = s.RandomizeOffWidth;+ this.numRandomizeOffWidth.Value = Form1.ClampToRange(this.numRandomizeOffWidth, s.RandomizeOffWidthAmount);+ this.chkRandomizePosition.Checked = s.RandomizePosition;+ this.numRandomizePosition.Value = Form1.ClampToRange(this.numRandomizePosition, s.RandomizePositionAmount);+ }+ finally+ {+ this._loadingSource = false;+ }+ this.UpdateSourceControlState();+ this.UpdateLambdaLabel();+ }++ /// <summary>Hooks the change events of every input control below <paramref name="container"/> (recursively) to the dirty marker.</summary>+ private void WireSourceDirtyTracking(Control container)+ {+ foreach (Control control in container.Controls)+ {+ if (control is TextBox textBox)+ {+ textBox.TextChanged += this.SourceDetail_Changed;+ }+ else if (control is NumericUpDown numericUpDown)+ {+ numericUpDown.ValueChanged += this.SourceDetail_Changed;+ }+ else if (control is CheckBox checkBox)+ {+ checkBox.CheckedChanged += this.SourceDetail_Changed;+ }+ else if (control is RadioButton radioButton)+ {+ radioButton.CheckedChanged += this.SourceDetail_Changed;+ }+ else if (control is ComboBox comboBox)+ {+ comboBox.SelectedIndexChanged += this.SourceDetail_Changed;+ }+ if (control.HasChildren)+ {+ this.WireSourceDirtyTracking(control);+ }+ }+ }++ /// <summary>Any user edit in the source details marks the editor dirty, unless the controls are being filled programmatically.</summary>+ private void SourceDetail_Changed(object sender, EventArgs e)+ {+ if (!this._loadingSource)+ {+ this.MarkSourceDirty();+ }+ }++ /// <summary>Signals unsaved edits by colouring the save button orange.</summary>+ private void MarkSourceDirty()+ {+ this.btnSaveSource.BackColor = Color.Orange;+ }++ /// <summary>Restores the save button to its default colour once the editor matches the saved source.</summary>+ private void ClearSourceDirty()+ {+ this.btnSaveSource.BackColor = this._sourceSaveButtonDefaultBackColor;+ }++ /// <summary>+ /// Copies the editor controls into <paramref name="target"/> and normalises it. The+ /// detach step count is parsed with the invariant culture and left unchanged when the+ /// text is not a non-negative integer. Does not touch <c>HasPosition</c> or the elements.+ /// </summary>+ private void ReadSourceControls(SourceSettings target)+ {+ target.Name = this.txtName.Text.Trim();+ target.MainType = ((this.cmbMainType.SelectedIndex == 1) ? SourceMainType.Composite : SourceMainType.Simple);+ target.SourceOn = this.chkSourceOn.Checked;+ target.DetachSource = this.chkDetachSource.Checked;+ int detachAfterSteps;+ if (int.TryParse(this.txtDetachAfterSteps.Text.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out detachAfterSteps) && detachAfterSteps >= 0)+ {+ target.DetachAfterSteps = detachAfterSteps;+ }+ target.PosX = Convert.ToInt32(this.numSourcePositionX.Value);+ target.PosY = Convert.ToInt32(this.numSourcePositionY.Value);+ target.Frequency = Convert.ToInt32(this.numFrequency.Value);+ target.Amplitude = Convert.ToInt32(this.numAmplitude.Value);+ target.PhaseDeg = Convert.ToInt32(this.numPhase.Value);+ target.Mode = (this.radModePulsed.Checked ? SourceMode.Pulsed : SourceMode.Continuous);+ target.PulseShape = ((this.cmbPulseShape.SelectedIndex == 1) ? SourcePulseShape.SmoothedSquare : SourcePulseShape.Gaussian);+ target.PulseWidthCycles = Convert.ToInt32(this.numPulseWidthCycles.Value);+ target.OffStateCycles = Convert.ToInt32(this.numOffStateCycles.Value);+ target.ArraySizeX = Convert.ToInt32(this.numArraySizeX.Value);+ target.ArraySizeY = Convert.ToInt32(this.numArraySizeY.Value);+ target.SpacingX = Convert.ToInt32(this.numSpacingSizeX.Value);+ target.SpacingY = Convert.ToInt32(this.numSpacingSizeY.Value);+ target.CompositeMode = ((this.cmbCompositeProperties.SelectedIndex == 1) ? SourceCompositeMode.InheritAndRandomize : SourceCompositeMode.InheritFromSingle);+ target.RandomizeFrequency = this.chkRandomizeFrequency.Checked;+ target.RandomizeFrequencyAmount = Convert.ToInt32(this.numRandomizeFrequency.Value);+ target.RandomizePhase = this.chkRandomizePhase.Checked;+ target.RandomizePhaseAmount = Convert.ToInt32(this.NumRandomizePhase.Value);+ target.RandomizeOffWidth = this.chkOffWidth.Checked;+ target.RandomizeOffWidthAmount = Convert.ToInt32(this.numRandomizeOffWidth.Value);+ target.RandomizePosition = this.chkRandomizePosition.Checked;+ target.RandomizePositionAmount = Convert.ToInt32(this.numRandomizePosition.Value);+ target.Normalize();+ }++ /// <summary>+ /// Enables or disables the dependent inputs: pulse controls only in pulsed mode, the+ /// detach step box only when detaching, the array and composite controls only for a+ /// composite source, and each randomise amount only when the composite mode is+ /// "randomize" and its own checkbox is ticked.+ /// </summary>+ private void UpdateSourceControlState()+ {+ bool isComposite = this.cmbMainType.SelectedIndex == 1;+ this.grpComposite.Enabled = isComposite;+ bool isPulsed = this.radModePulsed.Checked;+ this.cmbPulseShape.Enabled = isPulsed;+ this.numPulseWidthCycles.Enabled = isPulsed;+ this.numOffStateCycles.Enabled = isPulsed;+ this.txtDetachAfterSteps.Enabled = this.chkDetachSource.Checked;+ bool canRandomize = isComposite && this.cmbCompositeProperties.SelectedIndex == 1;+ this.cmbCompositeProperties.Enabled = isComposite;+ this.numArraySizeX.Enabled = isComposite;+ this.numArraySizeY.Enabled = isComposite;+ this.numSpacingSizeX.Enabled = isComposite;+ this.numSpacingSizeY.Enabled = isComposite;+ this.chkRandomizeFrequency.Enabled = canRandomize;+ this.chkRandomizePhase.Enabled = canRandomize;+ this.chkOffWidth.Enabled = canRandomize;+ this.chkRandomizePosition.Enabled = canRandomize;+ this.numRandomizeFrequency.Enabled = canRandomize && this.chkRandomizeFrequency.Checked;+ this.NumRandomizePhase.Enabled = canRandomize && this.chkRandomizePhase.Checked;+ this.numRandomizeOffWidth.Enabled = canRandomize && this.chkOffWidth.Checked;+ this.numRandomizePosition.Enabled = canRandomize && this.chkRandomizePosition.Checked;+ }++ /// <summary>Changing the main type or the composite mode combo box re-evaluates which inputs are enabled.</summary>+ private void SourceMainType_SelectedIndexChanged(object sender, EventArgs e)+ {+ if (!this._loadingSource)+ {+ this.UpdateSourceControlState();+ }+ }++ /// <summary>Switching between continuous and pulsed enables or disables the pulse inputs.</summary>+ private void SourceMode_CheckedChanged(object sender, EventArgs e)+ {+ if (!this._loadingSource)+ {+ this.UpdateSourceControlState();+ }+ }++ /// <summary>Changing the frequency updates the wavelength label.</summary>+ private void SourceFrequency_ValueChanged(object sender, EventArgs e)+ {+ this.UpdateLambdaLabel();+ }++ /// <summary>+ /// Shows the wavelength in canvas pixels that follows from the frequency input and the+ /// simulation settings: angular frequency = level / 255 * 0.5 * SourceFrequencyScale+ /// (radians per step), wavelength = WaveSpeedC (px per step) / cycles per step. Falls back+ /// to a scale of 2.0 and c = 0.563 before the simulation settings exist.+ /// </summary>+ private void UpdateLambdaLabel()+ {+ if (this.lblLambdaIs == null)+ {+ return;+ }+ int frequency = Convert.ToInt32(this.numFrequency.Value);+ double frequencyScale = ((this._simulation != null) ? this._simulation.SourceFrequencyScale : 2.0);+ double angularFrequency = frequency / 255.0 * 0.5 * frequencyScale;+ double cyclesPerStep = angularFrequency / (2.0 * Math.PI);+ if (cyclesPerStep <= 0.0)+ {+ this.lblLambdaIs.Text = "λ= - px";+ }+ else+ {+ double waveSpeed = ((this._simulation != null) ? this._simulation.WaveSpeedC : 0.563);+ double wavelength = waveSpeed / cyclesPerStep;+ this.lblLambdaIs.Text = "λ=" + wavelength.ToString("0.0", CultureInfo.CurrentCulture) + " px";+ }+ }++ /// <summary>Ticking "detach" enables the detach step box.</summary>+ private void SourceDetach_CheckedChanged(object sender, EventArgs e)+ {+ if (!this._loadingSource)+ {+ this.UpdateSourceControlState();+ }+ }++ /// <summary>Ticking one of the randomise checkboxes enables its amount input.</summary>+ private void SourceRandomizeCheck_CheckedChanged(object sender, EventArgs e)+ {+ if (!this._loadingSource)+ {+ this.UpdateSourceControlState();+ }+ }++ /// <summary>Changing frequency, off-width, array size or spacing recomputes the maxima of the randomise amounts.</summary>+ private void SourceRandomizeLimitInput_ValueChanged(object sender, EventArgs e)+ {+ this.UpdateRandomizeLimits();+ }++ /// <summary>+ /// Limits the randomise amounts so that randomised values stay within their valid+ /// ranges: frequency offset at most the distance to 1 or 255, off-width offset at most+ /// off-width - 1 (keeps the gap at least 1 cycle), position jitter at most half the+ /// smallest spacing along an axis with more than one element (16384 px for a 1x1 array).+ /// Lowering a maximum also clips the current value of that input.+ /// </summary>+ private void UpdateRandomizeLimits()+ {+ int frequency = Convert.ToInt32(this.numFrequency.Value);+ this.numRandomizeFrequency.Maximum = new decimal(Math.Max(0, Math.Min(frequency - 1, 255 - frequency)));+ int offStateCycles = Convert.ToInt32(this.numOffStateCycles.Value);+ this.numRandomizeOffWidth.Maximum = new decimal(Math.Max(0, offStateCycles - 1));+ int arraySizeX = Convert.ToInt32(this.numArraySizeX.Value);+ int arraySizeY = Convert.ToInt32(this.numArraySizeY.Value);+ if (arraySizeX <= 1 && arraySizeY <= 1)+ {+ this.numRandomizePosition.Maximum = 16384m;+ }+ else+ {+ List<int> spacings = new List<int>();+ if (arraySizeX > 1)+ {+ spacings.Add(Convert.ToInt32(this.numSpacingSizeX.Value));+ }+ if (arraySizeY > 1)+ {+ spacings.Add(Convert.ToInt32(this.numSpacingSizeY.Value));+ }+ int minSpacing = spacings[0];+ for (int i = 1; i < spacings.Count; i++)+ {+ if (spacings[i] < minSpacing)+ {+ minSpacing = spacings[i];+ }+ }+ this.numRandomizePosition.Maximum = new decimal(Math.Max(0, minSpacing / 2));+ }+ }++ /// <summary>Leaving an array size input with an even value bumps it to the next odd number (capped at the maximum) and tells the user; the array must have a centre element.</summary>+ private void ArraySize_Validating(object sender, CancelEventArgs e)+ {+ NumericUpDown input = (NumericUpDown)sender;+ int value = Convert.ToInt32(input.Value);+ if (value % 2 != 0)+ {+ return;+ }+ int adjusted = Math.Min(Convert.ToInt32(input.Maximum), value + 1);+ input.Value = new decimal(adjusted);+ MessageBox.Show(this, "Use uneven numbers only - the array size has been increased to " + adjusted.ToString(CultureInfo.InvariantCulture) + ".", "Array size", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ }++ /// <summary>Any main tab change cancels a running position pick; arriving on the source tab loads the scene picture if needed and re-syncs the list selection with the editor.</summary>+ private void SourceTabChanged(object sender, EventArgs e)+ {+ this.EndSourcePick();+ if (this.tabMainFunctions.SelectedTab == this.tabSourceList)+ {+ this.AutoLoadSceneImageIfEmpty(this._picSource);+ this.SyncSourceListSelectionToEditor();+ }+ }++ /// <summary>Makes the list selection match <c>_currentSourceIndex</c> without triggering the selection handler, then reloads the editor from <c>_editing</c>.</summary>+ private void SyncSourceListSelectionToEditor()+ {+ this._syncingSourceList = true;+ try+ {+ if (this._currentSourceIndex >= 0 && this._currentSourceIndex < this.lstSources.Items.Count)+ {+ this.lstSources.SelectedIndex = this._currentSourceIndex;+ }+ else+ {+ this.lstSources.SelectedIndex = -1;+ }+ }+ finally+ {+ this._syncingSourceList = false;+ }+ this.ShowSourceInControls(this._editing);+ }++ /// <summary>Toggles position picking on the scene picture; the button reads "Cancel" while picking.</summary>+ private void PickSourcePosition_Click(object sender, EventArgs e)+ {+ if (this._sourcePicking)+ {+ this.EndSourcePick();+ }+ else+ {+ this.StartSourcePick();+ }+ }++ /// <summary>Enters pick mode (cross cursor, "Cancel" button, status hint) after making sure the picture box has an image; shows a message and stays idle when the canvas size is unknown.</summary>+ private void StartSourcePick()+ {+ if (this._picSource.Image == null)+ {+ this.EnsureSourcePicture();+ }+ if (this._picSource.Image == null)+ {+ MessageBox.Show(this, "There is no picture to pick from yet, and the canvas size is not known either\r\n(choose a scene image, or a user defined width and height, on the Configuration tab first).", "Source position", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ this._sourcePicking = true;+ this._picSource.Cursor = Cursors.Cross;+ this.btnPickSourcePosition.Text = "Cancel";+ this.ToolStripStatusLabel1.Text = "Click in the picture for the position of the source (press Cancel to stop picking).";+ }++ /// <summary>Creates a black canvas-sized picture when no scene image is loaded yet; the bitmap is owned by the picture box. No-op when the canvas size is unknown.</summary>+ private void EnsureSourcePicture()+ {+ Size canvas = this.EffectiveCanvas();+ if (canvas.Width <= 0 || canvas.Height <= 0)+ {+ return;+ }+ Bitmap bitmap = new Bitmap(canvas.Width, canvas.Height);+ using (Graphics g = Graphics.FromImage(bitmap))+ {+ g.Clear(Color.Black);+ }+ this._picSource.Image = bitmap;+ }++ /// <summary>Leaves pick mode and restores cursor, button text and status bar; no-op when not picking.</summary>+ private void EndSourcePick()+ {+ if (!this._sourcePicking)+ {+ return;+ }+ this._sourcePicking = false;+ this.btnPickSourcePosition.Text = this._pickSourceButtonText;+ if (this._picSource != null)+ {+ this._picSource.Cursor = Cursors.Default;+ }+ this.ToolStripStatusLabel1.Text = "";+ }++ /// <summary>+ /// A left click on the scene picture while picking converts the click to canvas pixels,+ /// writes them into the position inputs and the edited source, ends the pick and, when+ /// an existing list entry is being edited, saves the source immediately. Clicks outside+ /// the image are ignored.+ /// </summary>+ private void SourcePicture_MouseClick(object sender, MouseEventArgs e)+ {+ if (!this._sourcePicking || e.Button != MouseButtons.Left)+ {+ return;+ }+ int canvasX = 0;+ int canvasY = 0;+ if (!this.TryPictureToCanvas(this._picSource, e.Location, ref canvasX, ref canvasY))+ {+ return;+ }+ this.numSourcePositionX.Value = Form1.ClampToRange(this.numSourcePositionX, canvasX);+ this.numSourcePositionY.Value = Form1.ClampToRange(this.numSourcePositionY, canvasY);+ if (!this._loadingSource)+ {+ this._editing.PosX = canvasX;+ this._editing.PosY = canvasY;+ this._editing.HasPosition = true;+ this._picSource.Invalidate();+ }+ this.EndSourcePick();+ if (this._currentSourceIndex >= 0)+ {+ this.CommitSourceEdits();+ }+ }++ /// <summary>Editing a position input moves the edited source (and flags it as positioned) so its marker follows on the scene picture before saving.</summary>+ private void SourcePosition_ValueChanged(object sender, EventArgs e)+ {+ if (this._loadingSource)+ {+ return;+ }+ this._editing.PosX = Convert.ToInt32(this.numSourcePositionX.Value);+ this._editing.PosY = Convert.ToInt32(this.numSourcePositionY.Value);+ this._editing.HasPosition = true;+ if (this._picSource != null)+ {+ this._picSource.Invalidate();+ }+ }++ /// <summary>+ /// Draws a marker for every positioned source over the scene picture: saved sources in+ /// blue, the one being edited (taken from <c>_editing</c>, so unsaved moves show) in+ /// yellow, plus the unsaved new source when nothing is selected. Canvas pixels are scaled+ /// to the zoomed image rectangle of the picture box.+ /// </summary>+ private void SourcePicture_Paint(object sender, PaintEventArgs e)+ {+ if (this._picSource.Image == null)+ {+ return;+ }+ Size canvas = this.EffectiveCanvas();+ if (canvas.Width <= 0)+ {+ canvas = this._picSource.Image.Size;+ }+ RectangleF imageRect = Form1.ZoomedImageRectangle(this._picSource);+ if (imageRect.Width <= 0f)+ {+ return;+ }+ float scaleX = imageRect.Width / canvas.Width;+ float scaleY = imageRect.Height / canvas.Height;+ for (int i = 0; i < this._sources.Count; i++)+ {+ bool isCurrent = i == this._currentSourceIndex;+ SourceSettings source = (isCurrent ? this._editing : this._sources[i]);+ if (source.HasPosition)+ {+ Form1.DrawSourceMarker(e.Graphics, source, imageRect, scaleX, scaleY, isCurrent);+ }+ }+ if (this._currentSourceIndex < 0 && this._editing.HasPosition)+ {+ Form1.DrawSourceMarker(e.Graphics, this._editing, imageRect, scaleX, scaleY, true);+ }+ }++ /// <summary>Draws a circle-and-crosshair marker with the source name at the source position; the current source is drawn larger and in yellow, others in blue.</summary>+ /// <param name="g">Target surface of the picture box's paint event.</param>+ /// <param name="s">Source whose canvas-pixel position and name are drawn.</param>+ /// <param name="area">Rectangle the canvas occupies inside the picture box, in picture-box pixels.</param>+ /// <param name="sx">Picture-box pixels per canvas pixel horizontally.</param>+ /// <param name="sy">Picture-box pixels per canvas pixel vertically.</param>+ /// <param name="isCurrent">True for the source being edited (larger yellow marker).</param>+ private static void DrawSourceMarker(Graphics g, SourceSettings s, RectangleF area, float sx, float sy, bool isCurrent)+ {+ Color color = (isCurrent ? Color.FromArgb(230, 255, 208, 64) : Color.FromArgb(200, 64, 180, 255));+ float radius = (isCurrent ? 5f : 4f);+ float cx = area.X + s.PosX * sx;+ float cy = area.Y + s.PosY * sy;+ using (Pen pen = new Pen(color, isCurrent ? 2f : 1.5f))+ {+ g.DrawEllipse(pen, cx - radius, cy - radius, radius * 2f, radius * 2f);+ g.DrawLine(pen, cx - radius - 3f, cy, cx + radius + 3f, cy);+ g.DrawLine(pen, cx, cy - radius - 3f, cx, cy + radius + 3f);+ }+ using (Font font = new Font("Segoe UI", 11f, FontStyle.Bold, GraphicsUnit.Pixel))+ {+ using (SolidBrush brush = new SolidBrush(color))+ {+ g.DrawString(s.Name, font, brush, cx + radius + 4f, cy - radius - 2f);+ }+ }+ }++ /// <summary>+ /// Draws the generated elements of the source being edited on black, centred in the+ /// preview box. With auto-rescale on, the element bounding box is scaled to 70 % of the+ /// smaller box dimension and each element is a 6 px dot; otherwise elements are drawn+ /// 1:1 as single pixels. Empty until the source has been saved once.+ /// </summary>+ private void picPreviewSource_Paint(object sender, PaintEventArgs e)+ {+ e.Graphics.Clear(Color.Black);+ List<SourceElement> elements = ((this._editing != null) ? this._editing.Elements : null);+ if (elements == null || elements.Count == 0)+ {+ return;+ }+ int minX = elements[0].PosX;+ int maxX = elements[0].PosX;+ int minY = elements[0].PosY;+ int maxY = elements[0].PosY;+ foreach (SourceElement element in elements)+ {+ if (element.PosX < minX)+ {+ minX = element.PosX;+ }+ if (element.PosX > maxX)+ {+ maxX = element.PosX;+ }+ if (element.PosY < minY)+ {+ minY = element.PosY;+ }+ if (element.PosY > maxY)+ {+ maxY = element.PosY;+ }+ }+ float width = this.picPreviewSource.ClientSize.Width;+ float height = this.picPreviewSource.ClientSize.Height;+ if (width <= 0f || height <= 0f)+ {+ return;+ }+ float centerX = (minX + maxX) / 2f;+ float centerY = (minY + maxY) / 2f;+ bool autoRescale = this.chkAutoRescaleSourceOn == null || this.chkAutoRescaleSourceOn.Checked;+ float scale;+ if (autoRescale)+ {+ float halfExtent = Math.Max(maxX - minX, maxY - minY) / 2f;+ if (halfExtent <= 0f)+ {+ halfExtent = 1f;+ }+ float targetSize = Math.Min(width, height) * 0.7f;+ scale = targetSize / (halfExtent * 2f);+ }+ else+ {+ scale = 1f;+ }+ using (SolidBrush brush = new SolidBrush(Color.White))+ {+ foreach (SourceElement element in elements)+ {+ float px = width / 2f + (element.PosX - centerX) * scale;+ float py = height / 2f + (element.PosY - centerY) * scale;+ if (autoRescale)+ {+ e.Graphics.FillEllipse(brush, px - 3f, py - 3f, 6f, 6f);+ }+ else+ {+ e.Graphics.FillRectangle(brush, px, py, 1f, 1f);+ }+ }+ }+ }++ /// <summary>Resizing the preview box repaints it so the elements stay centred.</summary>+ private void picPreviewSource_SizeChanged(object sender, EventArgs e)+ {+ this.picPreviewSource.Invalidate();+ }++ /// <summary>Toggling auto-rescale repaints the preview in the other scale mode.</summary>+ private void chkAutoRescaleSourceOn_CheckedChanged(object sender, EventArgs e)+ {+ this.picPreviewSource.Invalidate();+ }+ }+}diff --git a/Wave_Dude_2D/Form1.cs b/Wave_Dude_2D/Form1.csnew file mode 100644index 0000000..4a0ca3f--- /dev/null+++ b/Wave_Dude_2D/Form1.cs@@ -0,0 +1,1305 @@+using System;+using System.Collections.Generic;+using System.Diagnostics;+using System.Drawing;+using System.Globalization;+using System.IO;+using System.Runtime.InteropServices;+using System.Windows.Forms;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Main window of the wave simulator. This part holds start-up and shutdown, the File/Info+ /// menus, project open/save, the hand-built modal prompts, and every private field and+ /// nested type shared by the other <c>Form1.*.cs</c> parts (Colors, Projects, Output, Scene,+ /// Simulation, Probes, Sources). All of it runs on the UI thread; the only other thread is+ /// the <see cref="SimulationRunner"/> worker, whose events are marshalled back through+ /// <see cref="PostToUi"/> in the Simulation part.+ /// </summary>+ public partial class Form1 : Form+ {+ /// <summary>+ /// Wires the form lifetime events, gives every shared field its start value (empty+ /// settings objects, default sort orders, the root-blink timer, an unnamed source being+ /// edited) and then runs the designer code. The real set-up continues in+ /// <see cref="Form1_Load"/>.+ /// </summary>+ public Form1()+ {+ base.Load += this.Form1_Load;+ base.FormClosed += this.Form1_FormClosed;+ base.FormClosing += this.Form1_FormClosing;+ this._schemes = new List<ColorScheme>();+ this._selectedStop = -1;+ this._thumbs = new ImageList();+ this._projectSortColumn = 1;+ this._projectSortAscending = false;+ this._outputProjectSortColumn = 1;+ this._outputProjectSortAscending = false;+ this._schemeSortColumn = 2;+ this._schemeSortAscending = true;+ this._sceneSortColumn = 1;+ this._sceneSortAscending = false;+ this._imageSortColumn = 1;+ this._imageSortAscending = false;+ this._videoSortColumn = 1;+ this._videoSortAscending = false;+ this._thumbBitmaps = new List<Bitmap>();+ this._settings = new AppSettings();+ this._rootBlinkTimer = new global::System.Windows.Forms.Timer+ {+ Interval = 700+ };+ this._rootBlinkTimer.Tick += this.RootBlinkTimer_Tick;+ this._scene = new SceneSettings();+ this._sceneTip = new ToolTip();+ this._simulation = new SimulationSettings();+ this._simStatus = "";+ this._fieldVideoFile = "";+ this._intensityVideoFile = "";+ this._runInfo = "";+ this._progressText = "";+ this._probes = Form1.NewProbeList();+ this._probeTraces = new List<ProbeTrace>();+ this._sources = new List<SourceSettings>();+ this._currentSourceIndex = -1;+ this._editing = new SourceSettings();+ this._pickSourceButtonText = "Pick";+ this._sourceRandom = new Random();+ this.InitializeComponent();+ }++ /// <summary>+ /// Finishes what the designer cannot express: collects the nine colour-stop buttons,+ /// configures the scheme list view and its thumbnail list, embeds the+ /// <see cref="ColorPickerControl"/>, switches the main tab control to owner drawing,+ /// loads the default scheme folder, runs the per-tab initialisers, re-parents+ /// <c>btnPickRoot</c> so it stays clickable while <c>grpProjects</c> is disabled, loads the+ /// user settings and project list, and makes Enter in any <see cref="NumericUpDown"/>+ /// move the focus on.+ /// </summary>+ private void Form1_Load(object sender, EventArgs e)+ {+ this._stopButtons = new Button[] { this.btnColor1, this.btnCOlor2, this.btnColor3, this.btnColor4, this.btnColor5, this.btnColor6, this.btnColor7, this.btnColor8, this.btnColor9 };+ Debug.Assert(this._stopButtons.Length == 9, "The number of Color buttons must equal ColorScheme.StopCount.");+ foreach (Button button in this._stopButtons)+ {+ button.UseVisualStyleBackColor = false;+ button.FlatStyle = FlatStyle.Flat;+ button.FlatAppearance.BorderSize = 1;+ button.FlatAppearance.BorderColor = Color.Black;+ }+ this._thumbs.ImageSize = new Size(120, 16);+ this._thumbs.ColorDepth = ColorDepth.Depth32Bit;+ this.ListView1.View = View.Details;+ this.ListView1.FullRowSelect = true;+ this.ListView1.MultiSelect = false;+ this.ListView1.HideSelection = false;+ this.ListView1.HeaderStyle = ColumnHeaderStyle.Clickable;+ this.ListView1.SmallImageList = this._thumbs;+ this.ListView1.Columns.Clear();+ this.ListView1.Columns.Add("Scheme", 250);+ this.ListView1.Columns.Add("Kind", 55);+ this.ListView1.Columns.Add("Type", 62);+ this.UpdateSchemeListSortHeaders();+ this.pnlScheme.BorderStyle = BorderStyle.FixedSingle;+ this.Panel2.BorderStyle = BorderStyle.FixedSingle;+ this._picker = new ColorPickerControl();+ this._picker.Dock = DockStyle.Fill;+ this.Panel2.Controls.Add(this._picker);+ this._picker.ColorChanged += this.Picker_ColorChanged;+ this.txtCurrentColorScheme.ReadOnly = true;+ this.tabMainFunctions.DrawMode = TabDrawMode.OwnerDrawFixed;+ this.UpdateProjectListSortHeaders();+ this.txtSchemeFolder.Text = ColorSchemeStore.FindDefaultFolder();+ if (Directory.Exists(this.txtSchemeFolder.Text))+ {+ this.LoadSchemeList();+ }+ this.RefreshEditorState();+ this.lblInfo.ForeColor = Color.Blue;+ this.lblInfo.Cursor = Cursors.Hand;+ this.InitializeSceneControls();+ this.InitializeSimulationControls();+ this.InitializeProbeControls();+ this.InitializeSourceControls();+ // The designer places btnPickRoot inside grpProjects, but UpdateProjectAccess disables+ // that group while no root is chosen - which is exactly when the button is needed.+ // Move it to the tab page at the same screen position so it stays enabled.+ Point location = this.grpProjects.Location;+ location.Offset(this.btnPickRoot.Location);+ this.grpProjects.Controls.Remove(this.btnPickRoot);+ this.tabConfiguration.Controls.Add(this.btnPickRoot);+ this.btnPickRoot.Location = location;+ this.btnPickRoot.BringToFront();+ this.InitializeProject();+ this.InitializeOutputsTab();+ this.HookNumericUpDownEnterKey(this);+ }++ /// <summary>Recursively attaches <see cref="NumericUpDown_KeyDown"/> to every <see cref="NumericUpDown"/> below <paramref name="root"/>.</summary>+ private void HookNumericUpDownEnterKey(Control root)+ {+ foreach (Control control in root.Controls)+ {+ NumericUpDown numericUpDown = control as NumericUpDown;+ if (numericUpDown != null)+ {+ numericUpDown.KeyDown += this.NumericUpDown_KeyDown;+ }+ if (control.HasChildren)+ {+ this.HookNumericUpDownEnterKey(control);+ }+ }+ }++ /// <summary>Enter in a spinner commits its value by moving focus to the next control (and suppresses the beep).</summary>+ private void NumericUpDown_KeyDown(object sender, KeyEventArgs e)+ {+ if (e.KeyCode != Keys.Return)+ {+ return;+ }+ e.SuppressKeyPress = true;+ e.Handled = true;+ Control control = sender as Control;+ if (control != null)+ {+ base.SelectNextControl(control, true, true, true, true);+ }+ }++ /// <summary>Disposes every bitmap the form owns: preview frames, scheme thumbnails, the scene image, the empty-canvas placeholder and the output preview.</summary>+ private void Form1_FormClosed(object sender, FormClosedEventArgs e)+ {+ this.ClearPreviews();+ foreach (Bitmap bitmap in this._thumbBitmaps)+ {+ bitmap.Dispose();+ }+ this._thumbBitmaps.Clear();+ this.ReplaceSceneImage(null);+ this.DisposeEmptyPreview();+ this.ClearOutputPreview();+ }++ /// <summary>+ /// Vetoes closing when the user declines the save-project prompt, declines stopping a+ /// running simulation (otherwise it is cancelled and given up to 15 s to exit), or+ /// declines discarding unsaved colour-scheme edits.+ /// </summary>+ private void Form1_FormClosing(object sender, FormClosingEventArgs e)+ {+ if (!this.ConfirmSaveProject())+ {+ e.Cancel = true;+ return;+ }+ if (this._runner != null)+ {+ if (MessageBox.Show(this, "A simulation is running. Stop it and close the program?", "Simulation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)+ {+ e.Cancel = true;+ return;+ }+ this._runner.Cancel();+ this._runner.WaitForExit(15000);+ }+ if (this._dirty)+ {+ if (MessageBox.Show(this, "The current color scheme has unsaved changes. Close anyway?", "Unsaved changes", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)+ {+ e.Cancel = true;+ }+ }+ }++ /// <summary>+ /// Enables the project list and output tab only when a project root is chosen (and blinks+ /// <c>btnPickRoot</c> while none is), and the editing tabs, buttons and groups only when+ /// a project is open. Repaints the tab headers so disabled tabs grey out.+ /// </summary>+ private void UpdateProjectAccess()+ {+ bool hasRoot = this._settings.ProjectRoot.Length > 0;+ bool hasProject = this._project != null;+ this.grpProjects.Enabled = hasRoot;+ this.tabOutput.Enabled = hasRoot;+ if (hasRoot)+ {+ this._rootBlinkTimer.Stop();+ this._rootBlinkOn = false;+ this.btnPickRoot.UseVisualStyleBackColor = true;+ }+ else+ {+ this._rootBlinkTimer.Start();+ }+ this.grpSceneProperties.Enabled = hasProject;+ this.grpSimulationSettings.Enabled = hasProject;+ this.tabSourceList.Enabled = hasProject;+ this.tabProbeList.Enabled = hasProject;+ this.tabViewer.Enabled = hasProject;+ this.btnGotoPreview.Enabled = hasProject;+ this.btnGotoProbes.Enabled = hasProject;+ this.btnGotoSources.Enabled = hasProject;+ this.grpSimulationControlButtons.Enabled = hasProject;+ this.grpShareImage.Enabled = hasProject;+ this.btnSaveConfiguration.Enabled = hasProject;+ this.btnSaveConfiguration2.Enabled = hasProject;+ this.btnSaveAs.Enabled = hasProject;+ this.btnDescription.Enabled = hasProject;+ this.tabMainFunctions.Invalidate();+ }++ /// <summary>Every 700 ms while no root is chosen: toggles <c>btnPickRoot</c> between light blue and the normal button colour.</summary>+ private void RootBlinkTimer_Tick(object sender, EventArgs e)+ {+ this._rootBlinkOn = !this._rootBlinkOn;+ this.btnPickRoot.UseVisualStyleBackColor = false;+ this.btnPickRoot.BackColor = (this._rootBlinkOn ? Color.LightBlue : SystemColors.Control);+ }++ /// <summary>Refuses to switch to a tab that <see cref="UpdateProjectAccess"/> disabled and tells the user to open a project first.</summary>+ private void tabMainFunctions_Selecting(object sender, TabControlCancelEventArgs e)+ {+ if (!e.TabPage.Enabled)+ {+ e.Cancel = true;+ MessageBox.Show(this, "Please open or create a project first.", "No project", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ }+ }++ /// <summary>Owner-draws a tab header: window colour for the selected tab, control colour otherwise, silver text when the page is disabled.</summary>+ private void tabMainFunctions_DrawItem(object sender, DrawItemEventArgs e)+ {+ TabPage tabPage = this.tabMainFunctions.TabPages[e.Index];+ Rectangle tabRect = this.tabMainFunctions.GetTabRect(e.Index);+ Color backColor = ((e.Index == this.tabMainFunctions.SelectedIndex) ? SystemColors.Window : SystemColors.Control);+ using (SolidBrush brush = new SolidBrush(backColor))+ {+ e.Graphics.FillRectangle(brush, tabRect);+ }+ Color textColor = (tabPage.Enabled ? SystemColors.ControlText : Color.Silver);+ TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter;+ TextRenderer.DrawText(e.Graphics, tabPage.Text, this.tabMainFunctions.Font, tabRect, textColor, flags);+ }++ /// <summary>+ /// Replaces the placeholder <see cref="_settings"/> with the values read from disk, shows+ /// the stored project root, and refreshes access state, title and project list. No+ /// project is opened automatically.+ /// </summary>+ private void InitializeProject()+ {+ this._settings = AppSettings.Load();+ this.txtRootFolder.Text = this._settings.ProjectRoot;+ this.txtProjectName.Text = "";+ this.UpdateProjectAccess();+ this.UpdateTitle();+ this.RefreshProjectList();+ }++ /// <summary>File > Open: asks for an existing project folder, offers to save the current project, then opens the chosen one.</summary>+ private void OpenProject_Click(object sender, EventArgs e)+ {+ try+ {+ string folder = this.BrowseForFolder("Choose the main folder of the project (the folder that contains configuration.json)", this.txtRootFolder.Text.Trim(), false);+ if (folder.Length > 0 && this.ConfirmSaveProject())+ {+ this.SetCurrentProject(ProjectStore.Open(folder));+ }+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The project could not be opened:\r\n\r\n" + ex.Message, "Open project", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ }+ }++ /// <summary>File > Save and the "Save changes to project" button: saves the open project (see <see cref="SaveProject"/>).</summary>+ private void SaveProject_Click(object sender, EventArgs e)+ {+ this.SaveProject();+ }++ /// <summary>"Save as": asks for a new project name and saves the current settings as that project in the current root folder.</summary>+ private void SaveAs_Click(object sender, EventArgs e)+ {+ string root = this.txtRootFolder.Text.Trim();+ if (root.Length == 0)+ {+ MessageBox.Show(this, "Enter a root folder first (double-click the box to browse).", "Save project as", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ string projectName = this.txtProjectName.Text.Trim();+ if (!this.PromptForText("Save project as", "New project name (saved in the current root folder):", projectName, ref projectName))+ {+ return;+ }+ projectName = projectName.Trim();+ string error = ProjectStore.ValidateName(projectName);+ if (error.Length > 0)+ {+ MessageBox.Show(this, error, "Save project as", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ return;+ }+ this.SaveProjectTo(root, projectName);+ }++ /// <summary>Opens <see cref="frmDescription"/> for the open project and, on OK, writes the new description to disk at once (without touching <see cref="_projectDirty"/>).</summary>+ private void btnDescription_Click(object sender, EventArgs e)+ {+ if (this._project == null)+ {+ return;+ }+ using (frmDescription dialog = new frmDescription())+ {+ dialog.DescriptionText = this._project.Config.Description;+ if (dialog.ShowDialog(this) == DialogResult.OK)+ {+ this._project.Config.Description = dialog.DescriptionText;+ this._project.Save();+ }+ }+ }++ /// <summary>File > Exit: closes the window (the closing checks run in <see cref="Form1_FormClosing"/>).</summary>+ private void ExitProgram_Click(object sender, EventArgs e)+ {+ base.Close();+ }++ /// <summary>Info > Help: shows the <see cref="HelpForm"/> modally.</summary>+ private void HelpToolStripMenuItem_Click(object sender, EventArgs e)+ {+ using (HelpForm helpForm = new HelpForm())+ {+ helpForm.ShowDialog(this);+ }+ }++ /// <summary>Info > About: shows the <see cref="AboutForm"/> modally.</summary>+ private void AboutToolStripMenuItem_Click(object sender, EventArgs e)+ {+ using (AboutForm aboutForm = new AboutForm())+ {+ aboutForm.ShowDialog(this);+ }+ }++ /// <summary>+ /// File > Choose project root (also the Browse/Pick root buttons and a double-click on the+ /// root text box): asks for a folder, stores it in the user settings immediately and+ /// refreshes the project list. The open project, if any, is left as it is.+ /// </summary>+ private void ChooseProjectRootToolStripMenuItem_Click(object sender, EventArgs e)+ {+ string startFolder = ((this._settings.ProjectRoot.Length > 0) ? this._settings.ProjectRoot : this.txtRootFolder.Text.Trim());+ string folder = this.BrowseForFolder("Choose the root folder that contains your project folders", startFolder, true);+ if (folder.Length == 0)+ {+ return;+ }+ this._settings.ProjectRoot = folder;+ this._settings.Save();+ this.txtRootFolder.Text = folder;+ this.UpdateProjectAccess();+ this.RefreshProjectList();+ }++ /// <summary>Clicking the "(Info)" label shows the explanation of 4th-order processing, dispersion and the c-value.</summary>+ private void lblInfo_Click(object sender, EventArgs e)+ {+ MessageBox.Show(this, "The standard 3rd order Laplacian processing inherently leads to large dispersion, meaning that longer wavelengths propagate faster through the medium. Choosing 4th order processing (including sub-step sampling) reduces this effect significantly. However, processing is somewhat slower. Another effect of 4th order processing is that it requires a different propagation speed (c). The value can be specified per project and set in the File menu. For 4th order processing choose 1.00 for c. For standard processing, this value can be quite a bit different. For example, with standard processing for waves with a frequency of 100, c = 0.56, leading in this case to a wavelength of only 9 pixels (instead of 15). Because of the dispersion present in standard processing, the exact value of c is strongly dependent on the frequency. (lower frequencies -> higher c value; higher frequencies -> lower c value).", "4th order Laplacian and wave speed (c)", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ }++ /// <summary>+ /// File > Set c-value: prompts for the wave speed (pixels per step), stores it in+ /// <see cref="SimulationSettings.WaveSpeedC"/>, marks the project changed if it differs,+ /// and refreshes the wavelength read-out on the Sources tab.+ /// </summary>+ private void SetCValueToolStripMenuItem_Click(object sender, EventArgs e)+ {+ double cValue = 0.0;+ if (!this.PromptForCValue(this._simulation.WaveSpeedC, ref cValue))+ {+ return;+ }+ if (cValue != this._simulation.WaveSpeedC)+ {+ this._simulation.WaveSpeedC = cValue;+ this.MarkProjectChanged();+ }+ this.UpdateLambdaLabel();+ }++ /// <summary>+ /// Shows a hand-built modal dialog with a 3-decimal spinner (0.001 to 1,000,000) for the+ /// wave speed c. <paramref name="current"/> is clamped into that range before display.+ /// </summary>+ /// <param name="current">Value shown when the dialog opens.</param>+ /// <param name="result">Receives the entered value on OK, or <paramref name="current"/> on cancel.</param>+ /// <returns>True when the user pressed OK.</returns>+ private bool PromptForCValue(double current, ref double result)+ {+ using (Form dlg = new Form())+ {+ dlg.Text = "Set c-value";+ dlg.FormBorderStyle = FormBorderStyle.FixedDialog;+ dlg.StartPosition = FormStartPosition.CenterParent;+ dlg.MinimizeBox = false;+ dlg.MaximizeBox = false;+ dlg.ShowInTaskbar = false;+ dlg.ClientSize = new Size(340, 116);+ Label label = new Label();+ label.Text = "Wave propagation speed c (in pixels per step)\r\n(lambda = c / frequency).\r\nOnly used to estimate a source's wavelength in screen pixels";+ label.SetBounds(12, 10, 316, 44);+ NumericUpDown numValue = new NumericUpDown();+ numValue.DecimalPlaces = 3;+ numValue.Minimum = 0.001m;+ numValue.Maximum = 1000000m;+ numValue.Increment = 0.1m;+ numValue.SetBounds(12, 60, 110, 22);+ double clamped = Math.Max(Convert.ToDouble(numValue.Minimum), Math.Min(Convert.ToDouble(numValue.Maximum), current));+ numValue.Value = new decimal(clamped);+ Button btnOk = new Button();+ btnOk.Text = "OK";+ btnOk.DialogResult = DialogResult.OK;+ btnOk.SetBounds(152, 80, 84, 26);+ Button btnCancel = new Button();+ btnCancel.Text = "Cancel";+ btnCancel.DialogResult = DialogResult.Cancel;+ btnCancel.SetBounds(244, 80, 84, 26);+ dlg.Controls.AddRange(new Control[] { label, numValue, btnOk, btnCancel });+ dlg.AcceptButton = btnOk;+ dlg.CancelButton = btnCancel;+ if (dlg.ShowDialog(this) == DialogResult.OK)+ {+ result = Convert.ToDouble(numValue.Value);+ return true;+ }+ }+ result = current;+ return false;+ }++ /// <summary>+ /// Shows a hand-built modal dialog with one single-line text box (pre-filled and selected).+ /// Used for new/renamed project, scheme and video names.+ /// </summary>+ /// <param name="title">Dialog caption.</param>+ /// <param name="prompt">Label shown above the text box.</param>+ /// <param name="defaultValue">Initial text, shown selected.</param>+ /// <param name="result">Receives the untrimmed text on OK, or <paramref name="defaultValue"/> on cancel.</param>+ /// <returns>True when the user pressed OK.</returns>+ private bool PromptForText(string title, string prompt, string defaultValue, ref string result)+ {+ using (Form dlg = new Form())+ {+ dlg.Text = title;+ dlg.FormBorderStyle = FormBorderStyle.FixedDialog;+ dlg.StartPosition = FormStartPosition.CenterParent;+ dlg.MinimizeBox = false;+ dlg.MaximizeBox = false;+ dlg.ShowInTaskbar = false;+ dlg.ClientSize = new Size(340, 110);+ Label label = new Label();+ label.Text = prompt;+ label.SetBounds(12, 10, 316, 20);+ TextBox txt = new TextBox();+ txt.SetBounds(12, 34, 316, 22);+ txt.Text = defaultValue;+ txt.SelectAll();+ Button btnOk = new Button();+ btnOk.Text = "OK";+ btnOk.DialogResult = DialogResult.OK;+ btnOk.SetBounds(152, 68, 84, 26);+ Button btnCancel = new Button();+ btnCancel.Text = "Cancel";+ btnCancel.DialogResult = DialogResult.Cancel;+ btnCancel.SetBounds(244, 68, 84, 26);+ dlg.Controls.AddRange(new Control[] { label, txt, btnOk, btnCancel });+ dlg.AcceptButton = btnOk;+ dlg.CancelButton = btnCancel;+ dlg.ActiveControl = txt;+ if (dlg.ShowDialog(this) == DialogResult.OK)+ {+ result = txt.Text;+ return true;+ }+ }+ result = defaultValue;+ return false;+ }++ /// <summary>+ /// Saves the current settings under the root folder and project name shown in the text+ /// boxes, after validating both (focusing the offending box on failure).+ /// </summary>+ /// <returns>True when the project was written; false when validation failed, the user cancelled or saving failed.</returns>+ private bool SaveProject()+ {+ string root = this.txtRootFolder.Text.Trim();+ string projectName = this.txtProjectName.Text.Trim();+ if (root.Length == 0)+ {+ MessageBox.Show(this, "Enter a root folder first (double-click the box to browse).", "Save project", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ this.txtRootFolder.Focus();+ return false;+ }+ string error = ProjectStore.ValidateName(projectName);+ if (error.Length > 0)+ {+ MessageBox.Show(this, error, "Save project", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ this.txtProjectName.Focus();+ return false;+ }+ return this.SaveProjectTo(root, projectName);+ }++ /// <summary>+ /// Writes the scene, simulation, probe and source settings into the project+ /// <c><root>\<projectName></c> and makes it the current project. The target is the+ /// open project when it is that same folder; an existing project there after an overwrite+ /// confirmation; otherwise a newly created one (offering to create a missing root folder).+ /// A scene image from outside the target folder is copied in first+ /// (<see cref="PrepareSceneImageFor"/>).+ /// </summary>+ /// <returns>True when saved; false when the user declined a prompt or an error was shown.</returns>+ private bool SaveProjectTo(string root, string projectName)+ {+ try+ {+ string rootFolder = ProjectStore.NormalizeFolder(root);+ string projectFolder = Path.Combine(rootFolder, projectName);+ Project previous = this._project;+ Project target;+ if (previous != null && string.Equals(projectFolder, previous.FolderPath, StringComparison.OrdinalIgnoreCase))+ {+ target = previous;+ }+ else if (ProjectStore.IsProjectFolder(projectFolder))+ {+ if (MessageBox.Show(this, "A project named '" + projectName + "' already exists in the root folder\r\n" + rootFolder + "\r\n\r\nOverwrite its configuration with the current settings?", "Save project", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)+ {+ return false;+ }+ target = ProjectStore.Open(projectFolder);+ }+ else+ {+ if (!Directory.Exists(rootFolder))+ {+ if (MessageBox.Show(this, "The root folder does not exist:\r\n" + rootFolder + "\r\n\r\nCreate it?", "Save project", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)+ {+ return false;+ }+ }+ target = ProjectStore.Create(rootFolder, projectName);+ }+ this.PrepareSceneImageFor(target, previous);+ this._scene.ToConfig(target.Config);+ this._simulation.ToConfig(target.Config);+ ProbeSettings.ListToConfig(this._probes, target.Config);+ SourceSettings.ListToConfig(this._sources, target.Config);+ target.Save();+ this.SetCurrentProject(target);+ return true;+ }+ catch (Exception ex)+ {+ MessageBox.Show(this, "The project could not be saved:\r\n\r\n" + ex.Message, "Save project", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);+ return false;+ }+ }++ /// <summary>+ /// When saving into a different project than the scene image came from, copies the image+ /// into <paramref name="target"/>'s scene-image folder (unless it already lies inside the+ /// target) and rewrites <see cref="SceneSettings.ImageFile"/> as a path stored relative to+ /// the target. No-op when there is no scene image or the target is the previous project.+ /// </summary>+ /// <param name="target">The project about to be saved.</param>+ /// <param name="previous">The project the image path is currently relative to; null for an unsaved project.</param>+ private void PrepareSceneImageFor(Project target, Project previous)+ {+ if (this._scene.ImageFile.Length == 0 || object.ReferenceEquals(target, previous))+ {+ return;+ }+ string previousFolder = ((previous == null) ? "" : previous.FolderPath);+ string imagePath = SceneSettings.ToFullPath(previousFolder, this._scene.ImageFile);+ if (File.Exists(imagePath) && !Form1.IsInsideFolder(imagePath, target.FolderPath))+ {+ imagePath = Form1.CopyIntoSceneImageFolder(target, imagePath);+ }+ this._scene.ImageFile = SceneSettings.ToStoredPath(target.FolderPath, imagePath);+ }++ /// <summary>Case-insensitive test whether <paramref name="fullPath"/> lies below <paramref name="folder"/> (both resolved to full paths); false for an empty folder.</summary>+ private static bool IsInsideFolder(string fullPath, string folder)+ {+ if (string.IsNullOrEmpty(folder))+ {+ return false;+ }+ string prefix = folder.TrimEnd(new char[]+ {+ Path.DirectorySeparatorChar,+ Path.AltDirectorySeparatorChar+ }) + Path.DirectorySeparatorChar.ToString();+ return Path.GetFullPath(fullPath).StartsWith(Path.GetFullPath(prefix), StringComparison.OrdinalIgnoreCase);+ }++ /// <summary>+ /// Copies <paramref name="fullPath"/> into the project's <c>scene_images</c> folder. A file+ /// of the same name and the same length is assumed to be the same image and reused; one+ /// with a different length gets a " (2)", " (3)", ... suffix instead.+ /// </summary>+ /// <returns>Full path of the file inside the scene-image folder.</returns>+ private static string CopyIntoSceneImageFolder(Project project, string fullPath)+ {+ Directory.CreateDirectory(project.SceneImageFolder);+ string fileName = Path.GetFileName(fullPath);+ string destination = Path.Combine(project.SceneImageFolder, fileName);+ int suffix = 2;+ while (File.Exists(destination) && new FileInfo(destination).Length != new FileInfo(fullPath).Length)+ {+ destination = Path.Combine(project.SceneImageFolder, Path.GetFileNameWithoutExtension(fileName) + " (" + suffix.ToString(CultureInfo.InvariantCulture) + ")" + Path.GetExtension(fileName));+ suffix++;+ }+ if (!File.Exists(destination))+ {+ File.Copy(fullPath, destination);+ }+ return destination;+ }++ /// <summary>+ /// Before discarding the open project: offers Yes/No/Cancel when it has unsaved changes.+ /// </summary>+ /// <returns>True when the caller may proceed (nothing to save, saved successfully, or "No"); false on Cancel or a failed save.</returns>+ private bool ConfirmSaveProject()+ {+ if (this._project == null || !this._projectDirty)+ {+ return true;+ }+ DialogResult answer = MessageBox.Show(this, "There are unsaved changes in the project '" + this._project.Name + "'. Save them first?", "Unsaved changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);+ if (answer == DialogResult.Yes)+ {+ return this.SaveProject();+ }+ return answer == DialogResult.No;+ }++ /// <summary>+ /// Resets the editor to a fresh, unsaved project: new scene and simulation settings+ /// (keeping the damping-edge and object-source check boxes and the steps/decay spinners as+ /// they are), no scene image, default probes, no sources, no video files, not dirty.+ /// </summary>+ private void StartNewProject()+ {+ this._project = null;+ this._scene = new SceneSettings();+ this._scene.DampingEdgeEnabled = this.chkDampingEdge.Checked;+ this._scene.UseObjectSources = this.chkUseObjectSources.Checked;+ this.ReplaceSceneImage(null);+ this.txtProjectName.Text = "";+ this.ShowSceneInControls();+ this._simulation = new SimulationSettings();+ this._simulation.Steps = Convert.ToInt32(this.numSimulationSteps.Value);+ this._simulation.TimeDecayFactor = Convert.ToDouble(this.numTimeDecayFactor.Value);+ this.ShowSimulationInControls();+ this.ResetProbes();+ this.ResetSources();+ this._fieldVideoFile = "";+ this._intensityVideoFile = "";+ this.UpdateVideoButtons();+ this._projectDirty = false;+ this.UpdateTitle();+ this.txtProjectName.Focus();+ }++ /// <summary>+ /// Makes <paramref name="opened"/> the current project: shows its root and name, persists+ /// them in the user settings, clears the Sources/Probes background pictures when the+ /// folder differs from the previous project, loads scene, simulation, probes and sources+ /// from its configuration, clears the dirty flag and refreshes the project list.+ /// </summary>+ private void SetCurrentProject(Project opened)+ {+ bool projectChanged = this._project == null || !string.Equals(this._project.FolderPath, opened.FolderPath, StringComparison.OrdinalIgnoreCase);+ this._project = opened;+ this.txtRootFolder.Text = opened.RootFolder;+ this.txtProjectName.Text = opened.Name;+ this.UpdateProjectAccess();+ this._settings.LastRootFolder = opened.RootFolder;+ this._settings.LastProjectName = opened.Name;+ this._settings.Save();+ if (projectChanged)+ {+ this.ClearPreviewImage(this._picSource);+ this.ClearPreviewImage(this._picProbe);+ }+ this.LoadSceneFromProject();+ this._simulation = SimulationSettings.FromConfig(this._project.Config);+ this.ShowSimulationInControls();+ this.LoadProbesFromProject();+ this.LoadSourcesFromProject();+ this._projectDirty = false;+ this.UpdateTitle();+ this.RefreshProjectList();+ }++ /// <summary>Removes and disposes the image of <paramref name="pic"/>; tolerates a null box or no image.</summary>+ private void ClearPreviewImage(PictureBox pic)+ {+ if (pic == null || pic.Image == null)+ {+ return;+ }+ Image image = pic.Image;+ pic.Image = null;+ image.Dispose();+ pic.Invalidate();+ }++ /// <summary>+ /// Flags the project as having unsaved changes and updates the title, unless one of the+ /// <c>_loading*</c> re-entrancy guards is set (controls are being filled from settings).+ /// </summary>+ private void MarkProjectChanged()+ {+ if (this._loadingScene || this._loadingSim || this._loadingProbe || this._loadingSource)+ {+ return;+ }+ this._projectDirty = true;+ this.UpdateTitle();+ }++ /// <summary>Sets the window title to "2D wave simulation - name", with " *" when dirty and the run status appended while a simulation runs.</summary>+ private void UpdateTitle()+ {+ string projectName = ((this._project == null) ? "(new project)" : this._project.Name);+ this.Text = "2D wave simulation - " + projectName + (this._projectDirty ? " *" : "") + ((this._simStatus.Length > 0) ? (" | " + this._simStatus) : "");+ }++ /// <summary>+ /// Shows a hand-built modal dialog with a path text box, a "Browse..." button (a+ /// <see cref="FolderBrowserDialog"/> rooted at My Computer) and OK/Cancel. OK is refused+ /// for an empty path, and for a non-existent one unless <paramref name="allowNewFolder"/>.+ /// </summary>+ /// <param name="description">Text shown above the path box and in the folder browser.</param>+ /// <param name="startFolder">Initial contents of the path box.</param>+ /// <param name="allowNewFolder">Accept a folder that does not exist yet (and show the "New folder" button in the browser).</param>+ /// <returns>The trimmed folder path, or an empty string when cancelled.</returns>+ private string BrowseForFolder(string description, string startFolder, bool allowNewFolder)+ {+ using (Form dlg = new Form())+ {+ dlg.Text = "Choose a folder";+ dlg.FormBorderStyle = FormBorderStyle.FixedDialog;+ dlg.StartPosition = FormStartPosition.CenterParent;+ dlg.MinimizeBox = false;+ dlg.MaximizeBox = false;+ dlg.ShowInTaskbar = false;+ dlg.ClientSize = new Size(480, 124);++ Label label = new Label();+ label.Text = description;+ label.SetBounds(12, 10, 456, 34);++ TextBox txt = new TextBox();+ txt.SetBounds(12, 50, 362, 22);+ txt.Text = startFolder;++ Button btnBrowse = new Button();+ btnBrowse.Text = "Browse...";+ btnBrowse.SetBounds(380, 49, 88, 24);+ btnBrowse.Click += (sender, e) =>+ {+ using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())+ {+ folderDialog.Description = description;+ folderDialog.ShowNewFolderButton = allowNewFolder;+ folderDialog.RootFolder = Environment.SpecialFolder.MyComputer;+ if (Directory.Exists(txt.Text.Trim()))+ {+ folderDialog.SelectedPath = txt.Text.Trim();+ }+ if (folderDialog.ShowDialog(dlg) == DialogResult.OK)+ {+ txt.Text = folderDialog.SelectedPath;+ txt.SelectAll();+ }+ }+ };++ Button btnOk = new Button();+ btnOk.Text = "OK";+ btnOk.SetBounds(228, 86, 84, 26);+ btnOk.Click += (sender, e) =>+ {+ string folder = txt.Text.Trim();+ if (folder.Length == 0)+ {+ MessageBox.Show(dlg, "Enter or browse to a folder first.", "Choose a folder", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ }+ else if (!allowNewFolder && !Directory.Exists(folder))+ {+ MessageBox.Show(dlg, "This folder does not exist:\r\n" + folder, "Choose a folder", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);+ }+ else+ {+ dlg.DialogResult = DialogResult.OK;+ dlg.Close();+ }+ };++ Button btnCancel = new Button();+ btnCancel.Text = "Cancel";+ btnCancel.DialogResult = DialogResult.Cancel;+ btnCancel.SetBounds(320, 86, 84, 26);++ dlg.Controls.AddRange(new Control[] { label, txt, btnBrowse, btnOk, btnCancel });+ dlg.AcceptButton = btnOk;+ dlg.CancelButton = btnCancel;+ dlg.ActiveControl = txt;+ if (dlg.ShowDialog(this) == DialogResult.OK)+ {+ return txt.Text.Trim();+ }+ }+ return "";+ }++ // ----- Colors tab (Form1.Colors.cs) -----++ /// <summary>All schemes read from the folder in <c>txtSchemeFolder</c>; feeds the Colors tab list and the field/intensity scheme combos. Replaced wholesale by <see cref="LoadSchemeList"/>.</summary>+ private List<ColorScheme> _schemes;++ /// <summary>The scheme loaded into the editor (a clone of a list entry, or a new unsaved one); null until a scheme is loaded.</summary>+ private ColorScheme _current;++ /// <summary>True when <see cref="_current"/> has edits that are not saved to its file; checked again on closing.</summary>+ private bool _dirty;++ /// <summary>The scheme selected in <c>ListView1</c>, shown read-only in the editor and preview bar; null when nothing is selected.</summary>+ private ColorScheme _previewScheme;++ /// <summary>Index (0..8) of the colour stop of <see cref="_current"/> that the picker is editing; -1 when none.</summary>+ private int _selectedStop;++ /// <summary>Re-entrancy guard: set while <see cref="RefreshEditorState"/> programmatically checks the scheme-type radio buttons.</summary>+ private bool _updatingRadios;++ /// <summary>The nine "Color 1".."Color 9" buttons in stop order (filled in <see cref="Form1_Load"/>).</summary>+ private Button[] _stopButtons;++ /// <summary>The colour picker embedded in <c>Panel2</c> (created in <see cref="Form1_Load"/>).</summary>+ private ColorPickerControl _picker;++ /// <summary>Image list of the 120 x 16 scheme thumbnails shown in <c>ListView1</c>; the bitmaps themselves are owned by <see cref="_thumbBitmaps"/>.</summary>+ private readonly ImageList _thumbs;++ // ----- Project lists (Form1.Projects.cs / Form1.Output.cs) -----++ /// <summary>Sort column of the Settings-tab project list: 0 = name, 1 = last edited (default).</summary>+ private int _projectSortColumn;++ /// <summary>Sort direction of the Settings-tab project list; default descending (newest first).</summary>+ private bool _projectSortAscending;++ /// <summary>Sort column of the Manage-output project list: 0 = name, 1 = last edited (default).</summary>+ private int _outputProjectSortColumn;++ /// <summary>Sort direction of the Manage-output project list; default descending (newest first).</summary>+ private bool _outputProjectSortAscending;++ /// <summary>Sort column of the scheme list: 0 = name, 2 = type (default); column 1 ("Kind") is not sortable.</summary>+ private int _schemeSortColumn;++ /// <summary>Sort direction of the scheme list; default ascending.</summary>+ private bool _schemeSortAscending;++ /// <summary>Zoomed picture box filling <c>pnlPreview</c> on the Manage-output tab (created in <see cref="InitializeOutputsTab"/>); it owns its image.</summary>+ private PictureBox _outputPreviewPic;++ /// <summary>True when <see cref="_outputPreviewPic"/> shows a shell thumbnail of a video (such a picture cannot be shared to the Sources/Probes tabs).</summary>+ private bool _outputPreviewIsVideo;++ /// <summary>Sort column of the scene-image file list: 0 = file name, 1 = created date (default).</summary>+ private int _sceneSortColumn;++ /// <summary>Sort direction of the scene-image file list; default descending (newest first).</summary>+ private bool _sceneSortAscending;++ /// <summary>Sort column of the exported-image file list: 0 = file name, 1 = created date (default).</summary>+ private int _imageSortColumn;++ /// <summary>Sort direction of the exported-image file list; default descending (newest first).</summary>+ private bool _imageSortAscending;++ /// <summary>Sort column of the exported-video file list: 0 = file name, 1 = created date (default).</summary>+ private int _videoSortColumn;++ /// <summary>Sort direction of the exported-video file list; default descending (newest first).</summary>+ private bool _videoSortAscending;++ /// <summary>Owner of the thumbnail bitmaps added to <see cref="_thumbs"/>; disposed on every reload and on closing.</summary>+ private readonly List<Bitmap> _thumbBitmaps;++ /// <summary>Nominal scheme thumbnail width in pixels. Not referenced at present: the Colors part uses the literal 120.</summary>+ private const int ThumbWidth = 120;++ /// <summary>Nominal scheme thumbnail height in pixels. Not referenced at present: the Colors part uses the literal 16.</summary>+ private const int ThumbHeight = 16;++ // ----- Project state -----++ /// <summary>The open project; null while editing a new project that has never been saved.</summary>+ private Project _project;++ /// <summary>Per-user settings (project root, last project). A placeholder from the constructor until <see cref="InitializeProject"/> loads the real values.</summary>+ private AppSettings _settings;++ /// <summary>True when scene, simulation, probe or source settings differ from what is saved (title shows " *").</summary>+ private bool _projectDirty;++ /// <summary>Current phase of the <c>btnPickRoot</c> blink (true = highlighted).</summary>+ private bool _rootBlinkOn;++ /// <summary>700 ms timer that blinks <c>btnPickRoot</c> while no project root has been chosen; started/stopped by <see cref="UpdateProjectAccess"/>.</summary>+ private readonly global::System.Windows.Forms.Timer _rootBlinkTimer;++ // ----- Manage output tab (Form1.Output.cs) -----++ /// <summary>Lower-case extensions listed as scene images on the Manage-output tab.</summary>+ private static readonly string[] SceneImageExtensions = new string[] { ".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".gif" };++ /// <summary>Lower-case extensions listed as exported frames on the Manage-output tab.</summary>+ private static readonly string[] OutputImageExtensions = new string[] { ".png" };++ /// <summary>Lower-case extensions listed as exported videos on the Manage-output tab.</summary>+ private static readonly string[] OutputVideoExtensions = new string[] { ".mp4", ".avi" };++ /// <summary>Re-entrancy guard: set while <see cref="ClearOtherFileListSelections"/> clears the two inactive file lists, so their selection handlers return early.</summary>+ private bool _clearingFileListSelection;++ // ----- Scene (Form1.Scene.cs) -----++ /// <summary>The scene settings being edited (image or user-defined canvas, damping edge, image sources, refractive index); replaced on project load and new project.</summary>+ private SceneSettings _scene;++ /// <summary>Re-entrancy guard: set while scene controls are being filled from <see cref="_scene"/>, so their change handlers do not write back or mark the project dirty.</summary>+ private bool _loadingScene;++ /// <summary>The decoded scene image (owned; disposed by <see cref="ReplaceSceneImage"/>); null when none is loaded or the file was unreadable. Its size is the canvas size when <see cref="SceneSettings.UseImage"/> is set.</summary>+ private Bitmap _sceneImage;++ /// <summary>Placeholder bitmap shown in <c>picImagePreview</c> for a user-defined (empty) canvas; owned and replaced by <see cref="UpdateScenePreview"/>.</summary>+ private Bitmap _emptyPreview;++ /// <summary>Tooltip used to explain rejected canvas-size and damping-edge entries next to their text boxes.</summary>+ private readonly ToolTip _sceneTip;++ // ----- Simulation (Form1.Simulation.cs) -----++ /// <summary>The simulation settings being edited (steps, brightness/offset, export and preview flags, engine options, wave speed c); replaced on project load and new project.</summary>+ private SimulationSettings _simulation;++ /// <summary>Re-entrancy guard: set while simulation controls are filled from <see cref="_simulation"/>, and while a linked control on the other tab is mirrored silently.</summary>+ private bool _loadingSim;++ /// <summary>The active simulation runner; null when nothing is running. Its worker-thread events reach the form through <see cref="PostToUi"/>, and every callback compares the runner identity to ignore events from a stale run.</summary>+ private SimulationRunner _runner;++ /// <summary>Short run status shown in the window title ("starting...", "step n of m (p%)", "paused - ...", "stopping..."); empty when idle.</summary>+ private string _simStatus;++ /// <summary>Full path of the field video written by the last run; empty when none. Enables the "View field video" button.</summary>+ private string _fieldVideoFile;++ /// <summary>Full path of the intensity video written by the last run; empty when none. Enables the "View intensity video" button.</summary>+ private string _intensityVideoFile;++ /// <summary>Multi-line summary of the brightness, offset and image-source scale used by the last started run; appended to the status tooltip when the run finishes.</summary>+ private string _runInfo;++ /// <summary>True while the current run is paused with the Pause button.</summary>+ private bool _paused;++ /// <summary>True after Stop was pressed, until the runner reports that it has finished.</summary>+ private bool _stopRequested;++ /// <summary>Latest progress text, "step n of m (p%)"; <see cref="_simStatus"/> is derived from it.</summary>+ private string _progressText;++ /// <summary>Steps completed according to the latest progress report or run result; used in exported frame file names.</summary>+ private int _lastStepsDone;++ /// <summary>ARGB look-up table (from <see cref="ColorLut"/>) used to colour the field in the current or last run; null when the field view was not wanted. Used to render a frame while paused.</summary>+ private int[] _lastFieldLut;++ /// <summary>ARGB look-up table (from <see cref="ColorLut"/>) used to colour the intensity in the current or last run; null when the intensity view was not wanted. Used to render a frame while paused.</summary>+ private int[] _lastIntensityLut;++ /// <summary>Full canvas-size field frame delivered with the last run's <see cref="SimulationResult"/> (owned); null until a run has finished. Source for "Export frame" when not paused.</summary>+ private Bitmap _lastFullFieldFrame;++ /// <summary>Full canvas-size intensity frame delivered with the last run's <see cref="SimulationResult"/> (owned); null until a run has finished. Source for "Export frame" when not paused.</summary>+ private Bitmap _lastFullIntensityFrame;++ /// <summary>Live field preview box filling <c>pnlPreviewField</c> (created in <see cref="InitializeSimulationControls"/>). <c>Tag</c> holds the raw preview frame, <c>Image</c> that frame or its overlay composite (see <see cref="SetPreviewFrame"/>).</summary>+ private PictureBox _picField;++ /// <summary>Live intensity preview box filling <c>pnlPreviewIntensity</c> (created in <see cref="InitializeSimulationControls"/>). <c>Tag</c> holds the raw preview frame, <c>Image</c> that frame or its overlay composite (see <see cref="SetPreviewFrame"/>).</summary>+ private PictureBox _picIntensity;++ /// <summary>Sobel edge image of <see cref="_sceneImage"/> at canvas size (owned; see <see cref="ComputeGlowingEdges"/>); null when there is no scene image. Added on top of previews and exports as the "glowing edges" overlay.</summary>+ private Bitmap _glowEdgesImage;++ /// <summary><see cref="_glowEdgesImage"/> resized to <see cref="_glowOverlayCacheSize"/> (owned); null until first requested, rebuilt when the preview size changes.</summary>+ private Bitmap _glowOverlayCache;++ /// <summary>Pixel size of <see cref="_glowOverlayCache"/>.</summary>+ private Size _glowOverlayCacheSize;++ /// <summary>Background picture box on the Sources tab (filling <c>pnlSourceImage</c>). Receives copies of the scene, field or intensity picture via the share buttons; source markers are painted on top and clicks pick a source position.</summary>+ private PictureBox _picSource;++ /// <summary>Background picture box on the Probes tab (filling <c>pnlProbeImage</c>). Receives copies of the scene, field or intensity picture via the share buttons; probe markers and graph boxes are painted on top and clicks pick probe positions.</summary>+ private PictureBox _picProbe;++ /// <summary>Set once any simulation has finished. Not read anywhere at present.</summary>+ private bool _hasRun;++ /// <summary>Explorer <c>CurrentViewMode</c> value for the icons view (FOLDERVIEWMODE). Not referenced at present: callers of <see cref="OpenFolderInExplorer"/> pass the literal 1.</summary>+ private const int FVM_ICON = 1;++ /// <summary>Explorer <c>CurrentViewMode</c> value for the details view (FOLDERVIEWMODE). Not referenced at present: callers of <see cref="OpenFolderInExplorer"/> pass the literal 4.</summary>+ private const int FVM_DETAILS = 4;++ // ----- Probes (Form1.Probes.cs) -----++ /// <summary>Number of probes the UI supports.</summary>+ private const int ProbeCount = 2;++ /// <summary>Probe settings being edited, one per probe panel (always exactly two after <see cref="NormalizeProbeCount"/>); replaced on project load and new project.</summary>+ private List<ProbeSettings> _probes;++ /// <summary>The designer controls of each probe panel, indexed by probe (built in <see cref="InitializeProbeControls"/>); null before that.</summary>+ private Form1.ProbeControlSet[] _probeUi;++ /// <summary>Re-entrancy guard: set while probe controls are filled from <see cref="_probes"/>, so their change handlers do not write back or mark the project dirty.</summary>+ private bool _loadingProbe;++ /// <summary>State of position picking on <see cref="_picProbe"/>: 0 = not picking, 1 = waiting for position A, 2 = position B (line probes only), 3 = top-left corner of the graph box.</summary>+ private int _pickStep;++ /// <summary>Index of the probe whose positions are being picked; meaningful only while <see cref="_pickStep"/> is non-zero.</summary>+ private int _pickIndex;++ /// <summary>Last mouse position (picture-box pixels) over <see cref="_picProbe"/> during pick step 3, used to draw the graph box where it would land; null otherwise.</summary>+ private Point? _pickHover;++ /// <summary>Copies of the probe settings handed to the running or last run; preview markers and graphs are drawn from these (with display settings copied from <see cref="_probes"/>). Null before the first run.</summary>+ private List<ProbeSettings> _runProbes;++ /// <summary>Canvas size (pixels) of the running or last run, used to map probe positions onto the zoomed previews.</summary>+ private Size _runCanvas;++ /// <summary>Total step count of the running or last run (x-axis of full-scale probe graphs).</summary>+ private int _runSteps;++ /// <summary>Per-probe samples and line profiles collected during the running or last run; cleared by <see cref="BeginProbeRun"/>, appended on the UI thread in <see cref="ShowProbeSamples"/>.</summary>+ private readonly List<ProbeTrace> _probeTraces;++ // ----- Sources (Form1.Sources.cs) -----++ /// <summary>The project's object sources, in list order; replaced on project load and new project.</summary>+ private List<SourceSettings> _sources;++ /// <summary>Index in <see cref="_sources"/> of the source the editor is bound to; -1 while editing a new, not yet saved source.</summary>+ private int _currentSourceIndex;++ /// <summary>Working copy the editor controls are bound to (a clone of the selected source, or a fresh one); stored back into <see cref="_sources"/> by <see cref="CommitSourceEdits"/>.</summary>+ private SourceSettings _editing;++ /// <summary>Re-entrancy guard: set while source controls are filled from <see cref="_editing"/>, so they do not mark the source dirty.</summary>+ private bool _loadingSource;++ /// <summary>Re-entrancy guard: set while <c>lstSources</c>'s selection is changed programmatically, so the selection handler does not reload the editor.</summary>+ private bool _syncingSourceList;++ /// <summary>True while a click on <see cref="_picSource"/> is expected to set the source position.</summary>+ private bool _sourcePicking;++ /// <summary>Original caption of <c>btnPickSourcePosition</c>, restored after it has shown "Cancel" during picking.</summary>+ private string _pickSourceButtonText;++ /// <summary>Random generator used when composite sources generate randomised elements.</summary>+ private readonly Random _sourceRandom;++ /// <summary>Normal back colour of <c>btnSaveSource</c>; the button turns orange while the editor has unsaved edits.</summary>+ private Color _sourceSaveButtonDefaultBackColor;++ /// <summary>One row of the project list views (stored in the item's <c>Tag</c>).</summary>+ private sealed class ProjectListEntry+ {+ public ProjectListEntry(string name, DateTime lastModified)+ {+ this.Name = name;+ this.LastModified = lastModified;+ }++ /// <summary>Project (folder) name.</summary>+ public readonly string Name;++ /// <summary>Last write time of the project's configuration file, or of the folder when the file is missing (local time).</summary>+ public readonly DateTime LastModified;+ }++ /// <summary>Win32 <c>SIZE</c> structure passed to <see cref="IShellItemImageFactory.GetImage"/>.</summary>+ private struct NativeSize+ {+ /// <summary>Width in pixels.</summary>+ public int cx;++ /// <summary>Height in pixels.</summary>+ public int cy;+ }++ /// <summary>Subset of the shell's <c>SIIGBF</c> flags for <see cref="IShellItemImageFactory.GetImage"/>.</summary>+ [Flags]+ private enum ThumbnailOptions+ {+ /// <summary>No options.</summary>+ None = 0,+ /// <summary><c>SIIGBF_BIGGERSIZEOK</c>: a larger image than requested is acceptable.</summary>+ BiggerSizeOk = 1,+ /// <summary><c>SIIGBF_THUMBNAILONLY</c>: return a thumbnail only, never an icon.</summary>+ ThumbnailOnly = 8+ }++ /// <summary>COM interface used to ask the Windows shell for a file's thumbnail (video previews on the Manage-output tab).</summary>+ [Guid("bcc18b79-ba16-442f-80c4-8a59c30c463b")]+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ [ComImport]+ private interface IShellItemImageFactory+ {+ /// <summary>Returns a GDI bitmap handle of the requested size; the caller owns it and must release it with <c>DeleteObject</c>. Throws on failure (PreserveSig is off).</summary>+ void GetImage([In] Form1.NativeSize size, [In] Form1.ThumbnailOptions flags, out IntPtr phbm);+ }++ /// <summary>+ /// Bundles the designer controls of one probe panel so the two identical panels share the+ /// same handler code (see <see cref="InitializeProbeControls"/>). All members are set once+ /// in the constructor.+ /// </summary>+ private sealed class ProbeControlSet+ {+ public ProbeControlSet(int index, string title, CheckBox chkOn, ComboBox cmbPlaceOn, ComboBox cmbMeasurement, ComboBox cmbProbeType, ComboBox cmbBoxSize, NumericUpDown numAPosX, NumericUpDown numAPosY, NumericUpDown numBPosX, NumericUpDown numBPosY, Button butPick, RadioButton radRunning, RadioButton radFull, CheckBox chkAutoX, CheckBox chkAutoY, TextBox txtMinY, TextBox txtMaxY, CheckBox chkStartAfter, TextBox txtStartAfter, NumericUpDown numRunningWindow, Control[] bOnlyControls)+ {+ this.Index = index;+ this.Title = title;+ this.ChkOn = chkOn;+ this.CmbPlaceOn = cmbPlaceOn;+ this.CmbMeasurement = cmbMeasurement;+ this.CmbProbeType = cmbProbeType;+ this.CmbBoxSize = cmbBoxSize;+ this.NumAPosX = numAPosX;+ this.NumAPosY = numAPosY;+ this.NumBPosX = numBPosX;+ this.NumBPosY = numBPosY;+ this.ButPick = butPick;+ this.RadRunning = radRunning;+ this.RadFull = radFull;+ this.ChkAutoX = chkAutoX;+ this.ChkAutoY = chkAutoY;+ this.TxtMinY = txtMinY;+ this.TxtMaxY = txtMaxY;+ this.ChkStartAfter = chkStartAfter;+ this.TxtStartAfter = txtStartAfter;+ this.NumRunningWindow = numRunningWindow;+ this.BOnlyControls = bOnlyControls;+ this.PickButtonText = butPick.Text;+ }++ /// <summary>Probe index (0 or 1), also the index into <see cref="_probes"/>.</summary>+ public readonly int Index;++ /// <summary>Display name ("Probe 1" / "Probe 2") used in status messages.</summary>+ public readonly string Title;++ /// <summary>"Probe on" check box.</summary>+ public readonly CheckBox ChkOn;++ /// <summary>Picture the probe samples: Field or Intensity.</summary>+ public readonly ComboBox CmbPlaceOn;++ /// <summary>Measured quantity (depends on <see cref="CmbPlaceOn"/>): amplitude, intensity or integrated intensity.</summary>+ public readonly ComboBox CmbMeasurement;++ /// <summary>Probe kind: point (A) or line (A-B).</summary>+ public readonly ComboBox CmbProbeType;++ /// <summary>Size preset of the graph box drawn on the previews.</summary>+ public readonly ComboBox CmbBoxSize;++ /// <summary>X of position A in canvas pixels.</summary>+ public readonly NumericUpDown NumAPosX;++ /// <summary>Y of position A in canvas pixels.</summary>+ public readonly NumericUpDown NumAPosY;++ /// <summary>X of position B (line probes) in canvas pixels.</summary>+ public readonly NumericUpDown NumBPosX;++ /// <summary>Y of position B (line probes) in canvas pixels.</summary>+ public readonly NumericUpDown NumBPosY;++ /// <summary>"Pick" button that starts/cancels picking positions on the Probes picture.</summary>+ public readonly Button ButPick;++ /// <summary>Running-scale radio button (graph shows a recent window of steps).</summary>+ public readonly RadioButton RadRunning;++ /// <summary>Full-scale radio button (graph shows the whole run).</summary>+ public readonly RadioButton RadFull;++ /// <summary>Auto-scale X check box.</summary>+ public readonly CheckBox ChkAutoX;++ /// <summary>Auto-scale Y check box; when off, <see cref="TxtMinY"/>/<see cref="TxtMaxY"/> apply.</summary>+ public readonly CheckBox ChkAutoY;++ /// <summary>Manual Y-axis minimum (invariant-culture number).</summary>+ public readonly TextBox TxtMinY;++ /// <summary>Manual Y-axis maximum (invariant-culture number).</summary>+ public readonly TextBox TxtMaxY;++ /// <summary>"Start recording at step #" check box.</summary>+ public readonly CheckBox ChkStartAfter;++ /// <summary>Step number at which recording starts (integer text).</summary>+ public readonly TextBox TxtStartAfter;++ /// <summary>Width of the running-scale window in steps.</summary>+ public readonly NumericUpDown NumRunningWindow;++ /// <summary>Controls that are only enabled for line probes (the position-B spinners and their labels).</summary>+ public readonly Control[] BOnlyControls;++ /// <summary>Original caption of <see cref="ButPick"/>, restored after it has shown "Cancel".</summary>+ public readonly string PickButtonText;+ }+ }+}diff --git a/Wave_Dude_2D/Form1.resx b/Wave_Dude_2D/Form1.resxnew file mode 100644index 0000000..7285c15--- /dev/null+++ b/Wave_Dude_2D/Form1.resx@@ -0,0 +1,686 @@+<?xml version="1.0" encoding="utf-8"?>+<root>+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />+ <xsd:element name="root" msdata:IsDataSet="true">+ <xsd:complexType>+ <xsd:choice maxOccurs="unbounded">+ <xsd:element name="metadata">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" />+ </xsd:sequence>+ <xsd:attribute name="name" use="required" type="xsd:string" />+ <xsd:attribute name="type" type="xsd:string" />+ <xsd:attribute name="mimetype" type="xsd:string" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="assembly">+ <xsd:complexType>+ <xsd:attribute name="alias" type="xsd:string" />+ <xsd:attribute name="name" type="xsd:string" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="data">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="resheader">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" />+ </xsd:complexType>+ </xsd:element>+ </xsd:choice>+ </xsd:complexType>+ </xsd:element>+ </xsd:schema>+ <resheader name="resmimetype">+ <value>text/microsoft-resx</value>+ </resheader>+ <resheader name="version">+ <value>2.0</value>+ </resheader>+ <resheader name="reader">+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <resheader name="writer">+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <data name="$this.Icon" type="System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" mimetype="application/x-microsoft.net.object.binary.base64">+ <value>+ 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</value>+ </data>+</root>\ No newline at end of filediff --git a/Wave_Dude_2D/FrameRenderer.cs b/Wave_Dude_2D/FrameRenderer.csnew file mode 100644index 0000000..2aa1abb--- /dev/null+++ b/Wave_Dude_2D/FrameRenderer.cs@@ -0,0 +1,237 @@+using System;+using System.Drawing;+using System.Drawing.Imaging;+using System.Runtime.InteropServices;+using System.Threading.Tasks;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Static helpers that turn raw engine field/intensity data into packed ARGB pixel buffers+ /// (optionally through a colour LUT), blend a glow overlay on top and wrap the result in a+ /// <see cref="Bitmap"/>. Used by <see cref="SimulationRunner"/> (worker thread) and by the video sinks.+ /// Row loops run in parallel, so the methods are CPU-bound but not thread-affine.+ /// </summary>+ internal sealed class FrameRenderer+ {+ /// <summary>Not instantiable; all members are static.</summary>+ private FrameRenderer()+ {+ }++ /// <summary>+ /// Renders the wave field, nearest-neighbour scaled from the engine grid (<see cref="IWaveEngine.Width"/> x+ /// <see cref="IWaveEngine.Height"/>) to <paramref name="dw"/> x <paramref name="dh"/>. Reads the engine's padded+ /// buffer (row y starts at <c>(y + 1) * Stride + 1</c>); the caller must have called <see cref="IWaveEngine.PrepareFrame"/>.+ /// </summary>+ /// <param name="sim">Engine whose <see cref="IWaveEngine.FieldData"/> is read.</param>+ /// <param name="lut">ARGB palette indexed 0..254 (127 = zero field), or null for greyscale.</param>+ /// <param name="brightness">Gain applied before the value is clamped to -1..1.</param>+ /// <param name="pixels">Destination, at least <paramref name="dw"/> * <paramref name="dh"/> ARGB ints, row-major.</param>+ /// <param name="dw">Destination width in pixels.</param>+ /// <param name="dh">Destination height in pixels.</param>+ public static void RenderField(IWaveEngine sim, int[] lut, float brightness, int[] pixels, int dw, int dh)+ {+ float[] field = sim.FieldData;+ int stride = sim.Stride;+ int sw = sim.Width;+ int sh = sim.Height;++ Parallel.For(0, dh, y =>+ {+ int srcY = (int)((long)y * sh / dh);+ int srcRowStart = (srcY + 1) * stride + 1;+ int dstRowStart = y * dw;+ for (int x = 0; x < dw; x++)+ {+ int srcX = (int)((long)x * sw / dw);+ float value = field[srcRowStart + srcX];+ pixels[dstRowStart + x] = Colorize(ColorLut.FieldIndex(value, brightness), lut);+ }+ });+ }++ /// <summary>+ /// Renders the accumulated intensity, nearest-neighbour scaled to <paramref name="dw"/> x <paramref name="dh"/>.+ /// Each value is mapped as <c>sqrt(value) * brightness</c>, clamped to 1, then scaled to palette index 0..254+ /// (non-positive values map to 0). Same layout rules as <see cref="RenderField"/>.+ /// </summary>+ /// <param name="sim">Engine whose <see cref="IWaveEngine.IntensityData"/> is read (must not be null).</param>+ /// <param name="lut">ARGB palette indexed 0..254, or null for greyscale.</param>+ /// <param name="brightness">Gain applied after the square-root compression.</param>+ /// <param name="pixels">Destination, at least <paramref name="dw"/> * <paramref name="dh"/> ARGB ints, row-major.</param>+ /// <param name="dw">Destination width in pixels.</param>+ /// <param name="dh">Destination height in pixels.</param>+ public static void RenderIntensity(IWaveEngine sim, int[] lut, float brightness, int[] pixels, int dw, int dh)+ {+ float[] intensity = sim.IntensityData;+ int stride = sim.Stride;+ int sw = sim.Width;+ int sh = sim.Height;++ Parallel.For(0, dh, y =>+ {+ int srcY = (int)((long)y * sh / dh);+ int srcRowStart = (srcY + 1) * stride + 1;+ int dstRowStart = y * dw;+ for (int x = 0; x < dw; x++)+ {+ int srcX = (int)((long)x * sw / dw);+ float value = intensity[srcRowStart + srcX];+ int index = 0;+ if (value > 0f)+ {+ double scaled = Math.Sqrt(value) * brightness;+ if (scaled > 1.0)+ {+ scaled = 1.0;+ }+ index = (int)(scaled * 254.0);+ }+ pixels[dstRowStart + x] = Colorize(index, lut);+ }+ });+ }++ /// <summary>Looks up a palette index in <paramref name="lut"/>, or builds an opaque grey of that level when there is no LUT.</summary>+ private static int Colorize(int index, int[] lut)+ {+ if (lut != null)+ {+ return lut[index];+ }+ return unchecked((int)0xFF000000) | (index << 16) | (index << 8) | index;+ }++ /// <summary>+ /// Draws <paramref name="bmp"/> unscaled at (0,0) onto a black <paramref name="w"/> x <paramref name="h"/> canvas and+ /// returns the canvas as tightly packed 24-bit pixels, 3 bytes per pixel in memory order B,G,R, no row padding.+ /// </summary>+ /// <param name="bmp">Source image (any size; clipped or padded with black to the canvas).</param>+ /// <param name="w">Canvas width in pixels.</param>+ /// <param name="h">Canvas height in pixels.</param>+ /// <returns>A new array of <c>w * h * 3</c> bytes.</returns>+ public static byte[] ToRgbBytes(Bitmap bmp, int w, int h)+ {+ byte[] rgb = new byte[w * h * 3];+ using (Bitmap canvas = new Bitmap(w, h, PixelFormat.Format24bppRgb))+ {+ using (Graphics g = Graphics.FromImage(canvas))+ {+ g.Clear(Color.Black);+ g.DrawImageUnscaled(bmp, 0, 0);+ }+ Rectangle rect = new Rectangle(0, 0, w, h);+ BitmapData data = canvas.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);+ try+ {+ int stride = data.Stride;+ byte[] raw = new byte[stride * h];+ Marshal.Copy(data.Scan0, raw, 0, raw.Length);+ for (int y = 0; y < h; y++)+ {+ int srcRow = y * stride;+ int dstRow = y * w * 3;+ for (int x = 0; x < w; x++)+ {+ int src = srcRow + x * 3;+ int dst = dstRow + x * 3;+ rgb[dst] = raw[src];+ rgb[dst + 1] = raw[src + 1];+ rgb[dst + 2] = raw[src + 2];+ }+ }+ }+ finally+ {+ canvas.UnlockBits(data);+ }+ }+ return rgb;+ }++ /// <summary>+ /// Multiplies every byte of a <see cref="ToRgbBytes"/> buffer by <paramref name="gain"/>, rounded and clamped to 255.+ /// </summary>+ /// <param name="overlayRgb">Packed B,G,R overlay, or null.</param>+ /// <param name="gain">Multiplier; values <= 0 disable the overlay.</param>+ /// <returns>A new scaled copy, or null when the input is null or the gain is <= 0 (nothing to overlay).</returns>+ public static byte[] ScaleOverlayRgb(byte[] overlayRgb, double gain)+ {+ if (overlayRgb == null || gain <= 0.0)+ {+ return null;+ }+ byte[] scaled = new byte[overlayRgb.Length];+ for (int i = 0; i < overlayRgb.Length; i++)+ {+ scaled[i] = (byte)Math.Round(Math.Min(255.0, overlayRgb[i] * gain));+ }+ return scaled;+ }++ /// <summary>+ /// Additively blends a packed B,G,R overlay (see <see cref="ToRgbBytes"/>) onto ARGB pixels in place, each channel+ /// saturating at 255; the alpha byte is kept. Fully black overlay pixels are skipped. No-op when the overlay is null.+ /// </summary>+ /// <param name="pixels">ARGB buffer of <paramref name="w"/> * <paramref name="h"/> ints, modified in place.</param>+ /// <param name="scaledOverlayRgb">Overlay of <paramref name="w"/> * <paramref name="h"/> * 3 bytes, or null.</param>+ /// <param name="w">Width in pixels.</param>+ /// <param name="h">Height in pixels.</param>+ public static void AddOverlay(int[] pixels, byte[] scaledOverlayRgb, int w, int h)+ {+ if (scaledOverlayRgb == null)+ {+ return;+ }+ Parallel.For(0, h, y =>+ {+ int pixelRow = y * w;+ int overlayRow = y * w * 3;+ for (int x = 0; x < w; x++)+ {+ int o = overlayRow + x * 3;+ int ob = scaledOverlayRgb[o];+ int og = scaledOverlayRgb[o + 1];+ int or = scaledOverlayRgb[o + 2];+ if (ob == 0 && og == 0 && or == 0)+ {+ continue;+ }+ int p = pixelRow + x;+ int argb = pixels[p];+ int a = argb & unchecked((int)0xFF000000);+ int r = Math.Min(255, ((argb >> 16) & 255) + or);+ int g = Math.Min(255, ((argb >> 8) & 255) + og);+ int b = Math.Min(255, (argb & 255) + ob);+ pixels[p] = a | (r << 16) | (g << 8) | b;+ }+ });+ }++ /// <summary>+ /// Copies a row-major ARGB buffer into a new 32bpp ARGB <see cref="Bitmap"/> (top-down). The caller owns and+ /// must dispose the bitmap; the source array is not referenced afterwards.+ /// </summary>+ /// <param name="pixels">At least <paramref name="w"/> * <paramref name="h"/> ARGB ints.</param>+ /// <param name="w">Bitmap width in pixels.</param>+ /// <param name="h">Bitmap height in pixels.</param>+ public static Bitmap ToBitmap(int[] pixels, int w, int h)+ {+ Bitmap bitmap = new Bitmap(w, h, PixelFormat.Format32bppArgb);+ BitmapData data = bitmap.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);+ try+ {+ for (int y = 0; y < h; y++)+ {+ Marshal.Copy(pixels, y * w, IntPtr.Add(data.Scan0, y * data.Stride), w);+ }+ }+ finally+ {+ bitmap.UnlockBits(data);+ }+ return bitmap;+ }+ }+}diff --git a/Wave_Dude_2D/GpuDeviceInfo.cs b/Wave_Dude_2D/GpuDeviceInfo.csnew file mode 100644index 0000000..82bf8b3--- /dev/null+++ b/Wave_Dude_2D/GpuDeviceInfo.cs@@ -0,0 +1,118 @@+using System;+using System.Collections.Generic;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Describes one OpenCL GPU device and enumerates the available ones. Produced by <see cref="FindAll"/> and+ /// consumed by <see cref="GpuWaveSimulator"/>, which tries the devices in the returned order. The platform and+ /// device handles are driver-owned identifiers that need no release.+ /// </summary>+ internal sealed class GpuDeviceInfo+ {+ public GpuDeviceInfo()+ {+ this.Name = "";+ this.Vendor = "";+ }++ /// <summary>+ /// Lists every GPU on every OpenCL platform, best candidate first: discrete devices before those sharing+ /// host memory, then by descending <see cref="Score"/>. Platforms whose enumeration fails are skipped;+ /// a failing platform query yields an empty list. Throws the usual P/Invoke exceptions+ /// (<see cref="DllNotFoundException"/> etc.) when OpenCL.dll cannot be loaded.+ /// </summary>+ public static List<GpuDeviceInfo> FindAll()+ {+ List<GpuDeviceInfo> devices = new List<GpuDeviceInfo>();+ uint platformCount = 0U;+ if (OpenClApi.clGetPlatformIDs(0U, null, ref platformCount) != 0 || platformCount == 0U)+ {+ return devices;+ }+ IntPtr[] platforms = new IntPtr[platformCount];+ uint platformsReturned = 0U;+ if (OpenClApi.clGetPlatformIDs(platformCount, platforms, ref platformsReturned) != 0)+ {+ return devices;+ }+ foreach (IntPtr platform in platforms)+ {+ uint deviceCount = 0U;+ if (OpenClApi.clGetDeviceIDs(platform, OpenClApi.DeviceTypeGpu, 0U, null, ref deviceCount) != 0 || deviceCount == 0U)+ {+ continue;+ }+ IntPtr[] deviceIds = new IntPtr[deviceCount];+ uint devicesReturned = 0U;+ if (OpenClApi.clGetDeviceIDs(platform, OpenClApi.DeviceTypeGpu, deviceCount, deviceIds, ref devicesReturned) != 0)+ {+ continue;+ }+ foreach (IntPtr deviceId in deviceIds)+ {+ devices.Add(GpuDeviceInfo.Describe(platform, deviceId));+ }+ }+ devices.Sort((a, b) =>+ {+ // discrete GPUs first, then by score descending+ if (a.Discrete != b.Discrete)+ {+ return a.Discrete ? -1 : 1;+ }+ return b.Score.CompareTo(a.Score);+ });+ return devices;+ }++ /// <summary>+ /// Queries the device properties. Failed queries read as 0 or "", so an unnamed device is called "GPU" and a+ /// device whose host-unified-memory flag cannot be read counts as discrete.+ /// </summary>+ private static GpuDeviceInfo Describe(IntPtr plat, IntPtr id)+ {+ GpuDeviceInfo info = new GpuDeviceInfo();+ info.PlatformId = plat;+ info.DeviceId = id;+ info.Name = OpenClApi.DeviceString(id, OpenClApi.DeviceName);+ info.Vendor = OpenClApi.DeviceString(id, OpenClApi.DeviceVendor);+ info.Discrete = OpenClApi.DeviceNumber(id, OpenClApi.DeviceHostUnifiedMemory) == 0UL;+ double computeUnits = OpenClApi.DeviceNumber(id, OpenClApi.DeviceMaxComputeUnits);+ double clockMhz = OpenClApi.DeviceNumber(id, OpenClApi.DeviceMaxClockFrequency);+ info.Score = computeUnits * Math.Max(1.0, clockMhz);+ // Mask the sign bit so an odd 64-bit value cannot turn into a negative size.+ info.GlobalMemory = (long)(OpenClApi.DeviceNumber(id, OpenClApi.DeviceGlobalMemSize) & 0x7FFFFFFFFFFFFFFFUL);+ info.MaxAllocation = (long)(OpenClApi.DeviceNumber(id, OpenClApi.DeviceMaxMemAllocSize) & 0x7FFFFFFFFFFFFFFFUL);+ if (info.Name.Length == 0)+ {+ info.Name = "GPU";+ }+ return info;+ }++ /// <summary>OpenCL platform handle (cl_platform_id) the device belongs to.</summary>+ public IntPtr PlatformId;++ /// <summary>OpenCL device handle (cl_device_id).</summary>+ public IntPtr DeviceId;++ /// <summary>CL_DEVICE_NAME, or "GPU" when the query fails.</summary>+ public string Name;++ /// <summary>CL_DEVICE_VENDOR, or "" when the query fails.</summary>+ public string Vendor;++ /// <summary>True when the device does not share memory with the host (CL_DEVICE_HOST_UNIFIED_MEMORY is 0), i.e. a discrete card.</summary>+ public bool Discrete;++ /// <summary>Rough throughput rank: compute units × max clock in MHz (clock at least 1).</summary>+ public double Score;++ /// <summary>CL_DEVICE_GLOBAL_MEM_SIZE in bytes.</summary>+ public long GlobalMemory;++ /// <summary>CL_DEVICE_MAX_MEM_ALLOC_SIZE in bytes: the largest single buffer the device allows.</summary>+ public long MaxAllocation;+ }+}diff --git a/Wave_Dude_2D/GpuWaveSimulator.cs b/Wave_Dude_2D/GpuWaveSimulator.csnew file mode 100644index 0000000..177a152--- /dev/null+++ b/Wave_Dude_2D/GpuWaveSimulator.cs@@ -0,0 +1,1478 @@+using System;+using System.Collections.Generic;+using System.Text;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// OpenCL implementation of <see cref="IWaveEngine"/>: the same leapfrog scheme as <see cref="WaveSimulator"/>+ /// (padded grid, 9-point or sub-stepped 4th-order Laplacian, soft source blending, two-stage intensity+ /// average), with the field, the scene maps, the source tables and the probe buffers all resident on the+ /// device. Created through <see cref="TryCreate"/> by <see cref="WaveEngineFactory"/> and driven by+ /// <see cref="SimulationRunner"/> on its worker thread, which is the only thread that enqueues work; the UI+ /// thread touches only <see cref="PrepareFrame"/>, <see cref="FieldData"/> and <see cref="IntensityData"/>+ /// while the runner is paused.+ /// </summary>+ /// <remarks>+ /// The field lives in two ping-pong buffers (<see cref="_field"/>); every kernel that reads the field exists+ /// twice (index 0/1) with the buffers bound in opposite order, so a step merely picks the kernel for+ /// <see cref="_current"/> instead of re-binding arguments. Kernel launches and uploads are asynchronous;+ /// read-backs are blocking. All OpenCL handles are owned by this instance and released by+ /// <see cref="Dispose"/> (or by the constructor when building fails); the managed buffers+ /// (<see cref="FieldData"/>, <see cref="IntensityData"/>) are plain host copies.+ /// </remarks>+ internal sealed class GpuWaveSimulator : IWaveEngine+ {+ /// <summary>+ /// Tries to build an engine on each OpenCL GPU reported by <see cref="GpuDeviceInfo.FindAll"/> in turn and+ /// returns the first that succeeds. Parameters are those of the <see cref="WaveSimulator"/> constructor.+ /// </summary>+ /// <param name="scene">Per-cell c² and damping maps plus the image (green-channel) sources.</param>+ /// <param name="sourceFrequencyScale">Multiplier in the level-to-angular-frequency mapping; see <see cref="_frequencyBuffer"/>.</param>+ /// <param name="sourceAmplitude">Peak amplitude of the image sources (object sources carry their own).</param>+ /// <param name="trackIntensity">Whether to allocate and update the intensity buffers; when false <see cref="IntensityData"/> stays null.</param>+ /// <param name="use4thOrderLaplacian">Use the 4th-order 5-point-per-axis stencil (with sub-stepping) instead of the 9-point one.</param>+ /// <param name="timeDecayFactor">Intensity averaging time in units of 100/level steps; see <see cref="_intensityAlpha"/>.</param>+ /// <param name="intensityScale">Multiplier applied to the intensity output.</param>+ /// <param name="problems">Receives "" on success, otherwise why no device worked ("no GPU found …" or the+ /// per-device failure messages joined by "; ").</param>+ /// <param name="objectSources">Interactive sources; those outside the canvas are dropped.</param>+ /// <returns>The engine, or null when no device could be used (see <paramref name="problems"/>).</returns>+ public static GpuWaveSimulator TryCreate(SceneData scene, double sourceFrequencyScale, double sourceAmplitude, bool trackIntensity, bool use4thOrderLaplacian, double timeDecayFactor, double intensityScale, ref string problems, List<SourceElement> objectSources = null)+ {+ problems = "";+ List<GpuDeviceInfo> devices = GpuDeviceInfo.FindAll();+ if (devices.Count == 0)+ {+ problems = "no GPU found through OpenCL" + ((IntPtr.Size == 4) ? " (this is a 32-bit process; run the 64-bit build)" : "");+ return null;+ }+ StringBuilder errors = new StringBuilder();+ foreach (GpuDeviceInfo device in devices)+ {+ try+ {+ return new GpuWaveSimulator(device, scene, sourceFrequencyScale, sourceAmplitude, trackIntensity, use4thOrderLaplacian, timeDecayFactor, intensityScale, objectSources);+ }+ catch (Exception ex)+ {+ if (errors.Length > 0)+ {+ errors.Append("; ");+ }+ errors.Append(device.Name).Append(": ").Append(ex.Message);+ }+ }+ problems = errors.ToString();+ return null;+ }++ /// <summary>+ /// Records the scene geometry, rejects scenes whose per-cell buffer would exceed the device's maximum+ /// allocation, keeps only the object sources inside the canvas and then runs <see cref="Build"/>; if that+ /// throws, everything allocated so far is released before the exception propagates.+ /// </summary>+ /// <exception cref="InvalidOperationException">The scene is too large for the device, or the OpenCL program could not be built.</exception>+ private GpuWaveSimulator(GpuDeviceInfo device, SceneData scene, double sourceFrequencyScale, double sourceAmplitude, bool trackIntensity, bool use4thOrderLaplacian, double timeDecayFactor, double intensityScale, List<SourceElement> objectSources = null)+ {+ this._field = new IntPtr[2];+ this._stepKernel = new IntPtr[2];+ this._sourceKernel = new IntPtr[2];+ this._objSourceKernel = new IntPtr[2];+ this._objGrid1D = new IntPtr[1];+ this._grid2D = new IntPtr[2];+ this._grid1D = new IntPtr[1];+ this._probeKernel = new IntPtr[2];+ this._probeGrid = new IntPtr[1];+ this._probeValues = new List<List<float>>();+ this._gatherKernel = new IntPtr[2];+ this._profileGrid = new IntPtr[1];+ this._description = "GPU: " + device.Name + " (OpenCL)";+ this._width = scene.Width;+ this._height = scene.Height;+ this._stride = this._width + 2;+ this._cells = this._stride * (this._height + 2);+ this._track = trackIntensity;+ this._sourceCount = scene.SourceCount;+ this._amplitude = (float)sourceAmplitude;+ this._use4thOrderLaplacian = use4thOrderLaplacian;+ if (device.MaxAllocation > 0L && (long)this._cells * 4L > device.MaxAllocation)+ {+ throw new InvalidOperationException("the scene is too large for this GPU");+ }+ List<SourceElement> sourcesInScene = new List<SourceElement>();+ if (objectSources != null)+ {+ foreach (SourceElement source in objectSources)+ {+ if (source.PosX >= 0 && source.PosX < this._width && source.PosY >= 0 && source.PosY < this._height)+ {+ sourcesInScene.Add(source);+ }+ }+ }+ this._objSourceCount = sourcesInScene.Count;+ try+ {+ this.Build(device, scene, sourceFrequencyScale, timeDecayFactor, intensityScale, sourcesInScene);+ }+ catch+ {+ this.ReleaseAll();+ throw;+ }+ }++ /// <summary>+ /// Creates the context and queue, compiles <see cref="KernelSource"/>, uploads every buffer for the scene+ /// and binds the kernel arguments. Mirrors the <see cref="WaveSimulator"/> constructor: c² and damping are+ /// copied into the padded layout, the sub-step count and the per-sub-step damping / c² corrections are+ /// derived for the 4th-order stencil, the sources are indexed, and the intensity averaging constant is set+ /// from the lowest source level in use. When intensity is not tracked the three intensity buffers are+ /// 1-float dummies so the kernel arguments are still valid. The kernel arguments that change per step+ /// (time, per-sub-step track flag) are left to <see cref="AdvanceOneStep"/>.+ /// </summary>+ /// <param name="device">The OpenCL device (and its platform) to create the context on.</param>+ /// <param name="scene">Per-cell c² and damping maps plus the image sources.</param>+ /// <param name="sourceFrequencyScale">Multiplier in the level-to-angular-frequency mapping; see <see cref="_frequencyBuffer"/>.</param>+ /// <param name="timeDecayFactor">Intensity averaging time in units of 100/level steps; see <see cref="_intensityAlpha"/>.</param>+ /// <param name="intensityScale">Multiplier applied to the intensity output.</param>+ /// <param name="objectSources">Object sources already filtered to those inside the canvas.</param>+ /// <exception cref="InvalidOperationException">The OpenCL program could not be built (message includes the build log).</exception>+ private void Build(GpuDeviceInfo device, SceneData scene, double sourceFrequencyScale, double timeDecayFactor, double intensityScale, List<SourceElement> objectSources)+ {+ int err = 0;+ this._deviceId = device.DeviceId;+ IntPtr[] contextProperties = new IntPtr[]+ {+ new IntPtr(OpenClApi.ContextPlatformProperty),+ device.PlatformId,+ IntPtr.Zero+ };+ IntPtr[] deviceIds = new IntPtr[] { device.DeviceId };+ this._context = OpenClApi.clCreateContext(contextProperties, 1U, deviceIds, IntPtr.Zero, IntPtr.Zero, ref err);+ OpenClApi.Check(err, "clCreateContext");+ this._queue = OpenClApi.clCreateCommandQueue(this._context, device.DeviceId, 0UL, ref err);+ OpenClApi.Check(err, "clCreateCommandQueue");+ string[] sources = new string[] { GpuWaveSimulator.KernelSource(this._use4thOrderLaplacian) };+ this._program = OpenClApi.clCreateProgramWithSource(this._context, 1U, sources, null, ref err);+ OpenClApi.Check(err, "clCreateProgramWithSource");+ string buildOptions = "";+ err = OpenClApi.clBuildProgram(this._program, 1U, deviceIds, ref buildOptions, IntPtr.Zero, IntPtr.Zero);+ if (err != 0)+ {+ string buildLog = OpenClApi.BuildLog(this._program, device.DeviceId);+ throw new InvalidOperationException("the program for the GPU could not be built (" + OpenClApi.ErrorName(err) + ")" + ((buildLog.Length > 0) ? (": " + buildLog) : ""));+ }+ float[] c2 = new float[this._cells];+ float[] damping = new float[this._cells];+ for (int y = 0; y < this._height; y++)+ {+ Array.Copy(scene.C2, y * this._width, c2, (y + 1) * this._stride + 1, this._width);+ Array.Copy(scene.D, y * this._width, damping, (y + 1) * this._stride + 1, this._width);+ }+ float maxC2 = 0f;+ if (this._use4thOrderLaplacian)+ {+ for (int i = 0; i < c2.Length; i++)+ {+ if (c2[i] > maxC2)+ {+ maxC2 = c2[i];+ }+ }+ }+ this._subSteps = (this._use4thOrderLaplacian ? GpuWaveSimulator.ComputeSubSteps(maxC2) : 1);+ float[] dampingPerSubStep = damping;+ if (this._subSteps > 1)+ {+ // Damping is applied once per sub-step, so take the sub-step root to keep the per-step decay unchanged.+ float[] adjusted = new float[damping.Length];+ double exponent = 1.0 / this._subSteps;+ for (int i = 0; i < damping.Length; i++)+ {+ adjusted[i] = (float)Math.Pow(damping[i], exponent);+ }+ dampingPerSubStep = adjusted;+ // A sub-step is 1/subSteps long, so c²·dt² shrinks by 1/subSteps².+ this._c2Mult = 1f / (float)(this._subSteps * this._subSteps);+ }+ else+ {+ this._c2Mult = 1f;+ }+ this._c2Buffer = this.CreateFloatBuffer(c2);+ this._dBuffer = this.CreateFloatBuffer(dampingPerSubStep);+ float[] zeros = new float[this._cells];+ this._field[0] = this.CreateFloatBuffer(zeros);+ this._field[1] = this.CreateFloatBuffer(zeros);+ if (this._track)+ {+ this._intensityBuffer = this.CreateFloatBuffer(zeros);+ this._intensityStage1Buffer = this.CreateFloatBuffer(zeros);+ this._intensityOutBuffer = this.CreateFloatBuffer(zeros);+ }+ else+ {+ // Not tracked: the kernels still need valid buffer arguments, and they never touch them.+ this._intensityBuffer = this.CreateFloatBuffer(new float[1]);+ this._intensityStage1Buffer = this.CreateFloatBuffer(new float[1]);+ this._intensityOutBuffer = this.CreateFloatBuffer(new float[1]);+ }+ if (this._sourceCount > 0 || this._objSourceCount > 0)+ {+ float[] frequencies = new float[256];+ for (int level = 0; level <= 255; level++)+ {+ frequencies[level] = (float)(level / 255.0 * 0.5 * sourceFrequencyScale);+ }+ this._frequencyBuffer = this.CreateFloatBuffer(frequencies);+ }+ // The intensity decay time is scaled by the lowest (slowest) source level in use; 100 when none has a level.+ int minLevel = 0;+ for (int i = 0; i < this._sourceCount; i++)+ {+ int level = scene.SourceLevel[i];+ if (level > 0 && (minLevel == 0 || level < minLevel))+ {+ minLevel = level;+ }+ }+ foreach (SourceElement source in objectSources)+ {+ if (source.Level > 0 && (minLevel == 0 || source.Level < minLevel))+ {+ minLevel = source.Level;+ }+ }+ if (minLevel == 0)+ {+ minLevel = 100;+ }+ double decaySteps = Math.Max(1.0, timeDecayFactor * 100.0 / (double)minLevel);+ this._intensityAlpha = (float)Math.Exp(-1.0 / decaySteps);+ this._intensityScale = (float)intensityScale;+ if (this._sourceCount > 0)+ {+ int[] indices = new int[this._sourceCount];+ int[] levels = new int[this._sourceCount];+ for (int i = 0; i < this._sourceCount; i++)+ {+ indices[i] = (scene.SourceY[i] + 1) * this._stride + scene.SourceX[i] + 1;+ levels[i] = scene.SourceLevel[i];+ }+ this._indexBuffer = this.CreateIntBuffer(indices);+ this._levelBuffer = this.CreateIntBuffer(levels);+ }+ if (this._objSourceCount > 0)+ {+ int[] objIndices = new int[this._objSourceCount];+ int[] objLevels = new int[this._objSourceCount];+ float[] objAmplitudes = new float[this._objSourceCount];+ float[] objPhases = new float[this._objSourceCount];+ int[] objModes = new int[this._objSourceCount];+ int[] objPulseShapes = new int[this._objSourceCount];+ int[] objOnWidths = new int[this._objSourceCount];+ int[] objOffWidths = new int[this._objSourceCount];+ int[] objDetachSteps = new int[this._objSourceCount];+ int[] objOffWidthBases = new int[this._objSourceCount];+ int[] objRandomizeOffWidthAmounts = new int[this._objSourceCount];+ float[] objCycleAnchors = new float[this._objSourceCount];+ int[] objRngStates = new int[this._objSourceCount];+ Random random = new Random();+ for (int i = 0; i < this._objSourceCount; i++)+ {+ SourceElement source = objectSources[i];+ objIndices[i] = (source.PosY + 1) * this._stride + source.PosX + 1;+ objLevels[i] = source.Level;+ objAmplitudes[i] = (float)source.Amplitude;+ objPhases[i] = (float)source.PhaseRad;+ objModes[i] = ((source.Mode == SourceMode.Pulsed) ? 1 : 0);+ objPulseShapes[i] = ((source.PulseShape == SourcePulseShape.SmoothedSquare) ? 1 : 0);+ objOnWidths[i] = source.OnWidthCycles;+ objOffWidths[i] = source.OffWidthCycles;+ objDetachSteps[i] = source.DetachAfterStep;+ objOffWidthBases[i] = source.OffWidthBase;+ objRandomizeOffWidthAmounts[i] = source.RandomizeOffWidthAmount;+ objCycleAnchors[i] = 0f;+ // xorshift32 never leaves state 0, so a zero seed would make the off-width constant.+ int seed = random.Next(int.MinValue, int.MaxValue);+ if (seed == 0)+ {+ seed = 1;+ }+ objRngStates[i] = seed;+ }+ this._objIndexBuffer = this.CreateIntBuffer(objIndices);+ this._objLevelBuffer = this.CreateIntBuffer(objLevels);+ this._objAmplitudeBuffer = this.CreateFloatBuffer(objAmplitudes);+ this._objPhaseBuffer = this.CreateFloatBuffer(objPhases);+ this._objModeBuffer = this.CreateIntBuffer(objModes);+ this._objPulseShapeBuffer = this.CreateIntBuffer(objPulseShapes);+ this._objOnWidthBuffer = this.CreateIntBuffer(objOnWidths);+ this._objOffWidthBuffer = this.CreateIntBuffer(objOffWidths);+ this._objDetachStepBuffer = this.CreateIntBuffer(objDetachSteps);+ this._objOffWidthBaseBuffer = this.CreateIntBuffer(objOffWidthBases);+ this._objRandomizeOffWidthAmountBuffer = this.CreateIntBuffer(objRandomizeOffWidthAmounts);+ this._objCycleAnchorBuffer = this.CreateFloatBuffer(objCycleAnchors);+ this._objRngStateBuffer = this.CreateIntBuffer(objRngStates);+ }+ // Kernel k reads field[k] and writes field[1 - k]; argument 4 (sources) / 11 (object sources) is the+ // time and argument 8 of wave_step the track flag, both set per launch in AdvanceOneStep.+ for (int k = 0; k <= 1; k++)+ {+ this._stepKernel[k] = this.CreateKernel("wave_step");+ GpuWaveSimulator.SetMem(this._stepKernel[k], 0U, this._field[k]);+ GpuWaveSimulator.SetMem(this._stepKernel[k], 1U, this._field[1 - k]);+ GpuWaveSimulator.SetMem(this._stepKernel[k], 2U, this._c2Buffer);+ GpuWaveSimulator.SetMem(this._stepKernel[k], 3U, this._dBuffer);+ GpuWaveSimulator.SetMem(this._stepKernel[k], 4U, this._intensityBuffer);+ GpuWaveSimulator.SetInt(this._stepKernel[k], 5U, this._width);+ GpuWaveSimulator.SetInt(this._stepKernel[k], 6U, this._height);+ GpuWaveSimulator.SetInt(this._stepKernel[k], 7U, this._stride);+ GpuWaveSimulator.SetInt(this._stepKernel[k], 8U, this._track ? 1 : 0);+ GpuWaveSimulator.SetFloat(this._stepKernel[k], 9U, this._c2Mult);+ GpuWaveSimulator.SetFloat(this._stepKernel[k], 10U, this._intensityAlpha);+ GpuWaveSimulator.SetMem(this._stepKernel[k], 11U, this._intensityStage1Buffer);+ GpuWaveSimulator.SetMem(this._stepKernel[k], 12U, this._intensityOutBuffer);+ GpuWaveSimulator.SetFloat(this._stepKernel[k], 13U, this._intensityScale);+ if (this._sourceCount > 0)+ {+ this._sourceKernel[k] = this.CreateKernel("apply_sources");+ GpuWaveSimulator.SetMem(this._sourceKernel[k], 0U, this._field[k]);+ GpuWaveSimulator.SetMem(this._sourceKernel[k], 1U, this._indexBuffer);+ GpuWaveSimulator.SetMem(this._sourceKernel[k], 2U, this._levelBuffer);+ GpuWaveSimulator.SetMem(this._sourceKernel[k], 3U, this._frequencyBuffer);+ GpuWaveSimulator.SetFloat(this._sourceKernel[k], 5U, this._amplitude);+ GpuWaveSimulator.SetInt(this._sourceKernel[k], 6U, this._sourceCount);+ }+ if (this._objSourceCount > 0)+ {+ this._objSourceKernel[k] = this.CreateKernel("apply_object_sources");+ GpuWaveSimulator.SetMem(this._objSourceKernel[k], 0U, this._field[k]);+ GpuWaveSimulator.SetMem(this._objSourceKernel[k], 1U, this._objIndexBuffer);+ GpuWaveSimulator.SetMem(this._objSourceKernel[k], 2U, this._objLevelBuffer);+ GpuWaveSimulator.SetMem(this._objSourceKernel[k], 3U, this._objAmplitudeBuffer);+ GpuWaveSimulator.SetMem(this._objSourceKernel[k], 4U, this._objPhaseBuffer);+ GpuWaveSimulator.SetMem(this._objSourceKernel[k], 5U, this._objModeBuffer);+ GpuWaveSimulator.SetMem(this._objSourceKernel[k], 6U, this._objPulseShapeBuffer);+ GpuWaveSimulator.SetMem(this._objSourceKernel[k], 7U, this._objOnWidthBuffer);+ GpuWaveSimulator.SetMem(this._objSourceKernel[k], 8U, this._objOffWidthBuffer);+ GpuWaveSimulator.SetMem(this._objSourceKernel[k], 9U, this._objDetachStepBuffer);+ GpuWaveSimulator.SetMem(this._objSourceKernel[k], 10U, this._frequencyBuffer);+ GpuWaveSimulator.SetInt(this._objSourceKernel[k], 12U, this._objSourceCount);+ GpuWaveSimulator.SetMem(this._objSourceKernel[k], 13U, this._objOffWidthBaseBuffer);+ GpuWaveSimulator.SetMem(this._objSourceKernel[k], 14U, this._objRandomizeOffWidthAmountBuffer);+ GpuWaveSimulator.SetMem(this._objSourceKernel[k], 15U, this._objCycleAnchorBuffer);+ GpuWaveSimulator.SetMem(this._objSourceKernel[k], 16U, this._objRngStateBuffer);+ }+ }+ this._grid2D[0] = new IntPtr(this._width);+ this._grid2D[1] = new IntPtr(this._height);+ this._grid1D[0] = new IntPtr(Math.Max(1, this._sourceCount));+ this._objGrid1D[0] = new IntPtr(Math.Max(1, this._objSourceCount));+ this._hostField = new float[this._cells];+ if (this._track)+ {+ this._hostIntensity = new float[this._cells];+ }+ this._current = 0;+ }++ /// <summary>+ /// Number of sub-steps per step needed to keep the 4th-order stencil stable for the largest c² in the+ /// scene: the smallest n with c²·λmax/n² ≤ 2, at least 1. Same formula as+ /// <see cref="WaveSimulator"/> (λmax = 32/3 for the 2D 4th-order stencil, 2 leaves a margin below the+ /// leapfrog bound of 4).+ /// </summary>+ private static int ComputeSubSteps(float maxC2)+ {+ if (maxC2 <= 0f)+ {+ return 1;+ }+ // 10.666666984558105 is (double)10.666667f, i.e. the CPU engine's FourthOrderLambdaMax.+ double steps = Math.Ceiling(Math.Sqrt(maxC2 * 10.666666984558105 / 2.0));+ return Math.Max(1, (int)Math.Round(steps));+ }++ /// <summary>+ /// OpenCL source of the simulation program: <c>wave_step</c>, <c>apply_sources</c> and+ /// <c>apply_object_sources</c>, each a GPU transcription of the corresponding <see cref="WaveSimulator"/>+ /// routine. The stencil is chosen at compile time through the <c>USE_4TH_ORDER</c> define.+ /// </summary>+ private static string KernelSource(bool use4thOrderLaplacian)+ {+ StringBuilder source = new StringBuilder();+ source.AppendLine("#define USE_4TH_ORDER " + (use4thOrderLaplacian ? "1" : "0"));+ source.AppendLine();+ // wave_step: one leapfrog sub-step, one work item per interior cell (x, y in 0..w-1 / 0..h-1).+ // u current field, padded, stride floats per row; the cell is i = (y + 1) * stride + x + 1+ // up previous field on entry, overwritten in place with the new value (leapfrog), same layout+ // c2, d per-cell c² and per-sub-step damping, same layout+ // lap 4th-order 5-point-per-axis stencil for cells at least two away from the border (needs+ // USE_4TH_ORDER), otherwise the 9-point stencil (corners 0.066, edges 0.184, centre -1)+ // nv = u + (u - up)·d + lap·c2·c2Scale, with c2Scale = 1/subSteps²+ // inten1 / inten first and second stage exponential averages of nv², retention intensityAlpha+ // intenOut (stage1 + stage2)/2 · intensityScale; the three are only touched when track != 0+ source.AppendLine("__kernel void wave_step(__global const float* u, __global float* up, __global const float* c2,");+ source.AppendLine(" __global const float* d, __global float* inten,");+ source.AppendLine(" const int w, const int h, const int stride, const int track, const float c2Scale,");+ source.AppendLine(" const float intensityAlpha, __global float* inten1, __global float* intenOut,");+ source.AppendLine(" const float intensityScale)");+ source.AppendLine("{");+ source.AppendLine(" int x = get_global_id(0);");+ source.AppendLine(" int y = get_global_id(1);");+ source.AppendLine(" if (x >= w || y >= h) return;");+ source.AppendLine(" int i = (y + 1) * stride + x + 1;");+ source.AppendLine(" float uc = u[i];");+ source.AppendLine(" float lap;");+ source.AppendLine("#if USE_4TH_ORDER");+ source.AppendLine(" if (x >= 1 && x <= w - 2 && y >= 1 && y <= h - 2) {");+ source.AppendLine(" lap = (-1.0f / 12.0f) * (u[i - 2] + u[i + 2] + u[i - 2 * stride] + u[i + 2 * stride])");+ source.AppendLine(" + (4.0f / 3.0f) * (u[i - 1] + u[i + 1] + u[i - stride] + u[i + stride])");+ source.AppendLine(" - 5.0f * uc;");+ source.AppendLine(" } else {");+ source.AppendLine(" lap = 0.066f * (u[i - stride - 1] + u[i - stride + 1] + u[i + stride - 1] + u[i + stride + 1])");+ source.AppendLine(" + 0.184f * (u[i - 1] + u[i + 1] + u[i - stride] + u[i + stride]) - uc;");+ source.AppendLine(" }");+ source.AppendLine("#else");+ source.AppendLine(" lap = 0.066f * (u[i - stride - 1] + u[i - stride + 1] + u[i + stride - 1] + u[i + stride + 1])");+ source.AppendLine(" + 0.184f * (u[i - 1] + u[i + 1] + u[i - stride] + u[i + stride]) - uc;");+ source.AppendLine("#endif");+ source.AppendLine(" float nv = uc + (uc - up[i]) * d[i] + lap * c2[i] * c2Scale;");+ source.AppendLine(" up[i] = nv;");+ source.AppendLine(" if (track != 0) {");+ source.AppendLine(" float s1 = inten1[i] * intensityAlpha + nv * nv * (1.0f - intensityAlpha);");+ source.AppendLine(" inten1[i] = s1;");+ source.AppendLine(" float s2 = inten[i] * intensityAlpha + s1 * (1.0f - intensityAlpha);");+ source.AppendLine(" inten[i] = s2;");+ source.AppendLine(" intenOut[i] = (s1 * 0.5f + s2 * 0.5f) * intensityScale;");+ source.AppendLine(" }");+ source.AppendLine("}");+ source.AppendLine();+ // apply_sources: soft-blends the image sources into the field, one work item per source k < n.+ // idx[k] padded cell index of the source; level[k] its green level (index into freq)+ // freq 256 angular frequencies (radians per step); t the current step+ // u[idx] = 0.9·u + 0.1·sin(freq[level]·t)·amp (same 0.9/0.1 blend as the CPU SourceOpacity)+ source.AppendLine("__kernel void apply_sources(__global float* u, __global const int* idx, __global const int* level,");+ source.AppendLine(" __global const float* freq, const float t, const float amp, const int n)");+ source.AppendLine("{");+ source.AppendLine(" int k = get_global_id(0);");+ source.AppendLine(" if (k >= n) return;");+ source.AppendLine(" int p = idx[k];");+ source.AppendLine(" u[p] = u[p] * 0.9f + sin(freq[level[k]] * t) * amp * 0.1f;");+ source.AppendLine("}");+ source.AppendLine();+ // xorshift32: the per-source random generator for randomized off-widths (state must never be 0).+ source.AppendLine("inline uint xorshift32(uint x)");+ source.AppendLine("{");+ source.AppendLine(" x ^= x << 13;");+ source.AppendLine(" x ^= x >> 17;");+ source.AppendLine(" x ^= x << 5;");+ source.AppendLine(" return x;");+ source.AppendLine("}");+ source.AppendLine();+ // apply_object_sources: soft-blends the object sources into the field, one work item per source k < n.+ // All per-source tables are indexed by k:+ // idx, level, amp, phase cell index, frequency level (into freq), amplitude, phase (radians)+ // mode (0 continuous/1 pulsed), pulseShape (0 Gaussian/1 smoothed square), onWidth (cycles)+ // offWidth off-width in effect; rewritten here when it is randomized+ // detachStep step after which the source fades out linearly over 30 steps (-1 = never);+ // work items past the fade return without writing+ // offWidthBase ± offWidthRandomizeAmount range of a randomized off-width (amount <= 0 = fixed)+ // cycleAnchor, rngState kernel-owned state for the randomized mode: start (cycles) of the+ // current period and the xorshift32 state+ // The envelope logic is WaveSimulator.ComputePulsePosition + PulseEnvelope; the result is+ // u[idx] = 0.9·u + 0.1·sin(phase + f·t)·amp·envelope·detachFade.+ source.AppendLine("__kernel void apply_object_sources(__global float* u, __global const int* idx, __global const int* level,");+ source.AppendLine(" __global const float* amp, __global const float* phase, __global const int* mode,");+ source.AppendLine(" __global const int* pulseShape, __global const int* onWidth, __global int* offWidth,");+ source.AppendLine(" __global const int* detachStep,");+ source.AppendLine(" __global const float* freq, const float t, const int n,");+ source.AppendLine(" __global const int* offWidthBase, __global const int* offWidthRandomizeAmount,");+ source.AppendLine(" __global float* cycleAnchor, __global int* rngState)");+ source.AppendLine("{");+ source.AppendLine(" int k = get_global_id(0);");+ source.AppendLine(" if (k >= n) return;");+ source.AppendLine(" float detachFade = 1.0f;");+ source.AppendLine(" if (detachStep[k] >= 0) {");+ // The 30 below is SourceElement.DetachRampSteps, spliced into the kernel text.+ source.AppendLine(" float stepsSinceDetach = t - (float)detachStep[k];");+ source.AppendLine(" if (stepsSinceDetach >= " + 30.ToString() + ".0f) return;");+ source.AppendLine(" if (stepsSinceDetach > 0.0f) detachFade = 1.0f - stepsSinceDetach / " + 30.ToString() + ".0f;");+ source.AppendLine(" }");+ source.AppendLine(" float f = freq[level[k]];");+ source.AppendLine(" float envelope = 1.0f;");+ source.AppendLine(" if (mode[k] != 0) {");+ source.AppendLine(" int ow = offWidth[k];");+ source.AppendLine(" int period = onWidth[k] + ow;");+ source.AppendLine(" if (period > 0) {");+ source.AppendLine(" float cycleClock = f * t / (2.0f * M_PI_F);");+ source.AppendLine(" float pos;");+ source.AppendLine(" int isFirstCycle;");+ source.AppendLine(" if (offWidthRandomizeAmount[k] <= 0) {");+ source.AppendLine(" float adjustedClock = cycleClock + (float)ow;");+ source.AppendLine(" isFirstCycle = (floor(adjustedClock / (float)period) == 0.0f) ? 1 : 0;");+ source.AppendLine(" pos = adjustedClock - period * floor(adjustedClock / (float)period);");+ source.AppendLine(" } else {");+ source.AppendLine(" pos = cycleClock - cycleAnchor[k];");+ source.AppendLine(" int guard = 0;");+ source.AppendLine(" while (pos >= (float)period && guard < 1000) {");+ source.AppendLine(" cycleAnchor[k] += (float)period;");+ source.AppendLine(" pos -= (float)period;");+ source.AppendLine(" uint state = xorshift32((uint)rngState[k]);");+ source.AppendLine(" rngState[k] = (int)state;");+ source.AppendLine(" int amt = offWidthRandomizeAmount[k];");+ source.AppendLine(" int span = 2 * amt + 1;");+ source.AppendLine(" int r = (int)(state % (uint)span) - amt;");+ source.AppendLine(" ow = offWidthBase[k] + r;");+ source.AppendLine(" if (ow < 1) ow = 1;");+ source.AppendLine(" offWidth[k] = ow;");+ source.AppendLine(" period = onWidth[k] + ow;");+ source.AppendLine(" guard++;");+ source.AppendLine(" }");+ source.AppendLine(" if (pos < 0.0f) pos = 0.0f;");+ source.AppendLine(" isFirstCycle = (cycleAnchor[k] == 0.0f) ? 1 : 0;");+ source.AppendLine(" }");+ source.AppendLine(" if (pulseShape[k] == 0) {");+ source.AppendLine(" if (pos < (float)ow) {");+ source.AppendLine(" envelope = 0.0f;");+ source.AppendLine(" } else {");+ source.AppendLine(" float onPos = pos - (float)ow;");+ source.AppendLine(" float center = onWidth[k] / 2.0f;");+ source.AppendLine(" float sigma = max(onWidth[k] / 6.0f, 1.0e-6f);");+ source.AppendLine(" float dd = (onPos - center) / sigma;");+ source.AppendLine(" envelope = exp(-0.5f * dd * dd);");+ source.AppendLine(" }");+ source.AppendLine(" } else {");+ source.AppendLine(" // a flat-topped pulse (envelope 1 while on, 0 while off) with a short, FIXED-width");+ source.AppendLine(" // (in cycles) smoothed edge at the rise and the fall - fixed, so a long off span");+ source.AppendLine(" // sits at (very close to) 0 for nearly all of it instead of lingering. The math is");+ source.AppendLine(" // exactly the on-first formula, fed a coordinate shifted so the on span starts at 0.");+ source.AppendLine(" float shifted = pos - (float)ow;");+ source.AppendLine(" if (shifted < 0.0f && !isFirstCycle) shifted += (float)period;");+ source.AppendLine(" float edgeWidth = 0.35f;");+ source.AppendLine(" float dFall = shifted - (float)onWidth[k];");+ source.AppendLine(" float dRise = shifted;");+ source.AppendLine(" if (dRise > (float)period / 2.0f) dRise -= (float)period;");+ source.AppendLine(" float rising = 0.5f + atan(dRise / edgeWidth) / M_PI_F;");+ source.AppendLine(" float falling = 0.5f - atan(dFall / edgeWidth) / M_PI_F;");+ source.AppendLine(" envelope = rising * falling;");+ source.AppendLine(" }");+ source.AppendLine(" }");+ source.AppendLine(" }");+ source.AppendLine(" float v = sin(phase[k] + f * t) * amp[k] * envelope * detachFade;");+ source.AppendLine(" int p = idx[k];");+ source.AppendLine(" u[p] = u[p] * 0.9f + v * 0.1f;");+ source.AppendLine("}");+ return source.ToString();+ }++ /// <summary>Creates a read/write device buffer the size of <paramref name="data"/> and uploads it (blocking). The caller owns the handle and must release it with <see cref="ReleaseMem"/>.</summary>+ private IntPtr CreateFloatBuffer(float[] data)+ {+ IntPtr size = new IntPtr((long)data.Length * 4L);+ int err = 0;+ IntPtr buffer = OpenClApi.clCreateBuffer(this._context, OpenClApi.MemReadWrite, size, IntPtr.Zero, ref err);+ OpenClApi.Check(err, "clCreateBuffer");+ OpenClApi.Check(OpenClApi.clEnqueueWriteBufferFloat(this._queue, buffer, 1U, IntPtr.Zero, size, data, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueWriteBuffer");+ return buffer;+ }++ /// <summary>Int counterpart of <see cref="CreateFloatBuffer"/>.</summary>+ private IntPtr CreateIntBuffer(int[] data)+ {+ IntPtr size = new IntPtr((long)data.Length * 4L);+ int err = 0;+ IntPtr buffer = OpenClApi.clCreateBuffer(this._context, OpenClApi.MemReadWrite, size, IntPtr.Zero, ref err);+ OpenClApi.Check(err, "clCreateBuffer");+ OpenClApi.Check(OpenClApi.clEnqueueWriteBufferInt(this._queue, buffer, 1U, IntPtr.Zero, size, data, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueWriteBuffer");+ return buffer;+ }++ /// <summary>Creates a kernel of the simulation program (<see cref="_program"/>).</summary>+ private IntPtr CreateKernel(string name)+ {+ return this.CreateKernelFrom(this._program, name);+ }++ /// <summary>Creates the kernel <paramref name="name"/> from <paramref name="program"/>; the caller releases it with <see cref="ReleaseKernel"/>.</summary>+ private IntPtr CreateKernelFrom(IntPtr program, string name)+ {+ int err = 0;+ IntPtr kernel = OpenClApi.clCreateKernel(program, ref name, ref err);+ OpenClApi.Check(err, "clCreateKernel " + name);+ return kernel;+ }++ /// <summary>Binds a device buffer to kernel argument <paramref name="index"/>.</summary>+ private static void SetMem(IntPtr kernel, uint index, IntPtr value)+ {+ OpenClApi.Check(OpenClApi.clSetKernelArgMem(kernel, index, new IntPtr(IntPtr.Size), ref value), "clSetKernelArg");+ }++ /// <summary>Sets an <c>int</c> kernel argument.</summary>+ private static void SetInt(IntPtr kernel, uint index, int value)+ {+ OpenClApi.Check(OpenClApi.clSetKernelArgInt(kernel, index, new IntPtr(4), ref value), "clSetKernelArg");+ }++ /// <summary>Sets a <c>float</c> kernel argument.</summary>+ private static void SetFloat(IntPtr kernel, uint index, float value)+ {+ OpenClApi.Check(OpenClApi.clSetKernelArgFloat(kernel, index, new IntPtr(4), ref value), "clSetKernelArg");+ }++ /// <summary>Engine label for the UI/result: "GPU: <device name> (OpenCL)".</summary>+ public string Description+ {+ get+ {+ return this._description;+ }+ }++ /// <summary>Scene width in cells (canvas pixels), excluding the padding.</summary>+ public int Width+ {+ get+ {+ return this._width;+ }+ }++ /// <summary>Scene height in cells (canvas pixels), excluding the padding.</summary>+ public int Height+ {+ get+ {+ return this._height;+ }+ }++ /// <summary>Row pitch of the padded buffers: <see cref="Width"/> + 2.</summary>+ public int Stride+ {+ get+ {+ return this._stride;+ }+ }++ /// <summary>+ /// Host copy of the field (padded layout). Unlike the CPU engine the array instance never changes, but+ /// its contents are only as fresh as the last <see cref="PrepareFrame"/> with <c>needField</c>.+ /// </summary>+ public float[] FieldData+ {+ get+ {+ return this._hostField;+ }+ }++ /// <summary>Host copy of the scaled intensity (padded layout) as of the last <see cref="PrepareFrame"/> with <c>needIntensity</c>; null when the engine was created without intensity tracking.</summary>+ public float[] IntensityData+ {+ get+ {+ return this._hostIntensity;+ }+ }++ /// <summary>+ /// Enqueues one simulation step (nothing is waited for): the source kernels bound to the current field+ /// blend the sources in once, then <c>wave_step</c> runs <see cref="_subSteps"/> times, alternating+ /// between the two kernel instances so each sub-step reads the newest buffer and overwrites the older one+ /// (the leapfrog "previous" field). The track flag is set so only the last sub-step updates the intensity+ /// (with a single sub-step the flag keeps the value bound in <see cref="Build"/>). Afterwards+ /// <see cref="_current"/> points at the newest buffer and <see cref="_time"/> advances by one step.+ /// Every 16 steps the queue is drained with <c>clFinish</c> so unbounded asynchronous enqueueing cannot+ /// exhaust the driver.+ /// </summary>+ public void AdvanceOneStep()+ {+ int current = this._current;+ if (this._sourceCount > 0)+ {+ GpuWaveSimulator.SetFloat(this._sourceKernel[current], 4U, (float)this._time);+ OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(this._queue, this._sourceKernel[current], 1U, null, this._grid1D, null, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (sources)");+ }+ if (this._objSourceCount > 0)+ {+ GpuWaveSimulator.SetFloat(this._objSourceKernel[current], 11U, (float)this._time);+ OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(this._queue, this._objSourceKernel[current], 1U, null, this._objGrid1D, null, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (object sources)");+ }+ if (this._subSteps <= 1)+ {+ OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(this._queue, this._stepKernel[current], 2U, null, this._grid2D, null, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (step)");+ current = 1 - current;+ }+ else+ {+ for (int i = 1; i <= this._subSteps; i++)+ {+ int trackThisSubStep = ((i == this._subSteps && this._track) ? 1 : 0);+ GpuWaveSimulator.SetInt(this._stepKernel[current], 8U, trackThisSubStep);+ OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(this._queue, this._stepKernel[current], 2U, null, this._grid2D, null, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (step)");+ current = 1 - current;+ }+ }+ this._current = current;+ this._time += 1.0;+ this._sinceFinish++;+ if (this._sinceFinish >= 16)+ {+ this._sinceFinish = 0;+ OpenClApi.Check(OpenClApi.clFinish(this._queue), "clFinish");+ }+ }++ /// <summary>+ /// Blocking device-to-host copies of the newest field into <see cref="FieldData"/> and/or of the intensity+ /// into <see cref="IntensityData"/> (the latter only when tracked). Called by the runner before rendering,+ /// and from the UI thread while paused. As the reads drain the queue, the clFinish counter is reset.+ /// </summary>+ public void PrepareFrame(bool needField, bool needIntensity)+ {+ IntPtr size = new IntPtr((long)this._cells * 4L);+ if (needField)+ {+ OpenClApi.Check(OpenClApi.clEnqueueReadBufferFloat(this._queue, this._field[this._current], 1U, IntPtr.Zero, size, this._hostField, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueReadBuffer");+ }+ if (needIntensity && this._track)+ {+ OpenClApi.Check(OpenClApi.clEnqueueReadBufferFloat(this._queue, this._intensityOutBuffer, 1U, IntPtr.Zero, size, this._hostIntensity, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueReadBuffer");+ }+ this._sinceFinish = 0;+ }++ /// <summary>+ /// OpenCL source of the probe program (built lazily in <see cref="SetProbes"/>): <c>probe_sample</c> for+ /// point probes, <c>profile_accumulate</c> and <c>profile_gather</c> for line probes. Together they are+ /// the device side of <see cref="WaveSimulator.SampleProbes"/> / <see cref="WaveSimulator.ReadProbeProfiles"/>.+ /// </summary>+ private static string ProbeKernelSource()+ {+ StringBuilder source = new StringBuilder();+ // probe_sample: one work item per probe p < n (n = all probes, line probes included).+ // u, inten newest field and the intensity output, padded layout+ // pix pixel index lists of all point probes concatenated+ // info 4 ints per probe: [start in pix, count, 1 = sample inten instead of u, 1 = divide by count];+ // all 0 for line probes, which therefore write 0+ // hist ProbeRows × n floats, row-major: hist[row * n + p] receives this step's value+ source.AppendLine("__kernel void probe_sample(__global const float* u, __global const float* inten, __global const int* pix,");+ source.AppendLine(" __global const int* info, __global float* hist, const int row, const int n)");+ source.AppendLine("{");+ source.AppendLine(" int p = get_global_id(0);");+ source.AppendLine(" if (p >= n) return;");+ source.AppendLine(" int start = info[p * 4];");+ source.AppendLine(" int count = info[p * 4 + 1];");+ source.AppendLine(" int useI = info[p * 4 + 2];");+ source.AppendLine(" int mean = info[p * 4 + 3];");+ source.AppendLine(" float s = 0.0f;");+ source.AppendLine(" if (useI != 0) {");+ source.AppendLine(" for (int k = 0; k < count; k++) s += inten[pix[start + k]];");+ source.AppendLine(" } else {");+ source.AppendLine(" for (int k = 0; k < count; k++) s += u[pix[start + k]];");+ source.AppendLine(" }");+ source.AppendLine(" if (mean != 0 && count > 0) s = s / (float)count;");+ source.AppendLine(" hist[row * n + p] = s;");+ source.AppendLine("}");+ source.AppendLine();+ // profile_accumulate: one work item per line-probe pixel k < n (all line probes flattened):+ // ppix[k] padded cell index; pmode[k] 0 = field, 1 = intensity, 2 = integrated intensity+ // total[k] += inten[ppix[k]] for mode 2 only, and only once step >= pStartStep[k] when pStartFlag[k] is set+ source.AppendLine("__kernel void profile_accumulate(__global const float* inten, __global const int* ppix,");+ source.AppendLine(" __global const int* pmode, __global const int* pStartFlag, __global const int* pStartStep,");+ source.AppendLine(" __global float* total, const int step, const int n)");+ source.AppendLine("{");+ source.AppendLine(" int k = get_global_id(0);");+ source.AppendLine(" if (k >= n) return;");+ source.AppendLine(" if (pmode[k] != 2) return;");+ source.AppendLine(" if (pStartFlag[k] != 0 && step < pStartStep[k]) return;");+ source.AppendLine(" total[k] += inten[ppix[k]];");+ source.AppendLine("}");+ source.AppendLine();+ // profile_gather: one work item per line-probe pixel k < n; same ppix/pmode layout as above.+ // outv[k] = total[k] (mode 2), inten[ppix[k]] (mode 1) or u[ppix[k]] (mode 0)+ source.AppendLine("__kernel void profile_gather(__global const float* u, __global const float* inten, __global const int* ppix,");+ source.AppendLine(" __global const int* pmode, __global const float* total, __global float* outv, const int n)");+ source.AppendLine("{");+ source.AppendLine(" int k = get_global_id(0);");+ source.AppendLine(" if (k >= n) return;");+ source.AppendLine(" int m = pmode[k];");+ source.AppendLine(" float v;");+ source.AppendLine(" if (m == 2) v = total[k];");+ source.AppendLine(" else if (m == 1) v = inten[ppix[k]];");+ source.AppendLine(" else v = u[ppix[k]];");+ source.AppendLine(" outv[k] = v;");+ source.AppendLine("}");+ return source.ToString();+ }++ /// <summary>+ /// Installs the probe layout: builds the probe program (<see cref="ProbeKernelSource"/>), then uploads the+ /// pixel tables and creates the kernels for point probes (<see cref="SetUpSeriesProbes"/>) and line probes+ /// (<see cref="SetUpProfileProbes"/>). A null or empty sampler installs nothing and leaves a previously+ /// installed one in place. Meant to be called once per engine: a second call overwrites the probe handles+ /// without releasing the earlier ones.+ /// </summary>+ /// <exception cref="InvalidOperationException">The sampler needs intensity but this engine does not track it, or the probe program / buffers could not be created (inner exception has the OpenCL error).</exception>+ public void SetProbes(ProbeSampler sampler)+ {+ if (sampler == null || sampler.Count == 0)+ {+ return;+ }+ try+ {+ if (sampler.NeedsIntensity && !this._track)+ {+ throw new InvalidOperationException("the intensity is not tracked");+ }+ int err = 0;+ IntPtr[] deviceIds = new IntPtr[] { this._deviceId };+ string[] sources = new string[] { GpuWaveSimulator.ProbeKernelSource() };+ this._probeProgram = OpenClApi.clCreateProgramWithSource(this._context, 1U, sources, null, ref err);+ OpenClApi.Check(err, "clCreateProgramWithSource (probes)");+ string buildOptions = "";+ err = OpenClApi.clBuildProgram(this._probeProgram, 1U, deviceIds, ref buildOptions, IntPtr.Zero, IntPtr.Zero);+ if (err != 0)+ {+ string buildLog = OpenClApi.BuildLog(this._probeProgram, this._deviceId);+ throw new InvalidOperationException("the probe program for the GPU could not be built (" + OpenClApi.ErrorName(err) + ")" + ((buildLog.Length > 0) ? (": " + buildLog) : ""));+ }+ if (sampler.HasSeries)+ {+ this.SetUpSeriesProbes(sampler);+ }+ if (sampler.HasProfiles)+ {+ this.SetUpProfileProbes(sampler);+ }+ this._probeSampler = sampler;+ }+ catch (Exception ex)+ {+ throw new InvalidOperationException("the probes could not be set up on the GPU: " + ex.Message, ex);+ }+ }++ /// <summary>+ /// Packs the pixel lists of all point (non-profile) probes into <see cref="_pixelBuffer"/>, describes each+ /// probe in <see cref="_infoBuffer"/> (point probes average their pixels, so a single-pixel probe yields+ /// that pixel's value like <see cref="ProbeSampler.Compute"/>), allocates the <see cref="ProbeRows"/>-row+ /// history buffer and creates the two <c>probe_sample</c> kernels. Resets the host-side sample lists.+ /// </summary>+ private void SetUpSeriesProbes(ProbeSampler sampler)+ {+ int count = sampler.Count;+ int err = 0;+ int totalPixels = 0;+ for (int i = 0; i < count; i++)+ {+ if (!sampler.IsProfile[i])+ {+ totalPixels += sampler.Pixels[i].Length;+ }+ }+ int[] pixels = new int[Math.Max(totalPixels, 1)];+ int[] info = new int[count * 4];+ int offset = 0;+ for (int i = 0; i < count; i++)+ {+ if (!sampler.IsProfile[i])+ {+ int[] probePixels = sampler.Pixels[i];+ Array.Copy(probePixels, 0, pixels, offset, probePixels.Length);+ info[i * 4] = offset;+ info[i * 4 + 1] = probePixels.Length;+ info[i * 4 + 2] = (sampler.UseIntensity[i] ? 1 : 0);+ info[i * 4 + 3] = 1;+ offset += probePixels.Length;+ }+ }+ this._pixelBuffer = this.CreateIntBuffer(pixels);+ this._infoBuffer = this.CreateIntBuffer(info);+ // Never uploaded: the kernel writes every row before ReadProbeHistory reads it.+ IntPtr historySize = new IntPtr((long)GpuWaveSimulator.ProbeRows * count * 4L);+ this._historyBuffer = OpenClApi.clCreateBuffer(this._context, OpenClApi.MemReadWrite, historySize, IntPtr.Zero, ref err);+ OpenClApi.Check(err, "clCreateBuffer (probes)");+ for (int k = 0; k <= 1; k++)+ {+ this._probeKernel[k] = this.CreateKernelFrom(this._probeProgram, "probe_sample");+ GpuWaveSimulator.SetMem(this._probeKernel[k], 0U, this._field[k]);+ GpuWaveSimulator.SetMem(this._probeKernel[k], 1U, this._intensityOutBuffer);+ GpuWaveSimulator.SetMem(this._probeKernel[k], 2U, this._pixelBuffer);+ GpuWaveSimulator.SetMem(this._probeKernel[k], 3U, this._infoBuffer);+ GpuWaveSimulator.SetMem(this._probeKernel[k], 4U, this._historyBuffer);+ GpuWaveSimulator.SetInt(this._probeKernel[k], 5U, 0);+ GpuWaveSimulator.SetInt(this._probeKernel[k], 6U, count);+ }+ this._probeGrid[0] = new IntPtr(count);+ this._probeValues.Clear();+ for (int i = 0; i < count; i++)+ {+ this._probeValues.Add(new List<float>());+ }+ this._probeRow = 0;+ }++ /// <summary>+ /// Flattens the pixels of all line probes into per-pixel buffers (index, mode, start flag/step), records+ /// where each probe starts in <see cref="_profileStart"/>, zero-initialises the totals and output buffers+ /// and creates the two <c>profile_gather</c> kernels. The start-step buffers and the+ /// <c>profile_accumulate</c> kernel are only created when at least one probe integrates.+ /// </summary>+ private void SetUpProfileProbes(ProbeSampler sampler)+ {+ int count = sampler.Count;+ int totalPixels = 0;+ for (int i = 0; i < count; i++)+ {+ if (sampler.IsProfile[i])+ {+ totalPixels += sampler.Pixels[i].Length;+ }+ }+ int[] pixels = new int[totalPixels];+ int[] modes = new int[totalPixels];+ int[] startFlags = new int[totalPixels];+ int[] startSteps = new int[totalPixels];+ this._profileStart = new int[count];+ this._profileIntegrates = false;+ int offset = 0;+ for (int i = 0; i < count; i++)+ {+ this._profileStart[i] = offset;+ if (sampler.IsProfile[i])+ {+ int[] probePixels = sampler.Pixels[i];+ int mode = (sampler.Integrate[i] ? 2 : (sampler.UseIntensity[i] ? 1 : 0));+ if (mode == 2)+ {+ this._profileIntegrates = true;+ }+ int startFlag = (sampler.UseStartAfterStep[i] ? 1 : 0);+ int startStep = sampler.StartAfterStep[i];+ for (int k = 0; k < probePixels.Length; k++)+ {+ pixels[offset + k] = probePixels[k];+ modes[offset + k] = mode;+ startFlags[offset + k] = startFlag;+ startSteps[offset + k] = startStep;+ }+ offset += probePixels.Length;+ }+ }+ this._profileCount = totalPixels;+ this._profilePixelBuffer = this.CreateIntBuffer(pixels);+ this._profileModeBuffer = this.CreateIntBuffer(modes);+ this._profileTotalBuffer = this.CreateFloatBuffer(new float[totalPixels]);+ this._profileOutBuffer = this.CreateFloatBuffer(new float[totalPixels]);+ for (int k = 0; k <= 1; k++)+ {+ this._gatherKernel[k] = this.CreateKernelFrom(this._probeProgram, "profile_gather");+ GpuWaveSimulator.SetMem(this._gatherKernel[k], 0U, this._field[k]);+ GpuWaveSimulator.SetMem(this._gatherKernel[k], 1U, this._intensityOutBuffer);+ GpuWaveSimulator.SetMem(this._gatherKernel[k], 2U, this._profilePixelBuffer);+ GpuWaveSimulator.SetMem(this._gatherKernel[k], 3U, this._profileModeBuffer);+ GpuWaveSimulator.SetMem(this._gatherKernel[k], 4U, this._profileTotalBuffer);+ GpuWaveSimulator.SetMem(this._gatherKernel[k], 5U, this._profileOutBuffer);+ GpuWaveSimulator.SetInt(this._gatherKernel[k], 6U, totalPixels);+ }+ if (this._profileIntegrates)+ {+ this._profileStartFlagBuffer = this.CreateIntBuffer(startFlags);+ this._profileStartStepBuffer = this.CreateIntBuffer(startSteps);+ this._accumulateKernel = this.CreateKernelFrom(this._probeProgram, "profile_accumulate");+ GpuWaveSimulator.SetMem(this._accumulateKernel, 0U, this._intensityOutBuffer);+ GpuWaveSimulator.SetMem(this._accumulateKernel, 1U, this._profilePixelBuffer);+ GpuWaveSimulator.SetMem(this._accumulateKernel, 2U, this._profileModeBuffer);+ GpuWaveSimulator.SetMem(this._accumulateKernel, 3U, this._profileStartFlagBuffer);+ GpuWaveSimulator.SetMem(this._accumulateKernel, 4U, this._profileStartStepBuffer);+ GpuWaveSimulator.SetMem(this._accumulateKernel, 5U, this._profileTotalBuffer);+ GpuWaveSimulator.SetInt(this._accumulateKernel, 7U, totalPixels);+ }+ this._profileGrid[0] = new IntPtr(totalPixels);+ }++ /// <summary>+ /// Called by the runner after every step: enqueues <c>probe_sample</c> for the newest field into the next+ /// history row (first draining the history to the host when all <see cref="ProbeRows"/> rows are full),+ /// and <c>profile_accumulate</c> with the current step number when any line probe integrates. Nothing is+ /// waited for.+ /// </summary>+ public void SampleProbes()+ {+ if (this._probeSampler == null)+ {+ return;+ }+ int current = this._current;+ if (this._probeSampler.HasSeries)+ {+ if (this._probeRow >= GpuWaveSimulator.ProbeRows)+ {+ this.ReadProbeHistory();+ }+ GpuWaveSimulator.SetInt(this._probeKernel[current], 5U, this._probeRow);+ OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(this._queue, this._probeKernel[current], 1U, null, this._probeGrid, null, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (probes)");+ this._probeRow++;+ }+ if (this._profileIntegrates)+ {+ GpuWaveSimulator.SetInt(this._accumulateKernel, 6U, (int)Math.Round(this._time));+ OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(this._queue, this._accumulateKernel, 1U, null, this._profileGrid, null, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (totals)");+ }+ }++ /// <summary>+ /// Blocking download of the <see cref="_probeRow"/> rows sampled so far from <see cref="_historyBuffer"/>,+ /// appending each row's point-probe values to <see cref="_probeValues"/> (line-probe columns are skipped)+ /// and rewinding the row counter. No-op when no probes are set or no row is pending.+ /// </summary>+ private void ReadProbeHistory()+ {+ if (this._probeSampler == null || this._probeRow == 0)+ {+ return;+ }+ int count = this._probeSampler.Count;+ float[] history = new float[this._probeRow * count];+ OpenClApi.Check(OpenClApi.clEnqueueReadBufferFloat(this._queue, this._historyBuffer, 1U, IntPtr.Zero, new IntPtr((long)history.Length * 4L), history, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueReadBuffer (probes)");+ for (int row = 0; row < this._probeRow; row++)+ {+ for (int p = 0; p < count; p++)+ {+ if (!this._probeSampler.IsProfile[p])+ {+ this._probeValues[p].Add(history[row * count + p]);+ }+ }+ }+ this._probeRow = 0;+ this._sinceFinish = 0;+ }++ /// <summary>Drains the pending history rows from the device, then returns and clears the point-probe values collected since the previous call.</summary>+ /// <returns>One array per probe, one value per step (empty for line probes); an empty outer array when no sampler is set.</returns>+ public float[][] TakeProbeSamples()+ {+ if (this._probeSampler == null)+ {+ return new float[0][];+ }+ int count = this._probeSampler.Count;+ float[][] samples = new float[count][];+ if (this._probeSampler.HasSeries)+ {+ this.ReadProbeHistory();+ }+ for (int i = 0; i < count; i++)+ {+ if (this._probeSampler.IsProfile[i])+ {+ samples[i] = new float[0];+ }+ else+ {+ samples[i] = this._probeValues[i].ToArray();+ this._probeValues[i].Clear();+ }+ }+ return samples;+ }++ /// <summary>+ /// Runs <c>profile_gather</c> on the newest field and reads the flat result back (blocking), then slices it+ /// per line probe; nothing is cleared.+ /// </summary>+ /// <returns>+ /// One array per probe in pixel order along the line, holding the integrated intensity totals or the live+ /// field/intensity values; null entries for point probes; an empty outer array when no sampler is set.+ /// </returns>+ public float[][] ReadProbeProfiles()+ {+ if (this._probeSampler == null)+ {+ return new float[0][];+ }+ int count = this._probeSampler.Count;+ float[][] profiles = new float[count][];+ if (!this._probeSampler.HasProfiles)+ {+ return profiles;+ }+ int current = this._current;+ OpenClApi.Check(OpenClApi.clEnqueueNDRangeKernel(this._queue, this._gatherKernel[current], 1U, null, this._profileGrid, null, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueNDRangeKernel (profiles)");+ float[] values = new float[this._profileCount];+ OpenClApi.Check(OpenClApi.clEnqueueReadBufferFloat(this._queue, this._profileOutBuffer, 1U, IntPtr.Zero, new IntPtr((long)this._profileCount * 4L), values, 0U, IntPtr.Zero, IntPtr.Zero), "clEnqueueReadBuffer (profiles)");+ this._sinceFinish = 0;+ for (int i = 0; i < count; i++)+ {+ if (this._probeSampler.IsProfile[i])+ {+ int length = this._probeSampler.Pixels[i].Length;+ float[] profile = new float[length];+ Array.Copy(values, this._profileStart[i], profile, 0, length);+ profiles[i] = profile;+ }+ }+ return profiles;+ }++ /// <summary>Releases every OpenCL handle; called by the runner when the run ends. Safe to call more than once.</summary>+ public void Dispose()+ {+ this.ReleaseAll();+ }++ /// <summary>+ /// Releases all device resources exactly once (guarded by <see cref="_released"/>): drains the queue, then+ /// frees kernels and buffers (including the probe ones, if any), the two programs, the queue and finally+ /// the context, zeroing every handle. Unset handles are skipped and OpenCL failures are swallowed, so the+ /// method is also usable from the constructor after a partial <see cref="Build"/>.+ /// </summary>+ private void ReleaseAll()+ {+ if (this._released)+ {+ return;+ }+ this._released = true;+ try+ {+ if (this._queue != IntPtr.Zero)+ {+ OpenClApi.clFinish(this._queue);+ }+ }+ catch+ {+ }+ for (int k = 0; k <= 1; k++)+ {+ GpuWaveSimulator.ReleaseKernel(ref this._stepKernel[k]);+ GpuWaveSimulator.ReleaseKernel(ref this._sourceKernel[k]);+ GpuWaveSimulator.ReleaseKernel(ref this._objSourceKernel[k]);+ GpuWaveSimulator.ReleaseKernel(ref this._probeKernel[k]);+ GpuWaveSimulator.ReleaseKernel(ref this._gatherKernel[k]);+ GpuWaveSimulator.ReleaseMem(ref this._field[k]);+ }+ GpuWaveSimulator.ReleaseKernel(ref this._accumulateKernel);+ GpuWaveSimulator.ReleaseMem(ref this._pixelBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._infoBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._historyBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._profilePixelBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._profileModeBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._profileStartFlagBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._profileStartStepBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._profileTotalBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._profileOutBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._c2Buffer);+ GpuWaveSimulator.ReleaseMem(ref this._dBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._intensityBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._intensityStage1Buffer);+ GpuWaveSimulator.ReleaseMem(ref this._intensityOutBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._indexBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._levelBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._frequencyBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._objIndexBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._objLevelBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._objAmplitudeBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._objPhaseBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._objModeBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._objPulseShapeBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._objOnWidthBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._objOffWidthBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._objDetachStepBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._objOffWidthBaseBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._objRandomizeOffWidthAmountBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._objCycleAnchorBuffer);+ GpuWaveSimulator.ReleaseMem(ref this._objRngStateBuffer);+ try+ {+ if (this._probeProgram != IntPtr.Zero)+ {+ OpenClApi.clReleaseProgram(this._probeProgram);+ }+ if (this._program != IntPtr.Zero)+ {+ OpenClApi.clReleaseProgram(this._program);+ }+ if (this._queue != IntPtr.Zero)+ {+ OpenClApi.clReleaseCommandQueue(this._queue);+ }+ if (this._context != IntPtr.Zero)+ {+ OpenClApi.clReleaseContext(this._context);+ }+ }+ catch+ {+ }+ this._probeProgram = IntPtr.Zero;+ this._program = IntPtr.Zero;+ this._queue = IntPtr.Zero;+ this._context = IntPtr.Zero;+ }++ /// <summary>Releases a buffer handle unless it is <see cref="IntPtr.Zero"/>, ignoring errors, and zeroes it.</summary>+ private static void ReleaseMem(ref IntPtr handle)+ {+ try+ {+ if (handle != IntPtr.Zero)+ {+ OpenClApi.clReleaseMemObject(handle);+ }+ }+ catch+ {+ }+ handle = IntPtr.Zero;+ }++ /// <summary>Releases a kernel handle unless it is <see cref="IntPtr.Zero"/>, ignoring errors, and zeroes it.</summary>+ private static void ReleaseKernel(ref IntPtr handle)+ {+ try+ {+ if (handle != IntPtr.Zero)+ {+ OpenClApi.clReleaseKernel(handle);+ }+ }+ catch+ {+ }+ handle = IntPtr.Zero;+ }++ /// <summary>Engine label: "GPU: <device name> (OpenCL)".</summary>+ private readonly string _description;++ /// <summary>Scene width in cells (canvas pixels), without padding.</summary>+ private readonly int _width;++ /// <summary>Scene height in cells, without padding.</summary>+ private readonly int _height;++ /// <summary>Padded row pitch (<see cref="_width"/> + 2).</summary>+ private readonly int _stride;++ /// <summary>Number of floats in every padded per-cell buffer: <see cref="_stride"/> × (<see cref="_height"/> + 2).</summary>+ private readonly int _cells;++ /// <summary>Whether the intensity is tracked; when false the intensity buffers are 1-float dummies and <see cref="IntensityData"/> is null.</summary>+ private readonly bool _track;++ /// <summary>Number of image (green-channel) sources in the scene.</summary>+ private readonly int _sourceCount;++ /// <summary>Peak amplitude of the image sources (object sources carry their own).</summary>+ private readonly float _amplitude;++ /// <summary>Whether the program was compiled with the 4th-order stencil (<c>USE_4TH_ORDER</c>), which implies sub-stepping.</summary>+ private readonly bool _use4thOrderLaplacian;++ /// <summary>Leapfrog sub-steps per simulation step; 1 unless the 4th-order stencil is on. Set in <see cref="Build"/>.</summary>+ private int _subSteps;++ /// <summary>1/<see cref="_subSteps"/>², scaling c² for the shorter sub-step (kernel argument <c>c2Scale</c>).</summary>+ private float _c2Mult;++ /// <summary>Per-step retention of the two intensity averaging stages: exp(-1/decaySteps) with decaySteps = timeDecayFactor·100/lowest source level.</summary>+ private float _intensityAlpha;++ /// <summary>Multiplier on the intensity output.</summary>+ private float _intensityScale;++ /// <summary>OpenCL context on the chosen device; released last in <see cref="ReleaseAll"/>.</summary>+ private IntPtr _context;++ /// <summary>In-order command queue; every launch and transfer goes through it, from the worker thread.</summary>+ private IntPtr _queue;++ /// <summary>Program built from <see cref="KernelSource"/> (<c>wave_step</c>, <c>apply_sources</c>, <c>apply_object_sources</c>).</summary>+ private IntPtr _program;++ /// <summary>The two ping-pong field buffers (padded, <see cref="_cells"/> floats each); the one at <see cref="_current"/> holds the newest field, the other the previous one.</summary>+ private readonly IntPtr[] _field;++ /// <summary><c>wave_step</c> kernel per field index k: reads <see cref="_field"/>[k], writes <see cref="_field"/>[1 - k].</summary>+ private readonly IntPtr[] _stepKernel;++ /// <summary><c>apply_sources</c> kernel per field index k, bound to <see cref="_field"/>[k]; <see cref="IntPtr.Zero"/> when the scene has no image sources.</summary>+ private readonly IntPtr[] _sourceKernel;++ /// <summary>Index (0/1) of the field buffer holding the newest field; flips after every sub-step.</summary>+ private int _current;++ /// <summary>Per-cell c² = 1/n² (padded; border cells 0).</summary>+ private IntPtr _c2Buffer;++ /// <summary>Per-cell damping (padded), 1 = lossless; already raised to 1/<see cref="_subSteps"/> when sub-stepping.</summary>+ private IntPtr _dBuffer;++ /// <summary>Second-stage running average of u² (padded), or a 1-float dummy when not tracking.</summary>+ private IntPtr _intensityBuffer;++ /// <summary>First-stage running average of u² (padded), or a 1-float dummy when not tracking.</summary>+ private IntPtr _intensityStage1Buffer;++ /// <summary>Blended and scaled intensity (padded): read back into <see cref="_hostIntensity"/> and sampled by the probe kernels; a 1-float dummy when not tracking.</summary>+ private IntPtr _intensityOutBuffer;++ /// <summary>Padded cell index of every image source; unset when there are none.</summary>+ private IntPtr _indexBuffer;++ /// <summary>Green level (1..255) of every image source, indexing <see cref="_frequencyBuffer"/>; unset when there are none.</summary>+ private IntPtr _levelBuffer;++ /// <summary>256 angular frequencies in radians per step, one per level: level/255 × 0.5 × sourceFrequencyScale. Shared by both source kernels; unset when there are no sources at all.</summary>+ private IntPtr _frequencyBuffer;++ /// <summary>Number of object sources that lie inside the canvas.</summary>+ private readonly int _objSourceCount;++ /// <summary><c>apply_object_sources</c> kernel per field index k, bound to <see cref="_field"/>[k]; <see cref="IntPtr.Zero"/> when there are no object sources.</summary>+ private readonly IntPtr[] _objSourceKernel;++ /// <summary>Per object source: padded cell index.</summary>+ private IntPtr _objIndexBuffer;++ /// <summary>Per object source: level, indexing <see cref="_frequencyBuffer"/>.</summary>+ private IntPtr _objLevelBuffer;++ /// <summary>Per object source: peak amplitude.</summary>+ private IntPtr _objAmplitudeBuffer;++ /// <summary>Per object source: phase offset in radians.</summary>+ private IntPtr _objPhaseBuffer;++ /// <summary>Per object source: 0 = continuous, 1 = pulsed.</summary>+ private IntPtr _objModeBuffer;++ /// <summary>Per object source: 0 = Gaussian pulse, 1 = smoothed square.</summary>+ private IntPtr _objPulseShapeBuffer;++ /// <summary>Per object source: on-width of the pulse in cycles.</summary>+ private IntPtr _objOnWidthBuffer;++ /// <summary>Per object source: off-width in cycles currently in effect; rewritten by the kernel when the off-width is randomized.</summary>+ private IntPtr _objOffWidthBuffer;++ /// <summary>Per object source: step after which it detaches and fades out over <see cref="SourceElement.DetachRampSteps"/> steps, or -1 (never).</summary>+ private IntPtr _objDetachStepBuffer;++ /// <summary>Per object source: base off-width (cycles) a randomized off-width is drawn around.</summary>+ private IntPtr _objOffWidthBaseBuffer;++ /// <summary>Per object source: ± range (cycles) of the off-width randomization; 0 or less = fixed off-width.</summary>+ private IntPtr _objRandomizeOffWidthAmountBuffer;++ /// <summary>Per object source: start (in cycles) of its current period in randomized mode; kernel-owned state, uploaded as 0.</summary>+ private IntPtr _objCycleAnchorBuffer;++ /// <summary>Per object source: xorshift32 state for drawing off-widths; seeded on the host with a non-zero random int, advanced by the kernel.</summary>+ private IntPtr _objRngStateBuffer;++ /// <summary>Global work size of <c>apply_object_sources</c>: max(1, <see cref="_objSourceCount"/>).</summary>+ private readonly IntPtr[] _objGrid1D;++ /// <summary>Global work size of <c>wave_step</c>: <see cref="_width"/> × <see cref="_height"/> work items, one per interior cell.</summary>+ private readonly IntPtr[] _grid2D;++ /// <summary>Global work size of <c>apply_sources</c>: max(1, <see cref="_sourceCount"/>).</summary>+ private readonly IntPtr[] _grid1D;++ /// <summary>Host copy of the newest field, refreshed by <see cref="PrepareFrame"/>; exposed as <see cref="FieldData"/>.</summary>+ private float[] _hostField;++ /// <summary>Host copy of <see cref="_intensityOutBuffer"/>, refreshed by <see cref="PrepareFrame"/>; null when not tracking.</summary>+ private float[] _hostIntensity;++ /// <summary>Elapsed time in steps; passed to the source kernels as the float argument <c>t</c>.</summary>+ private double _time;++ /// <summary>Steps enqueued since the queue was last drained; <see cref="AdvanceOneStep"/> calls clFinish at 16. Reset by every blocking read, which drains the queue anyway.</summary>+ private int _sinceFinish;++ /// <summary>Set by <see cref="ReleaseAll"/> so a second release is a no-op.</summary>+ private bool _released;++ /// <summary>Rows (steps) the probe history buffer holds before it must be read back to the host.</summary>+ private const int ProbeRows = 2048;++ /// <summary>Device the context was created on; needed again to build the probe program.</summary>+ private IntPtr _deviceId;++ /// <summary>Probe layout installed by <see cref="SetProbes"/>, or null when no probes are set.</summary>+ private ProbeSampler _probeSampler;++ /// <summary>Program built from <see cref="ProbeKernelSource"/>; <see cref="IntPtr.Zero"/> until probes are set.</summary>+ private IntPtr _probeProgram;++ /// <summary><c>probe_sample</c> kernel per field index k, bound to <see cref="_field"/>[k]; unset without point probes.</summary>+ private readonly IntPtr[] _probeKernel;++ /// <summary>Pixel index lists of all point probes, concatenated (at least 1 int).</summary>+ private IntPtr _pixelBuffer;++ /// <summary>Per probe (all probes, 4 ints each): start offset in <see cref="_pixelBuffer"/>, pixel count, sample-intensity flag, average flag; all 0 for line probes.</summary>+ private IntPtr _infoBuffer;++ /// <summary>Sample history, <see cref="ProbeRows"/> rows × probe count floats, row-major; row r holds the samples of the r-th step since the last read-back.</summary>+ private IntPtr _historyBuffer;++ /// <summary>Next row of <see cref="_historyBuffer"/> to write, i.e. the number of rows waiting to be read back.</summary>+ private int _probeRow;++ /// <summary>Global work size of <c>probe_sample</c>: one work item per probe.</summary>+ private readonly IntPtr[] _probeGrid;++ /// <summary>Point-probe samples read back from the device and not yet taken by <see cref="TakeProbeSamples"/>, one list per probe (stays empty for line probes).</summary>+ private readonly List<List<float>> _probeValues;++ /// <summary><c>profile_gather</c> kernel per field index k, bound to <see cref="_field"/>[k]; unset without line probes.</summary>+ private readonly IntPtr[] _gatherKernel;++ /// <summary><c>profile_accumulate</c> kernel; created only when some line probe integrates (<see cref="_profileIntegrates"/>).</summary>+ private IntPtr _accumulateKernel;++ /// <summary>Padded cell index of every line-probe pixel, all line probes concatenated (<see cref="_profileCount"/> ints).</summary>+ private IntPtr _profilePixelBuffer;++ /// <summary>Per line-probe pixel: 0 = field, 1 = intensity, 2 = integrated intensity.</summary>+ private IntPtr _profileModeBuffer;++ /// <summary>Per line-probe pixel: whether integration only starts at <see cref="_profileStartStepBuffer"/>; created only when integrating.</summary>+ private IntPtr _profileStartFlagBuffer;++ /// <summary>Per line-probe pixel: step from which integration counts; created only when integrating.</summary>+ private IntPtr _profileStartStepBuffer;++ /// <summary>Per line-probe pixel: running intensity total, added to by <c>profile_accumulate</c>.</summary>+ private IntPtr _profileTotalBuffer;++ /// <summary>Per line-probe pixel: value written by <c>profile_gather</c> and read back by <see cref="ReadProbeProfiles"/>.</summary>+ private IntPtr _profileOutBuffer;++ /// <summary>Total number of line-probe pixels (length of the profile buffers).</summary>+ private int _profileCount;++ /// <summary>Whether any line probe integrates the intensity, i.e. <c>profile_accumulate</c> must run every step.</summary>+ private bool _profileIntegrates;++ /// <summary>Per probe: offset of its first pixel in the profile buffers (only meaningful for line probes).</summary>+ private int[] _profileStart;++ /// <summary>Global work size of the profile kernels: one work item per line-probe pixel.</summary>+ private readonly IntPtr[] _profileGrid;+ }+}diff --git a/Wave_Dude_2D/HelpForm.Designer.cs b/Wave_Dude_2D/HelpForm.Designer.csnew file mode 100644index 0000000..2ee430d--- /dev/null+++ b/Wave_Dude_2D/HelpForm.Designer.cs@@ -0,0 +1,83 @@+using System;+using System.ComponentModel;+using System.Windows.Forms;++namespace _2D_wave_sim_V01+{+ public partial class HelpForm : global::System.Windows.Forms.Form+ {+ /// <summary>Releases the designer-managed components when <paramref name="disposing"/> is true, then the form itself.</summary>+ /// <param name="disposing">True when called from <see cref="System.ComponentModel.Component.Dispose()"/>; false from the finalizer.</param>+ [global::System.Diagnostics.DebuggerNonUserCode]+ protected override void Dispose(bool disposing)+ {+ try+ {+ bool flag = disposing && this.components != null;+ if (flag)+ {+ this.components.Dispose();+ }+ }+ finally+ {+ base.Dispose(disposing);+ }+ }++ [global::System.Diagnostics.DebuggerStepThrough]+ private void InitializeComponent()+ {+ this.rtbHelp = new global::System.Windows.Forms.RichTextBox();+ this.pnlButtons = new global::System.Windows.Forms.FlowLayoutPanel();+ this.btnClose = new global::System.Windows.Forms.Button();+ this.pnlButtons.SuspendLayout();+ base.SuspendLayout();+ this.rtbHelp.BackColor = global::System.Drawing.SystemColors.Window;+ this.rtbHelp.BorderStyle = global::System.Windows.Forms.BorderStyle.None;+ this.rtbHelp.Dock = global::System.Windows.Forms.DockStyle.Fill;+ this.rtbHelp.Font = new global::System.Drawing.Font("Arial", 12f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.rtbHelp.Location = new global::System.Drawing.Point(0, 0);+ this.rtbHelp.Margin = new global::System.Windows.Forms.Padding(12);+ this.rtbHelp.Name = "rtbHelp";+ this.rtbHelp.ReadOnly = true;+ this.rtbHelp.Size = new global::System.Drawing.Size(1039, 843);+ this.rtbHelp.TabIndex = 0;+ this.rtbHelp.Text = "";+ this.pnlButtons.Controls.Add(this.btnClose);+ this.pnlButtons.Dock = global::System.Windows.Forms.DockStyle.Bottom;+ this.pnlButtons.FlowDirection = global::System.Windows.Forms.FlowDirection.RightToLeft;+ this.pnlButtons.Location = new global::System.Drawing.Point(0, 843);+ this.pnlButtons.Name = "pnlButtons";+ this.pnlButtons.Padding = new global::System.Windows.Forms.Padding(8);+ this.pnlButtons.Size = new global::System.Drawing.Size(1039, 46);+ this.pnlButtons.TabIndex = 1;+ this.btnClose.DialogResult = global::System.Windows.Forms.DialogResult.OK;+ this.btnClose.Location = new global::System.Drawing.Point(930, 11);+ this.btnClose.Name = "btnClose";+ this.btnClose.Size = new global::System.Drawing.Size(90, 30);+ this.btnClose.TabIndex = 0;+ this.btnClose.Text = "Close";+ this.btnClose.UseVisualStyleBackColor = true;+ base.AcceptButton = this.btnClose;+ base.CancelButton = this.btnClose;+ base.ClientSize = new global::System.Drawing.Size(1039, 889);+ base.Controls.Add(this.rtbHelp);+ base.Controls.Add(this.pnlButtons);+ base.MinimizeBox = false;+ this.MinimumSize = new global::System.Drawing.Size(560, 400);+ base.Name = "HelpForm";+ base.ShowIcon = false;+ base.ShowInTaskbar = false;+ base.StartPosition = global::System.Windows.Forms.FormStartPosition.CenterParent;+ this.Text = "Help - Wave Maker 2D";+ this.pnlButtons.ResumeLayout(false);+ base.ResumeLayout(false);+ }++ private RichTextBox rtbHelp;+ private FlowLayoutPanel pnlButtons;+ private Button btnClose;+ private global::System.ComponentModel.IContainer components;+ }+}diff --git a/Wave_Dude_2D/HelpForm.cs b/Wave_Dude_2D/HelpForm.csnew file mode 100644index 0000000..40466be--- /dev/null+++ b/Wave_Dude_2D/HelpForm.cs@@ -0,0 +1,137 @@+using System;+using System.Drawing;+using System.Windows.Forms;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Help window: a read-only <see cref="RichTextBox"/> whose contents are built in code by+ /// <see cref="FillHelpText"/> (headings, paragraphs and bullet points). Opened modally from+ /// the Info menu of <see cref="Form1"/>.+ /// </summary>+ public partial class HelpForm : Form+ {+ /// <summary>Builds the help text and moves the caret to the top so the box is not scrolled to the end.</summary>+ public HelpForm()+ {+ base.Load += this.HelpForm_Load;+ this.InitializeComponent();+ this.FillHelpText(this.rtbHelp);+ this.rtbHelp.SelectionStart = 0;+ this.rtbHelp.SelectionLength = 0;+ }++ /// <summary>+ /// Appends the whole help text to <paramref name="rtb"/>, one section per tab of the main+ /// window in UI order, followed by the explanation of the c-value and the menu.+ /// </summary>+ private void FillHelpText(RichTextBox rtb)+ {+ this.AppendHeading(rtb, "Wave Dude 2D - Help");+ this.AppendHeading(rtb, "Disclaimer");+ this.AppendBody(rtb, "The current software comes with no warranty or support and is used at your own risk. It is intended as a free tool for educational use only. Redistribution for commercial purposes is not allowed. Bugs or suggestions for future improvements can be send to the email address in the 'Info > About' screen");+ this.AppendHeading(rtb, "Getting started: the project root");+ this.AppendBody(rtb, "Every project, its settings, scene, sources, probes and exported files, lives in its own subfolder under one chosen 'project root' folder. Set it with File > Choose project root, or the 'Browse root' button on the Settings tab; the current root is shown above the tabs.");+ this.AppendBody(rtb, "The 'Projects in current root' list (Settings tab) shows every project found there: New project, Load, Rename, Delete and Save as all act on the selected one. File > New / Open / Save and 'Save changes to project' act on whichever project is currently open. Nothing is written to disk until you save your project.Projects can be shared between users by sharing the project folder and copy it to their root folder ");+ this.AppendBody(rtb, "Load, Rename, Delete and Save as all act on the selected one. File > New / Open / Save and 'Save changes to project' act on whichever project is currently open. Nothing is written to disk until you save.");+ this.AppendHeading(rtb, "Settings tab");+ this.AppendBody(rtb, "The main control panel: engine and rendering settings, the medium/scene, and starting a run.");+ this.AppendBullet(rtb, "Use GPU (generally faster)", "switches the simulation engine between CPU and GPU (OpenCL). Faster for larger grids or step counts, but needs a working OpenCL GPU; the CPU engine is the safe fallback.");+ this.AppendBullet(rtb, "Use 4th order Laplacian + sub-sampling", "switches the numerical scheme used to step the wave equation each frame. It runs somewhat slower but strongly reduces numerical dispersion (see 'Propagation speed c' below) - and changes what c should be set to.");+ this.AppendBullet(rtb, "Simulation steps / Visualize every", "how many steps a run performs, and how often (in steps) the live preview and probes are refreshed while it runs. A larger 'visualize every' makes a run finish faster at the cost of a choppier preview.");+ this.AppendBullet(rtb, "Intensity decay factor", "how quickly the accumulated Intensity view forgets past field energy, i.e. how 'persistent' the intensity build-up looks.");+ this.AppendBullet(rtb, "Field/Intensity color scheme, scale and offset", "which color table renders each view (see the Colors tab), and how the raw field/intensity values are stretched (scale) and shifted (offset) into that table's brightness range before coloring. The same scale controls also appear, linked, on the Preview tab.");+ this.AppendBullet(rtb, "Preview video of / Export video of (Field/Intensity)", "which of the two views is shown live while running, and which is written to a video file when the run finishes - independent choices.");+ this.AppendBullet(rtb, "Video quality (%)", "the compression quality used when writing exported video files.");+ this.AppendBullet(rtb, "Refractive index / Damping edge (Scene properties)", "the refractive index shapes the medium the wave travels through (a higher index locally slows the wave - it is what actually sets the per-pixel propagation speed the simulation uses, not c; see below). Damping edge adds an absorbing border so waves leave the grid instead of reflecting off its edges.");+ this.AppendBullet(rtb, "User defined (X/Y) scene vs. Scene image", "whether the medium's layout comes from a simple, hand-set shape or from an imported image (its brightness mapped to refractive index).");+ this.AppendBullet(rtb, "Use object sources / Use image sources, Edit source list", "whether wave sources are the ones built on the Sources tab, or amplitude taken from an image; 'Edit source list' jumps to the Sources tab.");+ this.AppendBody(rtb, "Found at the bottom of everly screen: Quick navigate (jump to Preview/Probes/Sources/Settings), Simulation control (Start Simulation / Pause-Resume), and Share with source/probe (send the current scene, field or intensity picture into the Sources or Probes tools as a background image).");+ this.AppendHeading(rtb, "About Scene Images");+ this.AppendBody(rtb, "Currently, scene images can only be created externally in a program like for example Photoshop. Save the images in a lossless format like .png . To add objects to a scene that the waves can interact with, you can use the red and green channels in the image color palette.");+ this.AppendBullet(rtb, "Red channel (Refractive index)", "can effectively use values ranging from 100 to 255, which represent refractive index values ranging from 1.00 to 2.55. Values lower than 100 will be set to 100 as a minimum. The red channel can be used to refract or reflect waves and create for example lenses.");+ this.AppendBullet(rtb, "Blue channel (Damping)", "reserved for damping - use values between 0 and 255, where zero means no damping and 255 heavy damping. It can be used to create regions that absorb waves like for example borders.");+ this.AppendBullet(rtb, "Green channel (Sources)", "reserved for creating wave sources, where the values 1-255 represent the frequency of the waves emitted by a pixel. If you use in-scene sources, do not use anti-aliasing to create them since this can cause the pixels next to a source to also contain a (lower) value in the green channel. When you want to use in-image sources, you must have 'use image sources' checked in the setup tab.");+ this.AppendHeading(rtb, "Sources tab");+ this.AppendBody(rtb, "Defines every object-type wave source placed in the scene; what Is set here directly drives what the simulation emits. When using ");+ this.AppendBullet(rtb, "Main type: Single vs. composite", "a single source is one emitter; a composite source is a whole array of them, laid out with a chosen spacing and array size - useful for e.g. simulating an extended or phased source.");+ this.AppendBullet(rtb, "Mode: Continuous vs. Pulsed, Frequency, Amplitude, Phase", "a continuous source oscillates forever at the set frequency; a pulsed one also uses the pulse shape/width to taper on and off. Frequency (via the estimated wavelength label) is one of the two things that determine the right value for c - see below.");+ this.AppendBullet(rtb, "Composite array: Spacing, Array size, Randomize (Phase/Position/Frequency/Off state)", "how densely and how far the individual emitters in a composite source are spread, and how much each one's properties should vary at random rather than being identical.");+ this.AppendBullet(rtb, "Place current source / Pick / Copy / Delete / Save source data", "positions a source in the scene, duplicates or removes it, and can save its data separately; 'Detach after' stops further edits in this panel from affecting an already-placed source.");+ this.AppendHeading(rtb, "Probes tab");+ this.AppendBody(rtb, "Two independent probes (Probe 1, Probe 2), each measuring the field or intensity over the course of a run and graphing it.");+ this.AppendBullet(rtb, "Place on: Field / Intensity, Measurement / Probe type", "which picture the probe samples, and what it reports from it (e.g. a value at a point, or an integrated quantity over a box).");+ this.AppendBullet(rtb, "Position A / Position B, Box size, Pick", "where the probe samples - a single point, or a box defined by two corners - set either numerically or by picking on the preview.");+ this.AppendBullet(rtb, "Full scale vs. Running scale, Auto scale X / Y", "whether the probe's graph shows the whole run at once or only a recent 'running' window, and whether its axes rescale automatically as new data comes in.");+ this.AppendBullet(rtb, "Start recording at step #", "delays when the probe starts collecting data, useful for skipping an initial transient before the wave pattern settles.");+ this.AppendHeading(rtb, "Preview tab");+ this.AppendBody(rtb, "Shows the live Field and Intensity pictures while a simulation runs, and is where finished pictures/video are exported.");+ this.AppendBullet(rtb, "Field/intensity scale factor", "the same brightness scale as on the Settings tab - the two are linked, so changing one updates the other.");+ this.AppendBullet(rtb, "Display overlay, overlay brightness", "blends a 'glowing edges' outline (derived from the scene image) on top of either preview, purely as a visual aid to see the scene layout under the field/intensity. This overlay is also baked into an exported frame or video when it is switched on, not just shown live.");+ this.AppendBullet(rtb, "Export video of (Field/Intensity), Export frame as image", "start a video export for the checked view(s) once a run starts, or immediately save the current picture as a PNG. Exported file names end in a plain running number (e.g. _0001) - one higher than the highest such number already in that output folder - rather than a date/time stamp.");+ this.AppendBullet(rtb, "Open image/video folder, View video in media player", "quick access to what has already been exported for this project.");+ this.AppendHeading(rtb, "Manage output tab");+ this.AppendBody(rtb, "An overview of everything a project has produced: scenes, exported images and exported videos, each with its creation date. From here files can be renamed, deleted, previewed, opened in their folder, viewed in the media player, copied to the clipboard, or shared back into the Sources/Probes tabs as a background image; external scene files can also be loaded in.");+ this.AppendHeading(rtb, "Colors tab");+ this.AppendBody(rtb, "Manages the color schemes used to render the Field and Intensity pictures everywhere else in the program.");+ this.AppendBullet(rtb, "Scheme list", "every scheme found in the scheme folder, sortable by clicking the Scheme or Type column header; Type marks whether a scheme is meant for the Field or the Intensity view (the Settings/Preview tabs' color-scheme pickers use this).");+ this.AppendBullet(rtb, "Color Scheme Editor: Color 1..9, color picker", "builds a 9-stop scheme by picking a color for each stop; Save, Save As, Rename and Delete act on the scheme currently being edited.");+ this.AppendBullet(rtb, "Scheme folder, Choose...", "where schemes are read from and saved to; changing it reloads the list.");+ this.AppendHeading(rtb, "Propagation speed (c): the Laplacian order and source frequency");+ this.AppendBody(rtb, "c (File > Set c-value, in pixels per simulation step) is only a display/estimate value: it is used solely to compute the estimated wavelength shown next to a source's frequency on the Sources tab (lambda = c / frequency). The wave speed the simulation actually uses at each point comes from the scene's refractive index instead, and can vary from point to point - c does not change how the run itself behaves, only what that wavelength readout says.");+ this.AppendBody(rtb, "Getting that readout right, however, depends on both the Laplacian order and the source's frequency, because of numerical dispersion - the standard (3rd order) Laplacian makes longer wavelengths propagate faster through the grid than shorter ones, purely as a numerical artifact of the scheme, not a real physical effect.");+ this.AppendBullet(rtb, "4th order Laplacian + sub-sampling (on)", "greatly reduces this dispersion. With it on, set c to 1.00 - the estimate then stays accurate across frequencies.");+ this.AppendBullet(rtb, "Standard 3rd order Laplacian (4th order off)", "dispersion is significant, so the correct c depends strongly on frequency: lower frequencies need a higher c, higher frequencies need a lower c. For example, at a source frequency where the true wavelength is 15 pixels, c must be set to about 0.56 (not 1.00) for the readout to show that; leaving c at 1.00 there would read out roughly 9 pixels instead.");+ this.AppendBody(rtb, "In short: when 4th order is off, re-check (or reduce) c whenever the source frequency changes noticeably. The '(Info)' label next to the 4th order checkbox on the Settings tab repeats this explanation in the program itself.");+ this.AppendHeading(rtb, "Menu");+ this.AppendBody(rtb, "File: New, Open, Choose project root, Set c-value, Save, Exit.\r\nInfo: this Help page, and About.");+ this.AppendBody(rtb, "Enjoy! Jeroen \r\n");+ }++ /// <summary>Appends a blank line and then <paramref name="text"/> in bold, near-black type, as a section heading.</summary>+ private void AppendHeading(RichTextBox rtb, string text)+ {+ rtb.SelectionStart = rtb.TextLength;+ rtb.SelectionLength = 0;+ rtb.SelectionFont = new Font(rtb.Font, FontStyle.Bold);+ rtb.SelectionColor = Color.FromArgb(20, 20, 20);+ rtb.AppendText("\r\n" + text + "\r\n");+ }++ /// <summary>Appends <paramref name="text"/> as a regular black paragraph ending in a line break.</summary>+ private void AppendBody(RichTextBox rtb, string text)+ {+ rtb.SelectionStart = rtb.TextLength;+ rtb.SelectionLength = 0;+ rtb.SelectionFont = new Font(rtb.Font, FontStyle.Regular);+ rtb.SelectionColor = Color.Black;+ rtb.AppendText(text + "\r\n");+ }++ /// <summary>+ /// Appends an indented bullet line: a dash, <paramref name="label"/> in bold followed by a+ /// colon, then <paramref name="explanation"/> in regular type.+ /// </summary>+ private void AppendBullet(RichTextBox rtb, string label, string explanation)+ {+ rtb.SelectionStart = rtb.TextLength;+ rtb.SelectionLength = 0;+ rtb.SelectionFont = new Font(rtb.Font, FontStyle.Regular);+ rtb.SelectionColor = Color.Black;+ rtb.AppendText(" - ");+ rtb.SelectionStart = rtb.TextLength;+ rtb.SelectionLength = 0;+ rtb.SelectionFont = new Font(rtb.Font, FontStyle.Bold);+ rtb.AppendText(label + ": ");+ rtb.SelectionStart = rtb.TextLength;+ rtb.SelectionLength = 0;+ rtb.SelectionFont = new Font(rtb.Font, FontStyle.Regular);+ rtb.AppendText(explanation + "\r\n");+ }++ /// <summary>Does nothing; still wired to <see cref="Form.Load"/> by the constructor.</summary>+ private void HelpForm_Load(object sender, EventArgs e)+ {+ }+ }+}diff --git a/Wave_Dude_2D/HelpForm.resx b/Wave_Dude_2D/HelpForm.resxnew file mode 100644index 0000000..7c72981--- /dev/null+++ b/Wave_Dude_2D/HelpForm.resx@@ -0,0 +1,61 @@+<?xml version="1.0" encoding="utf-8"?>+<root>+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />+ <xsd:element name="root" msdata:IsDataSet="true">+ <xsd:complexType>+ <xsd:choice maxOccurs="unbounded">+ <xsd:element name="metadata">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" />+ </xsd:sequence>+ <xsd:attribute name="name" use="required" type="xsd:string" />+ <xsd:attribute name="type" type="xsd:string" />+ <xsd:attribute name="mimetype" type="xsd:string" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="assembly">+ <xsd:complexType>+ <xsd:attribute name="alias" type="xsd:string" />+ <xsd:attribute name="name" type="xsd:string" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="data">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="resheader">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" />+ </xsd:complexType>+ </xsd:element>+ </xsd:choice>+ </xsd:complexType>+ </xsd:element>+ </xsd:schema>+ <resheader name="resmimetype">+ <value>text/microsoft-resx</value>+ </resheader>+ <resheader name="version">+ <value>2.0</value>+ </resheader>+ <resheader name="reader">+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <resheader name="writer">+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+</root>\ No newline at end of filediff --git a/Wave_Dude_2D/IFrameSink.cs b/Wave_Dude_2D/IFrameSink.csnew file mode 100644index 0000000..88858ff--- /dev/null+++ b/Wave_Dude_2D/IFrameSink.cs@@ -0,0 +1,25 @@+using System;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// A video file that accepts one rendered frame at a time. Implemented by <see cref="MfVideoWriter"/>+ /// (H.264 MP4) and <see cref="AviFrameSink"/> (Motion JPEG AVI); created by <see cref="SimulationRunner"/>+ /// and used only from its worker thread. Frames must have the width/height the sink was opened with.+ /// </summary>+ internal interface IFrameSink : IDisposable+ {+ /// <summary>+ /// Encodes and appends one frame given as a row-major ARGB buffer of width * height ints.+ /// The buffer may be reused by the caller once this returns.+ /// </summary>+ /// <exception cref="InvalidOperationException">The sink has already been closed.</exception>+ void AddPixels(int[] pixels);++ /// <summary>Finalizes and closes the file (writes trailers/index). Safe to call more than once; <see cref="IDisposable.Dispose"/> also closes.</summary>+ void Close();++ /// <summary>The path actually written (may differ in extension from the one requested, see <see cref="SimulationRunner"/>).</summary>+ string FilePath { get; }+ }+}diff --git a/Wave_Dude_2D/IMFAttributesNative.cs b/Wave_Dude_2D/IMFAttributesNative.csnew file mode 100644index 0000000..c5877e4--- /dev/null+++ b/Wave_Dude_2D/IMFAttributesNative.cs@@ -0,0 +1,137 @@+using System;+using System.Runtime.InteropServices;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Hand-written COM import of Media Foundation's <c>IMFAttributes</c> (IID 2CD2D921-...), used by+ /// <see cref="MfVideoWriter"/> to set media-type attributes. The method order mirrors the native vtable and+ /// must not change; only the three <c>Set*</c> members that are actually called carry real signatures, the rest+ /// are parameterless placeholders that keep the slots aligned (never call them). All methods return an HRESULT.+ /// </summary>+ [Guid("2CD2D921-C447-44A7-A13C-4ADABFC247E3")]+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ [ComImport]+ internal interface IMFAttributesNative+ {+ /// <summary>Slot for <c>IMFAttributes::GetItem</c> (placeholder).</summary>+ [PreserveSig]+ int GetItem();++ /// <summary>Slot for <c>IMFAttributes::GetItemType</c> (placeholder).</summary>+ [PreserveSig]+ int GetItemType();++ /// <summary>Slot for <c>IMFAttributes::CompareItem</c> (placeholder).</summary>+ [PreserveSig]+ int CompareItem();++ /// <summary>Slot for <c>IMFAttributes::Compare</c> (placeholder).</summary>+ [PreserveSig]+ int Compare();++ /// <summary>Slot for <c>IMFAttributes::GetUINT32</c> (placeholder).</summary>+ [PreserveSig]+ int GetUINT32();++ /// <summary>Slot for <c>IMFAttributes::GetUINT64</c> (placeholder).</summary>+ [PreserveSig]+ int GetUINT64();++ /// <summary>Slot for <c>IMFAttributes::GetDouble</c> (placeholder).</summary>+ [PreserveSig]+ int GetDouble();++ /// <summary>Slot for <c>IMFAttributes::GetGUID</c> (placeholder).</summary>+ [PreserveSig]+ int GetGUID();++ /// <summary>Slot for <c>IMFAttributes::GetStringLength</c> (placeholder).</summary>+ [PreserveSig]+ int GetStringLength();++ /// <summary>Slot for <c>IMFAttributes::GetString</c> (placeholder).</summary>+ [PreserveSig]+ int GetString();++ /// <summary>Slot for <c>IMFAttributes::GetAllocatedString</c> (placeholder).</summary>+ [PreserveSig]+ int GetAllocatedString();++ /// <summary>Slot for <c>IMFAttributes::GetBlobSize</c> (placeholder).</summary>+ [PreserveSig]+ int GetBlobSize();++ /// <summary>Slot for <c>IMFAttributes::GetBlob</c> (placeholder).</summary>+ [PreserveSig]+ int GetBlob();++ /// <summary>Slot for <c>IMFAttributes::GetAllocatedBlob</c> (placeholder).</summary>+ [PreserveSig]+ int GetAllocatedBlob();++ /// <summary>Slot for <c>IMFAttributes::GetUnknown</c> (placeholder).</summary>+ [PreserveSig]+ int GetUnknown();++ /// <summary>Slot for <c>IMFAttributes::SetItem</c> (placeholder).</summary>+ [PreserveSig]+ int SetItem();++ /// <summary>Slot for <c>IMFAttributes::DeleteItem</c> (placeholder).</summary>+ [PreserveSig]+ int DeleteItem();++ /// <summary>Slot for <c>IMFAttributes::DeleteAllItems</c> (placeholder).</summary>+ [PreserveSig]+ int DeleteAllItems();++ /// <summary><c>IMFAttributes::SetUINT32</c>: stores a 32-bit value under <paramref name="guidKey"/> (the GUID is passed by pointer).</summary>+ [PreserveSig]+ int SetUINT32([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, int value);++ /// <summary><c>IMFAttributes::SetUINT64</c>: stores a 64-bit value under <paramref name="guidKey"/>.</summary>+ [PreserveSig]+ int SetUINT64([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, ulong value);++ /// <summary>Slot for <c>IMFAttributes::SetDouble</c> (placeholder).</summary>+ [PreserveSig]+ int SetDouble();++ /// <summary><c>IMFAttributes::SetGUID</c>: stores a GUID value under <paramref name="guidKey"/>.</summary>+ [PreserveSig]+ int SetGUID([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [MarshalAs(UnmanagedType.LPStruct)] Guid value);++ /// <summary>Slot for <c>IMFAttributes::SetString</c> (placeholder).</summary>+ [PreserveSig]+ int SetString();++ /// <summary>Slot for <c>IMFAttributes::SetBlob</c> (placeholder).</summary>+ [PreserveSig]+ int SetBlob();++ /// <summary>Slot for <c>IMFAttributes::SetUnknown</c> (placeholder).</summary>+ [PreserveSig]+ int SetUnknown();++ /// <summary>Slot for <c>IMFAttributes::LockStore</c> (placeholder).</summary>+ [PreserveSig]+ int LockStore();++ /// <summary>Slot for <c>IMFAttributes::UnlockStore</c> (placeholder).</summary>+ [PreserveSig]+ int UnlockStore();++ /// <summary>Slot for <c>IMFAttributes::GetCount</c> (placeholder).</summary>+ [PreserveSig]+ int GetCount();++ /// <summary>Slot for <c>IMFAttributes::GetItemByIndex</c> (placeholder).</summary>+ [PreserveSig]+ int GetItemByIndex();++ /// <summary>Slot for <c>IMFAttributes::CopyAllItems</c> (placeholder).</summary>+ [PreserveSig]+ int CopyAllItems();+ }+}diff --git a/Wave_Dude_2D/IMFMediaBufferNative.cs b/Wave_Dude_2D/IMFMediaBufferNative.csnew file mode 100644index 0000000..62a5356--- /dev/null+++ b/Wave_Dude_2D/IMFMediaBufferNative.cs@@ -0,0 +1,36 @@+using System;+using System.Runtime.InteropServices;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Hand-written COM import of Media Foundation's <c>IMFMediaBuffer</c> (IID 045FA593-...), the byte buffer that+ /// <see cref="MfVideoWriter.AddPixels"/> fills with one RGB32 frame. Vtable order is frozen; all methods return+ /// an HRESULT. Only <see cref="Lock"/>, <see cref="Unlock"/> and <see cref="SetCurrentLength"/> are called.+ /// </summary>+ [Guid("045FA593-8799-42B8-BC8D-8968C6453507")]+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ [ComImport]+ internal interface IMFMediaBufferNative+ {+ /// <summary><c>IMFMediaBuffer::Lock</c>: returns the raw data pointer plus the buffer's maximum and current length in bytes; pair with <see cref="Unlock"/>.</summary>+ [PreserveSig]+ int Lock(ref IntPtr data, ref int maxLength, ref int currentLength);++ /// <summary><c>IMFMediaBuffer::Unlock</c>: releases the pointer obtained from <see cref="Lock"/>.</summary>+ [PreserveSig]+ int Unlock();++ /// <summary>Slot for <c>IMFMediaBuffer::GetCurrentLength</c> (placeholder, not called).</summary>+ [PreserveSig]+ int GetCurrentLength();++ /// <summary><c>IMFMediaBuffer::SetCurrentLength</c>: declares how many bytes of the buffer hold valid data.</summary>+ [PreserveSig]+ int SetCurrentLength(int length);++ /// <summary>Slot for <c>IMFMediaBuffer::GetMaxLength</c> (placeholder, not called).</summary>+ [PreserveSig]+ int GetMaxLength();+ }+}diff --git a/Wave_Dude_2D/IMFSampleNative.cs b/Wave_Dude_2D/IMFSampleNative.csnew file mode 100644index 0000000..40a8ebd--- /dev/null+++ b/Wave_Dude_2D/IMFSampleNative.cs@@ -0,0 +1,193 @@+using System;+using System.Runtime.InteropServices;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Hand-written COM import of Media Foundation's <c>IMFSample</c> (IID C40A00F2-...), one time-stamped video frame+ /// handed to the sink writer by <see cref="MfVideoWriter.AddPixels"/>. <c>IMFSample</c> derives from <c>IMFAttributes</c>,+ /// so the first 30 slots (<c>A01</c>..<c>A30</c>) are placeholders for the inherited attribute methods, followed by the+ /// sample's own methods. Vtable order is frozen; all methods return an HRESULT.+ /// </summary>+ [Guid("C40A00F2-B93A-4D80-AE8C-5A1C634F58E4")]+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ [ComImport]+ internal interface IMFSampleNative+ {+ /// <summary>Slot for inherited <c>IMFAttributes::GetItem</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A01();++ /// <summary>Slot for inherited <c>IMFAttributes::GetItemType</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A02();++ /// <summary>Slot for inherited <c>IMFAttributes::CompareItem</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A03();++ /// <summary>Slot for inherited <c>IMFAttributes::Compare</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A04();++ /// <summary>Slot for inherited <c>IMFAttributes::GetUINT32</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A05();++ /// <summary>Slot for inherited <c>IMFAttributes::GetUINT64</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A06();++ /// <summary>Slot for inherited <c>IMFAttributes::GetDouble</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A07();++ /// <summary>Slot for inherited <c>IMFAttributes::GetGUID</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A08();++ /// <summary>Slot for inherited <c>IMFAttributes::GetStringLength</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A09();++ /// <summary>Slot for inherited <c>IMFAttributes::GetString</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A10();++ /// <summary>Slot for inherited <c>IMFAttributes::GetAllocatedString</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A11();++ /// <summary>Slot for inherited <c>IMFAttributes::GetBlobSize</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A12();++ /// <summary>Slot for inherited <c>IMFAttributes::GetBlob</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A13();++ /// <summary>Slot for inherited <c>IMFAttributes::GetAllocatedBlob</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A14();++ /// <summary>Slot for inherited <c>IMFAttributes::GetUnknown</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A15();++ /// <summary>Slot for inherited <c>IMFAttributes::SetItem</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A16();++ /// <summary>Slot for inherited <c>IMFAttributes::DeleteItem</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A17();++ /// <summary>Slot for inherited <c>IMFAttributes::DeleteAllItems</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A18();++ /// <summary>Slot for inherited <c>IMFAttributes::SetUINT32</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A19();++ /// <summary>Slot for inherited <c>IMFAttributes::SetUINT64</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A20();++ /// <summary>Slot for inherited <c>IMFAttributes::SetDouble</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A21();++ /// <summary>Slot for inherited <c>IMFAttributes::SetGUID</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A22();++ /// <summary>Slot for inherited <c>IMFAttributes::SetString</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A23();++ /// <summary>Slot for inherited <c>IMFAttributes::SetBlob</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A24();++ /// <summary>Slot for inherited <c>IMFAttributes::SetUnknown</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A25();++ /// <summary>Slot for inherited <c>IMFAttributes::LockStore</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A26();++ /// <summary>Slot for inherited <c>IMFAttributes::UnlockStore</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A27();++ /// <summary>Slot for inherited <c>IMFAttributes::GetCount</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A28();++ /// <summary>Slot for inherited <c>IMFAttributes::GetItemByIndex</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A29();++ /// <summary>Slot for inherited <c>IMFAttributes::CopyAllItems</c> (placeholder, not called).</summary>+ [PreserveSig]+ int A30();++ /// <summary>Slot for <c>IMFSample::GetSampleFlags</c> (placeholder, not called).</summary>+ [PreserveSig]+ int GetSampleFlags();++ /// <summary>Slot for <c>IMFSample::SetSampleFlags</c> (placeholder, not called).</summary>+ [PreserveSig]+ int SetSampleFlags();++ /// <summary>Slot for <c>IMFSample::GetSampleTime</c> (placeholder, not called).</summary>+ [PreserveSig]+ int GetSampleTime();++ /// <summary><c>IMFSample::SetSampleTime</c>: presentation time in 100-nanosecond units.</summary>+ [PreserveSig]+ int SetSampleTime(long sampleTime);++ /// <summary>Slot for <c>IMFSample::GetSampleDuration</c> (placeholder, not called).</summary>+ [PreserveSig]+ int GetSampleDuration();++ /// <summary><c>IMFSample::SetSampleDuration</c>: duration in 100-nanosecond units.</summary>+ [PreserveSig]+ int SetSampleDuration(long duration);++ /// <summary>Slot for <c>IMFSample::GetBufferCount</c> (placeholder, not called).</summary>+ [PreserveSig]+ int GetBufferCount();++ /// <summary>Slot for <c>IMFSample::GetBufferByIndex</c> (placeholder, not called).</summary>+ [PreserveSig]+ int GetBufferByIndex();++ /// <summary>Slot for <c>IMFSample::ConvertToContiguousBuffer</c> (placeholder, not called).</summary>+ [PreserveSig]+ int ConvertToContiguousBuffer();++ /// <summary><c>IMFSample::AddBuffer</c>: appends an <c>IMFMediaBuffer</c> (raw pointer; the sample AddRefs it).</summary>+ [PreserveSig]+ int AddBuffer(IntPtr buffer);++ /// <summary>Slot for <c>IMFSample::RemoveBufferByIndex</c> (placeholder, not called).</summary>+ [PreserveSig]+ int RemoveBufferByIndex();++ /// <summary>Slot for <c>IMFSample::RemoveAllBuffers</c> (placeholder, not called).</summary>+ [PreserveSig]+ int RemoveAllBuffers();++ /// <summary>Slot for <c>IMFSample::GetTotalLength</c> (placeholder, not called).</summary>+ [PreserveSig]+ int GetTotalLength();++ /// <summary>Slot for <c>IMFSample::CopyToBuffer</c> (placeholder, not called).</summary>+ [PreserveSig]+ int CopyToBuffer();+ }+}diff --git a/Wave_Dude_2D/IMFSinkWriterNative.cs b/Wave_Dude_2D/IMFSinkWriterNative.csnew file mode 100644index 0000000..e55b38d--- /dev/null+++ b/Wave_Dude_2D/IMFSinkWriterNative.cs@@ -0,0 +1,60 @@+using System;+using System.Runtime.InteropServices;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Hand-written COM import of Media Foundation's <c>IMFSinkWriter</c> (IID 3137F1CD-...), the object that+ /// encodes and muxes the MP4 for <see cref="MfVideoWriter"/>. Vtable order is frozen; all methods return an+ /// HRESULT. Only the members with parameters (and <see cref="BeginWriting"/> / <see cref="FinalizeWriting"/>) are called.+ /// </summary>+ [Guid("3137F1CD-FE5E-4805-A5D8-FB477448CB3D")]+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ [ComImport]+ internal interface IMFSinkWriterNative+ {+ /// <summary><c>IMFSinkWriter::AddStream</c>: adds an output stream with the given encoded media type and returns its index.</summary>+ [PreserveSig]+ int AddStream(IntPtr mediaType, ref int streamIndex);++ /// <summary><c>IMFSinkWriter::SetInputMediaType</c>: sets the uncompressed input type for a stream (<paramref name="encodingParameters"/> may be null).</summary>+ [PreserveSig]+ int SetInputMediaType(int streamIndex, IntPtr mediaType, IntPtr encodingParameters);++ /// <summary><c>IMFSinkWriter::BeginWriting</c>: starts the encoder/muxer; must precede <see cref="WriteSample"/>.</summary>+ [PreserveSig]+ int BeginWriting();++ /// <summary><c>IMFSinkWriter::WriteSample</c>: delivers one time-stamped sample to a stream.</summary>+ [PreserveSig]+ int WriteSample(int streamIndex, IntPtr sample);++ /// <summary>Slot for <c>IMFSinkWriter::SendStreamTick</c> (placeholder, not called).</summary>+ [PreserveSig]+ int SendStreamTick();++ /// <summary>Slot for <c>IMFSinkWriter::PlaceMarker</c> (placeholder, not called).</summary>+ [PreserveSig]+ int PlaceMarker();++ /// <summary>Slot for <c>IMFSinkWriter::NotifyEndOfSegment</c> (placeholder, not called).</summary>+ [PreserveSig]+ int NotifyEndOfSegment();++ /// <summary>Slot for <c>IMFSinkWriter::Flush</c> (placeholder, not called).</summary>+ [PreserveSig]+ int Flush();++ /// <summary><c>IMFSinkWriter::Finalize</c>: flushes the encoder and writes the container trailer (named differently to avoid clashing with <see cref="object.Finalize"/>).</summary>+ [PreserveSig]+ int FinalizeWriting();++ /// <summary>Slot for <c>IMFSinkWriter::GetServiceForStream</c> (placeholder, not called).</summary>+ [PreserveSig]+ int GetServiceForStream();++ /// <summary>Slot for <c>IMFSinkWriter::GetStatistics</c> (placeholder, not called).</summary>+ [PreserveSig]+ int GetStatistics();+ }+}diff --git a/Wave_Dude_2D/IWaveEngine.cs b/Wave_Dude_2D/IWaveEngine.csnew file mode 100644index 0000000..5a7a7ad--- /dev/null+++ b/Wave_Dude_2D/IWaveEngine.cs@@ -0,0 +1,65 @@+using System;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// A wave-field solver (CPU <see cref="WaveSimulator"/> or OpenCL <see cref="GpuWaveSimulator"/>), created by+ /// <see cref="WaveEngineFactory"/> and driven by <see cref="SimulationRunner"/> on its worker thread. The field and+ /// intensity buffers are padded by one cell on each side, so row y of the scene starts at index (y + 1) * Stride + 1.+ /// Only <see cref="PrepareFrame"/> and the data properties are also used from the UI thread, and only while the+ /// runner is paused (see <see cref="SimulationRunner.RenderCurrentFrame"/>).+ /// </summary>+ internal interface IWaveEngine : IDisposable+ {+ /// <summary>Short name for the status bar and result: "CPU (n threads)" or "GPU: device name (OpenCL)".</summary>+ string Description { get; }++ /// <summary>Scene width in cells (= canvas pixels), without padding.</summary>+ int Width { get; }++ /// <summary>Scene height in cells (= canvas pixels), without padding.</summary>+ int Height { get; }++ /// <summary>Row pitch of <see cref="FieldData"/> and <see cref="IntensityData"/>: <see cref="Width"/> + 2.</summary>+ int Stride { get; }++ /// <summary>+ /// Current field amplitude, <see cref="Stride"/> * (<see cref="Height"/> + 2) floats. Valid for reading after+ /// <see cref="PrepareFrame"/>; the CPU engine exposes its live buffer (a different array instance after every+ /// sub-step, so re-read the property per frame), the GPU engine a host copy.+ /// </summary>+ float[] FieldData { get; }++ /// <summary>Accumulated intensity, same layout as <see cref="FieldData"/>; null when intensity tracking was not requested.</summary>+ float[] IntensityData { get; }++ /// <summary>Advances the simulation by one time step (internally several sub-steps with the 4th-order Laplacian).</summary>+ void AdvanceOneStep();++ /// <summary>+ /// Makes the requested buffers reflect the current state so the renderer can read them: a no-op on the CPU,+ /// a device-to-host copy on the GPU. Call before touching <see cref="FieldData"/> / <see cref="IntensityData"/>.+ /// </summary>+ void PrepareFrame(bool needField, bool needIntensity);++ /// <summary>+ /// Installs the probe definitions for this run (the GPU engine compiles its probe kernel here).+ /// A null or empty sampler installs nothing.+ /// </summary>+ /// <exception cref="InvalidOperationException">A probe needs the intensity but it is not tracked, or the GPU probe kernel cannot be built.</exception>+ void SetProbes(ProbeSampler sampler);++ /// <summary>Records one sample per series probe for the current step and accumulates integrating profiles; call after each <see cref="AdvanceOneStep"/>.</summary>+ void SampleProbes();++ /// <summary>+ /// Returns and clears the series samples gathered since the last call, one array per probe (empty for profile probes).+ /// </summary>+ /// <returns>Empty outer array when no probes are installed.</returns>+ float[][] TakeProbeSamples();++ /// <summary>Reads the current values along each profile probe, one array per profile probe.</summary>+ /// <returns>Null entries for non-profile probes; empty outer array when no probes are installed.</returns>+ float[][] ReadProbeProfiles();+ }+}diff --git a/Wave_Dude_2D/MfVideoWriter.cs b/Wave_Dude_2D/MfVideoWriter.csnew file mode 100644index 0000000..1f4b3d3--- /dev/null+++ b/Wave_Dude_2D/MfVideoWriter.cs@@ -0,0 +1,378 @@+using System;+using System.Runtime.InteropServices;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// <see cref="IFrameSink"/> that encodes H.264 MP4 through the Media Foundation sink writer+ /// (<c>mfplat.dll</c> / <c>mfreadwrite.dll</c>, talked to via the hand-written <c>IMF*Native</c> COM+ /// interfaces). Created by <see cref="SimulationRunner"/>; a failing constructor means+ /// "no H.264 on this machine" and triggers the AVI fallback. Used from the worker thread only.+ /// Media Foundation is started in the constructor and shut down in <see cref="Cleanup"/>.+ /// </summary>+ internal sealed class MfVideoWriter : IFrameSink+ {+ /// <summary>Native <c>MFStartup</c>: initializes Media Foundation for this process.</summary>+ [DllImport("mfplat.dll", ExactSpelling = true)]+ private static extern int MFStartup(int version, int flags);++ /// <summary>Native <c>MFShutdown</c>: counterpart of <see cref="MFStartup"/>.</summary>+ [DllImport("mfplat.dll", ExactSpelling = true)]+ private static extern int MFShutdown();++ /// <summary>Native <c>MFCreateMediaType</c>: returns a new, empty <c>IMFMediaType</c> (ref count 1) in <paramref name="mediaType"/>.</summary>+ [DllImport("mfplat.dll", ExactSpelling = true)]+ private static extern int MFCreateMediaType(ref IntPtr mediaType);++ /// <summary>Native <c>MFCreateSample</c>: returns a new, empty <c>IMFSample</c> in <paramref name="sample"/>.</summary>+ [DllImport("mfplat.dll", ExactSpelling = true)]+ private static extern int MFCreateSample(ref IntPtr sample);++ /// <summary>Native <c>MFCreateMemoryBuffer</c>: allocates a system-memory <c>IMFMediaBuffer</c> of <paramref name="maxLength"/> bytes.</summary>+ [DllImport("mfplat.dll", ExactSpelling = true)]+ private static extern int MFCreateMemoryBuffer(int maxLength, ref IntPtr buffer);++ /// <summary>Native <c>MFCreateSinkWriterFromURL</c>: creates an <c>IMFSinkWriter</c> for the file at <paramref name="url"/> (container chosen by extension).</summary>+ [DllImport("mfreadwrite.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]+ private static extern int MFCreateSinkWriterFromURL(string url, IntPtr byteStream, IntPtr attributes, ref IntPtr writer);++ /// <summary>+ /// Validates the size, starts Media Foundation, creates the sink writer with one H.264 output stream and an+ /// RGB32 input stream, and calls <c>BeginWriting</c>. Width and height are rounded down to even numbers+ /// (H.264 4:2:0 needs that); when that changes the size, frames are cropped to the top-left even region.+ /// The target bitrate is <c>width * height * fps * bpp</c> with <c>bpp = 0.01 * 50^(quality/100)</c>+ /// (0.01 .. 0.5 bits per pixel), clamped to 300 kbit/s .. 200 Mbit/s. On any failure everything is released+ /// (including <c>MFShutdown</c>) before the exception propagates.+ /// </summary>+ /// <param name="filePath">Output .mp4 path.</param>+ /// <param name="width">Width of the frames that will be passed to <see cref="AddPixels"/>.</param>+ /// <param name="height">Height of the frames that will be passed to <see cref="AddPixels"/>.</param>+ /// <param name="framesPerSecond">Playback frame rate.</param>+ /// <param name="quality">1..100 (clamped); controls the H.264 bitrate only.</param>+ /// <exception cref="NotSupportedException">The even-rounded size is below 16x16 or above 9,437,184 pixels (4096x2304), the limit of the Windows H.264 encoder.</exception>+ /// <exception cref="COMException">Media Foundation returned a failure HRESULT (no encoder, bad path, ...).</exception>+ public MfVideoWriter(string filePath, int width, int height, int framesPerSecond, int quality)+ {+ this._path = filePath;+ this._srcWidth = width;+ this._srcHeight = height;+ this._width = width & -2;+ this._height = height & -2;+ this._fps = framesPerSecond;+ if (this._width < 16 || this._height < 16)+ {+ throw new NotSupportedException("The canvas is too small for H.264 video.");+ }+ if ((long)this._width * this._height > 9437184L)+ {+ throw new NotSupportedException("The canvas is too large for the H.264 encoder of Windows.");+ }+ if (this._width != this._srcWidth || this._height != this._srcHeight)+ {+ this._cropped = new int[this._width * this._height];+ }+ MfVideoWriter.Check(MfVideoWriter.MFStartup(MfVersion, 0));+ this._started = true;+ try+ {+ MfVideoWriter.Check(MfVideoWriter.MFCreateSinkWriterFromURL(filePath, IntPtr.Zero, IntPtr.Zero, ref this._writerPtr));+ this._writer = (IMFSinkWriterNative)Marshal.GetObjectForIUnknown(this._writerPtr);+ int clampedQuality = Math.Max(1, Math.Min(100, quality));+ double bitsPerPixel = 0.01 * Math.Pow(50.0, clampedQuality / 100.0);+ long bitrate = (long)Math.Round((double)this._width * this._height * this._fps * bitsPerPixel);+ bitrate = Math.Max(300000L, Math.Min(200000000L, bitrate));+ IntPtr outputType = this.MakeType(MfVideoWriter.H264Format, (int)bitrate, false);+ int streamIndex = 0;+ try+ {+ MfVideoWriter.Check(this._writer.AddStream(outputType, ref streamIndex));+ }+ finally+ {+ Marshal.Release(outputType);+ }+ IntPtr inputType = this.MakeType(MfVideoWriter.Rgb32Format, 0, true);+ try+ {+ MfVideoWriter.Check(this._writer.SetInputMediaType(streamIndex, inputType, IntPtr.Zero));+ }+ finally+ {+ Marshal.Release(inputType);+ }+ MfVideoWriter.Check(this._writer.BeginWriting());+ }+ catch+ {+ this.Cleanup();+ throw;+ }+ }++ /// <summary>The MP4 path given to the constructor.</summary>+ public string FilePath+ {+ get+ {+ return this._path;+ }+ }++ /// <summary>+ /// Creates a progressive video <c>IMFMediaType</c> for <paramref name="format"/> at the writer's even size,+ /// <c>fps/1</c> frame rate and 1:1 pixel aspect ratio. The caller owns the returned reference and must+ /// <see cref="Marshal.Release"/> it. The RCW used for the attribute calls is released here.+ /// </summary>+ /// <param name="format">Subtype GUID: <see cref="H264Format"/> or <see cref="Rgb32Format"/>.</param>+ /// <param name="bitrate">Average bitrate in bits/s, written as <c>MF_MT_AVG_BITRATE</c> when > 0.</param>+ /// <param name="topDown">When true, sets a positive <c>MF_MT_DEFAULT_STRIDE</c> of <c>width * 4</c> so the top-down ARGB rows are not flipped.</param>+ private IntPtr MakeType(Guid format, int bitrate, bool topDown)+ {+ IntPtr mediaType = IntPtr.Zero;+ MfVideoWriter.Check(MfVideoWriter.MFCreateMediaType(ref mediaType));+ try+ {+ IMFAttributesNative attributes = (IMFAttributesNative)Marshal.GetObjectForIUnknown(mediaType);+ try+ {+ MfVideoWriter.Check(attributes.SetGUID(MfVideoWriter.MajorType, MfVideoWriter.VideoType));+ MfVideoWriter.Check(attributes.SetGUID(MfVideoWriter.SubType, format));+ if (bitrate > 0)+ {+ MfVideoWriter.Check(attributes.SetUINT32(MfVideoWriter.AvgBitrate, bitrate));+ }+ MfVideoWriter.Check(attributes.SetUINT32(MfVideoWriter.InterlaceMode, 2)); // MFVideoInterlace_Progressive+ MfVideoWriter.Check(attributes.SetUINT64(MfVideoWriter.FrameSize, ((ulong)this._width << 32) | (ulong)this._height));+ MfVideoWriter.Check(attributes.SetUINT64(MfVideoWriter.FrameRate, ((ulong)this._fps << 32) | 1UL));+ MfVideoWriter.Check(attributes.SetUINT64(MfVideoWriter.PixelAspectRatio, 4294967297UL)); // 1:1 packed as (1 << 32) | 1+ if (topDown)+ {+ MfVideoWriter.Check(attributes.SetUINT32(MfVideoWriter.DefaultStride, this._width * 4));+ }+ }+ finally+ {+ Marshal.ReleaseComObject(attributes);+ }+ }+ catch+ {+ Marshal.Release(mediaType);+ throw;+ }+ return mediaType;+ }++ /// <summary>+ /// Copies the ARGB frame into a new Media Foundation memory buffer (cropping to the even size when needed),+ /// wraps it in a sample stamped with time and duration in 100-ns units derived from the frame index and fps,+ /// and hands it to stream 0 of the sink writer. Both RCW and raw reference of the buffer and sample are+ /// released afterwards; Media Foundation keeps its own reference while encoding.+ /// </summary>+ /// <param name="pixels">Row-major ARGB buffer of the original (uncropped) width * height.</param>+ /// <exception cref="InvalidOperationException">The writer has already been closed.</exception>+ /// <exception cref="COMException">A Media Foundation call failed.</exception>+ public void AddPixels(int[] pixels)+ {+ if (this._closed)+ {+ throw new InvalidOperationException("The video file is already closed.");+ }+ int[] source = pixels;+ if (this._cropped != null)+ {+ for (int y = 0; y < this._height; y++)+ {+ Array.Copy(pixels, y * this._srcWidth, this._cropped, y * this._width, this._width);+ }+ source = this._cropped;+ }+ int byteLength = this._width * this._height * 4;+ IntPtr bufferPtr = IntPtr.Zero;+ IntPtr samplePtr = IntPtr.Zero;+ IMFMediaBufferNative buffer = null;+ IMFSampleNative sample = null;+ try+ {+ MfVideoWriter.Check(MfVideoWriter.MFCreateMemoryBuffer(byteLength, ref bufferPtr));+ buffer = (IMFMediaBufferNative)Marshal.GetObjectForIUnknown(bufferPtr);+ IntPtr data = IntPtr.Zero;+ int maxLength = 0;+ int currentLength = 0;+ MfVideoWriter.Check(buffer.Lock(ref data, ref maxLength, ref currentLength));+ try+ {+ Marshal.Copy(source, 0, data, this._width * this._height);+ }+ finally+ {+ buffer.Unlock();+ }+ MfVideoWriter.Check(buffer.SetCurrentLength(byteLength));+ MfVideoWriter.Check(MfVideoWriter.MFCreateSample(ref samplePtr));+ sample = (IMFSampleNative)Marshal.GetObjectForIUnknown(samplePtr);+ MfVideoWriter.Check(sample.AddBuffer(bufferPtr));+ MfVideoWriter.Check(sample.SetSampleTime(this._frames * 10000000L / this._fps));+ MfVideoWriter.Check(sample.SetSampleDuration(10000000L / this._fps));+ MfVideoWriter.Check(this._writer.WriteSample(0, samplePtr));+ this._frames++;+ }+ finally+ {+ if (sample != null)+ {+ Marshal.ReleaseComObject(sample);+ }+ if (samplePtr != IntPtr.Zero)+ {+ Marshal.Release(samplePtr);+ }+ if (buffer != null)+ {+ Marshal.ReleaseComObject(buffer);+ }+ if (bufferPtr != IntPtr.Zero)+ {+ Marshal.Release(bufferPtr);+ }+ }+ }++ /// <summary>+ /// Finalizes the MP4 (writes the moov box) when at least one frame was written, then releases the sink+ /// writer and shuts Media Foundation down. Idempotent. Finalizing is skipped for an empty file because the+ /// sink writer rejects it; cleanup still runs.+ /// </summary>+ /// <exception cref="COMException"><c>Finalize</c> failed; cleanup has still been performed.</exception>+ public void Close()+ {+ if (this._closed)+ {+ return;+ }+ this._closed = true;+ try+ {+ if (this._writer != null && this._frames > 0)+ {+ MfVideoWriter.Check(this._writer.FinalizeWriting());+ }+ }+ finally+ {+ this.Cleanup();+ }+ }++ /// <summary>+ /// Releases the sink writer RCW and the raw reference obtained from <c>MFCreateSinkWriterFromURL</c>+ /// (both are needed: <see cref="Marshal.GetObjectForIUnknown"/> added its own reference), then calls+ /// <c>MFShutdown</c> once if startup succeeded. Safe to call repeatedly.+ /// </summary>+ private void Cleanup()+ {+ if (this._writer != null)+ {+ Marshal.ReleaseComObject(this._writer);+ this._writer = null;+ }+ if (this._writerPtr != IntPtr.Zero)+ {+ Marshal.Release(this._writerPtr);+ this._writerPtr = IntPtr.Zero;+ }+ if (this._started)+ {+ this._started = false;+ MfVideoWriter.MFShutdown();+ }+ }++ /// <summary>Same as <see cref="Close"/>.</summary>+ public void Dispose()+ {+ this.Close();+ }++ /// <summary>Throws the matching .NET exception for a failed HRESULT (negative value); succeeds silently otherwise.</summary>+ private static void Check(int hr)+ {+ if (hr < 0)+ {+ Marshal.ThrowExceptionForHR(hr);+ }+ }++ /// <summary><c>MF_VERSION</c> = 0x00020070 (SDK version 2, API version 0x70) passed to <c>MFStartup</c>.</summary>+ private const int MfVersion = 131184;++ /// <summary><c>MF_MT_MAJOR_TYPE</c> attribute key.</summary>+ private static readonly Guid MajorType = new Guid("48eba18e-f8c9-4687-bf11-0a74c9f96a8f");++ /// <summary><c>MF_MT_SUBTYPE</c> attribute key.</summary>+ private static readonly Guid SubType = new Guid("f7e34c9a-42e8-4714-b74b-cb29d72c35e5");++ /// <summary><c>MF_MT_AVG_BITRATE</c> attribute key (bits per second).</summary>+ private static readonly Guid AvgBitrate = new Guid("20332624-fb0d-4d9e-bd0d-cbf6786c102e");++ /// <summary><c>MF_MT_INTERLACE_MODE</c> attribute key.</summary>+ private static readonly Guid InterlaceMode = new Guid("e2724bb8-e676-4806-b4b2-a8d6efb44ccd");++ /// <summary><c>MF_MT_FRAME_SIZE</c> attribute key (width in the high 32 bits, height in the low 32).</summary>+ private static readonly Guid FrameSize = new Guid("1652c33d-d6b2-4012-b834-72030849a37d");++ /// <summary><c>MF_MT_FRAME_RATE</c> attribute key (numerator high 32 bits, denominator low 32).</summary>+ private static readonly Guid FrameRate = new Guid("c459a2e8-3d2c-4e44-b132-fee5156c7bb0");++ /// <summary><c>MF_MT_PIXEL_ASPECT_RATIO</c> attribute key (same packing as the frame rate).</summary>+ private static readonly Guid PixelAspectRatio = new Guid("c6376a1e-8d0a-4027-be45-6d9a0ad39bb6");++ /// <summary><c>MF_MT_DEFAULT_STRIDE</c> attribute key (bytes per row; positive = top-down).</summary>+ private static readonly Guid DefaultStride = new Guid("644b4e48-1e02-4516-b0eb-c01ca9d49ac6");++ /// <summary><c>MFMediaType_Video</c> major type ('vids').</summary>+ private static readonly Guid VideoType = new Guid("73646976-0000-0010-8000-00AA00389B71");++ /// <summary><c>MFVideoFormat_H264</c> subtype ('H264').</summary>+ private static readonly Guid H264Format = new Guid("34363248-0000-0010-8000-00AA00389B71");++ /// <summary><c>MFVideoFormat_RGB32</c> subtype (D3DFMT_X8R8G8B8 = 22); matches the ARGB int layout in memory.</summary>+ private static readonly Guid Rgb32Format = new Guid("00000016-0000-0010-8000-00AA00389B71");++ /// <summary>Output file path.</summary>+ private readonly string _path;++ /// <summary>Width of the frames passed to <see cref="AddPixels"/>, before rounding to even.</summary>+ private readonly int _srcWidth;++ /// <summary>Height of the frames passed to <see cref="AddPixels"/>, before rounding to even.</summary>+ private readonly int _srcHeight;++ /// <summary>Encoded width (source width rounded down to even).</summary>+ private readonly int _width;++ /// <summary>Encoded height (source height rounded down to even).</summary>+ private readonly int _height;++ /// <summary>Frames per second; also used to derive sample time/duration.</summary>+ private readonly int _fps;++ /// <summary>Scratch buffer of the even size when cropping is needed; null when source and encoded sizes match.</summary>+ private readonly int[] _cropped;++ /// <summary>True between a successful <c>MFStartup</c> and the matching <c>MFShutdown</c>.</summary>+ private bool _started;++ /// <summary>Raw <c>IMFSinkWriter</c> pointer from <c>MFCreateSinkWriterFromURL</c>; released separately from the RCW.</summary>+ private IntPtr _writerPtr;++ /// <summary>RCW over <see cref="_writerPtr"/>; null after <see cref="Cleanup"/>.</summary>+ private IMFSinkWriterNative _writer;++ /// <summary>Number of samples written; the next sample's time is <c>_frames / fps</c> seconds.</summary>+ private int _frames;++ /// <summary>True once <see cref="Close"/> has run.</summary>+ private bool _closed;+ }+}diff --git a/Wave_Dude_2D/My/MyApplication.cs b/Wave_Dude_2D/My/MyApplication.csnew file mode 100644index 0000000..c8581e0--- /dev/null+++ b/Wave_Dude_2D/My/MyApplication.cs@@ -0,0 +1,51 @@+using System;+using System.CodeDom.Compiler;+using System.ComponentModel;+using System.Diagnostics;+using System.Runtime.CompilerServices;+using System.Windows.Forms;+using Microsoft.VisualBasic.ApplicationServices;++namespace _2D_wave_sim_V01.My+{+ // Token: 0x02000002 RID: 2+ [GeneratedCode("MyTemplate", "11.0.0.0")]+ [EditorBrowsable(EditorBrowsableState.Never)]+ internal class MyApplication : WindowsFormsApplicationBase+ {+ // Token: 0x06000001 RID: 1 RVA: 0x00002050 File Offset: 0x00000250+ [STAThread]+ [DebuggerHidden]+ [EditorBrowsable(EditorBrowsableState.Advanced)]+ [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]+ internal static void Main(string[] Args)+ {+ try+ {+ Application.SetCompatibleTextRenderingDefault(WindowsFormsApplicationBase.UseCompatibleTextRendering);+ }+ finally+ {+ }+ MyProject.Application.Run(Args);+ }++ // Token: 0x06000002 RID: 2 RVA: 0x0000208C File Offset: 0x0000028C+ [DebuggerStepThrough]+ public MyApplication()+ : base(AuthenticationMode.Windows)+ {+ base.IsSingleInstance = false;+ base.EnableVisualStyles = true;+ base.SaveMySettingsOnExit = true;+ base.ShutdownStyle = ShutdownMode.AfterMainFormCloses;+ }++ // Token: 0x06000003 RID: 3 RVA: 0x000020B7 File Offset: 0x000002B7+ [DebuggerStepThrough]+ protected override void OnCreateMainForm()+ {+ base.MainForm = MyProject.Forms.Form1;+ }+ }+}diff --git a/Wave_Dude_2D/My/MyComputer.cs b/Wave_Dude_2D/My/MyComputer.csnew file mode 100644index 0000000..5897512--- /dev/null+++ b/Wave_Dude_2D/My/MyComputer.cs@@ -0,0 +1,21 @@+using System;+using System.CodeDom.Compiler;+using System.ComponentModel;+using System.Diagnostics;+using Microsoft.VisualBasic.Devices;++namespace _2D_wave_sim_V01.My+{+ // Token: 0x02000003 RID: 3+ [GeneratedCode("MyTemplate", "11.0.0.0")]+ [EditorBrowsable(EditorBrowsableState.Never)]+ internal class MyComputer : Computer+ {+ // Token: 0x06000004 RID: 4 RVA: 0x000020CB File Offset: 0x000002CB+ [DebuggerHidden]+ [EditorBrowsable(EditorBrowsableState.Never)]+ public MyComputer()+ {+ }+ }+}diff --git a/Wave_Dude_2D/My/MyProject.cs b/Wave_Dude_2D/My/MyProject.csnew file mode 100644index 0000000..b3088a7--- /dev/null+++ b/Wave_Dude_2D/My/MyProject.cs@@ -0,0 +1,408 @@+using System;+using System.CodeDom.Compiler;+using System.Collections;+using System.ComponentModel;+using System.ComponentModel.Design;+using System.Diagnostics;+using System.Reflection;+using System.Runtime.CompilerServices;+using System.Runtime.InteropServices;+using System.Windows.Forms;+using Microsoft.VisualBasic;+using Microsoft.VisualBasic.ApplicationServices;+using Microsoft.VisualBasic.CompilerServices;++namespace _2D_wave_sim_V01.My+{+ // Token: 0x02000004 RID: 4+ [StandardModule]+ [HideModuleName]+ [GeneratedCode("MyTemplate", "11.0.0.0")]+ internal sealed class MyProject+ {+ // Token: 0x17000001 RID: 1+ // (get) Token: 0x06000006 RID: 6 RVA: 0x0000210C File Offset: 0x0000030C+ [HelpKeyword("My.Computer")]+ internal static MyComputer Computer+ {+ [DebuggerHidden]+ get+ {+ return MyProject.m_ComputerObjectProvider.GetInstance;+ }+ }++ // Token: 0x17000002 RID: 2+ // (get) Token: 0x06000007 RID: 7 RVA: 0x00002128 File Offset: 0x00000328+ [HelpKeyword("My.Application")]+ internal static MyApplication Application+ {+ [DebuggerHidden]+ get+ {+ return MyProject.m_AppObjectProvider.GetInstance;+ }+ }++ // Token: 0x17000003 RID: 3+ // (get) Token: 0x06000008 RID: 8 RVA: 0x00002144 File Offset: 0x00000344+ [HelpKeyword("My.User")]+ internal static User User+ {+ [DebuggerHidden]+ get+ {+ return MyProject.m_UserObjectProvider.GetInstance;+ }+ }++ // Token: 0x17000004 RID: 4+ // (get) Token: 0x06000009 RID: 9 RVA: 0x00002160 File Offset: 0x00000360+ [HelpKeyword("My.Forms")]+ internal static MyProject.MyForms Forms+ {+ [DebuggerHidden]+ get+ {+ return MyProject.m_MyFormsObjectProvider.GetInstance;+ }+ }++ // Token: 0x17000005 RID: 5+ // (get) Token: 0x0600000A RID: 10 RVA: 0x0000217C File Offset: 0x0000037C+ [HelpKeyword("My.WebServices")]+ internal static MyProject.MyWebServices WebServices+ {+ [DebuggerHidden]+ get+ {+ return MyProject.m_MyWebServicesObjectProvider.GetInstance;+ }+ }++ // Token: 0x04000001 RID: 1+ private static readonly MyProject.ThreadSafeObjectProvider<MyComputer> m_ComputerObjectProvider = new MyProject.ThreadSafeObjectProvider<MyComputer>();++ // Token: 0x04000002 RID: 2+ private static readonly MyProject.ThreadSafeObjectProvider<MyApplication> m_AppObjectProvider = new MyProject.ThreadSafeObjectProvider<MyApplication>();++ // Token: 0x04000003 RID: 3+ private static readonly MyProject.ThreadSafeObjectProvider<User> m_UserObjectProvider = new MyProject.ThreadSafeObjectProvider<User>();++ // Token: 0x04000004 RID: 4+ private static MyProject.ThreadSafeObjectProvider<MyProject.MyForms> m_MyFormsObjectProvider = new MyProject.ThreadSafeObjectProvider<MyProject.MyForms>();++ // Token: 0x04000005 RID: 5+ private static readonly MyProject.ThreadSafeObjectProvider<MyProject.MyWebServices> m_MyWebServicesObjectProvider = new MyProject.ThreadSafeObjectProvider<MyProject.MyWebServices>();++ // Token: 0x0200003E RID: 62+ [EditorBrowsable(EditorBrowsableState.Never)]+ [MyGroupCollection("System.Windows.Forms.Form", "Create__Instance__", "Dispose__Instance__", "My.MyProject.Forms")]+ internal sealed class MyForms+ {+ // Token: 0x060006B9 RID: 1721 RVA: 0x000339A4 File Offset: 0x00031BA4+ [DebuggerHidden]+ private static T Create__Instance__<T>(T Instance) where T : Form, new()+ {+ bool flag = Instance == null || Instance.IsDisposed;+ if (flag)+ {+ bool flag2 = MyProject.MyForms.m_FormBeingCreated != null;+ if (flag2)+ {+ bool flag3 = MyProject.MyForms.m_FormBeingCreated.ContainsKey(typeof(T));+ if (flag3)+ {+ throw new InvalidOperationException(Utils.GetResourceString("WinForms_RecursiveFormCreate", new string[0]));+ }+ }+ else+ {+ MyProject.MyForms.m_FormBeingCreated = new Hashtable();+ }+ MyProject.MyForms.m_FormBeingCreated.Add(typeof(T), null);+ try+ {+ return new T();+ }+ catch (TargetInvocationException ex) when (ex.InnerException != null)+ {+ string resourceString = Utils.GetResourceString("WinForms_SeeInnerException", new string[] { ex.InnerException.Message });+ throw new InvalidOperationException(resourceString, ex.InnerException);+ }+ finally+ {+ MyProject.MyForms.m_FormBeingCreated.Remove(typeof(T));+ }+ }+ return Instance;+ }++ // Token: 0x060006BA RID: 1722 RVA: 0x00033ACC File Offset: 0x00031CCC+ [DebuggerHidden]+ private void Dispose__Instance__<T>(ref T instance) where T : Form+ {+ instance.Dispose();+ instance = default(T);+ }++ // Token: 0x060006BB RID: 1723 RVA: 0x00033AE3 File Offset: 0x00031CE3+ [DebuggerHidden]+ [EditorBrowsable(EditorBrowsableState.Never)]+ public MyForms()+ {+ }++ // Token: 0x060006BC RID: 1724 RVA: 0x00033AF0 File Offset: 0x00031CF0+ [EditorBrowsable(EditorBrowsableState.Never)]+ public override bool Equals(object o)+ {+ return base.Equals(RuntimeHelpers.GetObjectValue(o));+ }++ // Token: 0x060006BD RID: 1725 RVA: 0x00033B10 File Offset: 0x00031D10+ [EditorBrowsable(EditorBrowsableState.Never)]+ public override int GetHashCode()+ {+ return base.GetHashCode();+ }++ // Token: 0x060006BE RID: 1726 RVA: 0x00033B28 File Offset: 0x00031D28+ [EditorBrowsable(EditorBrowsableState.Never)]+ internal new Type GetType()+ {+ return typeof(MyProject.MyForms);+ }++ // Token: 0x060006BF RID: 1727 RVA: 0x00033B44 File Offset: 0x00031D44+ [EditorBrowsable(EditorBrowsableState.Never)]+ public override string ToString()+ {+ return base.ToString();+ }++ // Token: 0x170001F1 RID: 497+ // (get) Token: 0x060006C0 RID: 1728 RVA: 0x00033B5C File Offset: 0x00031D5C+ // (set) Token: 0x060006C4 RID: 1732 RVA: 0x00033BC8 File Offset: 0x00031DC8+ public AboutForm AboutForm+ {+ [DebuggerHidden]+ get+ {+ this.m_AboutForm = MyProject.MyForms.Create__Instance__<AboutForm>(this.m_AboutForm);+ return this.m_AboutForm;+ }+ [DebuggerHidden]+ set+ {+ if (value != this.m_AboutForm)+ {+ if (value != null)+ {+ throw new ArgumentException("Property can only be set to Nothing");+ }+ this.Dispose__Instance__<AboutForm>(ref this.m_AboutForm);+ }+ }+ }++ // Token: 0x170001F2 RID: 498+ // (get) Token: 0x060006C1 RID: 1729 RVA: 0x00033B77 File Offset: 0x00031D77+ // (set) Token: 0x060006C5 RID: 1733 RVA: 0x00033BF4 File Offset: 0x00031DF4+ public Form1 Form1+ {+ [DebuggerHidden]+ get+ {+ this.m_Form1 = MyProject.MyForms.Create__Instance__<Form1>(this.m_Form1);+ return this.m_Form1;+ }+ [DebuggerHidden]+ set+ {+ if (value != this.m_Form1)+ {+ if (value != null)+ {+ throw new ArgumentException("Property can only be set to Nothing");+ }+ this.Dispose__Instance__<Form1>(ref this.m_Form1);+ }+ }+ }++ // Token: 0x170001F3 RID: 499+ // (get) Token: 0x060006C2 RID: 1730 RVA: 0x00033B92 File Offset: 0x00031D92+ // (set) Token: 0x060006C6 RID: 1734 RVA: 0x00033C20 File Offset: 0x00031E20+ public frmDescription frmDescription+ {+ [DebuggerHidden]+ get+ {+ this.m_frmDescription = MyProject.MyForms.Create__Instance__<frmDescription>(this.m_frmDescription);+ return this.m_frmDescription;+ }+ [DebuggerHidden]+ set+ {+ if (value != this.m_frmDescription)+ {+ if (value != null)+ {+ throw new ArgumentException("Property can only be set to Nothing");+ }+ this.Dispose__Instance__<frmDescription>(ref this.m_frmDescription);+ }+ }+ }++ // Token: 0x170001F4 RID: 500+ // (get) Token: 0x060006C3 RID: 1731 RVA: 0x00033BAD File Offset: 0x00031DAD+ // (set) Token: 0x060006C7 RID: 1735 RVA: 0x00033C4C File Offset: 0x00031E4C+ public HelpForm HelpForm+ {+ [DebuggerHidden]+ get+ {+ this.m_HelpForm = MyProject.MyForms.Create__Instance__<HelpForm>(this.m_HelpForm);+ return this.m_HelpForm;+ }+ [DebuggerHidden]+ set+ {+ if (value != this.m_HelpForm)+ {+ if (value != null)+ {+ throw new ArgumentException("Property can only be set to Nothing");+ }+ this.Dispose__Instance__<HelpForm>(ref this.m_HelpForm);+ }+ }+ }++ // Token: 0x0400038A RID: 906+ [ThreadStatic]+ private static Hashtable m_FormBeingCreated;++ // Token: 0x0400038B RID: 907+ [EditorBrowsable(EditorBrowsableState.Never)]+ public AboutForm m_AboutForm;++ // Token: 0x0400038C RID: 908+ [EditorBrowsable(EditorBrowsableState.Never)]+ public Form1 m_Form1;++ // Token: 0x0400038D RID: 909+ [EditorBrowsable(EditorBrowsableState.Never)]+ public frmDescription m_frmDescription;++ // Token: 0x0400038E RID: 910+ [EditorBrowsable(EditorBrowsableState.Never)]+ public HelpForm m_HelpForm;+ }++ // Token: 0x0200003F RID: 63+ [EditorBrowsable(EditorBrowsableState.Never)]+ [MyGroupCollection("System.Web.Services.Protocols.SoapHttpClientProtocol", "Create__Instance__", "Dispose__Instance__", "")]+ internal sealed class MyWebServices+ {+ // Token: 0x060006C8 RID: 1736 RVA: 0x00033C78 File Offset: 0x00031E78+ [EditorBrowsable(EditorBrowsableState.Never)]+ [DebuggerHidden]+ public override bool Equals(object o)+ {+ return base.Equals(RuntimeHelpers.GetObjectValue(o));+ }++ // Token: 0x060006C9 RID: 1737 RVA: 0x00033C98 File Offset: 0x00031E98+ [EditorBrowsable(EditorBrowsableState.Never)]+ [DebuggerHidden]+ public override int GetHashCode()+ {+ return base.GetHashCode();+ }++ // Token: 0x060006CA RID: 1738 RVA: 0x00033CB0 File Offset: 0x00031EB0+ [EditorBrowsable(EditorBrowsableState.Never)]+ [DebuggerHidden]+ internal new Type GetType()+ {+ return typeof(MyProject.MyWebServices);+ }++ // Token: 0x060006CB RID: 1739 RVA: 0x00033CCC File Offset: 0x00031ECC+ [EditorBrowsable(EditorBrowsableState.Never)]+ [DebuggerHidden]+ public override string ToString()+ {+ return base.ToString();+ }++ // Token: 0x060006CC RID: 1740 RVA: 0x00033CE4 File Offset: 0x00031EE4+ [DebuggerHidden]+ private static T Create__Instance__<T>(T instance) where T : new()+ {+ bool flag = instance == null;+ T t;+ if (flag)+ {+ t = new T();+ }+ else+ {+ t = instance;+ }+ return t;+ }++ // Token: 0x060006CD RID: 1741 RVA: 0x00033D0D File Offset: 0x00031F0D+ [DebuggerHidden]+ private void Dispose__Instance__<T>(ref T instance)+ {+ instance = default(T);+ }++ // Token: 0x060006CE RID: 1742 RVA: 0x00033D17 File Offset: 0x00031F17+ [DebuggerHidden]+ [EditorBrowsable(EditorBrowsableState.Never)]+ public MyWebServices()+ {+ }+ }++ // Token: 0x02000040 RID: 64+ [EditorBrowsable(EditorBrowsableState.Never)]+ [ComVisible(false)]+ internal sealed class ThreadSafeObjectProvider<T> where T : new()+ {+ // Token: 0x170001F5 RID: 501+ // (get) Token: 0x060006CF RID: 1743 RVA: 0x00033D24 File Offset: 0x00031F24+ internal T GetInstance+ {+ [DebuggerHidden]+ get+ {+ bool flag = MyProject.ThreadSafeObjectProvider<T>.m_ThreadStaticValue == null;+ if (flag)+ {+ MyProject.ThreadSafeObjectProvider<T>.m_ThreadStaticValue = new T();+ }+ return MyProject.ThreadSafeObjectProvider<T>.m_ThreadStaticValue;+ }+ }++ // Token: 0x060006D0 RID: 1744 RVA: 0x00033D56 File Offset: 0x00031F56+ [DebuggerHidden]+ [EditorBrowsable(EditorBrowsableState.Never)]+ public ThreadSafeObjectProvider()+ {+ }++ // Token: 0x0400038F RID: 911+ [CompilerGenerated]+ [ThreadStatic]+ private static T m_ThreadStaticValue;+ }+ }+}diff --git a/Wave_Dude_2D/My/MySettings.Designer.cs b/Wave_Dude_2D/My/MySettings.Designer.csnew file mode 100644index 0000000..effd52a--- /dev/null+++ b/Wave_Dude_2D/My/MySettings.Designer.cs@@ -0,0 +1,63 @@+using System;+using System.CodeDom.Compiler;+using System.ComponentModel;+using System.Configuration;+using System.Diagnostics;+using System.Runtime.CompilerServices;+using Microsoft.VisualBasic.CompilerServices;++namespace _2D_wave_sim_V01.My+{+ // Token: 0x02000006 RID: 6+ [CompilerGenerated]+ [GeneratedCode("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]+ [EditorBrowsable(EditorBrowsableState.Advanced)]+ internal sealed partial class MySettings : ApplicationSettingsBase+ {+ // Token: 0x06000011 RID: 17 RVA: 0x00002260 File Offset: 0x00000460+ [DebuggerNonUserCode]+ [EditorBrowsable(EditorBrowsableState.Advanced)]+ private static void AutoSaveSettings(object sender, EventArgs e)+ {+ bool saveMySettingsOnExit = MyProject.Application.SaveMySettingsOnExit;+ if (saveMySettingsOnExit)+ {+ MySettingsProperty.Settings.Save();+ }+ }++ // Token: 0x17000009 RID: 9+ // (get) Token: 0x06000012 RID: 18 RVA: 0x0000228C File Offset: 0x0000048C+ public static MySettings Default+ {+ get+ {+ bool flag = !MySettings.addedHandler;+ if (flag)+ {+ object obj = MySettings.addedHandlerLockObject;+ ObjectFlowControl.CheckForSyncLockOnValueType(obj);+ lock (obj)+ {+ bool flag3 = !MySettings.addedHandler;+ if (flag3)+ {+ MyProject.Application.Shutdown += MySettings.AutoSaveSettings;+ MySettings.addedHandler = true;+ }+ }+ }+ return MySettings.defaultInstance;+ }+ }++ // Token: 0x04000008 RID: 8+ private static MySettings defaultInstance = (MySettings)SettingsBase.Synchronized(new MySettings());++ // Token: 0x04000009 RID: 9+ private static bool addedHandler;++ // Token: 0x0400000A RID: 10+ private static object addedHandlerLockObject = RuntimeHelpers.GetObjectValue(new object());+ }+}diff --git a/Wave_Dude_2D/My/MySettings.settings b/Wave_Dude_2D/My/MySettings.settingsnew file mode 100644index 0000000..6108185--- /dev/null+++ b/Wave_Dude_2D/My/MySettings.settings@@ -0,0 +1,5 @@+<?xml version='1.0' encoding='utf-8'?>+<SettingsFile CurrentProfile="(Default)" GeneratedClassNamespace="_2D_wave_sim_V01.My" GeneratedClassName="MySettings" xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings">+ <Profiles />+ <Settings />+</SettingsFile>\ No newline at end of filediff --git a/Wave_Dude_2D/My/MySettingsProperty.cs b/Wave_Dude_2D/My/MySettingsProperty.csnew file mode 100644index 0000000..990dd01--- /dev/null+++ b/Wave_Dude_2D/My/MySettingsProperty.cs@@ -0,0 +1,28 @@+using System;+using System.ComponentModel.Design;+using System.Diagnostics;+using System.Runtime.CompilerServices;+using Microsoft.VisualBasic;+using Microsoft.VisualBasic.CompilerServices;++namespace _2D_wave_sim_V01.My+{+ // Token: 0x02000007 RID: 7+ [StandardModule]+ [HideModuleName]+ [DebuggerNonUserCode]+ [CompilerGenerated]+ internal sealed class MySettingsProperty+ {+ // Token: 0x1700000A RID: 10+ // (get) Token: 0x06000013 RID: 19 RVA: 0x00002318 File Offset: 0x00000518+ [HelpKeyword("My.Settings")]+ internal static MySettings Settings+ {+ get+ {+ return MySettings.Default;+ }+ }+ }+}diff --git a/Wave_Dude_2D/My/Resources/_2D_wave_sim_V01.Resources.Designer.cs b/Wave_Dude_2D/My/Resources/_2D_wave_sim_V01.Resources.Designer.csnew file mode 100644index 0000000..f6dea1c--- /dev/null+++ b/Wave_Dude_2D/My/Resources/_2D_wave_sim_V01.Resources.Designer.cs@@ -0,0 +1,72 @@+using System;+using System.CodeDom.Compiler;+using System.ComponentModel;+using System.Diagnostics;+using System.Drawing;+using System.Globalization;+using System.Resources;+using System.Runtime.CompilerServices;+using Microsoft.VisualBasic;+using Microsoft.VisualBasic.CompilerServices;++namespace _2D_wave_sim_V01.My.Resources+{+ // Token: 0x02000005 RID: 5+ [StandardModule]+ [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]+ [DebuggerNonUserCode]+ [CompilerGenerated]+ [HideModuleName]+ internal sealed class Resources+ {+ // Token: 0x17000006 RID: 6+ // (get) Token: 0x0600000B RID: 11 RVA: 0x00002198 File Offset: 0x00000398+ [EditorBrowsable(EditorBrowsableState.Advanced)]+ internal static ResourceManager ResourceManager+ {+ get+ {+ bool flag = object.ReferenceEquals(Resources.resourceMan, null);+ if (flag)+ {+ ResourceManager resourceManager = new ResourceManager("_2D_wave_sim_V01.Resources", typeof(Resources).Assembly);+ Resources.resourceMan = resourceManager;+ }+ return Resources.resourceMan;+ }+ }++ // Token: 0x17000007 RID: 7+ // (get) Token: 0x0600000C RID: 12 RVA: 0x000021E0 File Offset: 0x000003E0+ // (set) Token: 0x0600000D RID: 13 RVA: 0x000021F7 File Offset: 0x000003F7+ [EditorBrowsable(EditorBrowsableState.Advanced)]+ internal static CultureInfo Culture+ {+ get+ {+ return Resources.resourceCulture;+ }+ set+ {+ Resources.resourceCulture = value;+ }+ }++ // Token: 0x17000008 RID: 8+ // (get) Token: 0x0600000E RID: 14 RVA: 0x00002200 File Offset: 0x00000400+ internal static Bitmap QR_code+ {+ get+ {+ object objectValue = RuntimeHelpers.GetObjectValue(Resources.ResourceManager.GetObject("QR-code", Resources.resourceCulture));+ return (Bitmap)objectValue;+ }+ }++ // Token: 0x04000006 RID: 6+ private static ResourceManager resourceMan;++ // Token: 0x04000007 RID: 7+ private static CultureInfo resourceCulture;+ }+}diff --git a/Wave_Dude_2D/My/Resources/_2D_wave_sim_V01.Resources.resx b/Wave_Dude_2D/My/Resources/_2D_wave_sim_V01.Resources.resxnew file mode 100644index 0000000..6691558--- /dev/null+++ b/Wave_Dude_2D/My/Resources/_2D_wave_sim_V01.Resources.resx@@ -0,0 +1,134 @@+<?xml version="1.0" encoding="utf-8"?>+<root>+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />+ <xsd:element name="root" msdata:IsDataSet="true">+ <xsd:complexType>+ <xsd:choice maxOccurs="unbounded">+ <xsd:element name="metadata">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" />+ </xsd:sequence>+ <xsd:attribute name="name" use="required" type="xsd:string" />+ <xsd:attribute name="type" type="xsd:string" />+ <xsd:attribute name="mimetype" type="xsd:string" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="assembly">+ <xsd:complexType>+ <xsd:attribute name="alias" type="xsd:string" />+ <xsd:attribute name="name" type="xsd:string" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="data">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="resheader">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" />+ </xsd:complexType>+ </xsd:element>+ </xsd:choice>+ </xsd:complexType>+ </xsd:element>+ </xsd:schema>+ <resheader name="resmimetype">+ <value>text/microsoft-resx</value>+ </resheader>+ <resheader name="version">+ <value>2.0</value>+ </resheader>+ <resheader name="reader">+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <resheader name="writer">+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <data name="QR-code" type="System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" mimetype="application/x-microsoft.net.object.binary.base64">+ <value>+ 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 RU5ErkJgggs=+</value>+ </data>+</root>\ No newline at end of filediff --git a/Wave_Dude_2D/OpenClApi.cs b/Wave_Dude_2D/OpenClApi.csnew file mode 100644index 0000000..453583c--- /dev/null+++ b/Wave_Dude_2D/OpenClApi.cs@@ -0,0 +1,321 @@+using System;+using System.Globalization;+using System.Runtime.InteropServices;+using System.Text;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Thin P/Invoke layer over OpenCL.dll (the ICD loader installed with the graphics driver) plus a few query+ /// helpers. Used by <see cref="GpuDeviceInfo"/> and <see cref="GpuWaveSimulator"/>; every call returns an+ /// OpenCL error code (0 = CL_SUCCESS) that callers route through <see cref="Check"/>. Loading the DLL is+ /// deferred to the first call, so <see cref="DllNotFoundException"/> and friends surface there.+ /// </summary>+ internal sealed class OpenClApi+ {+ /// <summary>clGetPlatformIDs: with <paramref name="platforms"/> null only counts the platforms into <paramref name="numPlatforms"/>.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern int clGetPlatformIDs(uint numEntries, IntPtr[] platforms, ref uint numPlatforms);++ /// <summary>clGetDeviceIDs: lists the devices of a platform matching <paramref name="deviceType"/> (<see cref="DeviceTypeGpu"/>); with <paramref name="devices"/> null only counts them.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern int clGetDeviceIDs(IntPtr platform, ulong deviceType, uint numEntries, IntPtr[] devices, ref uint numDevices);++ /// <summary>clGetDeviceInfo: raw bytes of a device property; with <paramref name="paramValue"/> null only reports the size in <paramref name="sizeRet"/>. Wrapped by <see cref="DeviceInfoBytes"/>.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern int clGetDeviceInfo(IntPtr device, uint paramName, IntPtr paramSize, byte[] paramValue, ref IntPtr sizeRet);++ /// <summary>clCreateContext: creates a context for the given devices; <paramref name="properties"/> is a zero-terminated key/value list (see <see cref="ContextPlatformProperty"/>). Release with <see cref="clReleaseContext"/>.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern IntPtr clCreateContext(IntPtr[] properties, uint numDevices, IntPtr[] devices, IntPtr notify, IntPtr userData, ref int errcode);++ /// <summary>clCreateCommandQueue (OpenCL 1.x entry point): an in-order queue on one device. Release with <see cref="clReleaseCommandQueue"/>.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern IntPtr clCreateCommandQueue(IntPtr context, IntPtr device, ulong properties, ref int errcode);++ /// <summary>clCreateProgramWithSource: a program from ANSI source strings (<paramref name="lengths"/> null = zero-terminated). Release with <see cref="clReleaseProgram"/>.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern IntPtr clCreateProgramWithSource(IntPtr context, uint count, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)] string[] strings, IntPtr[] lengths, ref int errcode);++ /// <summary>clBuildProgram: compiles the program for the given devices; <paramref name="options"/> is passed as an ANSI string (VB-style by-ref marshalling, not modified). On failure see <see cref="BuildLog"/>.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern int clBuildProgram(IntPtr program, uint numDevices, IntPtr[] devices, [MarshalAs(UnmanagedType.VBByRefStr)] ref string options, IntPtr notify, IntPtr userData);++ /// <summary>clGetProgramBuildInfo: raw bytes of a build property such as <see cref="ProgramBuildLog"/>; with <paramref name="paramValue"/> null only reports the size.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern int clGetProgramBuildInfo(IntPtr program, IntPtr device, uint paramName, IntPtr paramSize, byte[] paramValue, ref IntPtr sizeRet);++ /// <summary>clCreateKernel: a kernel object for the named <c>__kernel</c> function of a built program. Release with <see cref="clReleaseKernel"/>.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern IntPtr clCreateKernel(IntPtr program, [MarshalAs(UnmanagedType.VBByRefStr)] ref string kernelName, ref int errcode);++ /// <summary>clSetKernelArg for a buffer argument (cl_mem handle; <paramref name="argSize"/> is the pointer size).</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, EntryPoint = "clSetKernelArg", ExactSpelling = true, SetLastError = true)]+ internal static extern int clSetKernelArgMem(IntPtr kernel, uint argIndex, IntPtr argSize, ref IntPtr argValue);++ /// <summary>clSetKernelArg for an <c>int</c> argument (<paramref name="argSize"/> = 4).</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, EntryPoint = "clSetKernelArg", ExactSpelling = true, SetLastError = true)]+ internal static extern int clSetKernelArgInt(IntPtr kernel, uint argIndex, IntPtr argSize, ref int argValue);++ /// <summary>clSetKernelArg for a <c>float</c> argument (<paramref name="argSize"/> = 4).</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, EntryPoint = "clSetKernelArg", ExactSpelling = true, SetLastError = true)]+ internal static extern int clSetKernelArgFloat(IntPtr kernel, uint argIndex, IntPtr argSize, ref float argValue);++ /// <summary>clCreateBuffer: a device buffer of <paramref name="size"/> bytes with the given CL_MEM flags (<see cref="MemReadWrite"/>). Release with <see cref="clReleaseMemObject"/>.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern IntPtr clCreateBuffer(IntPtr context, ulong flags, IntPtr size, IntPtr hostPtr, ref int errcode);++ /// <summary>clEnqueueWriteBuffer from a float array; <paramref name="blocking"/> 1 waits for completion, <paramref name="offset"/>/<paramref name="size"/> are in bytes.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, EntryPoint = "clEnqueueWriteBuffer", ExactSpelling = true, SetLastError = true)]+ internal static extern int clEnqueueWriteBufferFloat(IntPtr queue, IntPtr buffer, uint blocking, IntPtr offset, IntPtr size, float[] data, uint numEvents, IntPtr waitList, IntPtr evt);++ /// <summary>clEnqueueWriteBuffer from an int array; <paramref name="blocking"/> 1 waits for completion, <paramref name="offset"/>/<paramref name="size"/> are in bytes.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, EntryPoint = "clEnqueueWriteBuffer", ExactSpelling = true, SetLastError = true)]+ internal static extern int clEnqueueWriteBufferInt(IntPtr queue, IntPtr buffer, uint blocking, IntPtr offset, IntPtr size, int[] data, uint numEvents, IntPtr waitList, IntPtr evt);++ /// <summary>clEnqueueReadBuffer into a float array; <paramref name="blocking"/> 1 waits for completion, <paramref name="offset"/>/<paramref name="size"/> are in bytes.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, EntryPoint = "clEnqueueReadBuffer", ExactSpelling = true, SetLastError = true)]+ internal static extern int clEnqueueReadBufferFloat(IntPtr queue, IntPtr buffer, uint blocking, IntPtr offset, IntPtr size, float[] data, uint numEvents, IntPtr waitList, IntPtr evt);++ /// <summary>clEnqueueNDRangeKernel: launches the kernel over a <paramref name="workDim"/>-dimensional range; <paramref name="localSize"/> null lets the driver pick the work-group size.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern int clEnqueueNDRangeKernel(IntPtr queue, IntPtr kernel, uint workDim, IntPtr[] globalOffset, IntPtr[] globalSize, IntPtr[] localSize, uint numEvents, IntPtr waitList, IntPtr evt);++ /// <summary>clFinish: blocks until every command queued so far has completed.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern int clFinish(IntPtr queue);++ /// <summary>clReleaseMemObject: drops a reference to a buffer created by <see cref="clCreateBuffer"/>.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern int clReleaseMemObject(IntPtr memObj);++ /// <summary>clReleaseKernel: drops a reference to a kernel created by <see cref="clCreateKernel"/>.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern int clReleaseKernel(IntPtr kernel);++ /// <summary>clReleaseProgram: drops a reference to a program created by <see cref="clCreateProgramWithSource"/>.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern int clReleaseProgram(IntPtr program);++ /// <summary>clReleaseCommandQueue: drops a reference to a queue created by <see cref="clCreateCommandQueue"/>.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern int clReleaseCommandQueue(IntPtr queue);++ /// <summary>clReleaseContext: drops a reference to a context created by <see cref="clCreateContext"/>.</summary>+ [DllImport("OpenCL.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]+ internal static extern int clReleaseContext(IntPtr context);++ /// <summary>Throws if an OpenCL call did not return CL_SUCCESS.</summary>+ /// <param name="code">Return value or errcode output of the OpenCL call.</param>+ /// <param name="what">Name of the call, used in the exception message.</param>+ /// <exception cref="InvalidOperationException"><paramref name="code"/> is not 0; the message includes <see cref="ErrorName"/>.</exception>+ internal static void Check(int code, string what)+ {+ if (code != 0)+ {+ throw new InvalidOperationException(what + " failed: " + OpenClApi.ErrorName(code));+ }+ }++ /// <summary>Human-readable name of an OpenCL error code, e.g. "CL_INVALID_VALUE (-30)"; unknown codes give "error (code)".</summary>+ internal static string ErrorName(int code)+ {+ string name;+ switch (code)+ {+ case -1:+ name = "CL_DEVICE_NOT_FOUND";+ break;+ case -2:+ name = "CL_DEVICE_NOT_AVAILABLE";+ break;+ case -3:+ name = "CL_COMPILER_NOT_AVAILABLE";+ break;+ case -4:+ name = "CL_MEM_OBJECT_ALLOCATION_FAILURE (out of GPU memory)";+ break;+ case -5:+ name = "CL_OUT_OF_RESOURCES";+ break;+ case -6:+ name = "CL_OUT_OF_HOST_MEMORY";+ break;+ case -11:+ name = "CL_BUILD_PROGRAM_FAILURE";+ break;+ case -30:+ name = "CL_INVALID_VALUE";+ break;+ case -33:+ name = "CL_INVALID_DEVICE";+ break;+ case -34:+ name = "CL_INVALID_CONTEXT";+ break;+ case -36:+ name = "CL_INVALID_COMMAND_QUEUE";+ break;+ case -38:+ name = "CL_INVALID_MEM_OBJECT";+ break;+ case -45:+ name = "CL_INVALID_PROGRAM_EXECUTABLE";+ break;+ case -46:+ name = "CL_INVALID_KERNEL_NAME";+ break;+ case -48:+ name = "CL_INVALID_KERNEL";+ break;+ case -49:+ name = "CL_INVALID_ARG_INDEX";+ break;+ case -50:+ name = "CL_INVALID_ARG_VALUE";+ break;+ case -51:+ name = "CL_INVALID_ARG_SIZE";+ break;+ case -52:+ name = "CL_INVALID_KERNEL_ARGS";+ break;+ case -54:+ name = "CL_INVALID_WORK_GROUP_SIZE";+ break;+ case -55:+ name = "CL_INVALID_WORK_ITEM_SIZE";+ break;+ case -61:+ name = "CL_INVALID_BUFFER_SIZE";+ break;+ case -1001:+ // Returned by the ICD loader when no vendor driver is registered.+ name = "no OpenCL platform (CL_PLATFORM_NOT_FOUND_KHR)";+ break;+ default:+ name = "error";+ break;+ }+ return name + " (" + code.ToString(CultureInfo.InvariantCulture) + ")";+ }++ /// <summary>Raw bytes of a clGetDeviceInfo query (size probed first), or null if either call fails or the value is empty.</summary>+ /// <param name="device">OpenCL device handle.</param>+ /// <param name="paramName">A CL_DEVICE_* constant such as <see cref="DeviceName"/>.</param>+ internal static byte[] DeviceInfoBytes(IntPtr device, uint paramName)+ {+ IntPtr sizeRet = IntPtr.Zero;+ if (OpenClApi.clGetDeviceInfo(device, paramName, IntPtr.Zero, null, ref sizeRet) != 0)+ {+ return null;+ }+ int size = sizeRet.ToInt32();+ if (size <= 0)+ {+ return null;+ }+ byte[] value = new byte[size];+ IntPtr ignored = IntPtr.Zero;+ if (OpenClApi.clGetDeviceInfo(device, paramName, new IntPtr(size), value, ref ignored) != 0)+ {+ return null;+ }+ return value;+ }++ /// <summary>A string device property decoded as ASCII with the terminating NUL and padding trimmed; "" when the query fails.</summary>+ internal static string DeviceString(IntPtr device, uint paramName)+ {+ byte[] bytes = OpenClApi.DeviceInfoBytes(device, paramName);+ return bytes == null ? "" : Encoding.ASCII.GetString(bytes).Trim(new char[] { '\0', ' ' });+ }++ /// <summary>+ /// A numeric device property: 8-byte values (cl_ulong) are returned as is, 4-byte values (cl_uint, cl_bool)+ /// are widened; 0 when the query fails or the value is shorter than 4 bytes.+ /// </summary>+ internal static ulong DeviceNumber(IntPtr device, uint paramName)+ {+ byte[] bytes = OpenClApi.DeviceInfoBytes(device, paramName);+ if (bytes == null)+ {+ return 0UL;+ }+ if (bytes.Length >= 8)+ {+ return BitConverter.ToUInt64(bytes, 0);+ }+ if (bytes.Length >= 4)+ {+ return BitConverter.ToUInt32(bytes, 0);+ }+ return 0UL;+ }++ /// <summary>The compiler log for a program on a device (CL_PROGRAM_BUILD_LOG, trimmed); empty if unavailable or if the query throws.</summary>+ internal static string BuildLog(IntPtr program, IntPtr device)+ {+ try+ {+ IntPtr sizeRet = IntPtr.Zero;+ if (OpenClApi.clGetProgramBuildInfo(program, device, OpenClApi.ProgramBuildLog, IntPtr.Zero, null, ref sizeRet) != 0)+ {+ return "";+ }+ int size = sizeRet.ToInt32();+ if (size <= 0)+ {+ return "";+ }+ byte[] log = new byte[size];+ IntPtr ignored = IntPtr.Zero;+ if (OpenClApi.clGetProgramBuildInfo(program, device, OpenClApi.ProgramBuildLog, new IntPtr(size), log, ref ignored) != 0)+ {+ return "";+ }+ return Encoding.ASCII.GetString(log).Trim(new char[] { '\0', ' ', '\r', '\n' });+ }+ catch (Exception)+ {+ return "";+ }+ }++ /// <summary>CL_DEVICE_TYPE_GPU (1 << 2).</summary>+ internal const ulong DeviceTypeGpu = 4UL;++ /// <summary>CL_MEM_READ_WRITE (1 << 0) buffer flag.</summary>+ internal const ulong MemReadWrite = 1UL;++ /// <summary>CL_CONTEXT_PLATFORM (0x1084): property key for the platform in <see cref="clCreateContext"/>.</summary>+ internal const int ContextPlatformProperty = 4228;++ /// <summary>CL_PLATFORM_NAME (0x0902).</summary>+ internal const uint PlatformNameInfo = 2306U;++ /// <summary>CL_DEVICE_MAX_COMPUTE_UNITS (0x1002), cl_uint.</summary>+ internal const uint DeviceMaxComputeUnits = 4098U;++ /// <summary>CL_DEVICE_MAX_CLOCK_FREQUENCY (0x100C), cl_uint in MHz.</summary>+ internal const uint DeviceMaxClockFrequency = 4108U;++ /// <summary>CL_DEVICE_MAX_MEM_ALLOC_SIZE (0x1010), cl_ulong bytes.</summary>+ internal const uint DeviceMaxMemAllocSize = 4112U;++ /// <summary>CL_DEVICE_GLOBAL_MEM_SIZE (0x101F), cl_ulong bytes.</summary>+ internal const uint DeviceGlobalMemSize = 4127U;++ /// <summary>CL_DEVICE_NAME (0x102B), string.</summary>+ internal const uint DeviceName = 4139U;++ /// <summary>CL_DEVICE_VENDOR (0x102C), string.</summary>+ internal const uint DeviceVendor = 4140U;++ /// <summary>CL_DEVICE_HOST_UNIFIED_MEMORY (0x1035), cl_bool: non-zero for devices sharing host memory (integrated GPUs).</summary>+ internal const uint DeviceHostUnifiedMemory = 4149U;++ /// <summary>CL_PROGRAM_BUILD_LOG (0x1183), string.</summary>+ internal const uint ProgramBuildLog = 4483U;+ }+}diff --git a/Wave_Dude_2D/ProbeBoxSize.cs b/Wave_Dude_2D/ProbeBoxSize.csnew file mode 100644index 0000000..b98ca03--- /dev/null+++ b/Wave_Dude_2D/ProbeBoxSize.cs@@ -0,0 +1,22 @@+namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Nominal size of a probe's graph box in canvas pixels (<c>ProbeGraphPainter.NominalBoxSize</c>).+ /// The box is shrunk to fit half the canvas width and the full canvas height+ /// (<c>ProbeGraphPainter.BoxInCanvas</c>). The numeric value is the index of the "box size"+ /// combo box on the Probes tab.+ /// </summary>+ public enum ProbeBoxSize+ {+ /// <summary>200 x 100 canvas pixels.</summary>+ Tiny,+ /// <summary>300 x 150 canvas pixels.</summary>+ Small,+ /// <summary>400 x 200 canvas pixels (default).</summary>+ Medium,+ /// <summary>500 x 250 canvas pixels.</summary>+ Large,+ /// <summary>700 x 350 canvas pixels.</summary>+ ExtraLarge+ }+}diff --git a/Wave_Dude_2D/ProbeCollector.cs b/Wave_Dude_2D/ProbeCollector.csnew file mode 100644index 0000000..4a11035--- /dev/null+++ b/Wave_Dude_2D/ProbeCollector.cs@@ -0,0 +1,156 @@+using System.Collections.Generic;++namespace _2D_wave_sim_V01+{+ /// <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 simulation worker thread (<c>SimulationRunner.Run</c>):+ /// <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 runner raises as <c>ProbesUpdated</c> and the form applies to its own+ /// traces on the UI thread. The UI thread never touches this object itself; the only cross-thread reader of+ /// <see cref="Traces"/> is <c>SimulationRunner.RenderCurrentFrame</c>, which runs while the worker is parked+ /// at the pause gate.+ /// </summary>+ internal sealed class ProbeCollector+ {+ /// <summary>Creates one empty <see cref="ProbeTrace"/> and one pending sample list per probe of <paramref name="sampler"/>.</summary>+ public ProbeCollector(ProbeSampler sampler)+ {+ this._pending = new List<List<float>>();+ this._sampler = sampler;+ this.Traces = new ProbeTrace[sampler.Count];+ this._totals = new double[sampler.Count];+ this._fresh = new bool[sampler.Count];+ for (int i = 0; i < sampler.Count; i++)+ {+ this.Traces[i] = new ProbeTrace();+ this._pending.Add(new List<float>());+ }+ }++ /// <summary>+ /// Drains the engine's buffered point-probe samples (<see cref="IWaveEngine.TakeProbeSamples"/>, one value+ /// per step since the previous call) into the series traces and the pending UI batch. For cumulative+ /// probes (point + IntegratedIntensity) the per-step intensities are replaced in place by their running+ /// sum, which stays at 0 for steps before the probe's start step. Does nothing when there are no point+ /// probes.+ /// </summary>+ /// <param name="engine">Engine that buffered the samples since the previous call.</param>+ /// <param name="stepsDone">Steps completed so far; recorded as <see cref="ProbeTrace.StepsSampled"/>.</param>+ public void Collect(IWaveEngine engine, int stepsDone)+ {+ if (!this._sampler.HasSeries)+ {+ return;+ }+ float[][] samples = engine.TakeProbeSamples();+ int lastStepsDone = this._lastStepsDone;+ for (int i = 0; i < this._sampler.Count; i++)+ {+ if (this._sampler.IsProfile[i] || i >= samples.Length)+ {+ continue;+ }+ float[] values = samples[i];+ if (values == null || values.Length == 0)+ {+ continue;+ }+ if (this._sampler.Cumulative[i])+ {+ bool useStartAfterStep = this._sampler.UseStartAfterStep[i];+ int startAfterStep = this._sampler.StartAfterStep[i];+ for (int j = 0; j < values.Length; j++)+ {+ // sample j belongs to step lastStepsDone + j + 1 (one sample per step)+ if (useStartAfterStep && lastStepsDone + j + 1 < startAfterStep)+ {+ this._totals[i] = 0.0;+ values[j] = 0f;+ }+ else+ {+ this._totals[i] += values[j];+ values[j] = (float)this._totals[i];+ }+ }+ }+ this.Traces[i].Series.Add(values);+ this.Traces[i].StepsSampled = stepsDone;+ this._pending[i].AddRange(values);+ }+ this._lastStepsDone = stepsDone;+ }++ /// <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.+ /// </summary>+ /// <param name="engine">Engine holding the current profiles.</param>+ /// <param name="stepsDone">Steps completed so far; recorded as <see cref="ProbeTrace.StepsSampled"/>.</param>+ public void CollectProfiles(IWaveEngine engine, int stepsDone)+ {+ if (!this._sampler.HasProfiles)+ {+ return;+ }+ float[][] profiles = engine.ReadProbeProfiles();+ for (int i = 0; i < this._sampler.Count; i++)+ {+ if (!this._sampler.IsProfile[i] || i >= profiles.Length || profiles[i] == null)+ {+ continue;+ }+ this.Traces[i].SetProfile(profiles[i], this._sampler.Lengths[i]);+ this.Traces[i].StepsSampled = stepsDone;+ this._fresh[i] = true;+ }+ this._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.+ /// </summary>+ /// <returns>A batch covering everything since the previous call; never null.</returns>+ public ProbeUpdate TakeForUi()+ {+ int count = this._sampler.Count;+ float[][] series = new float[count][];+ float[][] profiles = new float[count][];+ for (int i = 0; i < count; i++)+ {+ series[i] = this._pending[i].ToArray();+ this._pending[i].Clear();+ if (this._fresh[i])+ {+ profiles[i] = this.Traces[i].Profile;+ this._fresh[i] = false;+ }+ }+ return new ProbeUpdate(series, profiles, this._sampler.Lengths, this._lastStepsDone);+ }++ /// <summary>Worker-side trace per probe (index parallel to the sampler). Read by <see cref="ProbeOverlay.Burn"/> when burning graphs into exported frames.</summary>+ public readonly ProbeTrace[] Traces;++ /// <summary>Per-probe pixel indices, flags and line lengths; immutable.</summary>+ private readonly ProbeSampler _sampler;++ /// <summary>Per probe: running sum for cumulative point probes, kept in double to limit drift; unused entries stay 0.</summary>+ private readonly double[] _totals;++ /// <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>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/Wave_Dude_2D/ProbeGraphPainter.cs b/Wave_Dude_2D/ProbeGraphPainter.csnew file mode 100644index 0000000..f4f91db--- /dev/null+++ b/Wave_Dude_2D/ProbeGraphPainter.cs@@ -0,0 +1,800 @@+using System;+using System.Collections.Generic;+using System.Drawing;+using System.Drawing.Drawing2D;+using System.Drawing.Text;+using System.Globalization;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// GDI+ rendering of probe graphs (time series / line profiles) and of the probe position markers.+ /// Stateless: every call draws onto the <see cref="Graphics"/> it is given. Used on the UI thread by the+ /// main form's paint handlers (painting the form's own copies of the traces onto the picture boxes) and on+ /// the simulation worker thread by <see cref="ProbeOverlay"/> (painting the collector's traces into an+ /// off-screen bitmap). A <see cref="ProbeTrace"/> must only be painted by the thread that owns it.+ /// </summary>+ internal sealed class ProbeGraphPainter+ {+ private ProbeGraphPainter()+ {+ }++ /// <summary>Unscaled graph box size in canvas pixels for a box size setting; Medium (and any unknown value) is 400 x 200.</summary>+ public static Size NominalBoxSize(ProbeBoxSize boxSize)+ {+ switch (boxSize)+ {+ case ProbeBoxSize.Tiny:+ return new Size(200, 100);+ case ProbeBoxSize.Small:+ return new Size(300, 150);+ case ProbeBoxSize.Large:+ return new Size(500, 250);+ case ProbeBoxSize.ExtraLarge:+ return new Size(700, 350);+ }+ return new Size(400, 200);+ }++ /// <summary>+ /// Graph box rectangle for a probe, shrunk (keeping its aspect ratio) so it fits into half the canvas width+ /// and the full canvas height, and clamped to stay inside the canvas.+ /// </summary>+ /// <param name="probe">Settings providing the box size and the wanted box position.</param>+ /// <param name="w">Canvas width in pixels.</param>+ /// <param name="h">Canvas height in pixels.</param>+ /// <returns>The box in canvas pixel coordinates, never smaller than 1 x 1.</returns>+ public static Rectangle BoxInCanvas(ProbeSettings probe, int w, int h)+ {+ Size nominal = ProbeGraphPainter.NominalBoxSize(probe.BoxSize);+ 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 Rectangle(boxX, boxY, boxWidth, boxHeight);+ }++ /// <summary>+ /// Computes 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 line profiles x is the distance along+ /// the line in canvas pixels. y comes from the probe's fixed YMin/YMax (falling back to -1..1 when the+ /// range is empty or inverted) or, with AutoScaleY, from the visible data plus a small margin.+ /// Also used by the form to freeze auto-scaled y limits into the probe settings.+ /// </summary>+ /// <param name="probe">Settings that select kind, scale mode, fixed y range and auto-scaling.</param>+ /// <param name="trace">Recorded data; may be null, which yields the ranges of an empty graph.</param>+ /// <param name="totalSteps">Total steps of the run; upper x limit of full-scale series graphs without AutoScaleX.</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(ProbeSettings probe, ProbeTrace trace, int totalSteps, ref double xMin, ref double xMax, ref double yMin, ref double yMax)+ {+ if (probe.Kind == ProbeKind.Line)+ {+ ProbeGraphPainter.ProfileRanges(probe, trace, ref xMin, ref xMax, ref yMin, ref yMax);+ }+ else+ {+ ProbeSeries series = (trace != null) ? trace.Series : null;+ double startStep = probe.UseStartAfterStep ? Math.Max(0, probe.StartAfterStep) : 0.0;+ ProbeGraphPainter.SeriesRanges(probe, series, totalSteps, startStep, ref xMin, ref xMax, ref yMin, ref yMax);+ }+ }++ /// <summary>+ /// Ranges of a time-series graph. Full mode spans from <paramref name="startStep"/> to the sample count+ /// (AutoScaleX) or to the run length. Running mode shows a window of <c>RunningWindow</c> (at least 10)+ /// steps that slides with the data; with AutoScaleX it starts narrow and grows to full width, otherwise it+ /// is full width from the start. With AutoScaleY the y range is fitted to the samples inside the x range.+ /// </summary>+ /// <param name="probe">Settings that select scale mode, running window, fixed y range and auto-scaling.</param>+ /// <param name="series">Sampled values; null is treated as empty.</param>+ /// <param name="totalSteps">Total steps of the run.</param>+ /// <param name="startStep">First step shown: the probe's start-after step, or 0.</param>+ /// <param name="xMin">Receives the lower x limit.</param>+ /// <param name="xMax">Receives the upper x limit.</param>+ /// <param name="yMin">Receives the lower y limit.</param>+ /// <param name="yMax">Receives the upper y limit.</param>+ private static void SeriesRanges(ProbeSettings probe, ProbeSeries series, int totalSteps, double startStep, ref double xMin, ref double xMax, ref double yMin, ref double yMax)+ {+ int count = (series == null) ? 0 : series.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(10, probe.RunningWindow);+ 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;+ }+ yMin = probe.YMin;+ yMax = probe.YMax;+ if (yMax <= yMin)+ {+ yMin = -1.0;+ yMax = 1.0;+ }+ 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));+ double lo = double.MaxValue;+ double hi = double.MinValue;+ float[] values = series.Values;+ for (int i = firstIndex; i <= lastIndex; i++)+ {+ float value = values[i];+ if (!float.IsNaN(value) && !float.IsInfinity(value))+ {+ if (value < lo)+ {+ lo = value;+ }+ if (value > hi)+ {+ hi = value;+ }+ }+ }+ if (lo <= hi)+ {+ ProbeGraphPainter.FitRange(lo, hi, false, ref yMin, ref yMax);+ }+ }+ }++ /// <summary>+ /// Ranges of a line-profile graph: x spans 0..line length in canvas pixels (0..1 without a trace); y is the+ /// fixed range or, with AutoScaleY, fitted to the profile values. Intensity profiles that are entirely+ /// non-negative are fitted from 0 upwards.+ /// </summary>+ /// <param name="probe">Settings providing the fixed y range, auto-scaling and measurement.</param>+ /// <param name="trace">Recorded data; null yields an empty graph.</param>+ /// <param name="xMin">Receives the lower x limit (always 0).</param>+ /// <param name="xMax">Receives the upper x limit.</param>+ /// <param name="yMin">Receives the lower y limit.</param>+ /// <param name="yMax">Receives the upper y limit.</param>+ private static void ProfileRanges(ProbeSettings probe, ProbeTrace trace, ref double xMin, ref double xMax, ref double yMin, ref double yMax)+ {+ double profileLength = 0.0;+ float[] profile = null;+ if (trace != null)+ {+ profileLength = trace.ProfileLength;+ profile = trace.Profile;+ }+ xMin = 0.0;+ xMax = (profileLength > 0.0) ? profileLength : 1.0;+ yMin = probe.YMin;+ yMax = probe.YMax;+ if (yMax <= yMin)+ {+ yMin = -1.0;+ yMax = 1.0;+ }+ if (probe.AutoScaleY && profile != null)+ {+ double lo = double.MaxValue;+ double hi = double.MinValue;+ for (int i = 0; i < profile.Length; i++)+ {+ float value = profile[i];+ if (!float.IsNaN(value) && !float.IsInfinity(value))+ {+ if (value < lo)+ {+ lo = value;+ }+ if (value > hi)+ {+ hi = value;+ }+ }+ }+ if (lo <= hi)+ {+ ProbeGraphPainter.FitRange(lo, hi, probe.Measurement != ProbeMeasurement.Amplitude && lo >= 0.0, ref yMin, ref yMax);+ }+ }+ }++ /// <summary>+ /// Expands [lo, hi] by an 8% margin so the curve does not touch the plot border. A (nearly) flat range+ /// gets a margin of 10% of its magnitude (at least 1e-6) instead, so it never collapses to zero height.+ /// </summary>+ /// <param name="lo">Smallest data value.</param>+ /// <param name="hi">Largest data value, not below <paramref name="lo"/>.</param>+ /// <param name="zeroBased">When true the lower limit is pinned to 0 instead of lo minus the margin.</param>+ /// <param name="yMin">Receives the lower y limit.</param>+ /// <param name="yMax">Receives the upper y limit.</param>+ private static void FitRange(double lo, double hi, bool zeroBased, ref double yMin, ref double yMax)+ {+ double span = hi - lo;+ double magnitude = Math.Max(Math.Abs(hi), Math.Abs(lo));+ double margin = span * 0.08;+ if (span < magnitude * 1E-09 || span < 1E-30)+ {+ margin = Math.Max(magnitude * 0.1, 1E-06);+ }+ yMin = zeroBased ? 0.0 : (lo - margin);+ yMax = hi + margin;+ }++ /// <summary>+ /// Returns "nice" (1/2/5 x 10^n) 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>+ private static List<double> NiceTicks(double lo, double hi, int target)+ {+ List<double> ticks = new List<double>();+ double span = hi - lo;+ 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;+ if (mantissa < 1.5)+ {+ step = 1.0;+ }+ else if (mantissa < 3.0)+ {+ step = 2.0;+ }+ else if (mantissa < 7.0)+ {+ step = 5.0;+ }+ else+ {+ step = 10.0;+ }+ step *= magnitude;+ double tick = Math.Ceiling(lo / step) * step;+ int tickCount = 0;+ while (tick <= hi + step * 1E-09 && tickCount < 40)+ {+ ticks.Add((Math.Abs(tick) < step * 1E-09) ? 0.0 : tick);+ tick += step;+ tickCount++;+ }+ return ticks;+ }++ /// <summary>Formats an axis value with three significant digits (invariant culture); 0 is just "0".</summary>+ private static string FormatTick(double v)+ {+ return (v == 0.0) ? "0" : v.ToString("G3", CultureInfo.InvariantCulture);+ }++ /// <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>+ private static string FormatPosition(double v, double span)+ {+ return (span >= 10.0) ? Math.Round(v).ToString("0", CultureInfo.InvariantCulture) : v.ToString("0.#", CultureInfo.InvariantCulture);+ }++ /// <summary>+ /// Draws one complete probe graph box (background, frame, axes, curve and title bar with live readout)+ /// into <paramref name="bounds"/>. Nothing is drawn when the box is smaller than 40 x 30 or the plot area+ /// would be smaller than 20 x 15. A line probe with "start after step" shows neither profile nor readout+ /// until <see cref="ProbeTrace.StepsSampled"/> has reached that step; series are always drawn. The+ /// Graphics state is saved and restored around the call.+ /// </summary>+ /// <param name="g">Target surface. <paramref name="bounds"/> is in its device pixels: picture-box pixels when painting the form, bitmap pixels for exported frames.</param>+ /// <param name="bounds">Outer rectangle of the graph box.</param>+ /// <param name="title">Title bar text, trimmed with an ellipsis if it does not fit next to the readout.</param>+ /// <param name="probe">Settings that select kind, scaling and the start-after gate.</param>+ /// <param name="trace">Recorded data, or null for an empty graph.</param>+ /// <param name="totalSteps">Total steps of the run, see <see cref="ComputeRanges"/>.</param>+ public static void DrawGraph(Graphics g, Rectangle bounds, string title, ProbeSettings probe, ProbeTrace trace, int totalSteps)+ {+ if (bounds.Width < 40 || bounds.Height < 30)+ {+ return;+ }+ GraphicsState savedState = g.Save();+ try+ {+ g.SmoothingMode = SmoothingMode.AntiAlias;+ g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;+ using (SolidBrush backgroundBrush = new SolidBrush(Color.FromArgb(235, 14, 16, 22)))+ {+ g.FillRectangle(backgroundBrush, bounds);+ }+ using (Pen borderPen = new Pen(Color.FromArgb(170, 200, 200, 210), 1f))+ {+ g.DrawRectangle(borderPen, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1);+ }+ // Font and margins scale with the box height so small boxes stay legible.+ float fontPx = Math.Max(9f, bounds.Height / 14f);+ using (Font font = new Font("Segoe UI", fontPx, FontStyle.Regular, GraphicsUnit.Pixel))+ {+ int leftMargin = (int)Math.Ceiling(fontPx * 4.4f);+ int topMargin = (int)Math.Round(fontPx * 2.3f);+ int bottomMargin = (int)Math.Round(fontPx * 1.9f);+ Rectangle plot = new Rectangle(bounds.X + leftMargin + 6, bounds.Y + topMargin, bounds.Width - leftMargin - 6 - 10, bounds.Height - topMargin - bottomMargin);+ if (plot.Width < 20 || plot.Height < 15)+ {+ return;+ }+ bool isLine = probe.Kind == ProbeKind.Line;+ ProbeTrace gatedTrace = (!probe.UseStartAfterStep || trace == null || trace.StepsSampled >= probe.StartAfterStep) ? trace : null;+ double xMin = 0.0;+ double xMax = 0.0;+ double yMin = 0.0;+ double yMax = 0.0;+ ProbeGraphPainter.ComputeRanges(probe, isLine ? gatedTrace : trace, totalSteps, ref xMin, ref xMax, ref yMin, ref yMax);+ ProbeGraphPainter.DrawAxes(g, font, fontPx, bounds, plot, xMin, xMax, yMin, yMax);+ float lineWidth = Math.Max(1.2f, bounds.Height / 110f);+ if (isLine)+ {+ if (gatedTrace != null)+ {+ ProbeGraphPainter.DrawProfile(g, plot, gatedTrace.Profile, yMin, yMax, lineWidth);+ }+ }+ else if (trace != null)+ {+ ProbeGraphPainter.DrawCurve(g, plot, trace.Series, xMin, xMax, yMin, yMax, lineWidth);+ }+ ProbeGraphPainter.DrawTitle(g, font, bounds, title, ProbeGraphPainter.ValueText(isLine, isLine ? gatedTrace : trace), fontPx);+ }+ }+ finally+ {+ g.Restore(savedState);+ }+ }++ /// <summary>Short readout shown in the title bar: "max" of the profile or "=" latest series value; empty when there is no valid value.</summary>+ private static string ValueText(bool isLine, ProbeTrace trace)+ {+ if (trace == null)+ {+ return "";+ }+ if (isLine)+ {+ float[] profile = trace.Profile;+ if (profile == null || profile.Length == 0)+ {+ return "";+ }+ float max = float.MinValue;+ for (int i = 0; i < profile.Length; i++)+ {+ float value = profile[i];+ if (!float.IsNaN(value) && !float.IsInfinity(value) && value > max)+ {+ max = value;+ }+ }+ if (max == float.MinValue)+ {+ return "";+ }+ return "max " + ProbeGraphPainter.FormatTick(max);+ }+ if (trace.Series.Count == 0)+ {+ return "";+ }+ float lastValue = trace.Series.LastValue;+ if (float.IsNaN(lastValue) || float.IsInfinity(lastValue))+ {+ return "";+ }+ return "= " + ProbeGraphPainter.FormatTick(lastValue);+ }++ /// <summary>+ /// Draws grid lines and labels at the "nice" ticks of both axes (the y = 0 line brighter than the rest),+ /// then the plot frame. y labels are right-aligned in the left margin, x labels centred below the plot.+ /// </summary>+ /// <param name="g">Target surface.</param>+ /// <param name="font">Label font.</param>+ /// <param name="fontPx">Font height in pixels, used to size the label rectangles.</param>+ /// <param name="bounds">Whole graph box.</param>+ /// <param name="plot">Plot area inside the box.</param>+ /// <param name="xMin">Lower x limit.</param>+ /// <param name="xMax">Upper x limit.</param>+ /// <param name="yMin">Lower y limit.</param>+ /// <param name="yMax">Upper y limit.</param>+ private static void DrawAxes(Graphics g, Font font, float fontPx, Rectangle bounds, Rectangle plot, double xMin, double xMax, double yMin, double yMax)+ {+ using (Pen gridPen = new Pen(Color.FromArgb(46, 255, 255, 255), 1f))+ {+ using (Pen zeroPen = new Pen(Color.FromArgb(120, 255, 255, 255), 1f))+ {+ using (SolidBrush labelBrush = new SolidBrush(Color.FromArgb(225, 225, 225, 230)))+ {+ using (StringFormat yLabelFormat = new StringFormat())+ {+ using (StringFormat xLabelFormat = new StringFormat())+ {+ yLabelFormat.Alignment = StringAlignment.Far;+ yLabelFormat.LineAlignment = StringAlignment.Center;+ yLabelFormat.FormatFlags = StringFormatFlags.NoWrap;+ xLabelFormat.Alignment = StringAlignment.Center;+ xLabelFormat.FormatFlags = StringFormatFlags.NoWrap;+ foreach (double tick in ProbeGraphPainter.NiceTicks(yMin, yMax, 4))+ {+ float py = ProbeGraphPainter.ToPixelY(tick, plot, yMin, yMax);+ g.DrawLine((tick == 0.0) ? zeroPen : gridPen, (float)plot.Left, py, (float)plot.Right, py);+ g.DrawString(ProbeGraphPainter.FormatTick(tick), font, labelBrush, new RectangleF(bounds.X + 1, py - fontPx * 0.7f, plot.Left - bounds.X - 4, fontPx * 1.4f), yLabelFormat);+ }+ foreach (double tick in ProbeGraphPainter.NiceTicks(xMin, xMax, 5))+ {+ float px = (float)(plot.Left + (tick - xMin) / (xMax - xMin) * plot.Width);+ g.DrawLine(gridPen, px, (float)plot.Top, px, (float)plot.Bottom);+ g.DrawString(ProbeGraphPainter.FormatPosition(tick, xMax - xMin), font, labelBrush, new RectangleF(px - fontPx * 2.5f, plot.Bottom + 2, fontPx * 5f, fontPx * 1.4f), xLabelFormat);+ }+ }+ }+ }+ }+ using (Pen framePen = new Pen(Color.FromArgb(130, 200, 200, 210), 1f))+ {+ g.DrawRectangle(framePen, plot.X, plot.Y, plot.Width, plot.Height);+ }+ }+ }++ /// <summary>+ /// Maps a data value to a pixel y inside <paramref name="plot"/> (bottom edge = yMin, top edge = yMax).+ /// The result is clamped to +/-30000 because GDI+ fails on coordinates far outside the surface.+ /// </summary>+ private static float ToPixelY(double v, Rectangle plot, double yMin, double yMax)+ {+ double py = plot.Bottom - (v - yMin) / (yMax - yMin) * plot.Height;+ if (py < -30000.0)+ {+ py = -30000.0;+ }+ if (py > 30000.0)+ {+ py = 30000.0;+ }+ return (float)py;+ }++ /// <summary>+ /// Draws a time series: sample i is placed at x = i + 1 (its step number); NaN and infinite samples are+ /// skipped. When there are more than two samples per pixel column, each column gets a vertical min/max+ /// segment instead of individual points.+ /// </summary>+ /// <param name="g">Target surface.</param>+ /// <param name="plot">Plot area in device pixels.</param>+ /// <param name="series">Sampled values; null or empty draws nothing.</param>+ /// <param name="xMin">Lower x limit in steps.</param>+ /// <param name="xMax">Upper x limit in steps.</param>+ /// <param name="yMin">Lower y limit.</param>+ /// <param name="yMax">Upper y limit.</param>+ /// <param name="lineWidth">Pen width in pixels.</param>+ private static void DrawCurve(Graphics g, Rectangle plot, ProbeSeries series, double xMin, double xMax, double yMin, double yMax, float lineWidth)+ {+ if (series == null || series.Count < 1)+ {+ return;+ }+ float[] values = series.Values;+ int count = series.Count;+ int firstIndex = Math.Max(0, (int)Math.Floor(xMin) - 1);+ int lastIndex = Math.Min(count - 1, (int)Math.Ceiling(xMax));+ if (lastIndex < firstIndex)+ {+ return;+ }+ List<PointF> points = new List<PointF>();+ int visibleCount = lastIndex - firstIndex + 1;+ double xScale = plot.Width / (xMax - xMin);+ if (visibleCount <= plot.Width * 2)+ {+ for (int i = firstIndex; i <= lastIndex; i++)+ {+ float value = values[i];+ if (!float.IsNaN(value) && !float.IsInfinity(value))+ {+ points.Add(new PointF((float)(plot.Left + (i + 1 - xMin) * xScale), ProbeGraphPainter.ToPixelY(value, plot, yMin, yMax)));+ }+ }+ }+ else+ {+ for (int column = 0; column < plot.Width; column++)+ {+ // long arithmetic: column * visibleCount can exceed the int range for long runs+ int binStart = firstIndex + (int)((long)column * (long)visibleCount / (long)plot.Width);+ int binEnd = firstIndex + (int)((long)(column + 1) * (long)visibleCount / (long)plot.Width) - 1;+ if (binEnd < binStart)+ {+ binEnd = binStart;+ }+ float binMin = float.MaxValue;+ float binMax = float.MinValue;+ int binLast = Math.Min(binEnd, lastIndex);+ for (int k = binStart; k <= binLast; k++)+ {+ float value = values[k];+ if (!float.IsNaN(value) && !float.IsInfinity(value))+ {+ if (value < binMin)+ {+ binMin = value;+ }+ if (value > binMax)+ {+ binMax = value;+ }+ }+ }+ if (binMin <= binMax)+ {+ float px = plot.Left + column + 0.5f;+ points.Add(new PointF(px, ProbeGraphPainter.ToPixelY(binMin, plot, yMin, yMax)));+ points.Add(new PointF(px, ProbeGraphPainter.ToPixelY(binMax, plot, yMin, yMax)));+ }+ }+ }+ ProbeGraphPainter.StrokePoints(g, plot, points, lineWidth);+ }++ /// <summary>+ /// Draws a line-probe profile stretched over the full plot width (first value at the left edge, last value+ /// at the right edge), min/max binned per pixel column when dense. NaN and infinite values are skipped.+ /// </summary>+ /// <param name="g">Target surface.</param>+ /// <param name="plot">Plot area in device pixels.</param>+ /// <param name="profile">Values along the line; null or empty draws nothing.</param>+ /// <param name="yMin">Lower y limit.</param>+ /// <param name="yMax">Upper y limit.</param>+ /// <param name="lineWidth">Pen width in pixels.</param>+ private static void DrawProfile(Graphics g, Rectangle plot, float[] profile, double yMin, double yMax, float lineWidth)+ {+ if (profile == null || profile.Length < 1)+ {+ return;+ }+ int count = profile.Length;+ List<PointF> points = new List<PointF>();+ if (count <= plot.Width * 2)+ {+ for (int i = 0; i < count; i++)+ {+ float value = profile[i];+ if (!float.IsNaN(value) && !float.IsInfinity(value))+ {+ double t = (count > 1) ? (i / (count - 1.0)) : 0.0;+ points.Add(new PointF((float)(plot.Left + t * plot.Width), ProbeGraphPainter.ToPixelY(value, plot, yMin, yMax)));+ }+ }+ }+ else+ {+ for (int column = 0; column < plot.Width; column++)+ {+ int binStart = (int)((long)column * (long)count / (long)plot.Width);+ int binEnd = (int)((long)(column + 1) * (long)count / (long)plot.Width) - 1;+ if (binEnd < binStart)+ {+ binEnd = binStart;+ }+ float binMin = float.MaxValue;+ float binMax = float.MinValue;+ int binLast = Math.Min(binEnd, count - 1);+ for (int k = binStart; k <= binLast; k++)+ {+ float value = profile[k];+ if (!float.IsNaN(value) && !float.IsInfinity(value))+ {+ if (value < binMin)+ {+ binMin = value;+ }+ if (value > binMax)+ {+ binMax = value;+ }+ }+ }+ if (binMin <= binMax)+ {+ float px = plot.Left + column + 0.5f;+ points.Add(new PointF(px, ProbeGraphPainter.ToPixelY(binMin, plot, yMin, yMax)));+ points.Add(new PointF(px, ProbeGraphPainter.ToPixelY(binMax, plot, yMin, yMax)));+ }+ }+ }+ ProbeGraphPainter.StrokePoints(g, plot, points, lineWidth);+ }++ /// <summary>+ /// Strokes the points as one polyline clipped to the plot area; a single point is drawn as a small dot,+ /// an empty list draws nothing. The previous clip region is restored afterwards.+ /// </summary>+ private static void StrokePoints(Graphics g, Rectangle plot, List<PointF> points, float lineWidth)+ {+ if (points.Count < 2)+ {+ if (points.Count == 1)+ {+ using (SolidBrush dotBrush = new SolidBrush(Color.FromArgb(255, 255, 208, 64)))+ {+ g.FillEllipse(dotBrush, points[0].X - 2f, points[0].Y - 2f, 4f, 4f);+ }+ }+ return;+ }+ // g.Clip returns a copy that we own and must dispose.+ Region savedClip = g.Clip;+ try+ {+ g.SetClip(plot);+ using (Pen curvePen = new Pen(Color.FromArgb(255, 255, 208, 64), lineWidth))+ {+ curvePen.LineJoin = LineJoin.Round;+ g.DrawLines(curvePen, points.ToArray());+ }+ }+ finally+ {+ g.Clip = savedClip;+ savedClip.Dispose();+ }+ }++ /// <summary>+ /// Draws the title strip of the box: the readout right-aligned in its own colour, then the title+ /// left-aligned in the remaining width (ellipsis-trimmed), so the readout always stays visible.+ /// </summary>+ /// <param name="g">Target surface.</param>+ /// <param name="font">Title font.</param>+ /// <param name="bounds">Outer rectangle of the graph box.</param>+ /// <param name="title">Title text.</param>+ /// <param name="valueText">Readout from <see cref="ValueText"/>; empty draws no readout.</param>+ /// <param name="fontPx">Font height in pixels, used to size the text rectangles.</param>+ private static void DrawTitle(Graphics g, Font font, Rectangle bounds, string title, string valueText, float fontPx)+ {+ using (SolidBrush titleBrush = new SolidBrush(Color.FromArgb(240, 240, 240, 245)))+ {+ using (SolidBrush valueBrush = new SolidBrush(Color.FromArgb(255, 255, 208, 64)))+ {+ using (StringFormat valueFormat = new StringFormat())+ {+ using (StringFormat titleFormat = new StringFormat())+ {+ valueFormat.Alignment = StringAlignment.Far;+ valueFormat.FormatFlags = StringFormatFlags.NoWrap;+ titleFormat.Alignment = StringAlignment.Near;+ titleFormat.Trimming = StringTrimming.EllipsisCharacter;+ titleFormat.FormatFlags = StringFormatFlags.NoWrap;+ float valueWidth = 0f;+ if (valueText.Length > 0)+ {+ valueWidth = g.MeasureString(valueText, font).Width;+ g.DrawString(valueText, font, valueBrush, new RectangleF(bounds.Right - valueWidth - 8f, bounds.Y + 3, valueWidth + 4f, fontPx * 1.4f), valueFormat);+ }+ g.DrawString(title, font, titleBrush, new RectangleF(bounds.X + 6, bounds.Y + 3, Math.Max(10f, bounds.Width - valueWidth - 16f), fontPx * 1.4f), titleFormat);+ }+ }+ }+ }+ }++ /// <summary>+ /// Draws the probe position cross(es), the connecting line (line probes) and the index label onto a+ /// scaled canvas view, as used by the form's paint handlers where the canvas is shown zoomed in a picture+ /// box. Canvas pixel (x, y) maps to device position origin + (x + 0.5) * scale, i.e. the marker sits on+ /// the pixel centre. Point probes are labelled with the 1-based index, line probes with "nA" and "nB".+ /// </summary>+ /// <param name="g">Target surface.</param>+ /// <param name="probe">Probe whose positions (canvas pixels) and kind are drawn.</param>+ /// <param name="index">Zero-based probe index; shown as index + 1.</param>+ /// <param name="originX">Device x of the canvas origin.</param>+ /// <param name="originY">Device y of the canvas origin.</param>+ /// <param name="scaleX">Device pixels per canvas pixel, horizontally.</param>+ /// <param name="scaleY">Device pixels per canvas pixel, vertically.</param>+ public static void DrawMarkers(Graphics g, ProbeSettings probe, int index, float originX, float originY, float scaleX, float scaleY)+ {+ float ax = originX + (probe.PosAX + 0.5f) * scaleX;+ float ay = originY + (probe.PosAY + 0.5f) * scaleY;+ float bx = originX + (probe.PosBX + 0.5f) * scaleX;+ float by = originY + (probe.PosBY + 0.5f) * scaleY;+ bool isLine = probe.Kind == ProbeKind.Line;+ string label = (index + 1).ToString(CultureInfo.InvariantCulture);+ GraphicsState savedState = g.Save();+ try+ {+ g.SmoothingMode = SmoothingMode.AntiAlias;+ g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;+ using (Pen darkPen = new Pen(Color.FromArgb(210, 0, 0, 0), 3.5f))+ {+ using (Pen lightPen = new Pen(Color.White, 1.5f))+ {+ if (isLine)+ {+ g.DrawLine(darkPen, ax, ay, bx, by);+ g.DrawLine(lightPen, ax, ay, bx, by);+ }+ ProbeGraphPainter.DrawCross(g, darkPen, lightPen, ax, ay);+ if (isLine)+ {+ ProbeGraphPainter.DrawCross(g, darkPen, lightPen, bx, by);+ }+ }+ }+ using (Font font = new Font("Segoe UI", 13f, FontStyle.Bold, GraphicsUnit.Pixel))+ {+ using (SolidBrush shadowBrush = new SolidBrush(Color.FromArgb(220, 0, 0, 0)))+ {+ using (SolidBrush textBrush = new SolidBrush(Color.White))+ {+ if (isLine)+ {+ ProbeGraphPainter.DrawNumber(g, font, shadowBrush, textBrush, label + "A", ax, ay);+ ProbeGraphPainter.DrawNumber(g, font, shadowBrush, textBrush, label + "B", bx, by);+ }+ else+ {+ ProbeGraphPainter.DrawNumber(g, font, shadowBrush, textBrush, label, ax, ay);+ }+ }+ }+ }+ }+ finally+ {+ g.Restore(savedState);+ }+ }++ /// <summary>Draws a plus-shaped cross with 7-pixel arms centred on (x, y): the wide dark pen first as outline, then the thin light pen on top.</summary>+ private static void DrawCross(Graphics g, Pen dark, Pen light, float x, float y)+ {+ g.DrawLine(dark, x - 7f, y, x + 7f, y);+ g.DrawLine(dark, x, y - 7f, x, y + 7f);+ g.DrawLine(light, x - 7f, y, x + 7f, y);+ g.DrawLine(light, x, y - 7f, x, y + 7f);+ }++ /// <summary>Draws a marker label above and to the right of (x, y) with a 1-pixel dark drop shadow.</summary>+ private static void DrawNumber(Graphics g, Font font, Brush shadow, Brush textBrush, string text, float x, float y)+ {+ g.DrawString(text, font, shadow, x + 9f, y - 18f);+ g.DrawString(text, font, textBrush, x + 8f, y - 19f);+ }+ }+}diff --git a/Wave_Dude_2D/ProbeKind.cs b/Wave_Dude_2D/ProbeKind.csnew file mode 100644index 0000000..55ee133--- /dev/null+++ b/Wave_Dude_2D/ProbeKind.cs@@ -0,0 +1,14 @@+namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Geometry of a probe. Stored in <see cref="ProbeSettings.Kind"/>; the numeric value is the+ /// index of the "probe type" combo box on the Probes tab, so the order must not change.+ /// </summary>+ public enum ProbeKind+ {+ /// <summary>Samples the single canvas pixel at position A once per simulation step, producing a time series.</summary>+ Point,+ /// <summary>Samples every pixel on the Bresenham line from A to B, producing a profile along the line (no time axis).</summary>+ Line+ }+}diff --git a/Wave_Dude_2D/ProbeMeasurement.cs b/Wave_Dude_2D/ProbeMeasurement.csnew file mode 100644index 0000000..6358e14--- /dev/null+++ b/Wave_Dude_2D/ProbeMeasurement.cs@@ -0,0 +1,21 @@+namespace _2D_wave_sim_V01+{+ /// <summary>+ /// The quantity a probe records. Which values are allowed depends on <see cref="ProbePlaceOn"/>+ /// (see <see cref="ProbeSettings.Normalize"/>). The engine treats every value above+ /// <see cref="Amplitude"/> as "read from the intensity buffer" (<c>ProbeSampler.UseIntensity</c>).+ /// </summary>+ public enum ProbeMeasurement+ {+ /// <summary>The instantaneous field value (wave amplitude, signed) at the probe pixel(s).</summary>+ Amplitude,+ /// <summary>The current value of the engine's running (exponentially decayed) intensity buffer at the probe pixel(s).</summary>+ Intensity,+ /// <summary>+ /// Intensity summed over simulation steps. For a point probe the running sum is formed in+ /// <c>ProbeCollector</c>; for a line probe the engine keeps per-pixel totals. Accumulation+ /// starts at <see cref="ProbeSettings.StartAfterStep"/> when that option is enabled.+ /// </summary>+ IntegratedIntensity+ }+}diff --git a/Wave_Dude_2D/ProbeOverlay.cs b/Wave_Dude_2D/ProbeOverlay.csnew file mode 100644index 0000000..c8c2e12--- /dev/null+++ b/Wave_Dude_2D/ProbeOverlay.cs@@ -0,0 +1,270 @@+using System;+using System.Collections.Generic;+using System.Drawing;+using System.Drawing.Imaging;+using System.Drawing.Text;+using System.Globalization;+using System.Runtime.InteropServices;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Burns probe markers and probe graph boxes directly into a 32-bit ARGB pixel buffer, for frames that go+ /// to a video sink or into the final result and therefore have no on-screen Graphics surface. Called by+ /// <c>SimulationRunner</c> on the simulation worker thread with the collector's traces+ /// (<see cref="ProbeCollector.Traces"/>); also from the UI thread through+ /// <c>SimulationRunner.RenderCurrentFrame</c>, but only while the worker is parked at the pause gate, so+ /// the traces are never read while they are being written.+ /// </summary>+ internal sealed class ProbeOverlay+ {+ private ProbeOverlay()+ {+ }++ /// <summary>+ /// Draws the markers and, where the box is at least 60 x 30 pixels, the graph of every active probe placed+ /// on <paramref name="placeOn"/> into <paramref name="pixels"/>. Graphs are rendered by+ /// <see cref="ProbeGraphPainter.DrawGraph"/> into a temporary premultiplied bitmap and alpha-blended in.+ /// </summary>+ /// <param name="pixels">Opaque ARGB frame, row-major, index y * w + x; modified in place.</param>+ /// <param name="w">Frame width in pixels (equals the canvas width).</param>+ /// <param name="h">Frame height in pixels.</param>+ /// <param name="probes">Run probe list.</param>+ /// <param name="traces">Trace per probe, index parallel to <paramref name="probes"/>.</param>+ /// <param name="placeOn">Surface this frame shows; only probes placed on it are drawn.</param>+ /// <param name="totalSteps">Total steps of the run, for the x-axis of full-scale series graphs.</param>+ public static void Burn(int[] pixels, int w, int h, IList<ProbeSettings> probes, ProbeTrace[] traces, ProbePlaceOn placeOn, int totalSteps)+ {+ for (int i = 0; i < probes.Count; i++)+ {+ ProbeSettings probe = probes[i];+ if (probe.PlaceOn != placeOn || !probe.Active)+ {+ continue;+ }+ ProbeOverlay.DrawMarkerPixels(pixels, w, h, probe, i);+ Rectangle box = ProbeGraphPainter.BoxInCanvas(probe, w, h);+ if (box.Width < 60 || box.Height < 30)+ {+ continue;+ }+ using (Bitmap graphBitmap = new Bitmap(box.Width, box.Height, PixelFormat.Format32bppPArgb))+ {+ using (Graphics g = Graphics.FromImage(graphBitmap))+ {+ g.Clear(Color.Transparent);+ ProbeGraphPainter.DrawGraph(g, new Rectangle(0, 0, box.Width, box.Height), probe.Title(i), probe, traces[i], totalSteps);+ }+ ProbeOverlay.Blend(pixels, w, h, graphBitmap, box);+ }+ }+ }++ /// <summary>+ /// Alpha-blends a premultiplied-ARGB bitmap onto the pixel buffer with its top-left corner at the position+ /// of <paramref name="rect"/> (buffer coordinates); parts outside the buffer are clipped. Fully transparent+ /// source pixels are skipped, result pixels are always opaque.+ /// </summary>+ private static void Blend(int[] pixels, int w, int h, Bitmap bmp, Rectangle rect)+ {+ BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb);+ try+ {+ int[] row = new int[bmp.Width];+ for (int i = 0; i < bmp.Height; i++)+ {+ int y = rect.Y + i;+ if (y < 0 || y >= h)+ {+ continue;+ }+ Marshal.Copy(IntPtr.Add(data.Scan0, i * data.Stride), row, 0, bmp.Width);+ for (int j = 0; j < bmp.Width; j++)+ {+ int x = rect.X + j;+ if (x < 0 || x >= w)+ {+ continue;+ }+ int src = row[j];+ int alpha = (src >> 24) & 255;+ if (alpha == 0)+ {+ continue;+ }+ int index = y * w + x;+ if (alpha == 255)+ {+ pixels[index] = src | unchecked((int)0xFF000000);+ }+ else+ {+ // src is premultiplied: out = src + dst * (1 - alpha), rounded to nearest+ int dst = pixels[index];+ int inverseAlpha = 255 - alpha;+ int r = Math.Min(255, ((src >> 16) & 255) + (((dst >> 16) & 255) * inverseAlpha + 127) / 255);+ int gr = Math.Min(255, ((src >> 8) & 255) + (((dst >> 8) & 255) * inverseAlpha + 127) / 255);+ int b = Math.Min(255, (src & 255) + ((dst & 255) * inverseAlpha + 127) / 255);+ pixels[index] = unchecked((int)0xFF000000) | (r << 16) | (gr << 8) | b;+ }+ }+ }+ }+ finally+ {+ bmp.UnlockBits(data);+ }+ }++ /// <summary>+ /// Draws the probe cross(es) and, for line probes, the connecting line in two passes (a black outline, then+ /// a thinner white core), followed by the 1-based index label ("nA"/"nB" for line probes) above and to the+ /// right of each cross. Arm length and font size scale with the frame height.+ /// </summary>+ /// <param name="pixels">Opaque ARGB frame, modified in place.</param>+ /// <param name="w">Frame width in pixels.</param>+ /// <param name="h">Frame height in pixels.</param>+ /// <param name="probe">Probe whose positions (canvas pixels) and kind are drawn.</param>+ /// <param name="index">Zero-based probe index; shown as index + 1.</param>+ private static void DrawMarkerPixels(int[] pixels, int w, int h, ProbeSettings probe, int index)+ {+ int arm = Math.Max(6, h / 120);+ bool isLine = probe.Kind == ProbeKind.Line;+ for (int pass = 0; pass <= 1; pass++)+ {+ int color = (pass == 0) ? unchecked((int)0xFF000000) : unchecked((int)0xFFFFFFFF);+ int radius = (pass == 0) ? 2 : 1;+ if (isLine)+ {+ ProbeOverlay.DrawThickLine(pixels, w, h, probe.PosAX, probe.PosAY, probe.PosBX, probe.PosBY, color, radius);+ }+ ProbeOverlay.DrawCrossPixels(pixels, w, h, probe.PosAX, probe.PosAY, arm, color, radius);+ if (isLine)+ {+ ProbeOverlay.DrawCrossPixels(pixels, w, h, probe.PosBX, probe.PosBY, arm, color, radius);+ }+ }+ string label = (index + 1).ToString(CultureInfo.InvariantCulture);+ float fontPx = Math.Max(12f, h / 60f);+ if (isLine)+ {+ ProbeOverlay.BurnLabel(pixels, w, h, label + "A", probe.PosAX + arm + 2, probe.PosAY - arm - (int)Math.Round(fontPx * 1.4f), fontPx);+ ProbeOverlay.BurnLabel(pixels, w, h, label + "B", probe.PosBX + arm + 2, probe.PosBY - arm - (int)Math.Round(fontPx * 1.4f), fontPx);+ }+ else+ {+ ProbeOverlay.BurnLabel(pixels, w, h, label, probe.PosAX + arm + 2, probe.PosAY - arm - (int)Math.Round(fontPx * 1.4f), fontPx);+ }+ }++ /// <summary>+ /// Renders <paramref name="text"/> with a drop shadow into a temporary bitmap (sized with a throwaway 1 x 1+ /// measuring bitmap) and blends it in with its top-left corner at (<paramref name="x"/>, <paramref name="y"/>)+ /// in buffer coordinates.+ /// </summary>+ /// <param name="pixels">Opaque ARGB frame, modified in place.</param>+ /// <param name="w">Frame width in pixels.</param>+ /// <param name="h">Frame height in pixels.</param>+ /// <param name="text">Label text.</param>+ /// <param name="x">Left edge of the label in buffer pixels.</param>+ /// <param name="y">Top edge of the label in buffer pixels.</param>+ /// <param name="fontPx">Font height in pixels.</param>+ private static void BurnLabel(int[] pixels, int w, int h, string text, int x, int y, float fontPx)+ {+ using (Font font = new Font("Segoe UI", fontPx, FontStyle.Bold, GraphicsUnit.Pixel))+ {+ int labelWidth;+ int labelHeight;+ using (Bitmap measureBitmap = new Bitmap(1, 1))+ {+ using (Graphics measureGraphics = Graphics.FromImage(measureBitmap))+ {+ SizeF textSize = measureGraphics.MeasureString(text, font);+ labelWidth = (int)Math.Ceiling(textSize.Width) + 4;+ labelHeight = (int)Math.Ceiling(textSize.Height) + 4;+ }+ }+ using (Bitmap labelBitmap = new Bitmap(labelWidth, labelHeight, PixelFormat.Format32bppPArgb))+ {+ using (Graphics g = Graphics.FromImage(labelBitmap))+ {+ g.Clear(Color.Transparent);+ g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;+ using (SolidBrush shadowBrush = new SolidBrush(Color.FromArgb(220, 0, 0, 0)))+ {+ using (SolidBrush textBrush = new SolidBrush(Color.White))+ {+ g.DrawString(text, font, shadowBrush, 3f, 3f);+ g.DrawString(text, font, textBrush, 2f, 2f);+ }+ }+ }+ ProbeOverlay.Blend(pixels, w, h, labelBitmap, new Rectangle(x, y, labelWidth, labelHeight));+ }+ }+ }++ /// <summary>Draws a plus-shaped cross centred on (x, y) with arms of <paramref name="arm"/> pixels, using <see cref="DrawThickLine"/>.</summary>+ private static void DrawCrossPixels(int[] pixels, int w, int h, int x, int y, int arm, int color, int radius)+ {+ ProbeOverlay.DrawThickLine(pixels, w, h, x - arm, y, x + arm, y, color, radius);+ ProbeOverlay.DrawThickLine(pixels, w, h, x, y - arm, x, y + arm, color, radius);+ }++ /// <summary>+ /// Bresenham line from (x0, y0) to (x1, y1), both inclusive, stamped with a square brush of side+ /// 2 * <paramref name="radius"/> + 1; pixels outside the buffer are skipped. Gives up after 100000 steps+ /// as a safety net against runaway coordinates.+ /// </summary>+ /// <param name="pixels">Opaque ARGB frame, modified in place.</param>+ /// <param name="w">Frame width in pixels.</param>+ /// <param name="h">Frame height in pixels.</param>+ /// <param name="x0">Start x in buffer pixels.</param>+ /// <param name="y0">Start y in buffer pixels.</param>+ /// <param name="x1">End x in buffer pixels.</param>+ /// <param name="y1">End y in buffer pixels.</param>+ /// <param name="color">ARGB value written to every covered pixel (no blending).</param>+ /// <param name="radius">Brush half-width in pixels; 0 draws a one-pixel line.</param>+ private static void DrawThickLine(int[] pixels, int w, int h, int x0, int y0, int x1, int y1, int color, int radius)+ {+ int dx = Math.Abs(x1 - x0);+ int dy = -Math.Abs(y1 - y0);+ int stepX = (x0 < x1) ? 1 : -1;+ int stepY = (y0 < y1) ? 1 : -1;+ int error = dx + dy;+ int iterations = 0;+ while (true)+ {+ for (int oy = -radius; oy <= radius; oy++)+ {+ for (int ox = -radius; ox <= radius; ox++)+ {+ int px = x0 + ox;+ int py = y0 + oy;+ if (px >= 0 && px < w && py >= 0 && py < h)+ {+ pixels[py * w + px] = color;+ }+ }+ }+ if ((x0 == x1 && y0 == y1) || iterations > 100000)+ {+ break;+ }+ iterations++;+ int error2 = 2 * error;+ if (error2 >= dy)+ {+ error += dy;+ x0 += stepX;+ }+ if (error2 <= dx)+ {+ error += dx;+ y0 += stepY;+ }+ }+ }+ }+}diff --git a/Wave_Dude_2D/ProbePlaceOn.cs b/Wave_Dude_2D/ProbePlaceOn.csnew file mode 100644index 0000000..1b6c810--- /dev/null+++ b/Wave_Dude_2D/ProbePlaceOn.cs@@ -0,0 +1,15 @@+namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Which simulation output a probe belongs to: it decides both the buffer that is sampled and+ /// the preview picture / exported video on which the probe markers and graph box are drawn.+ /// The numeric value is the index of the "place on" combo box on the Probes tab.+ /// </summary>+ public enum ProbePlaceOn+ {+ /// <summary>The wave field (amplitude) output. Only <see cref="ProbeMeasurement.Amplitude"/> is valid here.</summary>+ Field,+ /// <summary>The intensity output. Allows <see cref="ProbeMeasurement.Intensity"/> and <see cref="ProbeMeasurement.IntegratedIntensity"/>.</summary>+ Intensity+ }+}diff --git a/Wave_Dude_2D/ProbeSampler.cs b/Wave_Dude_2D/ProbeSampler.csnew file mode 100644index 0000000..9479e42--- /dev/null+++ b/Wave_Dude_2D/ProbeSampler.cs@@ -0,0 +1,192 @@+using System;+using System.Collections.Generic;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Precomputed per-probe pixel indices (into the padded field grid, see <see cref="IWaveEngine"/>) and+ /// sampling flags. Built once per run by <see cref="Build"/> on the simulation worker thread from the run's+ /// probe list and canvas size, then handed to the engine (<see cref="IWaveEngine.SetProbes"/>) and to the+ /// <see cref="ProbeCollector"/>. All per-probe arrays are indexed by the probe's position in that list.+ /// Immutable after construction, so it may be read from any thread.+ /// </summary>+ internal sealed class ProbeSampler+ {+ /// <summary>Stores the per-probe arrays and derives the aggregate <see cref="NeedsIntensity"/>, <see cref="HasSeries"/> and <see cref="HasProfiles"/> flags.</summary>+ private ProbeSampler(int[][] pixels, bool[] isProfile, bool[] useIntensity, bool[] cumulative, bool[] integrate, double[] lengths, bool[] useStartAfterStep, int[] startAfterStep)+ {+ this.Count = pixels.Length;+ this.Pixels = pixels;+ this.IsProfile = isProfile;+ this.UseIntensity = useIntensity;+ this.Cumulative = cumulative;+ this.Integrate = integrate;+ this.Lengths = lengths;+ this.UseStartAfterStep = useStartAfterStep;+ this.StartAfterStep = startAfterStep;+ for (int i = 0; i < this.Count; i++)+ {+ if (useIntensity[i])+ {+ this.NeedsIntensity = true;+ }+ if (isProfile[i])+ {+ this.HasProfiles = true;+ }+ else+ {+ this.HasSeries = true;+ }+ }+ }++ /// <summary>+ /// Builds the sampler for a canvas of <paramref name="w"/> x <paramref name="h"/> pixels. Probe positions+ /// are clamped into the canvas; point probes get a single pixel index, line probes the Bresenham path from+ /// A to B. The padded grid stride is <paramref name="w"/> + 2.+ /// </summary>+ /// <param name="probes">Run probe list; the per-probe arrays of the result use the same order.</param>+ /// <param name="w">Canvas width in pixels.</param>+ /// <param name="h">Canvas height in pixels.</param>+ public static ProbeSampler Build(IList<ProbeSettings> probes, int w, int h)+ {+ int count = probes.Count;+ int[][] pixels = new int[count][];+ bool[] isProfile = new bool[count];+ bool[] useIntensity = new bool[count];+ bool[] cumulative = new bool[count];+ bool[] integrate = new bool[count];+ double[] lengths = new double[count];+ bool[] useStartAfterStep = new bool[count];+ int[] startAfterStep = new int[count];+ int stride = w + 2;+ for (int i = 0; i < count; i++)+ {+ ProbeSettings probe = probes[i];+ int ax = ProbeSampler.Clamp(probe.PosAX, w - 1);+ int ay = ProbeSampler.Clamp(probe.PosAY, h - 1);+ bool isIntegrated = probe.Measurement == ProbeMeasurement.IntegratedIntensity;+ if (probe.Kind == ProbeKind.Line)+ {+ int bx = ProbeSampler.Clamp(probe.PosBX, w - 1);+ int by = ProbeSampler.Clamp(probe.PosBY, h - 1);+ pixels[i] = ProbeSampler.LinePixels(ax, ay, bx, by, stride);+ isProfile[i] = true;+ integrate[i] = isIntegrated;+ double dx = bx - ax;+ double dy = by - ay;+ lengths[i] = Math.Sqrt(dx * dx + dy * dy);+ }+ else+ {+ pixels[i] = new int[] { (ay + 1) * stride + ax + 1 };+ cumulative[i] = isIntegrated;+ }+ // Intensity and IntegratedIntensity both read the intensity buffer.+ useIntensity[i] = probe.Measurement > ProbeMeasurement.Amplitude;+ useStartAfterStep[i] = probe.UseStartAfterStep;+ startAfterStep[i] = probe.StartAfterStep;+ }+ return new ProbeSampler(pixels, isProfile, useIntensity, cumulative, integrate, lengths, useStartAfterStep, startAfterStep);+ }++ /// <summary>Clamps <paramref name="value"/> into [0, <paramref name="maxValue"/>].</summary>+ private static int Clamp(int value, int maxValue)+ {+ if (value < 0)+ {+ return 0;+ }+ if (value > maxValue)+ {+ return maxValue;+ }+ return value;+ }++ /// <summary>Bresenham walk from (x0, y0) to (x1, y1), both inclusive, returning padded-grid indices in walking order (A first).</summary>+ /// <param name="x0">Start x in canvas pixels.</param>+ /// <param name="y0">Start y in canvas pixels.</param>+ /// <param name="x1">End x in canvas pixels.</param>+ /// <param name="y1">End y in canvas pixels.</param>+ /// <param name="stride">Row length of the padded grid (canvas width + 2).</param>+ private static int[] LinePixels(int x0, int y0, int x1, int y1, int stride)+ {+ List<int> indices = new List<int>();+ int dx = Math.Abs(x1 - x0);+ int dy = -Math.Abs(y1 - y0);+ int stepX = (x0 < x1) ? 1 : -1;+ int stepY = (y0 < y1) ? 1 : -1;+ int err = dx + dy;+ while (true)+ {+ indices.Add((y0 + 1) * stride + x0 + 1);+ if (x0 == x1 && y0 == y1)+ {+ break;+ }+ int e2 = 2 * err;+ if (e2 >= dy)+ {+ err += dy;+ x0 += stepX;+ }+ if (e2 <= dx)+ {+ err += dx;+ y0 += stepY;+ }+ }+ return indices.ToArray();+ }++ /// <summary>+ /// Reads the current value of a point probe from a padded-grid buffer. Used by the CPU engine+ /// (<c>WaveSimulator.SampleProbes</c>) on the worker thread after every step.+ /// </summary>+ /// <param name="probeIndex">Index of a point probe.</param>+ /// <param name="data">Padded field or intensity buffer, chosen by the caller according to <see cref="UseIntensity"/>.</param>+ /// <returns>The value at the probe's first pixel, or 0 when <paramref name="data"/> is null.</returns>+ public float Compute(int probeIndex, float[] data)+ {+ return (data == null) ? 0f : data[this.Pixels[probeIndex][0]];+ }++ /// <summary>Number of probes; the length of every per-probe array.</summary>+ public readonly int Count;++ /// <summary>Per probe: indices into the padded field/intensity buffer. A single entry for point probes, the whole A-to-B pixel path for line probes.</summary>+ public readonly int[][] Pixels;++ /// <summary>Per probe: true for line probes (which deliver a profile), false for point probes (which deliver a time series).</summary>+ public readonly bool[] IsProfile;++ /// <summary>Per probe: true when the measurement is Intensity or IntegratedIntensity, i.e. the intensity buffer is sampled instead of the field.</summary>+ public readonly bool[] UseIntensity;++ /// <summary>Per probe: point probe with IntegratedIntensity; <see cref="ProbeCollector.Collect"/> turns its per-step intensity samples into a running sum.</summary>+ public readonly bool[] Cumulative;++ /// <summary>Per probe: line probe with IntegratedIntensity; the engine accumulates per-pixel intensity totals over the steps.</summary>+ public readonly bool[] Integrate;++ /// <summary>Per probe: Euclidean length of the (clamped) probe line in canvas pixels; 0 for point probes.</summary>+ public readonly double[] Lengths;++ /// <summary>True when any probe samples the intensity; the runner then forces intensity tracking on in the engine.</summary>+ public readonly bool NeedsIntensity;++ /// <summary>True when at least one point probe exists.</summary>+ public readonly bool HasSeries;++ /// <summary>True when at least one line probe exists.</summary>+ public readonly bool HasProfiles;++ /// <summary>Per probe: whether integrated measurements only start counting at <see cref="StartAfterStep"/>.</summary>+ public readonly bool[] UseStartAfterStep;++ /// <summary>Per probe: step number before which integrated measurements are ignored; only meaningful when <see cref="UseStartAfterStep"/> is set.</summary>+ public readonly int[] StartAfterStep;+ }+}diff --git a/Wave_Dude_2D/ProbeScaleMode.cs b/Wave_Dude_2D/ProbeScaleMode.csnew file mode 100644index 0000000..0e9533b--- /dev/null+++ b/Wave_Dude_2D/ProbeScaleMode.cs@@ -0,0 +1,15 @@+namespace _2D_wave_sim_V01+{+ /// <summary>+ /// How the X (step) axis of a point probe's time-series graph is chosen; see+ /// <c>ProbeGraphPainter.ComputeRanges</c>. Line probes ignore it (their X axis is the+ /// distance along the line) and the UI disables the radio buttons for them.+ /// </summary>+ public enum ProbeScaleMode+ {+ /// <summary>Shows a sliding window of the last <see cref="ProbeSettings.RunningWindow"/> steps.</summary>+ Running,+ /// <summary>Shows the whole run: from the start step to the total step count (or to the samples so far when <see cref="ProbeSettings.AutoScaleX"/> is set).</summary>+ Full+ }+}diff --git a/Wave_Dude_2D/ProbeSeries.cs b/Wave_Dude_2D/ProbeSeries.csnew file mode 100644index 0000000..75dcfa3--- /dev/null+++ b/Wave_Dude_2D/ProbeSeries.cs@@ -0,0 +1,76 @@+using System;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Growable buffer of sampled probe values, one per simulation step, in step order. Not thread-safe: each+ /// instance belongs to one <see cref="ProbeTrace"/> and is only touched by that trace's owning thread.+ /// </summary>+ internal sealed class ProbeSeries+ {+ public ProbeSeries()+ {+ this._values = new float[1024];+ }++ /// <summary>Number of valid values; only the first <see cref="Count"/> entries of <see cref="Values"/> are meaningful.</summary>+ public int Count+ {+ get+ {+ return this._count;+ }+ }++ /// <summary>+ /// Backing array, exposed without copying. Its length is the capacity, not the sample count, so read only+ /// indices below <see cref="Count"/>. The reference changes whenever the buffer grows.+ /// </summary>+ public float[] Values+ {+ get+ {+ return this._values;+ }+ }++ /// <summary>Most recently added value, or NaN when the series is empty.</summary>+ public float LastValue+ {+ get+ {+ return this._count == 0 ? float.NaN : this._values[this._count - 1];+ }+ }++ /// <summary>Appends values in step order, at least doubling the backing array when it is full. Null or empty input is ignored.</summary>+ public void Add(float[] items)+ {+ if (items == null || items.Length == 0)+ {+ return;+ }+ int newCount = this._count + items.Length;+ if (newCount > this._values.Length)+ {+ float[] grown = new float[Math.Max(newCount, this._values.Length * 2)];+ Array.Copy(this._values, grown, this._count);+ this._values = grown;+ }+ Array.Copy(items, 0, this._values, this._count, items.Length);+ this._count = newCount;+ }++ /// <summary>Discards all values but keeps the allocated storage.</summary>+ public void Clear()+ {+ this._count = 0;+ }++ /// <summary>Backing storage; starts at 1024 entries, grows by at least doubling and never shrinks.</summary>+ private float[] _values;++ /// <summary>Number of valid entries at the start of <see cref="_values"/>.</summary>+ private int _count;+ }+}diff --git a/Wave_Dude_2D/ProbeSettings.cs b/Wave_Dude_2D/ProbeSettings.csnew file mode 100644index 0000000..8ef053f--- /dev/null+++ b/Wave_Dude_2D/ProbeSettings.cs@@ -0,0 +1,423 @@+using System;+using System.Collections;+using System.Collections.Generic;+using System.Globalization;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// User-editable configuration of one probe: where it measures, what it measures and how its+ /// graph is shown. Edited on the Probes tab (<c>Form1.Probes.cs</c>), persisted in the project+ /// config (<see cref="ListToConfig"/> / <see cref="ListFromConfig"/>) and handed to the+ /// simulation as a <see cref="Clone"/> so the worker thread never sees the copy being edited.+ /// All positions are canvas pixels (0-based column/row of the simulation grid, origin top-left).+ /// </summary>+ public sealed class ProbeSettings+ {+ /// <summary>Creates an inactive point probe on the field at (100,100) with a medium graph box at (450,20) and auto scaling on both axes.</summary>+ public ProbeSettings()+ {+ this.PlaceOn = ProbePlaceOn.Field;+ this.Measurement = ProbeMeasurement.Amplitude;+ this.Kind = ProbeKind.Point;+ this.PosAX = 100;+ this.PosAY = 100;+ this.PosBX = 300;+ this.PosBY = 100;+ this.BoxSize = ProbeBoxSize.Medium;+ this.BoxX = 450;+ this.BoxY = 20;+ this.Active = false;+ this.ScaleMode = ProbeScaleMode.Running;+ this.AutoScaleX = true;+ this.AutoScaleY = true;+ this.YMin = -1.0;+ this.YMax = 1.0;+ this.RunningWindow = ProbeSettings.DefaultRunningWindow;+ this.UseStartAfterStep = false;+ this.StartAfterStep = 0;+ }++ /// <summary>Gets or sets the output (field or intensity) the probe samples and is drawn on.</summary>+ public ProbePlaceOn PlaceOn { get; set; }++ /// <summary>Gets or sets the recorded quantity. Must be consistent with <see cref="PlaceOn"/>; <see cref="Normalize"/> enforces that.</summary>+ public ProbeMeasurement Measurement { get; set; }++ /// <summary>Gets or sets whether this is a point probe (A only) or a line probe (A to B).</summary>+ public ProbeKind Kind { get; set; }++ /// <summary>Gets or sets the X of position A in canvas pixels (the probe pixel, or the start of the line).</summary>+ public int PosAX { get; set; }++ /// <summary>Gets or sets the Y of position A in canvas pixels.</summary>+ public int PosAY { get; set; }++ /// <summary>Gets or sets the X of position B in canvas pixels (end of the line; unused for point probes).</summary>+ public int PosBX { get; set; }++ /// <summary>Gets or sets the Y of position B in canvas pixels (end of the line; unused for point probes).</summary>+ public int PosBY { get; set; }++ /// <summary>Gets or sets the nominal size of the graph box drawn over the output picture.</summary>+ public ProbeBoxSize BoxSize { get; set; }++ /// <summary>Gets or sets the left edge of the graph box in canvas pixels. May lie outside the canvas; the painter clamps the box to stay inside.</summary>+ public int BoxX { get; set; }++ /// <summary>Gets or sets the top edge of the graph box in canvas pixels (clamped by the painter like <see cref="BoxX"/>).</summary>+ public int BoxY { get; set; }++ /// <summary>Gets or sets whether the probe is sampled and drawn at all.</summary>+ public bool Active { get; set; }++ /// <summary>Gets or sets how the step axis of a point probe's time series is chosen; ignored for line probes.</summary>+ public ProbeScaleMode ScaleMode { get; set; }++ /// <summary>Gets or sets whether the step axis follows the samples recorded so far instead of the full step count / window; ignored for line probes.</summary>+ public bool AutoScaleX { get; set; }++ /// <summary>Gets or sets whether the value axis is fitted to the visible data; when false <see cref="YMin"/>/<see cref="YMax"/> are used.</summary>+ public bool AutoScaleY { get; set; }++ /// <summary>Gets or sets the lower bound of the value axis, in the units of <see cref="Measurement"/>. Only used when <see cref="AutoScaleY"/> is false.</summary>+ public double YMin { get; set; }++ /// <summary>Gets or sets the upper bound of the value axis; must be greater than <see cref="YMin"/> or <see cref="Normalize"/> resets both to -1..1.</summary>+ public double YMax { get; set; }++ /// <summary>Gets or sets the width of the sliding step window for <see cref="ProbeScaleMode.Running"/>, in simulation steps (10 .. <see cref="MaxRunningWindow"/>).</summary>+ public int RunningWindow { get; set; }++ /// <summary>Gets or sets whether sampling/accumulation and the graph are gated until <see cref="StartAfterStep"/> is reached.</summary>+ public bool UseStartAfterStep { get; set; }++ /// <summary>Gets or sets the simulation step (0-based, never negative) at which recording starts when <see cref="UseStartAfterStep"/> is set.</summary>+ public int StartAfterStep { get; set; }++ /// <summary>Returns an independent copy. All members are value types, so the memberwise clone is a full copy.</summary>+ public ProbeSettings Clone()+ {+ return (ProbeSettings)base.MemberwiseClone();+ }++ /// <summary>+ /// Copies only the graph/display settings (active flag, box size and position, scaling, Y range,+ /// running window, start-after gating) from <paramref name="other"/>, leaving position, kind and+ /// measurement untouched. Used to show a running simulation's probes with the display settings+ /// the user is editing right now.+ /// </summary>+ public void CopyDisplayFrom(ProbeSettings other)+ {+ this.Active = other.Active;+ this.BoxSize = other.BoxSize;+ this.BoxX = other.BoxX;+ this.BoxY = other.BoxY;+ this.ScaleMode = other.ScaleMode;+ this.AutoScaleX = other.AutoScaleX;+ this.AutoScaleY = other.AutoScaleY;+ this.YMin = other.YMin;+ this.YMax = other.YMax;+ this.RunningWindow = other.RunningWindow;+ this.UseStartAfterStep = other.UseStartAfterStep;+ this.StartAfterStep = other.StartAfterStep;+ }++ /// <summary>+ /// Forces the settings into a consistent state: the field only allows+ /// <see cref="ProbeMeasurement.Amplitude"/>, the intensity output never does (amplitude is+ /// turned into <see cref="ProbeMeasurement.Intensity"/>); an empty or inverted Y range becomes+ /// -1..1; <see cref="RunningWindow"/> is clamped to 10..<see cref="MaxRunningWindow"/> and+ /// <see cref="StartAfterStep"/> to zero or more.+ /// </summary>+ public void Normalize()+ {+ if (this.PlaceOn == ProbePlaceOn.Field)+ {+ this.Measurement = ProbeMeasurement.Amplitude;+ }+ else if (this.Measurement == ProbeMeasurement.Amplitude)+ {+ this.Measurement = ProbeMeasurement.Intensity;+ }+ if (this.YMax <= this.YMin)+ {+ this.YMin = -1.0;+ this.YMax = 1.0;+ }+ if (this.RunningWindow < 10)+ {+ this.RunningWindow = 10;+ }+ if (this.RunningWindow > ProbeSettings.MaxRunningWindow)+ {+ this.RunningWindow = ProbeSettings.MaxRunningWindow;+ }+ if (this.StartAfterStep < 0)+ {+ this.StartAfterStep = 0;+ }+ }++ /// <summary>The UI label of <see cref="Measurement"/> ("Amplitude", "Intensity" or "Integrated intensity").</summary>+ public string MeasurementText()+ {+ switch (this.Measurement)+ {+ case ProbeMeasurement.Amplitude:+ return "Amplitude";+ case ProbeMeasurement.IntegratedIntensity:+ return "Integrated intensity";+ default:+ return "Intensity";+ }+ }++ /// <summary>Title shown in the graph box, e.g. "Probe 1 - Amplitude".</summary>+ /// <param name="index">0-based probe index; the title shows it 1-based.</param>+ public string Title(int index)+ {+ return "Probe " + (index + 1).ToString(CultureInfo.InvariantCulture) + " - " + this.MeasurementText();+ }++ /// <summary>+ /// Reads the probe list from the <c>probes</c> section of a project config. Entries in the+ /// section's <c>items</c> list that are not dictionaries are skipped; each read probe is+ /// normalized. Never returns an empty list: a single default probe is returned when the+ /// section is missing or holds no usable entries.+ /// </summary>+ public static List<ProbeSettings> ListFromConfig(ProjectConfig config)+ {+ List<ProbeSettings> probes = new List<ProbeSettings>();+ if (config.ContainsKey(ProbeSettings.SectionName))+ {+ Dictionary<string, object> section = config.GetSection(ProbeSettings.SectionName);+ object items;+ if (section.TryGetValue("items", out items))+ {+ IEnumerable sequence = items as IEnumerable;+ if (sequence != null && !(items is string))+ {+ foreach (object entry in sequence)+ {+ Dictionary<string, object> values = entry as Dictionary<string, object>;+ if (values != null)+ {+ probes.Add(ProbeSettings.FromDictionary(values));+ }+ }+ }+ }+ }+ if (probes.Count == 0)+ {+ probes.Add(new ProbeSettings());+ }+ return probes;+ }++ /// <summary>Writes <paramref name="probes"/> into the <c>probes</c> section of <paramref name="config"/> as <c>count</c> plus an <c>items</c> list of dictionaries.</summary>+ public static void ListToConfig(List<ProbeSettings> probes, ProjectConfig config)+ {+ Dictionary<string, object> section = config.GetSection(ProbeSettings.SectionName);+ List<object> items = new List<object>();+ foreach (ProbeSettings probe in probes)+ {+ items.Add(probe.ToDictionary());+ }+ section["count"] = items.Count;+ section["items"] = items;+ }++ /// <summary>+ /// Serializes the probe to the config dictionary form. Enum values are stored as lower-case+ /// snake_case strings (<c>field</c>/<c>intensity</c>, <c>amplitude</c>/<c>intensity</c>/+ /// <c>integrated_intensity</c>, <c>point</c>/<c>line</c>, <c>tiny</c>..<c>extra_large</c>,+ /// <c>running</c>/<c>full</c>); numbers and booleans as-is.+ /// </summary>+ private Dictionary<string, object> ToDictionary()+ {+ Dictionary<string, object> values = new Dictionary<string, object>();+ values["active"] = this.Active;+ values["place_on"] = ((this.PlaceOn == ProbePlaceOn.Field) ? "field" : "intensity");+ switch (this.Measurement)+ {+ case ProbeMeasurement.Amplitude:+ values["measurement"] = "amplitude";+ break;+ case ProbeMeasurement.IntegratedIntensity:+ values["measurement"] = "integrated_intensity";+ break;+ default:+ values["measurement"] = "intensity";+ break;+ }+ values["probe_type"] = ((this.Kind == ProbeKind.Line) ? "line" : "point");+ values["ax"] = this.PosAX;+ values["ay"] = this.PosAY;+ values["bx"] = this.PosBX;+ values["by"] = this.PosBY;+ switch (this.BoxSize)+ {+ case ProbeBoxSize.Tiny:+ values["box_size"] = "tiny";+ break;+ case ProbeBoxSize.Small:+ values["box_size"] = "small";+ break;+ case ProbeBoxSize.Large:+ values["box_size"] = "large";+ break;+ case ProbeBoxSize.ExtraLarge:+ values["box_size"] = "extra_large";+ break;+ default:+ values["box_size"] = "medium";+ break;+ }+ values["box_x"] = this.BoxX;+ values["box_y"] = this.BoxY;+ values["scale_mode"] = ((this.ScaleMode == ProbeScaleMode.Full) ? "full" : "running");+ values["auto_scale_x"] = this.AutoScaleX;+ values["auto_scale_y"] = this.AutoScaleY;+ values["y_min"] = this.YMin;+ values["y_max"] = this.YMax;+ values["running_window"] = this.RunningWindow;+ values["use_start_after_step"] = this.UseStartAfterStep;+ values["start_after_step"] = this.StartAfterStep;+ return values;+ }++ /// <summary>+ /// Inverse of <see cref="ToDictionary"/>. Missing, unparsable or out-of-range values fall back to+ /// defaults (note that a missing <c>active</c> defaults to <c>true</c>, unlike the constructor),+ /// unknown enum strings map to the default enum value, and the result is normalized.+ /// </summary>+ private static ProbeSettings FromDictionary(Dictionary<string, object> d)+ {+ ProbeSettings probe = new ProbeSettings();+ probe.Active = ProbeSettings.ReadBool(d, "active", true);+ probe.PlaceOn = ((ProbeSettings.ReadText(d, "place_on", "field") == "intensity") ? ProbePlaceOn.Intensity : ProbePlaceOn.Field);+ switch (ProbeSettings.ReadText(d, "measurement", "amplitude"))+ {+ case "intensity":+ probe.Measurement = ProbeMeasurement.Intensity;+ break;+ case "integrated_intensity":+ probe.Measurement = ProbeMeasurement.IntegratedIntensity;+ break;+ default:+ probe.Measurement = ProbeMeasurement.Amplitude;+ break;+ }+ probe.Kind = ((ProbeSettings.ReadText(d, "probe_type", "point") == "line") ? ProbeKind.Line : ProbeKind.Point);+ probe.PosAX = ProbeSettings.ReadInt(d, "ax", 100, 0, 100000);+ probe.PosAY = ProbeSettings.ReadInt(d, "ay", 100, 0, 100000);+ probe.PosBX = ProbeSettings.ReadInt(d, "bx", 300, 0, 100000);+ probe.PosBY = ProbeSettings.ReadInt(d, "by", 100, 0, 100000);+ switch (ProbeSettings.ReadText(d, "box_size", "medium"))+ {+ case "tiny":+ probe.BoxSize = ProbeBoxSize.Tiny;+ break;+ case "small":+ probe.BoxSize = ProbeBoxSize.Small;+ break;+ case "large":+ probe.BoxSize = ProbeBoxSize.Large;+ break;+ case "extra_large":+ probe.BoxSize = ProbeBoxSize.ExtraLarge;+ break;+ default:+ probe.BoxSize = ProbeBoxSize.Medium;+ break;+ }+ probe.BoxX = ProbeSettings.ReadInt(d, "box_x", 450, 0, 100000);+ probe.BoxY = ProbeSettings.ReadInt(d, "box_y", 20, 0, 100000);+ probe.ScaleMode = ((ProbeSettings.ReadText(d, "scale_mode", "running") == "full") ? ProbeScaleMode.Full : ProbeScaleMode.Running);+ probe.AutoScaleX = ProbeSettings.ReadBool(d, "auto_scale_x", true);+ probe.AutoScaleY = ProbeSettings.ReadBool(d, "auto_scale_y", true);+ probe.YMin = ProbeSettings.ReadDouble(d, "y_min", -1.0, -1E+30, 1E+30);+ probe.YMax = ProbeSettings.ReadDouble(d, "y_max", 1.0, -1E+30, 1E+30);+ probe.RunningWindow = ProbeSettings.ReadInt(d, "running_window", ProbeSettings.DefaultRunningWindow, 10, ProbeSettings.MaxRunningWindow);+ probe.UseStartAfterStep = ProbeSettings.ReadBool(d, "use_start_after_step", false);+ probe.StartAfterStep = ProbeSettings.ReadInt(d, "start_after_step", 0, 0, 1000000000);+ probe.Normalize();+ return probe;+ }++ /// <summary>Reads a config value as text (invariant culture for non-strings); <paramref name="fallback"/> when missing or null.</summary>+ private static string ReadText(Dictionary<string, object> d, string key, string fallback)+ {+ object value;+ if (d.TryGetValue(key, out value) && value != null)+ {+ return Convert.ToString(value, CultureInfo.InvariantCulture);+ }+ return fallback;+ }++ /// <summary>Reads a config value that must already be a <see cref="bool"/>; anything else yields <paramref name="fallback"/>.</summary>+ private static bool ReadBool(Dictionary<string, object> d, string key, bool fallback)+ {+ object value;+ if (d.TryGetValue(key, out value) && value is bool)+ {+ return (bool)value;+ }+ return fallback;+ }++ /// <summary>Reads an integer config value (invariant-culture conversion). Missing, unconvertible or out-of-range values yield <paramref name="fallback"/>.</summary>+ private static int ReadInt(Dictionary<string, object> d, string key, int fallback, int minValue, int maxValue)+ {+ object raw;+ if (d.TryGetValue(key, out raw) && raw != null)+ {+ try+ {+ int value = Convert.ToInt32(raw, CultureInfo.InvariantCulture);+ if (value >= minValue && value <= maxValue)+ {+ return value;+ }+ }+ catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException)+ {+ }+ }+ return fallback;+ }++ /// <summary>Reads a double config value (invariant-culture conversion). Missing, unconvertible or out-of-range values yield <paramref name="fallback"/>.</summary>+ private static double ReadDouble(Dictionary<string, object> d, string key, double fallback, double minValue, double maxValue)+ {+ object raw;+ if (d.TryGetValue(key, out raw) && raw != null)+ {+ try+ {+ double value = Convert.ToDouble(raw, CultureInfo.InvariantCulture);+ if (value >= minValue && value <= maxValue)+ {+ return value;+ }+ }+ catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException)+ {+ }+ }+ return fallback;+ }++ /// <summary>Name of the project config section that holds the probe list.</summary>+ public const string SectionName = "probes";++ /// <summary>Default <see cref="RunningWindow"/>, in simulation steps.</summary>+ public const int DefaultRunningWindow = 500;++ /// <summary>Largest allowed <see cref="RunningWindow"/>, in simulation steps (also the spinner maximum on the Probes tab).</summary>+ public const int MaxRunningWindow = 1000000;+ }+}diff --git a/Wave_Dude_2D/ProbeTrace.cs b/Wave_Dude_2D/ProbeTrace.csnew file mode 100644index 0000000..060d072--- /dev/null+++ b/Wave_Dude_2D/ProbeTrace.cs@@ -0,0 +1,56 @@+namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Everything recorded for one probe during a run: the time series and, for line probes, the latest profile.+ /// Two independent sets exist per run: <see cref="ProbeCollector.Traces"/> is owned by the simulation worker+ /// thread (and read by <see cref="ProbeOverlay"/> for exported frames); the main form keeps its own copies,+ /// filled from <see cref="ProbeUpdate"/> batches on the UI thread and painted by <see cref="ProbeGraphPainter"/>.+ /// An instance is never shared between threads.+ /// </summary>+ internal sealed class ProbeTrace+ {+ public ProbeTrace()+ {+ this.Series = new ProbeSeries();+ }++ /// <summary>Number of simulation steps completed when this trace was last updated; used to gate "start after step" line probes in the painter.</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+ {+ get+ {+ return this._profile;+ }+ }++ /// <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+ {+ get+ {+ return this._profileLength;+ }+ }++ /// <summary>Replaces the current profile. 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)+ {+ this._profile = values;+ this._profileLength = length;+ }++ /// <summary>Latest profile array; null until <see cref="SetProfile"/> is first called.</summary>+ private float[] _profile;++ /// <summary>Line length in canvas pixels belonging to <see cref="_profile"/>.</summary>+ private double _profileLength;++ /// <summary>Time series of a point probe, one value per sampled step; stays empty for line probes.</summary>+ public readonly ProbeSeries Series;+ }+}diff --git a/Wave_Dude_2D/ProbeUpdate.cs b/Wave_Dude_2D/ProbeUpdate.csnew file mode 100644index 0000000..ddcd556--- /dev/null+++ b/Wave_Dude_2D/ProbeUpdate.cs@@ -0,0 +1,38 @@+namespace _2D_wave_sim_V01+{+ /// <summary>+ /// One batch of probe results handed from the simulation worker thread to the UI. Created by+ /// <see cref="ProbeCollector.TakeForUi"/> on the worker, raised through <c>SimulationRunner.ProbesUpdated</c>+ /// and applied to the form's own <see cref="ProbeTrace"/>s on the UI thread (marshalled via <c>PostToUi</c>).+ /// Never modified after construction, so no locking is needed.+ /// </summary>+ internal sealed class ProbeUpdate+ {+ public ProbeUpdate(float[][] samples, float[][] profiles, double[] lengths, int stepsDone)+ {+ this.Samples = samples;+ this.Profiles = profiles;+ this.Lengths = lengths;+ this.StepsDone = stepsDone;+ }++ /// <summary>+ /// Per probe (index parallel to the run's probe list): the series values sampled since the previous batch,+ /// in step order. Freshly allocated per batch; empty (never null) for line probes or when nothing new arrived.+ /// </summary>+ public readonly float[][] Samples;++ /// <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.+ /// </summary>+ public readonly float[][] Profiles;++ /// <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 readonly double[] Lengths;++ /// <summary>Simulation steps completed when the batch was taken; becomes <see cref="ProbeTrace.StepsSampled"/> on the UI side.</summary>+ public readonly int StepsDone;+ }+}diff --git a/Wave_Dude_2D/Project.cs b/Wave_Dude_2D/Project.csnew file mode 100644index 0000000..9707687--- /dev/null+++ b/Wave_Dude_2D/Project.cs@@ -0,0 +1,126 @@+using System;+using System.IO;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// An opened project on disk: its folder, the well-known sub-folders inside it and the+ /// in-memory <see cref="ProjectConfig"/>. Instances are created only by+ /// <see cref="ProjectStore"/> (open, create, rename); <see cref="Form1"/> holds the current+ /// one, edits <see cref="Config"/> and calls <see cref="Save"/>. The project name is always+ /// the folder name. None of the folder properties create the directory they point to.+ /// </summary>+ public sealed class Project+ {+ /// <summary>+ /// Wraps an existing folder and its configuration, and immediately stamps+ /// <see cref="ProjectConfig.ProjectName"/> with the folder name so a copied or renamed+ /// project folder is self-consistent even before it is saved.+ /// </summary>+ /// <param name="folderPath">Full path of the project folder; its last segment is the project name.</param>+ /// <param name="config">The configuration loaded from, or to be written to, that folder.</param>+ internal Project(string folderPath, ProjectConfig config)+ {+ this._folderPath = folderPath;+ this._config = config;+ this._config.ProjectName = this.Name;+ }++ /// <summary>Project name, i.e. the name of the project folder.</summary>+ public string Name+ {+ get+ {+ return Path.GetFileName(this._folderPath);+ }+ }++ /// <summary>Full path of the project folder.</summary>+ public string FolderPath+ {+ get+ {+ return this._folderPath;+ }+ }++ /// <summary>Parent of the project folder (the project root), or an empty string when the folder has no parent.</summary>+ public string RootFolder+ {+ get+ {+ return Path.GetDirectoryName(this._folderPath) ?? "";+ }+ }++ /// <summary>The configuration loaded from (or to be written to) <see cref="ConfigFilePath"/>; mutable, shared with the editor.</summary>+ public ProjectConfig Config+ {+ get+ {+ return this._config;+ }+ }++ /// <summary>Full path of the <c>configuration.json</c> file inside the project folder.</summary>+ public string ConfigFilePath+ {+ get+ {+ return Path.Combine(this._folderPath, "configuration.json");+ }+ }++ /// <summary>The <c>assets</c> sub-folder (user files kept with the project).</summary>+ public string AssetsFolder+ {+ get+ {+ return Path.Combine(this._folderPath, "assets");+ }+ }++ /// <summary>The <c>output_frames</c> sub-folder where exported PNG frames are written.</summary>+ public string OutputFramesFolder+ {+ get+ {+ return Path.Combine(this._folderPath, "output_frames");+ }+ }++ /// <summary>The <c>output_video</c> sub-folder where exported videos are written.</summary>+ public string OutputVideoFolder+ {+ get+ {+ return Path.Combine(this._folderPath, "output_video");+ }+ }++ /// <summary>The <c>scene_images</c> sub-folder into which scene images chosen from elsewhere are copied.</summary>+ public string SceneImageFolder+ {+ get+ {+ return Path.Combine(this._folderPath, "scene_images");+ }+ }++ /// <summary>+ /// Re-stamps the project name and writes <see cref="Config"/> to <see cref="ConfigFilePath"/>+ /// (atomically, via <see cref="ProjectConfig.Save(string)"/>).+ /// </summary>+ public void Save()+ {+ this._config.ProjectName = this.Name;+ this._config.Save(this.ConfigFilePath);+ }++ /// <summary>Full path of the project folder; its last segment is the project name.</summary>+ private readonly string _folderPath;++ /// <summary>The project's configuration; never null.</summary>+ private readonly ProjectConfig _config;+ }+}diff --git a/Wave_Dude_2D/ProjectConfig.cs b/Wave_Dude_2D/ProjectConfig.csnew file mode 100644index 0000000..29be3c5--- /dev/null+++ b/Wave_Dude_2D/ProjectConfig.cs@@ -0,0 +1,457 @@+using System;+using System.Collections;+using System.Collections.Generic;+using System.Globalization;+using System.IO;+using System.Text;+using System.Web.Script.Serialization;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// The contents of a project's configuration.json: a flat dictionary of top-level values+ /// (format version, project name, created/modified timestamps, description) plus named+ /// sub-dictionaries ("sections") that <see cref="SceneSettings"/>, <see cref="SimulationSettings"/>,+ /// <see cref="ProbeSettings"/> and <see cref="SourceSettings"/> read and write through+ /// <see cref="GetSection"/>. Owned by a <see cref="Project"/>; created by <see cref="ProjectStore"/>.+ /// Reading uses <see cref="JavaScriptSerializer"/>; writing is done by hand so the file stays+ /// stable, indented and human-readable. Values are stored as the serializer produces them+ /// (string, int, long, decimal, double, bool, nested dictionaries and object arrays), so the+ /// typed getters convert with the invariant culture.+ /// </summary>+ public sealed class ProjectConfig+ {+ /// <summary>Creates an empty configuration for a new project, stamping the current format version and the UTC created/modified time.</summary>+ public ProjectConfig(string projectName)+ {+ string now = ProjectConfig.Timestamp(DateTime.UtcNow);+ this._values = new Dictionary<string, object>();+ this._values[KeyFormatVersion] = CurrentFormatVersion;+ this._values[KeyProjectName] = projectName;+ this._values[KeyCreated] = now;+ this._values[KeyModified] = now;+ }++ /// <summary>Wraps a deserialised dictionary (used by <see cref="Load"/>); adds the format version if the file had none.</summary>+ private ProjectConfig(Dictionary<string, object> values)+ {+ this._values = values;+ if (!this._values.ContainsKey(KeyFormatVersion))+ {+ this._values[KeyFormatVersion] = CurrentFormatVersion;+ }+ }++ /// <summary>Format version stored in the file; <see cref="CurrentFormatVersion"/> when missing or unreadable.</summary>+ public int FormatVersion+ {+ get+ {+ return this.GetInteger(KeyFormatVersion, CurrentFormatVersion);+ }+ }++ /// <summary>Gets or sets the project name ("" when missing). <see cref="Project.Save"/> overwrites it with the folder name before saving.</summary>+ public string ProjectName+ {+ get+ {+ return this.GetString(KeyProjectName, "");+ }+ set+ {+ this._values[KeyProjectName] = value;+ }+ }++ /// <summary>UTC creation timestamp as "yyyy-MM-ddTHH:mm:ssZ", or "" when missing.</summary>+ public string Created+ {+ get+ {+ return this.GetString(KeyCreated, "");+ }+ }++ /// <summary>UTC timestamp of the last <see cref="Save"/> as "yyyy-MM-ddTHH:mm:ssZ", or "" when missing.</summary>+ public string Modified+ {+ get+ {+ return this.GetString(KeyModified, "");+ }+ }++ /// <summary>Gets or sets the free-text project description ("" when missing).</summary>+ public string Description+ {+ get+ {+ return this.GetString(KeyDescription, "");+ }+ set+ {+ this._values[KeyDescription] = value;+ }+ }++ /// <summary>True when a top-level value or section named <paramref name="key"/> exists (even if its value is null).</summary>+ public bool ContainsKey(string key)+ {+ return this._values.ContainsKey(key);+ }++ /// <summary>Top-level value <paramref name="key"/> converted to a string with the invariant culture, or <paramref name="fallback"/> when missing or null.</summary>+ public string GetString(string key, string fallback)+ {+ object value;+ if (this._values.TryGetValue(key, out value) && value != null)+ {+ return Convert.ToString(value, CultureInfo.InvariantCulture);+ }+ return fallback;+ }++ /// <summary>Top-level value <paramref name="key"/> converted to an int with the invariant culture, or <paramref name="fallback"/> when missing, null, not numeric or out of range.</summary>+ public int GetInteger(string key, int fallback)+ {+ object value;+ if (this._values.TryGetValue(key, out value) && value != null)+ {+ try+ {+ return Convert.ToInt32(value, CultureInfo.InvariantCulture);+ }+ catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException)+ {+ return fallback;+ }+ }+ return fallback;+ }++ /// <summary>Sets (or replaces) the top-level value <paramref name="key"/>; a dictionary value becomes a section.</summary>+ public void SetValue(string key, object value)+ {+ this._values[key] = value;+ }++ /// <summary>+ /// Returns the named sub-dictionary, creating an empty one (and storing it) if it is missing+ /// or the existing value is not a dictionary. Callers edit the returned dictionary in place.+ /// </summary>+ public Dictionary<string, object> GetSection(string name)+ {+ object existing;+ if (this._values.TryGetValue(name, out existing))+ {+ Dictionary<string, object> section = existing as Dictionary<string, object>;+ if (section != null)+ {+ return section;+ }+ }+ Dictionary<string, object> created = new Dictionary<string, object>();+ this._values[name] = created;+ return created;+ }++ /// <summary>Reads and parses a configuration.json (UTF-8, any size).</summary>+ /// <exception cref="InvalidDataException">The file is not valid JSON, its root is not an object, or its format version is newer than <see cref="CurrentFormatVersion"/>.</exception>+ public static ProjectConfig Load(string filePath)+ {+ string json = File.ReadAllText(filePath, Encoding.UTF8);+ JavaScriptSerializer serializer = new JavaScriptSerializer();+ serializer.MaxJsonLength = int.MaxValue;+ Dictionary<string, object> values = null;+ try+ {+ values = serializer.DeserializeObject(json) as Dictionary<string, object>;+ }+ catch (Exception ex) when (ex is ArgumentException || ex is InvalidOperationException)+ {+ throw new InvalidDataException("The file " + Path.GetFileName(filePath) + " is not valid JSON: " + ex.Message, ex);+ }+ if (values == null)+ {+ throw new InvalidDataException("The file " + Path.GetFileName(filePath) + " is not a project configuration (a JSON object was expected).");+ }+ ProjectConfig config = new ProjectConfig(values);+ if (config.FormatVersion > CurrentFormatVersion)+ {+ throw new InvalidDataException("The file " + Path.GetFileName(filePath) + " was made by a newer version of the program (format " + config.FormatVersion.ToString(CultureInfo.InvariantCulture) + ").");+ }+ return config;+ }++ /// <summary>+ /// Writes the configuration to <paramref name="filePath"/> as indented JSON (UTF-8 without BOM),+ /// first stamping the current format version and the UTC "modified" time. The text goes to+ /// <c>filePath + ".tmp"</c> and is then moved over the old file, so a crash mid-write cannot+ /// leave a truncated configuration. Missing parent folders are created.+ /// </summary>+ public void Save(string filePath)+ {+ this._values[KeyFormatVersion] = CurrentFormatVersion;+ this._values[KeyModified] = ProjectConfig.Timestamp(DateTime.UtcNow);+ StringBuilder sb = new StringBuilder();+ ProjectConfig.WriteObject(sb, this._values, 0);+ sb.AppendLine();+ string directory = Path.GetDirectoryName(filePath);+ if (!string.IsNullOrEmpty(directory))+ {+ Directory.CreateDirectory(directory);+ }+ string tempPath = filePath + ".tmp";+ File.WriteAllText(tempPath, sb.ToString(), new UTF8Encoding(false));+ if (File.Exists(filePath))+ {+ File.Delete(filePath);+ }+ File.Move(tempPath, filePath);+ }++ /// <summary>Formats a UTC time as "yyyy-MM-ddTHH:mm:ssZ" (the value is not converted; pass UTC).</summary>+ private static string Timestamp(DateTime value)+ {+ return value.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);+ }++ /// <summary>+ /// Appends one JSON value. Dictionaries and non-string enumerables recurse into+ /// <see cref="WriteObject"/> / <see cref="WriteArray"/>; numbers use the invariant culture+ /// (doubles with round-trip "R" format, NaN/infinity become <c>null</c>); DateTime is written+ /// as a UTC timestamp string; other objects are written as their quoted string form; unknown+ /// type codes become <c>null</c>. <paramref name="level"/> is the nesting depth, used only to+ /// indent nested containers.+ /// </summary>+ private static void WriteValue(StringBuilder sb, object value, int level)+ {+ if (value == null)+ {+ sb.Append("null");+ return;+ }+ switch (Type.GetTypeCode(value.GetType()))+ {+ case TypeCode.Object:+ {+ IDictionary dict = value as IDictionary;+ IEnumerable list = value as IEnumerable;+ if (dict != null)+ {+ ProjectConfig.WriteObject(sb, dict, level);+ }+ else if (list != null)+ {+ ProjectConfig.WriteArray(sb, list, level);+ }+ else+ {+ sb.Append(ProjectConfig.Quote(Convert.ToString(value, CultureInfo.InvariantCulture)));+ }+ break;+ }+ case TypeCode.Boolean:+ sb.Append(Convert.ToBoolean(value, CultureInfo.InvariantCulture) ? "true" : "false");+ break;+ case TypeCode.Char:+ case TypeCode.String:+ sb.Append(ProjectConfig.Quote(Convert.ToString(value, CultureInfo.InvariantCulture)));+ break;+ case TypeCode.SByte:+ case TypeCode.Byte:+ case TypeCode.Int16:+ case TypeCode.UInt16:+ case TypeCode.Int32:+ case TypeCode.UInt32:+ case TypeCode.Int64:+ case TypeCode.UInt64:+ case TypeCode.Decimal:+ sb.Append(Convert.ToString(value, CultureInfo.InvariantCulture));+ break;+ case TypeCode.Single:+ case TypeCode.Double:+ {+ double number = Convert.ToDouble(value, CultureInfo.InvariantCulture);+ if (double.IsNaN(number) || double.IsInfinity(number))+ {+ sb.Append("null");+ }+ else+ {+ sb.Append(number.ToString("R", CultureInfo.InvariantCulture));+ }+ break;+ }+ case TypeCode.DateTime:+ sb.Append(ProjectConfig.Quote(ProjectConfig.Timestamp(Convert.ToDateTime(value, CultureInfo.InvariantCulture).ToUniversalTime())));+ break;+ default:+ sb.Append("null");+ break;+ }+ }++ /// <summary>Appends a dictionary as a JSON object, one <c>"key": value</c> pair per line indented by <paramref name="level"/> + 1; an empty dictionary becomes <c>{}</c>. Keys keep the dictionary's enumeration order.</summary>+ private static void WriteObject(StringBuilder sb, IDictionary dict, int level)+ {+ if (dict.Count == 0)+ {+ sb.Append("{}");+ return;+ }+ sb.AppendLine("{");+ int written = 0;+ foreach (DictionaryEntry entry in dict)+ {+ written++;+ sb.Append(ProjectConfig.Indent(level + 1));+ sb.Append(ProjectConfig.Quote(Convert.ToString(entry.Key, CultureInfo.InvariantCulture)));+ sb.Append(": ");+ ProjectConfig.WriteValue(sb, entry.Value, level + 1);+ if (written < dict.Count)+ {+ sb.Append(",");+ }+ sb.AppendLine();+ }+ sb.Append(ProjectConfig.Indent(level));+ sb.Append("}");+ }++ /// <summary>+ /// Appends an enumerable as a JSON array. Arrays of scalars only are written on one line+ /// (<c>[1, 2, 3]</c>); arrays containing a dictionary or a nested non-string enumerable put+ /// one element per line. Empty arrays become <c>[]</c>.+ /// </summary>+ private static void WriteArray(StringBuilder sb, IEnumerable list, int level)+ {+ List<object> items = new List<object>();+ bool allScalar = true;+ foreach (object item in list)+ {+ items.Add(item);+ if (item != null && (item is IDictionary || (item is IEnumerable && !(item is string))))+ {+ allScalar = false;+ }+ }+ if (items.Count == 0)+ {+ sb.Append("[]");+ }+ else if (allScalar)+ {+ sb.Append("[");+ for (int i = 0; i < items.Count; i++)+ {+ if (i > 0)+ {+ sb.Append(", ");+ }+ ProjectConfig.WriteValue(sb, items[i], level + 1);+ }+ sb.Append("]");+ }+ else+ {+ sb.AppendLine("[");+ for (int i = 0; i < items.Count; i++)+ {+ sb.Append(ProjectConfig.Indent(level + 1));+ ProjectConfig.WriteValue(sb, items[i], level + 1);+ if (i < items.Count - 1)+ {+ sb.Append(",");+ }+ sb.AppendLine();+ }+ sb.Append(ProjectConfig.Indent(level));+ sb.Append("]");+ }+ }++ /// <summary>Two spaces of indentation per nesting level.</summary>+ private static string Indent(int level)+ {+ return new string(' ', level * 2);+ }++ /// <summary>+ /// Returns <paramref name="text"/> as a double-quoted JSON string literal, escaping tab, LF,+ /// CR, quote and backslash with their short forms and any other control character as+ /// <c>\uXXXX</c>. Non-ASCII characters are written unescaped (the file is UTF-8). Null+ /// becomes <c>""</c>.+ /// </summary>+ private static string Quote(string text)+ {+ if (text == null)+ {+ return "\"\"";+ }+ StringBuilder sb = new StringBuilder();+ sb.Append('"');+ foreach (char c in text)+ {+ switch (c)+ {+ case '\t':+ sb.Append("\\t");+ break;+ case '\n':+ sb.Append("\\n");+ break;+ case '\r':+ sb.Append("\\r");+ break;+ case '"':+ sb.Append("\\\"");+ break;+ case '\\':+ sb.Append("\\\\");+ break;+ default:+ if (c < ' ')+ {+ sb.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));+ }+ else+ {+ sb.Append(c);+ }+ break;+ }+ }+ sb.Append('"');+ return sb.ToString();+ }++ /// <summary>File name of the configuration inside a project folder.</summary>+ public const string FileName = "configuration.json";++ /// <summary>File name of the pre-JSON configuration; an empty one marks a legacy project folder that <see cref="ProjectStore.Open"/> upgrades.</summary>+ public const string LegacyFileName = "Configuration.txt";++ /// <summary>Format version this build writes; files with a higher version are refused by <see cref="Load"/>.</summary>+ public const int CurrentFormatVersion = 1;++ /// <summary>JSON key of the format version (int).</summary>+ private const string KeyFormatVersion = "format_version";++ /// <summary>JSON key of the project name (string).</summary>+ private const string KeyProjectName = "project_name";++ /// <summary>JSON key of the creation timestamp (string, UTC).</summary>+ private const string KeyCreated = "created";++ /// <summary>JSON key of the last-saved timestamp (string, UTC).</summary>+ private const string KeyModified = "modified";++ /// <summary>JSON key of the description (string).</summary>+ private const string KeyDescription = "description";++ /// <summary>The top-level JSON object: scalar values and section dictionaries keyed by name. Never null; shared by reference with the sections handed out by <see cref="GetSection"/>.</summary>+ private readonly Dictionary<string, object> _values;+ }+}diff --git a/Wave_Dude_2D/ProjectStore.cs b/Wave_Dude_2D/ProjectStore.csnew file mode 100644index 0000000..64836fb--- /dev/null+++ b/Wave_Dude_2D/ProjectStore.cs@@ -0,0 +1,295 @@+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Static helper that creates, opens, lists, renames and deletes project folders under a root+ /// folder, and is the only code that constructs <see cref="Project"/> instances. A project folder+ /// is any folder directly below the root that contains a configuration.json (or an empty legacy+ /// Configuration.txt, which <see cref="Open"/> upgrades in place). Used by the Projects and+ /// Outputs tabs and by the File menu; all methods are synchronous and do their own disk I/O.+ /// </summary>+ public sealed class ProjectStore+ {+ /// <summary>Not instantiable; all members are static.</summary>+ private ProjectStore()+ {+ }++ /// <summary>+ /// Checks that <paramref name="projectName"/> can be used as a folder name on Windows: not+ /// blank, no surrounding whitespace, no trailing dot, at most <see cref="MaxNameLength"/>+ /// characters, no characters from <see cref="Path.GetInvalidFileNameChars"/>, and not a+ /// reserved device name (CON, NUL, COM1, ...; the part before the first dot is checked).+ /// </summary>+ /// <returns>A user-facing error message, or "" when the name is acceptable.</returns>+ public static string ValidateName(string projectName)+ {+ if (string.IsNullOrWhiteSpace(projectName))+ {+ return "Enter a project name.";+ }+ if (projectName != projectName.Trim())+ {+ return "The project name must not start or end with a space.";+ }+ if (projectName.EndsWith(".", StringComparison.Ordinal))+ {+ return "The project name must not end with a dot.";+ }+ if (projectName.Length > ProjectStore.MaxNameLength)+ {+ return "The project name is too long (at most " + ProjectStore.MaxNameLength.ToString() + " characters).";+ }+ char[] invalidChars = Path.GetInvalidFileNameChars();+ for (int i = 0; i < projectName.Length; i++)+ {+ char c = projectName[i];+ if (Array.IndexOf(invalidChars, c) >= 0)+ {+ if (c < ' ')+ {+ return "The project name contains a control character.";+ }+ return "The project name contains the character '" + c.ToString() + "', which is not allowed in a folder name.";+ }+ }+ string baseName = projectName.Split('.')[0].ToUpperInvariant();+ if (Array.IndexOf(ProjectStore.ReservedNames, baseName) >= 0)+ {+ return "'" + projectName + "' is a reserved name in Windows and cannot be used as a folder name.";+ }+ return "";+ }++ /// <summary>Full path of the folder a project named <paramref name="projectName"/> has (or would have) under <paramref name="rootFolder"/>. Does not touch the disk.</summary>+ public static string FolderPathFor(string rootFolder, string projectName)+ {+ return Path.Combine(ProjectStore.NormalizeFolder(rootFolder), projectName);+ }++ /// <summary>True when <paramref name="folderPath"/> exists and contains a configuration.json or a legacy Configuration.txt.</summary>+ public static bool IsProjectFolder(string folderPath)+ {+ if (string.IsNullOrWhiteSpace(folderPath) || !Directory.Exists(folderPath))+ {+ return false;+ }+ return File.Exists(Path.Combine(folderPath, ProjectConfig.FileName)) || File.Exists(Path.Combine(folderPath, ProjectConfig.LegacyFileName));+ }++ /// <summary>+ /// Opens the project in <paramref name="folderPath"/> and makes sure its standard sub-folders+ /// exist. A folder that only has an empty legacy Configuration.txt is upgraded:+ /// a fresh configuration.json is written and the legacy file deleted.+ /// </summary>+ /// <exception cref="DirectoryNotFoundException">The folder does not exist.</exception>+ /// <exception cref="InvalidDataException">The folder has no configuration file, its legacy+ /// Configuration.txt is not empty, or configuration.json is malformed or from a newer format+ /// version (see <see cref="ProjectConfig.Load"/>).</exception>+ public static Project Open(string folderPath)+ {+ string folder = ProjectStore.NormalizeFolder(folderPath);+ if (!Directory.Exists(folder))+ {+ throw new DirectoryNotFoundException("The folder '" + folder + "' does not exist.");+ }+ string configPath = Path.Combine(folder, ProjectConfig.FileName);+ string legacyPath = Path.Combine(folder, ProjectConfig.LegacyFileName);+ Project project;+ if (File.Exists(configPath))+ {+ project = new Project(folder, ProjectConfig.Load(configPath));+ }+ else+ {+ if (!File.Exists(legacyPath))+ {+ throw new InvalidDataException("The folder '" + Path.GetFileName(folder) + "' is not a project folder: it contains no configuration.json.");+ }+ if (File.ReadAllText(legacyPath).Trim().Length > 0)+ {+ throw new InvalidDataException("The file Configuration.txt is not empty and has no known format, so it was not replaced.");+ }+ project = new Project(folder, new ProjectConfig(Path.GetFileName(folder)));+ project.Save();+ File.Delete(legacyPath);+ }+ ProjectStore.EnsureSubFolders(folder);+ return project;+ }++ /// <summary>+ /// Creates the folder <c>rootFolder\projectName</c> with its standard sub-folders and an+ /// initial configuration.json, and returns the opened project. An existing folder is+ /// accepted only when it is completely empty.+ /// </summary>+ /// <exception cref="ArgumentException">The name fails <see cref="ValidateName"/> or the root folder is blank.</exception>+ /// <exception cref="IOException">A project of that name already exists, or the folder exists and is not empty.</exception>+ public static Project Create(string rootFolder, string projectName)+ {+ string error = ProjectStore.ValidateName(projectName);+ if (error.Length > 0)+ {+ throw new ArgumentException(error, "projectName");+ }+ if (string.IsNullOrWhiteSpace(rootFolder))+ {+ throw new ArgumentException("Enter a root folder.", "rootFolder");+ }+ string folder = ProjectStore.FolderPathFor(rootFolder, projectName);+ if (ProjectStore.IsProjectFolder(folder))+ {+ throw new IOException("A project named '" + projectName + "' already exists in this root folder. Use 'Open existing' to open it.");+ }+ if (Directory.Exists(folder) && Directory.EnumerateFileSystemEntries(folder).Any())+ {+ throw new IOException("The folder '" + folder + "' already exists and is not empty, so it cannot be used for a new project.");+ }+ Directory.CreateDirectory(folder);+ ProjectStore.EnsureSubFolders(folder);+ Project project = new Project(folder, new ProjectConfig(projectName));+ project.Save();+ return project;+ }++ /// <summary>+ /// Names (folder names, not paths) of all project folders directly below+ /// <paramref name="rootFolder"/>, sorted case-insensitively.+ /// </summary>+ /// <returns>An empty list when the root is blank, missing or cannot be enumerated (I/O or access errors are swallowed).</returns>+ public static List<string> ListProjects(string rootFolder)+ {+ List<string> names = new List<string>();+ if (string.IsNullOrWhiteSpace(rootFolder) || !Directory.Exists(rootFolder))+ {+ return names;+ }+ try+ {+ foreach (string folder in Directory.GetDirectories(rootFolder))+ {+ if (ProjectStore.IsProjectFolder(folder))+ {+ names.Add(Path.GetFileName(folder));+ }+ }+ }+ catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)+ {+ return new List<string>();+ }+ names.Sort((a, b) => string.Compare(a, b, StringComparison.OrdinalIgnoreCase));+ return names;+ }++ /// <summary>Deletes a project folder and everything inside it.</summary>+ /// <exception cref="InvalidDataException">The folder is not a project folder (safety check so arbitrary folders cannot be removed).</exception>+ public static void Delete(string folderPath)+ {+ string folder = ProjectStore.NormalizeFolder(folderPath);+ if (!ProjectStore.IsProjectFolder(folder))+ {+ throw new InvalidDataException("The folder '" + Path.GetFileName(folder) + "' is not a project folder, so it was not deleted.");+ }+ Directory.Delete(folder, true);+ }++ /// <summary>+ /// Renames the project folder <paramref name="folderPath"/> to <paramref name="newProjectName"/>+ /// within the same root and returns the new folder path. A name that differs only in case+ /// is treated as unchanged and the original path is returned without touching the disk.+ /// </summary>+ /// <exception cref="InvalidDataException">The folder is not a project folder.</exception>+ /// <exception cref="ArgumentException">The new name fails <see cref="ValidateName"/>.</exception>+ /// <exception cref="IOException">A file or folder with the new name already exists.</exception>+ public static string Rename(string folderPath, string newProjectName)+ {+ string folder = ProjectStore.NormalizeFolder(folderPath);+ if (!ProjectStore.IsProjectFolder(folder))+ {+ throw new InvalidDataException("The folder '" + Path.GetFileName(folder) + "' is not a project folder, so it was not renamed.");+ }+ string error = ProjectStore.ValidateName(newProjectName);+ if (error.Length > 0)+ {+ throw new ArgumentException(error, "newProjectName");+ }+ string rootFolder = Path.GetDirectoryName(folder);+ string newFolder = ProjectStore.FolderPathFor(rootFolder, newProjectName);+ if (string.Equals(folder, newFolder, StringComparison.OrdinalIgnoreCase))+ {+ return folder;+ }+ if (Directory.Exists(newFolder) || File.Exists(newFolder))+ {+ throw new IOException("'" + newProjectName + "' already exists in this root folder. Choose a different name.");+ }+ Directory.Move(folder, newFolder);+ return newFolder;+ }++ /// <summary>Creates the standard sub-folders (<see cref="SubFolderNames"/>) inside a project folder; I/O and access errors are ignored.</summary>+ private static void EnsureSubFolders(string folder)+ {+ try+ {+ foreach (string name in ProjectStore.SubFolderNames)+ {+ Directory.CreateDirectory(Path.Combine(folder, name));+ }+ }+ catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)+ {+ }+ }++ /// <summary>+ /// Canonical form of a folder path for comparisons: trimmed, made absolute, and without a+ /// trailing separator (except for a bare drive root such as <c>C:\</c>).+ /// </summary>+ internal static string NormalizeFolder(string folderPath)+ {+ string path = Path.GetFullPath(folderPath.Trim());+ string pathRoot = Path.GetPathRoot(path);+ if (path.Length > pathRoot.Length)+ {+ path = path.TrimEnd(new char[]+ {+ Path.DirectorySeparatorChar,+ Path.AltDirectorySeparatorChar+ });+ }+ return path;+ }++ /// <summary>Sub-folder for user files that belong to the project (counted in the delete warning).</summary>+ public const string AssetsFolderName = "assets";++ /// <summary>Sub-folder the simulation writes rendered PNG frames into.</summary>+ public const string OutputFramesFolderName = "output_frames";++ /// <summary>Sub-folder the simulation writes video files into.</summary>+ public const string OutputVideoFolderName = "output_video";++ /// <summary>Sub-folder that holds the project's scene images (imported images are copied here).</summary>+ public const string SceneImageFolderName = "scene_images";++ /// <summary>Maximum length of a project name in characters.</summary>+ private const int MaxNameLength = 100;++ /// <summary>The sub-folders every project folder gets, in creation order.</summary>+ private static readonly string[] SubFolderNames = new string[] { AssetsFolderName, OutputFramesFolderName, OutputVideoFolderName, SceneImageFolderName };++ /// <summary>Windows device names that cannot be used as a folder name (compared upper-case against the part before the first dot).</summary>+ private static readonly string[] ReservedNames = new string[]+ {+ "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6",+ "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7",+ "LPT8", "LPT9"+ };+ }+}diff --git a/Wave_Dude_2D/Properties/AssemblyInfo.cs b/Wave_Dude_2D/Properties/AssemblyInfo.csnew file mode 100644index 0000000..ecb4496--- /dev/null+++ b/Wave_Dude_2D/Properties/AssemblyInfo.cs@@ -0,0 +1,17 @@+using System;+using System.Diagnostics;+using System.Reflection;+using System.Runtime.CompilerServices;+using System.Runtime.InteropServices;+using System.Runtime.Versioning;++[assembly: AssemblyVersion("1.0.0.0")]+[assembly: AssemblyTitle("Wave_Dude_2D")]+[assembly: AssemblyDescription("")]+[assembly: AssemblyCompany("")]+[assembly: AssemblyProduct("Wave_Dude_2D")]+[assembly: AssemblyCopyright("Copyright © 2026")]+[assembly: AssemblyTrademark("")]+[assembly: ComVisible(false)]+[assembly: Guid("51c8e121-f5ae-493a-bd03-487bca68a6fc")]+[assembly: AssemblyFileVersion("1.0.0.0")]diff --git a/Wave_Dude_2D/SceneData.cs b/Wave_Dude_2D/SceneData.csnew file mode 100644index 0000000..9e7c34e--- /dev/null+++ b/Wave_Dude_2D/SceneData.cs@@ -0,0 +1,222 @@+using System;+using System.Collections.Generic;+using System.Drawing;+using System.Drawing.Imaging;+using System.Runtime.InteropServices;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Per-pixel simulation input derived from a scene image: squared wave speed (<see cref="C2"/>),+ /// damping factor (<see cref="D"/>) and the positions / levels of image-defined sources.+ /// Red channel = refractive index * 100 (clamped to 0.9..10), green = source level (0 = none),+ /// blue = damping strength (0 = none, 255 = full; stored as <c>D = 1 - blue / 255</c>).+ /// Created by <see cref="SimulationRunner"/> on its worker thread+ /// via <see cref="FromImage"/> or <see cref="Empty"/> and then copied into the padded grids of+ /// <see cref="WaveSimulator"/> / <see cref="GpuWaveSimulator"/>. The arrays are row-major+ /// (<c>y * Width + x</c>) without padding and are not modified after construction.+ /// </summary>+ internal sealed class SceneData+ {+ private SceneData(int w, int h, float[] c2, float[] d, int[] srcX, int[] srcY, byte[] srcLevel)+ {+ this.Width = w;+ this.Height = h;+ this.C2 = c2;+ this.D = d;+ this.SourceX = srcX;+ this.SourceY = srcY;+ this.SourceLevel = srcLevel;+ }++ /// <summary>Number of image-defined source pixels (length of <see cref="SourceX"/>, <see cref="SourceY"/> and <see cref="SourceLevel"/>).</summary>+ public int SourceCount+ {+ get+ {+ return this.SourceX.Length;+ }+ }++ /// <summary>+ /// Decodes <paramref name="image"/> (any pixel format; read as 32bpp ARGB) into per-pixel squared+ /// speed and damping factor and, when <paramref name="useSources"/> is set, collects every pixel+ /// with green > 0 as a source whose level is that green value, in row-major order. Finally+ /// fades the damping in a border of <paramref name="dampingEdge"/> pixels (see <see cref="ApplyBorder"/>).+ /// The bitmap is only locked for reading and is not disposed.+ /// </summary>+ /// <param name="image">Scene image; its size becomes the canvas size.</param>+ /// <param name="useSources">Collect green pixels as sources; otherwise the source arrays are empty.</param>+ /// <param name="dampingEdge">Thickness of the absorbing border in pixels; 0 or less for none.</param>+ public static SceneData FromImage(Bitmap image, bool useSources, int dampingEdge)+ {+ int width = image.Width;+ int height = image.Height;+ float[] c2 = new float[width * height];+ float[] d = new float[width * height];+ List<int> sourceX = new List<int>();+ List<int> sourceY = new List<int>();+ List<byte> sourceLevel = new List<byte>();+ BitmapData data = image.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);+ try+ {+ byte[] row = new byte[width * 4];+ for (int y = 0; y < height; y++)+ {+ Marshal.Copy(IntPtr.Add(data.Scan0, y * data.Stride), row, 0, width * 4);+ for (int x = 0; x < width; x++)+ {+ int offset = x * 4;+ int blue = row[offset];+ int green = row[offset + 1];+ int red = row[offset + 2];+ double refractiveIndex = red / 100.0;+ if (refractiveIndex < 0.9)+ {+ refractiveIndex = 0.9;+ }+ if (refractiveIndex > 10.0)+ {+ refractiveIndex = 10.0;+ }+ double speed = 1.0 / refractiveIndex;+ int index = y * width + x;+ c2[index] = (float)(speed * speed);+ d[index] = (float)(1.0 - blue / 255.0);+ if (useSources && green > 0)+ {+ sourceX.Add(x);+ sourceY.Add(y);+ sourceLevel.Add((byte)green);+ }+ }+ }+ }+ finally+ {+ image.UnlockBits(data);+ }+ SceneData.ApplyBorder(d, width, height, dampingEdge);+ return new SceneData(width, height, c2, d, sourceX.ToArray(), sourceY.ToArray(), sourceLevel.ToArray());+ }++ /// <summary>+ /// Creates a uniform <paramref name="w"/> x <paramref name="h"/> scene without sources: the+ /// speed is derived from <paramref name="refractiveIndex"/> (clamped to 0.9..10) and the damping+ /// factor is 1 (none) everywhere except in the <paramref name="dampingEdge"/> border.+ /// </summary>+ /// <param name="w">Canvas width in pixels.</param>+ /// <param name="h">Canvas height in pixels.</param>+ /// <param name="dampingEdge">Thickness of the absorbing border in pixels; 0 or less for none.</param>+ /// <param name="refractiveIndex">Background refractive index (1 = vacuum speed).</param>+ public static SceneData Empty(int w, int h, int dampingEdge, double refractiveIndex = 1.0)+ {+ double clampedIndex = refractiveIndex;+ if (clampedIndex < 0.9)+ {+ clampedIndex = 0.9;+ }+ if (clampedIndex > 10.0)+ {+ clampedIndex = 10.0;+ }+ float speed = (float)(1.0 / clampedIndex);+ float[] c2 = new float[w * h];+ float[] d = new float[w * h];+ for (int i = 0; i < c2.Length; i++)+ {+ c2[i] = speed * speed;+ d[i] = 1f;+ }+ SceneData.ApplyBorder(d, w, h, dampingEdge);+ return new SceneData(w, h, c2, d, new int[0], new int[0], new byte[0]);+ }++ /// <summary>+ /// Counts the pixels of <paramref name="image"/> with green > 0, i.e. the number of sources+ /// <see cref="FromImage"/> would collect. Used by <see cref="Form1"/> on the UI thread before a+ /// run to warn when image sources are enabled but the image contains none.+ /// </summary>+ public static int CountSources(Bitmap image)+ {+ int width = image.Width;+ int height = image.Height;+ int count = 0;+ BitmapData data = image.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);+ try+ {+ byte[] row = new byte[width * 4];+ for (int y = 0; y < height; y++)+ {+ Marshal.Copy(IntPtr.Add(data.Scan0, y * data.Stride), row, 0, width * 4);+ for (int x = 0; x < width; x++)+ {+ if (row[x * 4 + 1] > 0)+ {+ count++;+ }+ }+ }+ }+ finally+ {+ image.UnlockBits(data);+ }+ return count;+ }++ /// <summary>+ /// Overwrites the damping factor in a frame of <paramref name="thickness"/> pixels (capped at+ /// half the smaller side) around the edge of the <paramref name="w"/> x <paramref name="h"/>+ /// grid with <c>sqrt(i / border)</c>, where i is the distance from the edge: 0 on the outermost+ /// ring, rising towards 1 at the inner edge of the frame. Does nothing for a thickness of 0 or less.+ /// </summary>+ /// <param name="d">Damping array, row-major, modified in place.</param>+ /// <param name="w">Grid width in pixels.</param>+ /// <param name="h">Grid height in pixels.</param>+ /// <param name="thickness">Requested border thickness in pixels.</param>+ internal static void ApplyBorder(float[] d, int w, int h, int thickness)+ {+ int border = Math.Min(thickness, Math.Min(w, h) / 2);+ if (border <= 0)+ {+ return;+ }+ for (int i = 0; i < border; i++)+ {+ float factor = (float)Math.Sqrt((double)i / border);+ for (int x = i; x <= w - 1 - i; x++)+ {+ d[i * w + x] = factor;+ d[(h - 1 - i) * w + x] = factor;+ }+ for (int y = i; y <= h - 1 - i; y++)+ {+ d[y * w + i] = factor;+ d[y * w + (w - 1 - i)] = factor;+ }+ }+ }++ /// <summary>Canvas width in pixels.</summary>+ public readonly int Width;++ /// <summary>Canvas height in pixels.</summary>+ public readonly int Height;++ /// <summary>Squared wave speed per pixel (<c>1 / n^2</c> for refractive index n, so 1 for n = 1), row-major.</summary>+ public readonly float[] C2;++ /// <summary>Damping factor per pixel, 0..1 where 1 = no damping, row-major.</summary>+ public readonly float[] D;++ /// <summary>X canvas coordinate of each image-defined source pixel; parallel to <see cref="SourceY"/> and <see cref="SourceLevel"/>.</summary>+ public readonly int[] SourceX;++ /// <summary>Y canvas coordinate of each image-defined source pixel.</summary>+ public readonly int[] SourceY;++ /// <summary>Green channel value (1..255) of each image-defined source pixel; the engines treat it as the source's level.</summary>+ public readonly byte[] SourceLevel;+ }+}diff --git a/Wave_Dude_2D/SceneSettings.cs b/Wave_Dude_2D/SceneSettings.csnew file mode 100644index 0000000..b451e50--- /dev/null+++ b/Wave_Dude_2D/SceneSettings.cs@@ -0,0 +1,253 @@+using System;+using System.Collections.Generic;+using System.Globalization;+using System.IO;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// The "scene" section of a project: where the canvas comes from (an image or a blank user-sized canvas),+ /// the damping border and the source options. Edited by <c>Form1</c> on the UI thread and persisted through+ /// <see cref="ProjectConfig"/>; the runner turns it into a <see cref="SceneData"/> when a run starts.+ /// </summary>+ public sealed class SceneSettings+ {+ /// <summary>Creates settings with the defaults: a blank 1920 × 1080 canvas, 64 px damping edge, no sources.</summary>+ public SceneSettings()+ {+ this.UseImage = false;+ this.ImageFile = "";+ this.UserWidth = DefaultWidth;+ this.UserHeight = DefaultHeight;+ this.DampingEdgeSize = DefaultDampingEdgeSize;+ this.UseSources = false;+ this.ImageSourceScale = DefaultImageSourceScale;+ this.BackgroundRefractiveIndex = DefaultBackgroundRefractiveIndex;+ }++ /// <summary>True to build the canvas from <see cref="ImageFile"/>; false for a blank <see cref="UserWidth"/> × <see cref="UserHeight"/> canvas.</summary>+ public bool UseImage { get; set; }++ /// <summary>Scene image path as stored in the project (relative to the project folder when inside it; see <see cref="ToStoredPath"/>), or "".</summary>+ public string ImageFile { get; set; }++ /// <summary>Width in canvas pixels of a user-defined canvas.</summary>+ public int UserWidth { get; set; }++ /// <summary>Height in canvas pixels of a user-defined canvas.</summary>+ public int UserHeight { get; set; }++ /// <summary>Whether a damping frame is applied around the canvas edge.</summary>+ public bool DampingEdgeEnabled { get; set; }++ /// <summary>Thickness of the damping frame in canvas pixels.</summary>+ public int DampingEdgeSize { get; set; }++ /// <summary>Whether green pixels of the scene image act as wave sources.</summary>+ public bool UseSources { get; set; }++ /// <summary>Peak amplitude of the image sources (passed to the engine as the source amplitude).</summary>+ public double ImageSourceScale { get; set; }++ /// <summary>Whether the interactive object sources of the project are used in the run.</summary>+ public bool UseObjectSources { get; set; }++ /// <summary>Refractive index of a user-defined canvas (c = 1/n cells per step); 1.0 to 2.55.</summary>+ public double BackgroundRefractiveIndex { get; set; }++ /// <summary>+ /// Reads the "scene" section of <paramref name="config"/>. Missing keys and out-of-range values fall back to+ /// the defaults; a missing section yields a default instance.+ /// </summary>+ public static SceneSettings FromConfig(ProjectConfig config)+ {+ SceneSettings settings = new SceneSettings();+ if (!config.ContainsKey(SectionName))+ {+ return settings;+ }+ Dictionary<string, object> section = config.GetSection(SectionName);+ settings.UseImage = string.CompareOrdinal(SceneSettings.ReadText(section, "mode", ModeUserDefined), ModeImage) == 0;+ settings.ImageFile = SceneSettings.ReadText(section, "image_file", "");+ settings.UserWidth = SceneSettings.ReadInt(section, "user_width", DefaultWidth, MinCanvasSize, MaxCanvasSize);+ settings.UserHeight = SceneSettings.ReadInt(section, "user_height", DefaultHeight, MinCanvasSize, MaxCanvasSize);+ settings.DampingEdgeEnabled = SceneSettings.ReadBool(section, "damping_edge_enabled", false);+ settings.DampingEdgeSize = SceneSettings.ReadInt(section, "damping_edge_size_px", DefaultDampingEdgeSize, 1, MaxDampingEdgeSize);+ settings.UseSources = SceneSettings.ReadBool(section, "use_sources", false);+ settings.ImageSourceScale = SceneSettings.ReadDouble(section, "image_source_scale", DefaultImageSourceScale, 0.0, MaxImageSourceScale);+ settings.UseObjectSources = SceneSettings.ReadBool(section, "use_object_sources", false);+ settings.BackgroundRefractiveIndex = SceneSettings.ReadDouble(section, "background_refractive_index", DefaultBackgroundRefractiveIndex, MinBackgroundRefractiveIndex, MaxBackgroundRefractiveIndex);+ return settings;+ }++ /// <summary>Writes every value into the "scene" section of <paramref name="config"/>, creating the section if needed.</summary>+ public void ToConfig(ProjectConfig config)+ {+ Dictionary<string, object> section = config.GetSection(SectionName);+ section["mode"] = (this.UseImage ? ModeImage : ModeUserDefined);+ section["image_file"] = this.ImageFile;+ section["user_width"] = this.UserWidth;+ section["user_height"] = this.UserHeight;+ section["damping_edge_enabled"] = this.DampingEdgeEnabled;+ section["damping_edge_size_px"] = this.DampingEdgeSize;+ section["use_sources"] = this.UseSources;+ section["image_source_scale"] = this.ImageSourceScale;+ section["use_object_sources"] = this.UseObjectSources;+ section["background_refractive_index"] = this.BackgroundRefractiveIndex;+ }++ /// <summary>+ /// Converts a full path to the form stored in the project file: relative to the project folder+ /// (with forward slashes) when it lies inside it (case-insensitive prefix match), otherwise unchanged.+ /// </summary>+ /// <param name="projectFolder">Project folder; when null or empty <paramref name="fullPath"/> is returned as is.</param>+ /// <param name="fullPath">Absolute path of the scene image.</param>+ public static string ToStoredPath(string projectFolder, string fullPath)+ {+ if (string.IsNullOrEmpty(projectFolder))+ {+ return fullPath;+ }+ string folderPrefix = projectFolder.TrimEnd(new char[]+ {+ Path.DirectorySeparatorChar,+ Path.AltDirectorySeparatorChar+ }) + Path.DirectorySeparatorChar.ToString();+ if (fullPath.StartsWith(folderPrefix, StringComparison.OrdinalIgnoreCase))+ {+ return fullPath.Substring(folderPrefix.Length).Replace(Path.DirectorySeparatorChar, '/');+ }+ return fullPath;+ }++ /// <summary>+ /// Inverse of <see cref="ToStoredPath"/>: resolves a stored (possibly relative, forward-slash) path+ /// against the project folder. Rooted paths are returned unchanged.+ /// </summary>+ /// <returns>The full path, or "" when <paramref name="storedPath"/> is null or empty.</returns>+ public static string ToFullPath(string projectFolder, string storedPath)+ {+ if (string.IsNullOrEmpty(storedPath))+ {+ return "";+ }+ if (Path.IsPathRooted(storedPath))+ {+ return storedPath;+ }+ return Path.Combine(projectFolder, storedPath.Replace('/', Path.DirectorySeparatorChar));+ }++ /// <summary>The value under <paramref name="key"/> converted to text (invariant culture), or the fallback when absent or null.</summary>+ private static string ReadText(Dictionary<string, object> section, string key, string fallback)+ {+ object value;+ if (section.TryGetValue(key, out value) && value != null)+ {+ return Convert.ToString(value, CultureInfo.InvariantCulture);+ }+ return fallback;+ }++ /// <summary>The value under <paramref name="key"/> if it is an actual <see cref="bool"/>; anything else yields the fallback.</summary>+ private static bool ReadBool(Dictionary<string, object> section, string key, bool fallback)+ {+ object value;+ if (section.TryGetValue(key, out value) && value is bool)+ {+ return Convert.ToBoolean(value);+ }+ return fallback;+ }++ /// <summary>+ /// The value under <paramref name="key"/> converted to a double (invariant culture) when it converts and+ /// lies within [<paramref name="minValue"/>, <paramref name="maxValue"/>]; otherwise the fallback.+ /// </summary>+ private static double ReadDouble(Dictionary<string, object> section, string key, double fallback, double minValue, double maxValue)+ {+ object value;+ if (section.TryGetValue(key, out value) && value != null)+ {+ try+ {+ double parsed = Convert.ToDouble(value, CultureInfo.InvariantCulture);+ if (parsed >= minValue && parsed <= maxValue)+ {+ return parsed;+ }+ }+ catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException)+ {+ }+ }+ return fallback;+ }++ /// <summary>+ /// The value under <paramref name="key"/> converted to an int (invariant culture) when it converts and+ /// lies within [<paramref name="minValue"/>, <paramref name="maxValue"/>]; otherwise the fallback.+ /// </summary>+ private static int ReadInt(Dictionary<string, object> section, string key, int fallback, int minValue, int maxValue)+ {+ object value;+ if (section.TryGetValue(key, out value) && value != null)+ {+ try+ {+ int parsed = Convert.ToInt32(value, CultureInfo.InvariantCulture);+ if (parsed >= minValue && parsed <= maxValue)+ {+ return parsed;+ }+ }+ catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException)+ {+ }+ }+ return fallback;+ }++ /// <summary>Name of this section in the project file.</summary>+ public const string SectionName = "scene";++ /// <summary>Value of the "mode" key when the canvas comes from an image.</summary>+ public const string ModeImage = "image";++ /// <summary>Value of the "mode" key for a blank user-sized canvas.</summary>+ public const string ModeUserDefined = "user_defined";++ /// <summary>Default <see cref="UserWidth"/> in canvas pixels.</summary>+ public const int DefaultWidth = 1920;++ /// <summary>Default <see cref="UserHeight"/> in canvas pixels.</summary>+ public const int DefaultHeight = 1080;++ /// <summary>Default <see cref="DampingEdgeSize"/> in canvas pixels.</summary>+ public const int DefaultDampingEdgeSize = 64;++ /// <summary>Smallest accepted canvas width or height in pixels.</summary>+ public const int MinCanvasSize = 8;++ /// <summary>Largest accepted canvas width or height in pixels.</summary>+ public const int MaxCanvasSize = 16384;++ /// <summary>Largest accepted <see cref="DampingEdgeSize"/> in pixels.</summary>+ public const int MaxDampingEdgeSize = 8192;++ /// <summary>Default <see cref="ImageSourceScale"/>.</summary>+ public const double DefaultImageSourceScale = 1.0;++ /// <summary>Largest accepted <see cref="ImageSourceScale"/>.</summary>+ public const double MaxImageSourceScale = 1000.0;++ /// <summary>Default <see cref="BackgroundRefractiveIndex"/>.</summary>+ public const double DefaultBackgroundRefractiveIndex = 1.0;++ /// <summary>Smallest accepted <see cref="BackgroundRefractiveIndex"/>.</summary>+ public const double MinBackgroundRefractiveIndex = 1.0;++ /// <summary>Largest accepted <see cref="BackgroundRefractiveIndex"/>.</summary>+ public const double MaxBackgroundRefractiveIndex = 2.55;+ }+}diff --git a/Wave_Dude_2D/SimulationJob.cs b/Wave_Dude_2D/SimulationJob.csnew file mode 100644index 0000000..1578136--- /dev/null+++ b/Wave_Dude_2D/SimulationJob.cs@@ -0,0 +1,84 @@+using System.Collections.Generic;+using System.Drawing;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Everything the background worker needs to run one simulation: scene, settings, colour LUTs, output paths and probes.+ /// Built by <c>Form1.StartSimulation</c> on the UI thread, then owned exclusively by <see cref="SimulationRunner"/>'s+ /// worker thread, which also disposes the bitmaps. Scene size and all pixel values are in canvas (scene image) pixels.+ /// </summary>+ internal sealed class SimulationJob+ {+ public SimulationJob()+ {+ this.BackgroundRefractiveIndex = 1.0;+ this.SourceAmplitude = 1.0;+ this.FieldVideoPath = "";+ this.IntensityVideoPath = "";+ }++ /// <summary>+ /// Private copy of the scene image (red = refractive index, green = source level, blue = damping); null for an empty+ /// canvas of <see cref="Width"/> x <see cref="Height"/>. The runner disposes it as soon as the <see cref="SceneData"/> is built.+ /// </summary>+ public Bitmap Image;++ /// <summary>Canvas width in pixels; only used when <see cref="Image"/> is null.</summary>+ public int Width;++ /// <summary>Canvas height in pixels; only used when <see cref="Image"/> is null.</summary>+ public int Height;++ /// <summary>Refractive index of the whole empty canvas (not used with an image); defaults to 1.0.</summary>+ public double BackgroundRefractiveIndex;++ /// <summary>Whether pixels with a green value above 0 in <see cref="Image"/> act as sources.</summary>+ public bool UseSources;++ /// <summary>Amplitude multiplier for the image-defined sources (the scene's image source scale); defaults to 1.0.</summary>+ public double SourceAmplitude;++ /// <summary>Thickness in pixels of the absorbing border around the canvas; 0 = none.</summary>+ public int DampingEdge;++ /// <summary>Snapshot (clone) of the simulation settings, so later edits in the UI do not affect the running job.</summary>+ public SimulationSettings Settings;++ /// <summary>ARGB palette of <see cref="ColorLut.Size"/> entries for field frames; null when neither field export nor field preview is wanted.</summary>+ public int[] FieldLut;++ /// <summary>ARGB palette of <see cref="ColorLut.Size"/> entries for intensity frames; null when neither intensity export nor preview is wanted.</summary>+ public int[] IntensityLut;++ /// <summary>Full path of the field video to write (.mp4, may fall back to .avi); empty = do not export the field.</summary>+ public string FieldVideoPath;++ /// <summary>Full path of the intensity video to write (.mp4, may fall back to .avi); empty = do not export the intensity.</summary>+ public string IntensityVideoPath;++ /// <summary>Probes to sample during the run; null or empty when there are none.</summary>+ public List<ProbeSettings> Probes;++ /// <summary>Object sources (added on the Sources tab) to drive in addition to the image sources; may be null.</summary>+ public List<SourceElement> ObjectSources;++ /// <summary>Maximum preview width in picture-box pixels; the runner shrinks previews to fit (keeping the aspect ratio) but never enlarges them.</summary>+ public int PreviewWidth;++ /// <summary>Maximum preview height in picture-box pixels; see <see cref="PreviewWidth"/>.</summary>+ public int PreviewHeight;++ /// <summary>+ /// Glowing-edges image of the scene, canvas sized, to add onto the exported video frames; null when not exporting or both gains are 0.+ /// The runner converts and disposes it before the first step.+ /// </summary>+ public Bitmap GlowOverlay;++ /// <summary>Brightness multiplier for <see cref="GlowOverlay"/> on field frames; 0 = no overlay.</summary>+ public double FieldOverlayGain;++ /// <summary>Brightness multiplier for <see cref="GlowOverlay"/> on intensity frames; 0 = no overlay.</summary>+ public double IntensityOverlayGain;+ }+}diff --git a/Wave_Dude_2D/SimulationResult.cs b/Wave_Dude_2D/SimulationResult.csnew file mode 100644index 0000000..dd6a0fd--- /dev/null+++ b/Wave_Dude_2D/SimulationResult.cs@@ -0,0 +1,61 @@+using System;+using System.Collections.Generic;+using System.Drawing;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Outcome of one simulation run. Filled by <see cref="SimulationRunner"/> on its worker thread and+ /// handed to the form through the <c>Finished</c> event (marshalled to the UI thread by+ /// <c>Form1.PostToUi</c>); after that only the UI thread touches it. String members are never null+ /// (empty means "none"). The receiver takes ownership of the two bitmaps.+ /// </summary>+ internal sealed class SimulationResult+ {+ public SimulationResult()+ {+ this.Message = "";+ this.Files = new List<string>();+ this.FieldFile = "";+ this.IntensityFile = "";+ this.Engine = "";+ this.EngineNote = "";+ }++ /// <summary>How the run ended.</summary>+ public SimulationStatus Status;++ /// <summary>+ /// Failure reason when <see cref="Status"/> is <see cref="SimulationStatus.Failed"/>; for other outcomes it may+ /// carry the note that MP4 encoding was unavailable and .avi files were written instead. Empty when there is nothing to say.+ /// </summary>+ public string Message;++ /// <summary>Number of time steps actually computed (equals the requested steps when completed).</summary>+ public int StepsDone;++ /// <summary>Wall-clock time of the run, excluding the time spent paused.</summary>+ public TimeSpan Elapsed;++ /// <summary>Full paths of the video files that were written, in the order field then intensity (after any .mp4 to .avi fallback).</summary>+ public List<string> Files;++ /// <summary>Full path of the field video, or empty when the field was not exported.</summary>+ public string FieldFile;++ /// <summary>Full path of the intensity video, or empty when the intensity was not exported.</summary>+ public string IntensityFile;++ /// <summary><see cref="IWaveEngine.Description"/> of the engine that ran; empty when engine creation itself failed.</summary>+ public string Engine;++ /// <summary>Note from <see cref="WaveEngineFactory.Create"/> about why the GPU was not used; empty when there is none.</summary>+ public string EngineNote;++ /// <summary>Full-size field frame of the final state (with probe overlays burned in); null when no engine was created or rendering failed.</summary>+ public Bitmap LastFieldFrame;++ /// <summary>Full-size intensity frame of the final state; null when the intensity was not tracked or rendering failed.</summary>+ public Bitmap LastIntensityFrame;+ }+}diff --git a/Wave_Dude_2D/SimulationRunner.cs b/Wave_Dude_2D/SimulationRunner.csnew file mode 100644index 0000000..0e6e7f1--- /dev/null+++ b/Wave_Dude_2D/SimulationRunner.cs@@ -0,0 +1,552 @@+using System;+using System.Diagnostics;+using System.Drawing;+using System.IO;+using System.Threading;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Runs a <see cref="SimulationJob"/> on a dedicated background thread ("Wave simulation"),+ /// writing video frames, collecting probe data and raising progress / preview events as it goes.+ /// Created and started by <c>Form1</c> (one instance per run); the form keeps the reference in+ /// <c>_runner</c> so stale callbacks from an older run can be ignored.+ /// </summary>+ /// <remarks>+ /// <para><b>Event contract.</b> Every event (<see cref="ProgressChanged"/>, <see cref="EngineReady"/>,+ /// <see cref="ProbesUpdated"/>, <see cref="PreviewReady"/>, <see cref="Finished"/>) is raised+ /// synchronously on the <em>worker thread</em>, never on the UI thread. Handlers must marshal to the UI+ /// themselves; <c>Form1</c> does so through <c>PostToUi</c> (<c>BeginInvoke</c>). Order of events:+ /// <see cref="EngineReady"/> once (after the engine is built, before any frames), then interleaved+ /// <see cref="ProgressChanged"/> / <see cref="ProbesUpdated"/> / <see cref="PreviewReady"/>, then a+ /// final <see cref="ProgressChanged"/> and exactly one <see cref="Finished"/>. If engine creation fails,+ /// only <see cref="ProgressChanged"/> and <see cref="Finished"/> are raised.</para>+ /// <para><b>Pause / cancel handshake.</b> <see cref="_gate"/> is a <see cref="ManualResetEventSlim"/>+ /// that is set while running. <see cref="PauseRun"/> resets it; the worker notices at the top of the+ /// next step, reports the exact step count, stops the elapsed-time stopwatch and blocks on the gate.+ /// <see cref="ResumeRun"/> sets it again. <see cref="Cancel"/> sets the <see cref="_cancel"/> flag and+ /// also sets the gate so a paused run wakes up; the loop exits before the next step with+ /// <see cref="SimulationStatus.Cancelled"/> and the video files are still closed properly.</para>+ /// <para><b>Preview handshake.</b> The worker only renders a new preview when at least+ /// <see cref="PreviewIntervalMs"/> have elapsed since the last one and <see cref="_previewPending"/>+ /// is <= 0. Before raising <see cref="PreviewReady"/> it sets <see cref="_previewPending"/> to the+ /// number of bitmaps it is about to hand out (1 or 2); the UI must call <see cref="PreviewShown"/> once+ /// per bitmap it received (also when it discards it), which decrements the counter. This stops the+ /// worker from flooding the UI message queue with bitmaps faster than they can be displayed.</para>+ /// </remarks>+ internal sealed class SimulationRunner+ {+ /// <summary>+ /// Raised on the worker thread at most every 100 ms with (steps done, total steps), plus once when+ /// pausing (with the exact count) and once just before <see cref="Finished"/>.+ /// </summary>+ public event SimulationRunner.ProgressChangedEventHandler ProgressChanged;++ /// <summary>+ /// Raised once on the worker thread after <see cref="WaveEngineFactory.Create"/> succeeded, with the+ /// engine description (e.g. CPU/GPU) and an optional note (empty string when there is none).+ /// </summary>+ public event SimulationRunner.EngineReadyEventHandler EngineReady;++ /// <summary>+ /// Raised on the worker thread at most every 50 ms (and once at the end) with the probe samples+ /// drained since the previous update. Only raised when the job has probes.+ /// </summary>+ public event SimulationRunner.ProbesUpdatedEventHandler ProbesUpdated;++ /// <summary>+ /// Raised on the worker thread with a freshly allocated preview <see cref="Bitmap"/> (field or+ /// intensity, scaled to fit the preview box). The handler owns the bitmap and must call+ /// <see cref="PreviewShown"/> for every bitmap it receives. Preview bitmaps carry no glow or probe+ /// overlay; the UI composes those.+ /// </summary>+ public event SimulationRunner.PreviewReadyEventHandler PreviewReady;++ /// <summary>+ /// Raised exactly once on the worker thread as the very last action of the run, after the video+ /// files are closed and the engine is disposed. The receiver owns the bitmaps in the result.+ /// </summary>+ public event SimulationRunner.FinishedEventHandler Finished;++ /// <summary>Stores the job and creates the pause gate in the "running" (set) state.</summary>+ public SimulationRunner(SimulationJob job)+ {+ this._gate = new ManualResetEventSlim(true);+ this._job = job;+ }++ /// <summary>Starts the background worker thread; returns immediately. Call once.</summary>+ public void Start()+ {+ this._thread = new Thread(new ThreadStart(this.Run));+ this._thread.IsBackground = true;+ this._thread.Name = "Wave simulation";+ this._thread.Start();+ }++ /// <summary>+ /// Requests cancellation (thread-safe, callable from the UI thread). Also opens the pause gate so a+ /// paused run can wake up and finish; the run then ends with <see cref="SimulationStatus.Cancelled"/>+ /// and <see cref="Finished"/> is still raised.+ /// </summary>+ public void Cancel()+ {+ Interlocked.Exchange(ref this._cancel, 1);+ this._gate.Set();+ }++ /// <summary>+ /// Closes the gate so the worker blocks before its next step (it finishes the step in progress+ /// first). While paused, <see cref="RenderCurrentFrame"/> may be used.+ /// </summary>+ public void PauseRun()+ {+ this._gate.Reset();+ }++ /// <summary>Opens the gate so a paused worker continues.</summary>+ public void ResumeRun()+ {+ this._gate.Set();+ }++ /// <summary>+ /// Acknowledges one <see cref="PreviewReady"/> bitmap (UI thread). When all outstanding bitmaps are+ /// acknowledged the worker may produce the next preview.+ /// </summary>+ public void PreviewShown()+ {+ Interlocked.Decrement(ref this._previewPending);+ }++ /// <summary>+ /// Blocks until the worker thread has ended or the timeout elapses.+ /// </summary>+ /// <returns><c>true</c> if the thread ended (or was never started), <c>false</c> on timeout.</returns>+ public bool WaitForExit(int milliseconds)+ {+ Thread thread = this._thread;+ return thread == null || thread.Join(milliseconds);+ }++ /// <summary>+ /// Renders the current field or intensity frame at full engine resolution, with probe markers burned+ /// in but without the glow overlay. Intended for the UI thread while the run is paused: it reads the+ /// engine buffers directly, which is only safe because the worker is parked on the gate.+ /// </summary>+ /// <param name="isField"><c>true</c> for the wave field, <c>false</c> for the intensity.</param>+ /// <param name="lut">ARGB palette with at least 255 entries, or null for greyscale.</param>+ /// <param name="brightness">Gain applied to the raw values before palette lookup.</param>+ /// <returns>+ /// A new <see cref="Bitmap"/> owned by the caller, or null when the run is not paused, no engine+ /// exists yet, or intensity was requested but the engine does not accumulate it.+ /// </returns>+ public Bitmap RenderCurrentFrame(bool isField, int[] lut, float brightness)+ {+ if (this._gate.IsSet)+ {+ return null;+ }+ IWaveEngine sim = this._sim;+ if (sim == null)+ {+ return null;+ }+ if (!isField && sim.IntensityData == null)+ {+ return null;+ }+ int width = sim.Width;+ int height = sim.Height;+ sim.PrepareFrame(isField, !isField);+ int[] pixels = new int[width * height];+ if (isField)+ {+ FrameRenderer.RenderField(sim, lut, brightness, pixels, width, height);+ if (this._collector != null)+ {+ ProbeOverlay.Burn(pixels, width, height, this._job.Probes, this._collector.Traces, ProbePlaceOn.Field, this._job.Settings.Steps);+ }+ }+ else+ {+ FrameRenderer.RenderIntensity(sim, lut, brightness, pixels, width, height);+ if (this._collector != null)+ {+ ProbeOverlay.Burn(pixels, width, height, this._job.Probes, this._collector.Traces, ProbePlaceOn.Intensity, this._job.Settings.Steps);+ }+ }+ return FrameRenderer.ToBitmap(pixels, width, height);+ }++ /// <summary>+ /// Worker thread body. Builds the scene and engine, opens the video sinks, steps the simulation,+ /// and in <c>finally</c> closes the sinks, captures the last full-size frames into the result and+ /// disposes the engine. Never throws: failures end up in <see cref="SimulationResult.Status"/> /+ /// <see cref="SimulationResult.Message"/>. The job's <see cref="SimulationJob.Image"/> and+ /// <see cref="SimulationJob.GlowOverlay"/> bitmaps are disposed here once consumed.+ /// </summary>+ private void Run()+ {+ SimulationResult result = new SimulationResult();+ Stopwatch stopwatch = Stopwatch.StartNew();+ IFrameSink fieldSink = null;+ IFrameSink intensitySink = null;+ IWaveEngine engine = null;+ ProbeCollector collector = null;+ int totalSteps = 0;+ try+ {+ SimulationSettings settings = this._job.Settings;+ bool writeField = this._job.FieldVideoPath.Length > 0;+ bool writeIntensity = this._job.IntensityVideoPath.Length > 0;+ bool needIntensity = writeIntensity || settings.PreviewIntensity;+ SceneData scene;+ if (this._job.Image != null)+ {+ scene = SceneData.FromImage(this._job.Image, this._job.UseSources, this._job.DampingEdge);+ this._job.Image.Dispose();+ this._job.Image = null;+ }+ else+ {+ scene = SceneData.Empty(this._job.Width, this._job.Height, this._job.DampingEdge, this._job.BackgroundRefractiveIndex);+ }+ int width = scene.Width;+ int height = scene.Height;+ ProbeSampler sampler = null;+ if (this._job.Probes != null && this._job.Probes.Count > 0)+ {+ sampler = ProbeSampler.Build(this._job.Probes, width, height);+ collector = new ProbeCollector(sampler);+ if (sampler.NeedsIntensity)+ {+ needIntensity = true;+ }+ }+ string engineNote = "";+ engine = WaveEngineFactory.Create(scene, settings, this._job.SourceAmplitude, needIntensity, ref engineNote, this._job.ObjectSources);+ this._sim = engine;+ this._collector = collector;+ result.Engine = engine.Description;+ result.EngineNote = engineNote;+ this.EngineReady?.Invoke(engine.Description, engineNote);+ if (sampler != null)+ {+ engine.SetProbes(sampler);+ }+ if (writeField)+ {+ fieldSink = SimulationRunner.OpenSink(this._job.FieldVideoPath, width, height, settings.VideoFps, settings.VideoQuality, result);+ result.Files.Add(fieldSink.FilePath);+ result.FieldFile = fieldSink.FilePath;+ }+ if (writeIntensity)+ {+ intensitySink = SimulationRunner.OpenSink(this._job.IntensityVideoPath, width, height, settings.VideoFps, settings.VideoQuality, result);+ result.Files.Add(intensitySink.FilePath);+ result.IntensityFile = intensitySink.FilePath;+ }+ int[] framePixels = null;+ if (writeField || writeIntensity)+ {+ framePixels = new int[width * height];+ }+ byte[] fieldOverlay = null;+ byte[] intensityOverlay = null;+ if (this._job.GlowOverlay != null && (writeField || writeIntensity))+ {+ byte[] overlayRgb = FrameRenderer.ToRgbBytes(this._job.GlowOverlay, width, height);+ if (writeField)+ {+ fieldOverlay = FrameRenderer.ScaleOverlayRgb(overlayRgb, this._job.FieldOverlayGain);+ }+ if (writeIntensity)+ {+ intensityOverlay = FrameRenderer.ScaleOverlayRgb(overlayRgb, this._job.IntensityOverlayGain);+ }+ }+ if (this._job.GlowOverlay != null)+ {+ this._job.GlowOverlay.Dispose();+ this._job.GlowOverlay = null;+ }+ // Preview is shrunk (never enlarged) to fit the preview box, keeping the aspect ratio.+ int previewWidth = width;+ int previewHeight = height;+ double previewScale = Math.Min((double)this._job.PreviewWidth / width, (double)this._job.PreviewHeight / height);+ if (previewScale < 1.0)+ {+ previewWidth = Math.Max(1, (int)Math.Floor(width * previewScale));+ previewHeight = Math.Max(1, (int)Math.Floor(height * previewScale));+ }+ int[] previewPixels = null;+ if (settings.PreviewField || settings.PreviewIntensity)+ {+ previewPixels = new int[previewWidth * previewHeight];+ }+ float fieldBrightness = (float)settings.FieldBrightness;+ float intensityBrightness = (float)settings.IntensityBrightness;+ int visualizeEvery = Math.Max(1, settings.VisualizeEvery);+ totalSteps = settings.Steps;+ long lastProgressMs = 0L;+ long lastProbeMs = 0L;+ long lastPreviewMs = 0L;+ result.Status = SimulationStatus.Completed;+ for (int i = 0; i < totalSteps; i++)+ {+ if (!this._gate.IsSet)+ {+ // Paused: report the exact step count and exclude the wait from the elapsed time.+ stopwatch.Stop();+ this.ProgressChanged?.Invoke(result.StepsDone, totalSteps);+ this._gate.Wait();+ stopwatch.Start();+ }+ if (Thread.VolatileRead(ref this._cancel) != 0)+ {+ result.Status = SimulationStatus.Cancelled;+ break;+ }+ engine.AdvanceOneStep();+ if (sampler != null)+ {+ engine.SampleProbes();+ }+ result.StepsDone = i + 1;+ if (i % visualizeEvery == 0)+ {+ if (collector != null)+ {+ collector.Collect(engine, result.StepsDone);+ if (writeField || writeIntensity)+ {+ collector.CollectProfiles(engine, result.StepsDone);+ }+ }+ bool previewDue = stopwatch.ElapsedMilliseconds - lastPreviewMs >= PreviewIntervalMs;+ bool doPreview = previewPixels != null && previewDue && Thread.VolatileRead(ref this._previewPending) <= 0;+ if (doPreview)+ {+ lastPreviewMs = stopwatch.ElapsedMilliseconds;+ }+ engine.PrepareFrame(writeField || (doPreview && settings.PreviewField), writeIntensity || (doPreview && settings.PreviewIntensity));+ if (writeField)+ {+ FrameRenderer.RenderField(engine, this._job.FieldLut, fieldBrightness, framePixels, width, height);+ FrameRenderer.AddOverlay(framePixels, fieldOverlay, width, height);+ if (collector != null)+ {+ ProbeOverlay.Burn(framePixels, width, height, this._job.Probes, collector.Traces, ProbePlaceOn.Field, totalSteps);+ }+ fieldSink.AddPixels(framePixels);+ }+ if (writeIntensity)+ {+ FrameRenderer.RenderIntensity(engine, this._job.IntensityLut, intensityBrightness, framePixels, width, height);+ FrameRenderer.AddOverlay(framePixels, intensityOverlay, width, height);+ if (collector != null)+ {+ ProbeOverlay.Burn(framePixels, width, height, this._job.Probes, collector.Traces, ProbePlaceOn.Intensity, totalSteps);+ }+ intensitySink.AddPixels(framePixels);+ }+ if (doPreview)+ {+ // Set the outstanding count before raising, so PreviewShown() cannot race it to 0.+ int previewCount = (settings.PreviewField ? 1 : 0) + (settings.PreviewIntensity ? 1 : 0);+ Interlocked.Exchange(ref this._previewPending, previewCount);+ if (settings.PreviewField)+ {+ FrameRenderer.RenderField(engine, this._job.FieldLut, fieldBrightness, previewPixels, previewWidth, previewHeight);+ this.PreviewReady?.Invoke(true, FrameRenderer.ToBitmap(previewPixels, previewWidth, previewHeight));+ }+ if (settings.PreviewIntensity)+ {+ FrameRenderer.RenderIntensity(engine, this._job.IntensityLut, intensityBrightness, previewPixels, previewWidth, previewHeight);+ this.PreviewReady?.Invoke(false, FrameRenderer.ToBitmap(previewPixels, previewWidth, previewHeight));+ }+ }+ }+ if (collector != null && stopwatch.ElapsedMilliseconds - lastProbeMs >= 50L)+ {+ lastProbeMs = stopwatch.ElapsedMilliseconds;+ collector.Collect(engine, result.StepsDone);+ collector.CollectProfiles(engine, result.StepsDone);+ this.ProbesUpdated?.Invoke(collector.TakeForUi());+ }+ if (stopwatch.ElapsedMilliseconds - lastProgressMs >= 100L)+ {+ lastProgressMs = stopwatch.ElapsedMilliseconds;+ this.ProgressChanged?.Invoke(i + 1, totalSteps);+ }+ }+ if (collector != null)+ {+ collector.Collect(engine, result.StepsDone);+ collector.CollectProfiles(engine, result.StepsDone);+ this.ProbesUpdated?.Invoke(collector.TakeForUi());+ }+ }+ catch (OutOfMemoryException)+ {+ result.Status = SimulationStatus.Failed;+ result.Message = "There is not enough memory for a simulation of this size. Use a smaller canvas.";+ }+ catch (Exception ex)+ {+ result.Status = SimulationStatus.Failed;+ result.Message = ex.Message;+ }+ finally+ {+ try+ {+ if (fieldSink != null)+ {+ fieldSink.Close();+ }+ }+ catch (Exception)+ {+ }+ try+ {+ if (intensitySink != null)+ {+ intensitySink.Close();+ }+ }+ catch (Exception)+ {+ }+ if (engine != null)+ {+ try+ {+ // Capture the final full-size frames for the UI / frame export before the engine goes away.+ int[] lastPixels = new int[engine.Width * engine.Height];+ bool hasIntensity = engine.IntensityData != null;+ engine.PrepareFrame(true, hasIntensity);+ FrameRenderer.RenderField(engine, this._job.FieldLut, (float)this._job.Settings.FieldBrightness, lastPixels, engine.Width, engine.Height);+ if (collector != null)+ {+ ProbeOverlay.Burn(lastPixels, engine.Width, engine.Height, this._job.Probes, collector.Traces, ProbePlaceOn.Field, totalSteps);+ }+ result.LastFieldFrame = FrameRenderer.ToBitmap(lastPixels, engine.Width, engine.Height);+ if (hasIntensity)+ {+ FrameRenderer.RenderIntensity(engine, this._job.IntensityLut, (float)this._job.Settings.IntensityBrightness, lastPixels, engine.Width, engine.Height);+ if (collector != null)+ {+ ProbeOverlay.Burn(lastPixels, engine.Width, engine.Height, this._job.Probes, collector.Traces, ProbePlaceOn.Intensity, totalSteps);+ }+ result.LastIntensityFrame = FrameRenderer.ToBitmap(lastPixels, engine.Width, engine.Height);+ }+ }+ catch (Exception)+ {+ }+ try+ {+ engine.Dispose();+ }+ catch (Exception)+ {+ }+ this._sim = null;+ this._collector = null;+ }+ if (this._job.Image != null)+ {+ this._job.Image.Dispose();+ }+ }+ stopwatch.Stop();+ result.Elapsed = stopwatch.Elapsed;+ this.ProgressChanged?.Invoke(result.StepsDone, this._job.Settings.Steps);+ this.Finished?.Invoke(result);+ }++ /// <summary>+ /// Opens an H.264 MP4 writer for .mp4 paths, falling back to a Motion JPEG .avi (same name, .avi+ /// extension) when the Media Foundation encoder cannot be set up; any partial .mp4 is deleted and+ /// the reason is stored in <see cref="SimulationResult.Message"/>. Other extensions always get AVI.+ /// </summary>+ /// <param name="filePath">Requested output path; the extension decides the container.</param>+ /// <param name="w">Frame width in pixels.</param>+ /// <param name="h">Frame height in pixels.</param>+ /// <param name="fps">Playback frame rate.</param>+ /// <param name="quality">1..100; bitrate for MP4, JPEG quality for AVI.</param>+ /// <param name="result">Receives the fallback message; its file lists are filled by the caller.</param>+ /// <returns>An open sink; its <see cref="IFrameSink.FilePath"/> is the path actually used.</returns>+ private static IFrameSink OpenSink(string filePath, int w, int h, int fps, int quality, SimulationResult result)+ {+ if (string.Equals(Path.GetExtension(filePath), ".mp4", StringComparison.OrdinalIgnoreCase))+ {+ try+ {+ return new MfVideoWriter(filePath, w, h, fps, quality);+ }+ catch (Exception ex)+ {+ if (File.Exists(filePath))+ {+ try+ {+ File.Delete(filePath);+ }+ catch (Exception)+ {+ }+ }+ result.Message = "MP4 (H.264) video could not be made on this computer (" + ex.Message.Trim() + "). The videos were written as Motion JPEG .avi files instead; play them with VLC.";+ filePath = Path.ChangeExtension(filePath, ".avi");+ }+ }+ return new AviFrameSink(filePath, w, h, fps, quality);+ }++ /// <summary>Unused leftover; the JPEG quality actually comes from <see cref="SimulationSettings.VideoQuality"/>.</summary>+ private const long JpegQuality = 90L;++ /// <summary>Minimum time between two preview frames, in stopwatch milliseconds (about 30 fps).</summary>+ private const long PreviewIntervalMs = 33L;++ /// <summary>The job to run; its bitmaps are consumed and disposed by the worker.</summary>+ private readonly SimulationJob _job;++ /// <summary>The worker thread; null until <see cref="Start"/>.</summary>+ private Thread _thread;++ /// <summary>Cancel flag (0/1), written by the UI thread via <see cref="Interlocked"/>, read volatile by the worker.</summary>+ private int _cancel;++ /// <summary>Number of preview bitmaps handed to the UI that have not been acknowledged by <see cref="PreviewShown"/> yet.</summary>+ private int _previewPending;++ /// <summary>Pause gate: set = running, reset = paused. The worker waits on it at the top of each step.</summary>+ private readonly ManualResetEventSlim _gate;++ /// <summary>The live engine, published for <see cref="RenderCurrentFrame"/>; null before creation and after the run ends.</summary>+ private IWaveEngine _sim;++ /// <summary>The live probe collector (null when the job has no probes or after the run ends); used by <see cref="RenderCurrentFrame"/>.</summary>+ private ProbeCollector _collector;++ /// <summary>Handler for <see cref="ProgressChanged"/>: steps completed so far and the total step count.</summary>+ public delegate void ProgressChangedEventHandler(int stepsDone, int totalSteps);++ /// <summary>Handler for <see cref="EngineReady"/>: engine description and an optional note (empty when none).</summary>+ public delegate void EngineReadyEventHandler(string description, string note);++ /// <summary>Handler for <see cref="ProbesUpdated"/>: the samples drained since the previous update.</summary>+ public delegate void ProbesUpdatedEventHandler(ProbeUpdate update);++ /// <summary>Handler for <see cref="PreviewReady"/>: <paramref name="isField"/> tells which picture box the (caller-owned) bitmap is for.</summary>+ public delegate void PreviewReadyEventHandler(bool isField, Bitmap frame);++ /// <summary>Handler for <see cref="Finished"/>: the completed result, including status, files and last frames.</summary>+ public delegate void FinishedEventHandler(SimulationResult result);+ }+}diff --git a/Wave_Dude_2D/SimulationSettings.cs b/Wave_Dude_2D/SimulationSettings.csnew file mode 100644index 0000000..b4df11c--- /dev/null+++ b/Wave_Dude_2D/SimulationSettings.cs@@ -0,0 +1,259 @@+using System;+using System.Collections.Generic;+using System.Globalization;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// The "simulation" section of a project: step count, visualisation and export options, and solver+ /// parameters. Edited by <c>Form1</c> on the UI thread, persisted through <see cref="ProjectConfig"/> and+ /// handed to the runner as a <see cref="Clone"/> inside the <see cref="SimulationJob"/>.+ /// </summary>+ public sealed class SimulationSettings+ {+ /// <summary>Creates settings with the UI defaults (preview on, export off, 4th-order stencil, CPU engine); <see cref="Steps"/> and <see cref="TimeDecayFactor"/> stay 0.</summary>+ public SimulationSettings()+ {+ this.VisualizeEvery = 2;+ this.ExportField = false;+ this.ExportIntensity = false;+ this.PreviewField = true;+ this.PreviewIntensity = true;+ this.FieldColorScheme = "Default_Field";+ this.IntensityColorScheme = "Default_intensity";+ this.FieldBrightness = 30.0;+ this.IntensityBrightness = 30.0;+ this.FieldBlackLevel = -0.05;+ this.IntensityBlackLevel = 0.0;+ this.SourceFrequencyScale = 2.0;+ this.VideoFps = 60;+ this.VideoQuality = DefaultVideoQuality;+ this.UseGpu = false;+ this.Use4thOrderLaplacian = true;+ this.WaveSpeedC = 1.0;+ this.IntensityScale = 1.0;+ }++ /// <summary>Total number of simulation steps to run.</summary>+ public int Steps { get; set; }++ /// <summary>Render, export and collect probe data every this many steps.</summary>+ public int VisualizeEvery { get; set; }++ /// <summary>Whether to write the field frames to a video file.</summary>+ public bool ExportField { get; set; }++ /// <summary>Whether to write the intensity frames to a video file.</summary>+ public bool ExportIntensity { get; set; }++ /// <summary>Whether to show the field in the live preview.</summary>+ public bool PreviewField { get; set; }++ /// <summary>Whether to show the intensity in the live preview.</summary>+ public bool PreviewIntensity { get; set; }++ /// <summary>Name of the <see cref="ColorScheme"/> used for field frames.</summary>+ public string FieldColorScheme { get; set; }++ /// <summary>Name of the <see cref="ColorScheme"/> used for intensity frames.</summary>+ public string IntensityColorScheme { get; set; }++ /// <summary>Display gain for field frames (multiplies the field value before the colour lookup).</summary>+ public double FieldBrightness { get; set; }++ /// <summary>Display gain for intensity frames (multiplies the square root of the intensity before the colour lookup).</summary>+ public double IntensityBrightness { get; set; }++ /// <summary>Offset baked into the field colour LUT (the "offset" spinner in the UI); see <see cref="ColorLut.Build"/>.</summary>+ public double FieldBlackLevel { get; set; }++ /// <summary>Offset baked into the intensity colour LUT (the "offset" spinner in the UI); see <see cref="ColorLut.Build"/>.</summary>+ public double IntensityBlackLevel { get; set; }++ /// <summary>Multiplier in the source level-to-frequency mapping: angular frequency = level/255 × 0.5 × this, in radians per step.</summary>+ public double SourceFrequencyScale { get; set; }++ /// <summary>Frame rate of the exported videos.</summary>+ public int VideoFps { get; set; }++ /// <summary>Encoder quality of the exported videos, 1..100.</summary>+ public int VideoQuality { get; set; }++ /// <summary>Prefer the OpenCL engine; the CPU engine is used when no usable GPU is found.</summary>+ public bool UseGpu { get; set; }++ /// <summary>Use the 4th-order Laplacian stencil (with sub-stepping) instead of the 9-point one.</summary>+ public bool Use4thOrderLaplacian { get; set; }++ /// <summary>+ /// Nominal wave speed c in canvas pixels per step, used only to estimate a source's wavelength in the UI+ /// (λ = c / frequency); the engines derive the actual speed from the refractive index map.+ /// </summary>+ public double WaveSpeedC { get; set; }++ /// <summary>Intensity averaging time factor: the engines average over timeDecayFactor × 100 / (lowest source level) steps.</summary>+ public double TimeDecayFactor { get; set; }++ /// <summary>Multiplier applied to the intensity values produced by the engine.</summary>+ public double IntensityScale { get; set; }++ /// <summary>Shallow copy; all members are value types or immutable strings, so the copy is independent.</summary>+ public SimulationSettings Clone()+ {+ return (SimulationSettings)base.MemberwiseClone();+ }++ /// <summary>+ /// Reads the "simulation" section of <paramref name="config"/>. Missing keys and out-of-range values fall+ /// back to per-key defaults; a missing section yields a default instance.+ /// </summary>+ /// <remarks>+ /// The per-key fallbacks differ from the constructor defaults for some keys (steps 2500 vs 0,+ /// use_4th_order_laplacian false vs true, wave_speed_c 0.563 vs 1.0, time_decay_factor 10 vs 0).+ /// </remarks>+ public static SimulationSettings FromConfig(ProjectConfig config)+ {+ SimulationSettings settings = new SimulationSettings();+ if (!config.ContainsKey(SectionName))+ {+ return settings;+ }+ Dictionary<string, object> section = config.GetSection(SectionName);+ settings.Steps = SimulationSettings.ReadInt(section, "steps", DefaultSteps, 1, MaxSteps);+ settings.VisualizeEvery = SimulationSettings.ReadInt(section, "visualize_every", 2, 1, MaxVisualizeEvery);+ settings.ExportField = SimulationSettings.ReadBool(section, "export_field", false);+ settings.ExportIntensity = SimulationSettings.ReadBool(section, "export_intensity", false);+ settings.PreviewField = SimulationSettings.ReadBool(section, "preview_field", true);+ settings.PreviewIntensity = SimulationSettings.ReadBool(section, "preview_intensity", true);+ settings.FieldColorScheme = SimulationSettings.ReadText(section, "field_color_scheme", "Default_Field");+ settings.IntensityColorScheme = SimulationSettings.ReadText(section, "intensity_color_scheme", "Default_intensity");+ settings.FieldBrightness = SimulationSettings.ReadDouble(section, "field_brightness", 30.0, 0.0001, 100000.0);+ settings.IntensityBrightness = SimulationSettings.ReadDouble(section, "intensity_brightness", 30.0, 0.0001, 100000.0);+ settings.FieldBlackLevel = SimulationSettings.ReadDouble(section, "field_black_level", -0.05, -10.0, 1.0);+ settings.IntensityBlackLevel = SimulationSettings.ReadDouble(section, "intensity_black_level", 0.0, -10.0, 1.0);+ settings.SourceFrequencyScale = SimulationSettings.ReadDouble(section, "source_frequency_scale", 2.0, 0.0, 1000.0);+ settings.VideoFps = SimulationSettings.ReadInt(section, "video_fps", 60, 1, MaxVideoFps);+ settings.VideoQuality = SimulationSettings.ReadInt(section, "video_quality", DefaultVideoQuality, 1, 100);+ settings.UseGpu = SimulationSettings.ReadBool(section, "use_gpu", false);+ settings.Use4thOrderLaplacian = SimulationSettings.ReadBool(section, "use_4th_order_laplacian", false);+ settings.WaveSpeedC = SimulationSettings.ReadDouble(section, "wave_speed_c", 0.563, 1E-06, 1000000.0);+ settings.TimeDecayFactor = SimulationSettings.ReadDouble(section, "time_decay_factor", 10.0, 1.0, 100.0);+ settings.IntensityScale = SimulationSettings.ReadDouble(section, "intensity_scale", 1.0, 1E-07, 1000000.0);+ return settings;+ }++ /// <summary>Writes every value into the "simulation" section of <paramref name="config"/>, creating the section if needed.</summary>+ public void ToConfig(ProjectConfig config)+ {+ Dictionary<string, object> section = config.GetSection(SectionName);+ section["steps"] = this.Steps;+ section["visualize_every"] = this.VisualizeEvery;+ section["export_field"] = this.ExportField;+ section["export_intensity"] = this.ExportIntensity;+ section["preview_field"] = this.PreviewField;+ section["preview_intensity"] = this.PreviewIntensity;+ section["field_color_scheme"] = this.FieldColorScheme;+ section["intensity_color_scheme"] = this.IntensityColorScheme;+ section["field_brightness"] = this.FieldBrightness;+ section["intensity_brightness"] = this.IntensityBrightness;+ section["field_black_level"] = this.FieldBlackLevel;+ section["intensity_black_level"] = this.IntensityBlackLevel;+ section["source_frequency_scale"] = this.SourceFrequencyScale;+ section["video_fps"] = this.VideoFps;+ section["video_quality"] = this.VideoQuality;+ section["use_gpu"] = this.UseGpu;+ section["use_4th_order_laplacian"] = this.Use4thOrderLaplacian;+ section["wave_speed_c"] = this.WaveSpeedC;+ section["time_decay_factor"] = this.TimeDecayFactor;+ section["intensity_scale"] = this.IntensityScale;+ }++ /// <summary>The value under <paramref name="key"/> converted to text (invariant culture), or the fallback when absent or null.</summary>+ private static string ReadText(Dictionary<string, object> section, string key, string fallback)+ {+ object value;+ if (section.TryGetValue(key, out value) && value != null)+ {+ return Convert.ToString(value, CultureInfo.InvariantCulture);+ }+ return fallback;+ }++ /// <summary>The value under <paramref name="key"/> if it is an actual <see cref="bool"/>; anything else yields the fallback.</summary>+ private static bool ReadBool(Dictionary<string, object> section, string key, bool fallback)+ {+ object value;+ if (section.TryGetValue(key, out value) && value is bool)+ {+ return Convert.ToBoolean(value);+ }+ return fallback;+ }++ /// <summary>+ /// The value under <paramref name="key"/> converted to an int (invariant culture) when it converts and+ /// lies within [<paramref name="minValue"/>, <paramref name="maxValue"/>]; otherwise the fallback.+ /// </summary>+ private static int ReadInt(Dictionary<string, object> section, string key, int fallback, int minValue, int maxValue)+ {+ object value;+ if (section.TryGetValue(key, out value) && value != null)+ {+ try+ {+ int parsed = Convert.ToInt32(value, CultureInfo.InvariantCulture);+ if (parsed >= minValue && parsed <= maxValue)+ {+ return parsed;+ }+ }+ catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException)+ {+ }+ }+ return fallback;+ }++ /// <summary>+ /// The value under <paramref name="key"/> converted to a double (invariant culture) when it converts and+ /// lies within [<paramref name="minValue"/>, <paramref name="maxValue"/>]; otherwise the fallback.+ /// </summary>+ private static double ReadDouble(Dictionary<string, object> section, string key, double fallback, double minValue, double maxValue)+ {+ object value;+ if (section.TryGetValue(key, out value) && value != null)+ {+ try+ {+ double parsed = Convert.ToDouble(value, CultureInfo.InvariantCulture);+ if (parsed >= minValue && parsed <= maxValue)+ {+ return parsed;+ }+ }+ catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException)+ {+ }+ }+ return fallback;+ }++ /// <summary>Name of this section in the project file.</summary>+ public const string SectionName = "simulation";++ /// <summary>Fallback for <see cref="Steps"/> when the key is missing from a project file.</summary>+ public const int DefaultSteps = 2500;++ /// <summary>Largest accepted <see cref="Steps"/>.</summary>+ public const int MaxSteps = 10000000;++ /// <summary>Largest accepted <see cref="VisualizeEvery"/>.</summary>+ public const int MaxVisualizeEvery = 1000;++ /// <summary>Largest accepted <see cref="VideoFps"/>.</summary>+ public const int MaxVideoFps = 240;++ /// <summary>Default <see cref="VideoQuality"/>.</summary>+ public const int DefaultVideoQuality = 70;+ }+}diff --git a/Wave_Dude_2D/SimulationStatus.cs b/Wave_Dude_2D/SimulationStatus.csnew file mode 100644index 0000000..5783469--- /dev/null+++ b/Wave_Dude_2D/SimulationStatus.cs@@ -0,0 +1,16 @@+namespace _2D_wave_sim_V01+{+ /// <summary>+ /// How a simulation run ended. Set by <see cref="SimulationRunner"/> on its worker thread in+ /// <see cref="SimulationResult.Status"/> and read by <c>Form1.OnSimulationFinished</c> on the UI thread.+ /// </summary>+ internal enum SimulationStatus+ {+ /// <summary>All requested steps were computed.</summary>+ Completed,+ /// <summary>The user stopped the run (or closed the program) before the last step.</summary>+ Cancelled,+ /// <summary>An exception ended the run early; the reason is in <see cref="SimulationResult.Message"/>.</summary>+ Failed+ }+}diff --git a/Wave_Dude_2D/SourceCompositeMode.cs b/Wave_Dude_2D/SourceCompositeMode.csnew file mode 100644index 0000000..0d4676a--- /dev/null+++ b/Wave_Dude_2D/SourceCompositeMode.cs@@ -0,0 +1,17 @@+using System;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// How the elements of a <see cref="SourceMainType.Composite"/> array derive their properties+ /// from the single-source settings. Ignored for simple sources. Stored in the project as+ /// <c>"inherit"</c> / <c>"randomize"</c>.+ /// </summary>+ public enum SourceCompositeMode+ {+ /// <summary>Every element is an exact copy of the single-source settings; only its position differs.</summary>+ InheritFromSingle,+ /// <summary>Elements inherit the settings, and each enabled "randomize" option (frequency, phase, off-width, position) adds an independent random offset per element when the elements are generated.</summary>+ InheritAndRandomize+ }+}diff --git a/Wave_Dude_2D/SourceElement.cs b/Wave_Dude_2D/SourceElement.csnew file mode 100644index 0000000..34158ce--- /dev/null+++ b/Wave_Dude_2D/SourceElement.cs@@ -0,0 +1,91 @@+using System;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// One point source as the wave engines consume it: a resolved, per-element copy of the+ /// user's <see cref="SourceSettings"/> with all units already converted (phase in radians,+ /// amplitude 0..1). Produced by <see cref="SourceSettings.GenerateElements"/> on the UI+ /// thread, stored in the project file, and handed by reference to+ /// <c>SimulationJob.ObjectSources</c>, where <c>WaveSimulator</c> / <c>GpuWaveSimulator</c>+ /// read it from the <c>SimulationRunner</c> worker thread. The engines never write to it+ /// (they keep their own per-element off-width state), so it must simply not be mutated+ /// while a run is in progress.+ /// </summary>+ public sealed class SourceElement+ {+ /// <summary>Creates an element at (0, 0) with the fallback values: level 100, amplitude 0.5, no phase, continuous, 10-cycle on/off widths, never detached.</summary>+ public SourceElement()+ {+ this.Level = 100;+ this.Amplitude = 0.5;+ this.PhaseRad = 0.0;+ this.Mode = SourceMode.Continuous;+ this.PulseShape = SourcePulseShape.Gaussian;+ this.OnWidthCycles = 10;+ this.OffWidthCycles = 10;+ this.OffWidthBase = 10;+ this.RandomizeOffWidthAmount = 0;+ this.DetachAfterStep = -1;+ }++ /// <summary>X position in canvas pixels (0 = left edge). Elements outside the canvas are dropped by the engines.</summary>+ public int PosX { get; set; }++ /// <summary>Y position in canvas pixels (0 = top edge). Elements outside the canvas are dropped by the engines.</summary>+ public int PosY { get; set; }++ /// <summary>+ /// Frequency as a source level 1..255, the same scale as the brightness of image-based+ /// sources. The engines map it to an angular frequency of+ /// <c>Level / 255 * 0.5 * SimulationSettings.SourceFrequencyScale</c> radians per step.+ /// </summary>+ public int Level { get; set; }++ /// <summary>Peak field amplitude 0..1 (the settings' 0..100 % divided by 100).</summary>+ public double Amplitude { get; set; }++ /// <summary>Phase offset in radians added to the sine argument (<c>sin(PhaseRad + omega * t)</c>); positive values lead.</summary>+ public double PhaseRad { get; set; }++ /// <summary>Continuous or pulsed emission.</summary>+ public SourceMode Mode { get; set; }++ /// <summary>Envelope shape of each burst; only used when <see cref="Mode"/> is <see cref="SourceMode.Pulsed"/>.</summary>+ public SourcePulseShape PulseShape { get; set; }++ /// <summary>Length of the "on" burst in cycles of this element's own frequency (pulsed mode only).</summary>+ public int OnWidthCycles { get; set; }++ /// <summary>+ /// Length of the "off" gap in cycles (pulsed mode only). With a fixed gap+ /// (<see cref="RandomizeOffWidthAmount"/> is 0) the engines shift the period so the first+ /// burst starts at step 0 and the gap follows each burst. With a randomised gap the first+ /// period begins with a gap of this length before the first burst, and every later gap is+ /// re-drawn by the engine around <see cref="OffWidthBase"/>.+ /// </summary>+ public int OffWidthCycles { get; set; }++ /// <summary>Nominal off gap in cycles that the engine randomises around for every new period when <see cref="RandomizeOffWidthAmount"/> is positive.</summary>+ public int OffWidthBase { get; set; }++ /// <summary>Half-range in cycles of the per-period random off-width offset (gap = max(1, OffWidthBase +/- amount)); 0 keeps <see cref="OffWidthCycles"/> fixed.</summary>+ public int RandomizeOffWidthAmount { get; set; }++ /// <summary>Simulation step after which the source is switched off, fading out linearly over <see cref="DetachRampSteps"/> steps; -1 means it stays on for the whole run.</summary>+ public int DetachAfterStep { get; set; }++ /// <summary>Shallow copy; sufficient because every property is a value type.</summary>+ public SourceElement Clone()+ {+ return (SourceElement)base.MemberwiseClone();+ }++ /// <summary>+ /// Number of steps over which a detached source fades from full amplitude to zero.+ /// Documents the value the engines use; both <c>WaveSimulator</c> and the OpenCL kernel+ /// currently hard-code 30 rather than referencing this constant.+ /// </summary>+ public const int DetachRampSteps = 30;+ }+}diff --git a/Wave_Dude_2D/SourceMainType.cs b/Wave_Dude_2D/SourceMainType.csnew file mode 100644index 0000000..809ea9a--- /dev/null+++ b/Wave_Dude_2D/SourceMainType.cs@@ -0,0 +1,17 @@+using System;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Whether a <see cref="SourceSettings"/> entry describes one point source or a rectangular+ /// array of identical point sources. Selected with the "main type" combo box on the source+ /// tab and stored in the project as <c>"single"</c> / <c>"composite"</c>.+ /// </summary>+ public enum SourceMainType+ {+ /// <summary>A single point source at (PosX, PosY); generates exactly one <see cref="SourceElement"/>.</summary>+ Simple,+ /// <summary>An ArraySizeX x ArraySizeY grid of point sources centred on (PosX, PosY), optionally randomised per element.</summary>+ Composite+ }+}diff --git a/Wave_Dude_2D/SourceMode.cs b/Wave_Dude_2D/SourceMode.csnew file mode 100644index 0000000..34db81c--- /dev/null+++ b/Wave_Dude_2D/SourceMode.cs@@ -0,0 +1,17 @@+using System;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Time behaviour of a point source. Chosen with the mode radio buttons on the source tab,+ /// copied into every generated <see cref="SourceElement"/> and evaluated by the wave engines+ /// on each simulation step.+ /// </summary>+ public enum SourceMode+ {+ /// <summary>The source emits a steady sine wave for the whole run (envelope is always 1).</summary>+ Continuous,+ /// <summary>The sine wave is gated by a repeating on/off envelope whose shape is a <see cref="SourcePulseShape"/> and whose on and off lengths are given in cycles.</summary>+ Pulsed+ }+}diff --git a/Wave_Dude_2D/SourcePulseShape.cs b/Wave_Dude_2D/SourcePulseShape.csnew file mode 100644index 0000000..14eaade--- /dev/null+++ b/Wave_Dude_2D/SourcePulseShape.cs@@ -0,0 +1,16 @@+using System;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Envelope shape of one "on" burst of a <see cref="SourceMode.Pulsed"/> source. Only used+ /// when the mode is pulsed; stored in the project as <c>"gaussian"</c> / <c>"smoothed_square"</c>.+ /// </summary>+ public enum SourcePulseShape+ {+ /// <summary>Gaussian bell centred in the on-window; its sigma is one sixth of the on-width, so the burst is essentially zero at both edges.</summary>+ Gaussian,+ /// <summary>Flat-topped burst with smoothed rising and falling edges that spans the whole on-width.</summary>+ SmoothedSquare+ }+}diff --git a/Wave_Dude_2D/SourceSettings.cs b/Wave_Dude_2D/SourceSettings.csnew file mode 100644index 0000000..0799095--- /dev/null+++ b/Wave_Dude_2D/SourceSettings.cs@@ -0,0 +1,540 @@+using System;+using System.Collections;+using System.Collections.Generic;+using System.Globalization;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// User-editable description of one wave source (single or composite array) plus the+ /// generated <see cref="SourceElement"/> list that the simulation actually consumes.+ /// Edited on the source tab of <c>Form1</c> (UI thread only), persisted in the+ /// <see cref="SectionName"/> section of the project config, and expanded into elements by+ /// <see cref="GenerateElements"/> whenever the user saves the source. Units are the ones+ /// shown in the UI: positions in canvas pixels, frequency as a 1..255 level, amplitude in+ /// percent, phase in degrees, pulse widths in cycles, detach time in simulation steps.+ /// </summary>+ public sealed class SourceSettings+ {+ /// <summary>Creates a source with the editor defaults: "Source 1", simple, continuous Gaussian at (100, 100) but not yet positioned, frequency level 100, 100 % amplitude, 10-cycle widths, 1x1 array with 10 px spacing, nothing randomised, no elements.</summary>+ public SourceSettings()+ {+ this.Name = "Source 1";+ this.MainType = SourceMainType.Simple;+ this.PosX = 100;+ this.PosY = 100;+ this.HasPosition = false;+ this.SourceOn = true;+ this.DetachSource = false;+ this.DetachAfterSteps = 1000;+ this.Frequency = 100;+ this.Amplitude = 100;+ this.PhaseDeg = 0;+ this.Mode = SourceMode.Continuous;+ this.PulseShape = SourcePulseShape.Gaussian;+ this.PulseWidthCycles = 10;+ this.OffStateCycles = 10;+ this.ArraySizeX = 1;+ this.ArraySizeY = 1;+ this.SpacingX = 10;+ this.SpacingY = 10;+ this.CompositeMode = SourceCompositeMode.InheritFromSingle;+ this.RandomizeFrequency = false;+ this.RandomizeFrequencyAmount = 0;+ this.RandomizePhase = false;+ this.RandomizePhaseAmount = 0;+ this.RandomizeOffWidth = false;+ this.RandomizeOffWidthAmount = 0;+ this.RandomizePosition = false;+ this.RandomizePositionAmount = 0;+ this.Elements = new List<SourceElement>();+ }++ /// <summary>Display name shown in the source list and next to the marker on the scene picture; must be non-blank to save.</summary>+ public string Name { get; set; }++ /// <summary>Single point source or composite array.</summary>+ public SourceMainType MainType { get; set; }++ /// <summary>X position in canvas pixels of the source, or of the array centre for a composite source.</summary>+ public int PosX { get; set; }++ /// <summary>Y position in canvas pixels of the source, or of the array centre for a composite source.</summary>+ public int PosY { get; set; }++ /// <summary>+ /// True once the user has placed the source (by picking on the picture or editing the+ /// position inputs); only sources with a position get a marker drawn on the scene picture.+ /// Defaults to false for a new source but to true when loaded from a project without the key.+ /// </summary>+ public bool HasPosition { get; set; }++ /// <summary>Whether the source takes part in simulation runs; disabled sources are listed in grey and skipped.</summary>+ public bool SourceOn { get; set; }++ /// <summary>Whether the source is switched off during the run after <see cref="DetachAfterSteps"/>.</summary>+ public bool DetachSource { get; set; }++ /// <summary>Simulation step at which the source starts fading out when <see cref="DetachSource"/> is set; 0 or greater.</summary>+ public int DetachAfterSteps { get; set; }++ /// <summary>+ /// Frequency as a source level 1..255, the same scale as the brightness of image-based+ /// sources (angular frequency = level / 255 * 0.5 * <c>SimulationSettings.SourceFrequencyScale</c>+ /// radians per step). Copied to <see cref="SourceElement.Level"/>.+ /// </summary>+ public int Frequency { get; set; }++ /// <summary>Amplitude in percent, 0..100; becomes 0..1 on the element.</summary>+ public int Amplitude { get; set; }++ /// <summary>Phase offset in degrees, -180..180; converted to radians on the element.</summary>+ public int PhaseDeg { get; set; }++ /// <summary>Continuous or pulsed emission.</summary>+ public SourceMode Mode { get; set; }++ /// <summary>Burst envelope shape; only used in pulsed mode.</summary>+ public SourcePulseShape PulseShape { get; set; }++ /// <summary>Length of each "on" burst in cycles of the source frequency, at least 1 (pulsed mode only).</summary>+ public int PulseWidthCycles { get; set; }++ /// <summary>Length of the "off" gap between bursts in cycles, at least 1 (pulsed mode only).</summary>+ public int OffStateCycles { get; set; }++ /// <summary>Number of array columns for a composite source, at least 1; the UI enforces odd values so the centre element sits on (PosX, PosY).</summary>+ public int ArraySizeX { get; set; }++ /// <summary>Number of array rows for a composite source, at least 1; the UI enforces odd values.</summary>+ public int ArraySizeY { get; set; }++ /// <summary>Horizontal distance between neighbouring array elements in canvas pixels.</summary>+ public int SpacingX { get; set; }++ /// <summary>Vertical distance between neighbouring array elements in canvas pixels.</summary>+ public int SpacingY { get; set; }++ /// <summary>Whether composite elements are exact copies or get per-element random offsets.</summary>+ public SourceCompositeMode CompositeMode { get; set; }++ /// <summary>Enables the per-element frequency offset (composite + randomize mode only).</summary>+ public bool RandomizeFrequency { get; set; }++ /// <summary>Half-range of the random frequency offset in levels: each element gets Frequency +/- up to this, clamped to 1..255.</summary>+ public int RandomizeFrequencyAmount { get; set; }++ /// <summary>Enables the per-element phase offset (composite + randomize mode only).</summary>+ public bool RandomizePhase { get; set; }++ /// <summary>Half-range of the random phase offset in degrees: each element gets PhaseDeg +/- up to this, clamped to -180..180.</summary>+ public int RandomizePhaseAmount { get; set; }++ /// <summary>Enables the per-element and per-period off-width randomisation (composite + randomize mode only).</summary>+ public bool RandomizeOffWidth { get; set; }++ /// <summary>Half-range of the random off-gap offset in cycles; also passed on to the elements so the engine re-draws the gap every period.</summary>+ public int RandomizeOffWidthAmount { get; set; }++ /// <summary>Enables the per-element position jitter (composite + randomize mode only).</summary>+ public bool RandomizePosition { get; set; }++ /// <summary>Half-range of the position jitter in canvas pixels, drawn independently for X and Y of each element; the UI caps it at half the smallest spacing.</summary>+ public int RandomizePositionAmount { get; set; }++ /// <summary>+ /// The point sources generated from these settings by <see cref="GenerateElements"/>;+ /// empty until the source has been saved at least once. Persisted with the project so a+ /// randomised layout survives reloads. Handed to the simulation by reference.+ /// </summary>+ public List<SourceElement> Elements { get; set; }++ /// <summary>Deep copy: the element list and every element are cloned as well.</summary>+ public SourceSettings Clone()+ {+ SourceSettings copy = (SourceSettings)base.MemberwiseClone();+ copy.Elements = new List<SourceElement>();+ foreach (SourceElement element in this.Elements)+ {+ copy.Elements.Add(element.Clone());+ }+ return copy;+ }++ /// <summary>+ /// Clamps every setting into its valid range (frequency 1..255, amplitude 0..100, phase+ /// -180..180, widths and array sizes at least 1, detach steps at least 0). Positions,+ /// spacings and randomise amounts are not touched.+ /// </summary>+ public void Normalize()+ {+ if (this.Frequency < 1)+ {+ this.Frequency = 1;+ }+ if (this.Frequency > 255)+ {+ this.Frequency = 255;+ }+ if (this.Amplitude < 0)+ {+ this.Amplitude = 0;+ }+ if (this.Amplitude > 100)+ {+ this.Amplitude = 100;+ }+ if (this.PhaseDeg < -180)+ {+ this.PhaseDeg = -180;+ }+ if (this.PhaseDeg > 180)+ {+ this.PhaseDeg = 180;+ }+ if (this.PulseWidthCycles < 1)+ {+ this.PulseWidthCycles = 1;+ }+ if (this.OffStateCycles < 1)+ {+ this.OffStateCycles = 1;+ }+ if (this.ArraySizeX < 1)+ {+ this.ArraySizeX = 1;+ }+ if (this.ArraySizeY < 1)+ {+ this.ArraySizeY = 1;+ }+ if (this.DetachAfterSteps < 0)+ {+ this.DetachAfterSteps = 0;+ }+ }++ /// <summary>+ /// Rebuilds <see cref="Elements"/> from the settings: one element for a simple source,+ /// or an ArraySizeX x ArraySizeY grid centred on (PosX, PosY) for a composite source,+ /// optionally randomised per element. Calls <see cref="Normalize"/> first. Random offsets+ /// are only applied when <see cref="CompositeMode"/> is+ /// <see cref="SourceCompositeMode.InheritAndRandomize"/>, the matching Randomize flag is+ /// set and its amount is positive; frequency and phase offsets are clamped back into+ /// their valid ranges, the off gap is kept at least 1 cycle. Element positions are not+ /// clamped to the canvas. Every call replaces the list, so a randomised layout changes+ /// each time the source is saved.+ /// </summary>+ /// <param name="rng">Random generator for the per-element offsets; may be any instance when nothing is randomised.</param>+ public void GenerateElements(Random rng)+ {+ this.Normalize();+ List<SourceElement> elements = new List<SourceElement>();+ if (this.MainType == SourceMainType.Simple)+ {+ elements.Add(this.MakeBaseElement(this.PosX, this.PosY));+ }+ else+ {+ int arraySizeX = this.ArraySizeX;+ int arraySizeY = this.ArraySizeY;+ bool randomize = this.CompositeMode == SourceCompositeMode.InheritAndRandomize;+ for (int i = 0; i < arraySizeY; i++)+ {+ for (int j = 0; j < arraySizeX; j++)+ {+ // Grid is centred on (PosX, PosY); with an even size the centre falls between two elements.+ int x = this.PosX + (int)Math.Round((j - (arraySizeX - 1) / 2.0) * this.SpacingX);+ int y = this.PosY + (int)Math.Round((i - (arraySizeY - 1) / 2.0) * this.SpacingY);+ if (randomize && this.RandomizePosition && this.RandomizePositionAmount > 0)+ {+ x += SourceSettings.RandomInt(rng, this.RandomizePositionAmount);+ y += SourceSettings.RandomInt(rng, this.RandomizePositionAmount);+ }+ SourceElement element = this.MakeBaseElement(x, y);+ if (randomize && this.RandomizeFrequency && this.RandomizeFrequencyAmount > 0)+ {+ element.Level = SourceSettings.Clamp(this.Frequency + SourceSettings.RandomInt(rng, this.RandomizeFrequencyAmount), 1, 255);+ }+ if (randomize && this.RandomizePhase && this.RandomizePhaseAmount > 0)+ {+ int phaseDeg = SourceSettings.Clamp(this.PhaseDeg + SourceSettings.RandomInt(rng, this.RandomizePhaseAmount), -180, 180);+ element.PhaseRad = phaseDeg * Math.PI / 180.0;+ }+ if (randomize && this.RandomizeOffWidth && this.RandomizeOffWidthAmount > 0)+ {+ element.OffWidthCycles = Math.Max(1, this.OffStateCycles + SourceSettings.RandomInt(rng, this.RandomizeOffWidthAmount));+ element.RandomizeOffWidthAmount = this.RandomizeOffWidthAmount;+ }+ elements.Add(element);+ }+ }+ }+ this.Elements = elements;+ }++ /// <summary>+ /// Creates an element at the given canvas position with the non-randomised settings,+ /// converting amplitude to 0..1 and phase to radians; <c>DetachAfterStep</c> is -1 when+ /// <see cref="DetachSource"/> is off.+ /// </summary>+ private SourceElement MakeBaseElement(int x, int y)+ {+ return new SourceElement+ {+ PosX = x,+ PosY = y,+ Level = this.Frequency,+ Amplitude = this.Amplitude / 100.0,+ PhaseRad = this.PhaseDeg * Math.PI / 180.0,+ Mode = this.Mode,+ PulseShape = this.PulseShape,+ OnWidthCycles = this.PulseWidthCycles,+ OffWidthCycles = this.OffStateCycles,+ OffWidthBase = this.OffStateCycles,+ RandomizeOffWidthAmount = 0,+ DetachAfterStep = this.DetachSource ? this.DetachAfterSteps : -1+ };+ }++ /// <summary>Uniform random integer in [-amount, +amount]; 0 when amount is not positive. Also used by <c>WaveSimulator</c> for the per-period off-width.</summary>+ internal static int RandomInt(Random rng, int amount)+ {+ return amount <= 0 ? 0 : rng.Next(-amount, amount + 1);+ }++ /// <summary>Clamps <paramref name="value"/> into [minValue, maxValue].</summary>+ private static int Clamp(int value, int minValue, int maxValue)+ {+ return Math.Max(minValue, Math.Min(maxValue, value));+ }++ /// <summary>+ /// Reads all sources from the <see cref="SectionName"/> section of a project config.+ /// Returns an empty list when the section or its <c>"items"</c> list is missing; entries+ /// that are not dictionaries are skipped. Each source is clamped via <see cref="Normalize"/>.+ /// </summary>+ public static List<SourceSettings> ListFromConfig(ProjectConfig config)+ {+ List<SourceSettings> sources = new List<SourceSettings>();+ if (!config.ContainsKey(SourceSettings.SectionName))+ {+ return sources;+ }+ Dictionary<string, object> section = config.GetSection(SourceSettings.SectionName);+ if (!section.TryGetValue("items", out object itemsValue))+ {+ return sources;+ }+ IEnumerable items = itemsValue as IEnumerable;+ // A string is IEnumerable too; it is not a list of sources.+ if (items == null || itemsValue is string)+ {+ return sources;+ }+ foreach (object item in items)+ {+ Dictionary<string, object> itemDict = item as Dictionary<string, object>;+ if (itemDict != null)+ {+ sources.Add(SourceSettings.FromDictionary(itemDict));+ }+ }+ return sources;+ }++ /// <summary>Writes all sources (settings and generated elements) into the <see cref="SectionName"/> section of a project config, replacing its <c>"count"</c> and <c>"items"</c> entries.</summary>+ public static void ListToConfig(List<SourceSettings> sources, ProjectConfig config)+ {+ Dictionary<string, object> section = config.GetSection(SourceSettings.SectionName);+ List<object> items = new List<object>();+ foreach (SourceSettings source in sources)+ {+ items.Add(source.ToDictionary());+ }+ section["count"] = items.Count;+ section["items"] = items;+ }++ /// <summary>Serialises the settings and the generated elements into the key/value form stored in the project file (enums as lower-case strings, phase of elements in radians).</summary>+ private Dictionary<string, object> ToDictionary()+ {+ Dictionary<string, object> data = new Dictionary<string, object>();+ data["name"] = this.Name;+ data["main_type"] = ((this.MainType == SourceMainType.Composite) ? "composite" : "single");+ data["x"] = this.PosX;+ data["y"] = this.PosY;+ data["has_position"] = this.HasPosition;+ data["source_on"] = this.SourceOn;+ data["detach_source"] = this.DetachSource;+ data["detach_after_steps"] = this.DetachAfterSteps;+ data["frequency"] = this.Frequency;+ data["amplitude"] = this.Amplitude;+ data["phase_deg"] = this.PhaseDeg;+ data["mode"] = ((this.Mode == SourceMode.Pulsed) ? "pulsed" : "continuous");+ data["pulse_shape"] = ((this.PulseShape == SourcePulseShape.SmoothedSquare) ? "smoothed_square" : "gaussian");+ data["pulse_width_cycles"] = this.PulseWidthCycles;+ data["off_state_cycles"] = this.OffStateCycles;+ data["array_size_x"] = this.ArraySizeX;+ data["array_size_y"] = this.ArraySizeY;+ data["spacing_x"] = this.SpacingX;+ data["spacing_y"] = this.SpacingY;+ data["composite_mode"] = ((this.CompositeMode == SourceCompositeMode.InheritAndRandomize) ? "randomize" : "inherit");+ data["randomize_frequency"] = this.RandomizeFrequency;+ data["randomize_frequency_amount"] = this.RandomizeFrequencyAmount;+ data["randomize_phase"] = this.RandomizePhase;+ data["randomize_phase_amount"] = this.RandomizePhaseAmount;+ data["randomize_off_width"] = this.RandomizeOffWidth;+ data["randomize_off_width_amount"] = this.RandomizeOffWidthAmount;+ data["randomize_position"] = this.RandomizePosition;+ data["randomize_position_amount"] = this.RandomizePositionAmount;+ List<object> elements = new List<object>();+ foreach (SourceElement element in this.Elements)+ {+ Dictionary<string, object> elementData = new Dictionary<string, object>();+ elementData["x"] = element.PosX;+ elementData["y"] = element.PosY;+ elementData["level"] = element.Level;+ elementData["amplitude"] = element.Amplitude;+ elementData["phase_rad"] = element.PhaseRad;+ elementData["mode"] = ((element.Mode == SourceMode.Pulsed) ? "pulsed" : "continuous");+ elementData["pulse_shape"] = ((element.PulseShape == SourcePulseShape.SmoothedSquare) ? "smoothed_square" : "gaussian");+ elementData["on_width_cycles"] = element.OnWidthCycles;+ elementData["off_width_cycles"] = element.OffWidthCycles;+ elementData["off_width_base"] = element.OffWidthBase;+ elementData["randomize_off_width_amount"] = element.RandomizeOffWidthAmount;+ elementData["detach_after_step"] = element.DetachAfterStep;+ elements.Add(elementData);+ }+ data["elements"] = elements;+ return data;+ }++ /// <summary>+ /// Inverse of <see cref="ToDictionary"/>. Missing or out-of-range values fall back to the+ /// constructor defaults, except <c>has_position</c> which defaults to true; unknown enum+ /// strings map to the first enum value. Stored elements are restored as they are (they are+ /// not regenerated), with a 0.5 amplitude fallback and the phase range left wide open.+ /// </summary>+ private static SourceSettings FromDictionary(Dictionary<string, object> d)+ {+ SourceSettings s = new SourceSettings();+ s.Name = SourceSettings.ReadText(d, "name", s.Name);+ s.MainType = ((SourceSettings.ReadText(d, "main_type", "single") == "composite") ? SourceMainType.Composite : SourceMainType.Simple);+ s.PosX = SourceSettings.ReadInt(d, "x", s.PosX, -1000000, 1000000);+ s.PosY = SourceSettings.ReadInt(d, "y", s.PosY, -1000000, 1000000);+ s.HasPosition = SourceSettings.ReadBool(d, "has_position", true);+ s.SourceOn = SourceSettings.ReadBool(d, "source_on", true);+ s.DetachSource = SourceSettings.ReadBool(d, "detach_source", false);+ s.DetachAfterSteps = SourceSettings.ReadInt(d, "detach_after_steps", s.DetachAfterSteps, 0, 1000000000);+ s.Frequency = SourceSettings.ReadInt(d, "frequency", s.Frequency, 1, 255);+ s.Amplitude = SourceSettings.ReadInt(d, "amplitude", s.Amplitude, 0, 100);+ s.PhaseDeg = SourceSettings.ReadInt(d, "phase_deg", s.PhaseDeg, -180, 180);+ s.Mode = ((SourceSettings.ReadText(d, "mode", "continuous") == "pulsed") ? SourceMode.Pulsed : SourceMode.Continuous);+ s.PulseShape = ((SourceSettings.ReadText(d, "pulse_shape", "gaussian") == "smoothed_square") ? SourcePulseShape.SmoothedSquare : SourcePulseShape.Gaussian);+ s.PulseWidthCycles = SourceSettings.ReadInt(d, "pulse_width_cycles", s.PulseWidthCycles, 1, 1000000);+ s.OffStateCycles = SourceSettings.ReadInt(d, "off_state_cycles", s.OffStateCycles, 1, 1000000);+ s.ArraySizeX = SourceSettings.ReadInt(d, "array_size_x", s.ArraySizeX, 1, 100000);+ s.ArraySizeY = SourceSettings.ReadInt(d, "array_size_y", s.ArraySizeY, 1, 100000);+ s.SpacingX = SourceSettings.ReadInt(d, "spacing_x", s.SpacingX, -1000000, 1000000);+ s.SpacingY = SourceSettings.ReadInt(d, "spacing_y", s.SpacingY, -1000000, 1000000);+ s.CompositeMode = ((SourceSettings.ReadText(d, "composite_mode", "inherit") == "randomize") ? SourceCompositeMode.InheritAndRandomize : SourceCompositeMode.InheritFromSingle);+ s.RandomizeFrequency = SourceSettings.ReadBool(d, "randomize_frequency", false);+ s.RandomizeFrequencyAmount = SourceSettings.ReadInt(d, "randomize_frequency_amount", 0, 0, 1000000);+ s.RandomizePhase = SourceSettings.ReadBool(d, "randomize_phase", false);+ s.RandomizePhaseAmount = SourceSettings.ReadInt(d, "randomize_phase_amount", 0, 0, 1000000);+ s.RandomizeOffWidth = SourceSettings.ReadBool(d, "randomize_off_width", false);+ s.RandomizeOffWidthAmount = SourceSettings.ReadInt(d, "randomize_off_width_amount", 0, 0, 1000000);+ s.RandomizePosition = SourceSettings.ReadBool(d, "randomize_position", false);+ s.RandomizePositionAmount = SourceSettings.ReadInt(d, "randomize_position_amount", 0, 0, 1000000);+ List<SourceElement> elements = new List<SourceElement>();+ if (d.TryGetValue("elements", out object elementsValue))+ {+ IEnumerable items = elementsValue as IEnumerable;+ if (items != null && !(elementsValue is string))+ {+ foreach (object item in items)+ {+ Dictionary<string, object> elementDict = item as Dictionary<string, object>;+ if (elementDict == null)+ {+ continue;+ }+ SourceElement element = new SourceElement();+ element.PosX = SourceSettings.ReadInt(elementDict, "x", 0, -1000000, 1000000);+ element.PosY = SourceSettings.ReadInt(elementDict, "y", 0, -1000000, 1000000);+ element.Level = SourceSettings.ReadInt(elementDict, "level", 100, 1, 255);+ element.Amplitude = SourceSettings.ReadDouble(elementDict, "amplitude", 0.5, 0.0, 1.0);+ element.PhaseRad = SourceSettings.ReadDouble(elementDict, "phase_rad", 0.0, -1000.0, 1000.0);+ element.Mode = ((SourceSettings.ReadText(elementDict, "mode", "continuous") == "pulsed") ? SourceMode.Pulsed : SourceMode.Continuous);+ element.PulseShape = ((SourceSettings.ReadText(elementDict, "pulse_shape", "gaussian") == "smoothed_square") ? SourcePulseShape.SmoothedSquare : SourcePulseShape.Gaussian);+ element.OnWidthCycles = SourceSettings.ReadInt(elementDict, "on_width_cycles", 10, 1, 1000000);+ element.OffWidthCycles = SourceSettings.ReadInt(elementDict, "off_width_cycles", 10, 1, 1000000);+ element.OffWidthBase = SourceSettings.ReadInt(elementDict, "off_width_base", element.OffWidthCycles, 1, 1000000);+ element.RandomizeOffWidthAmount = SourceSettings.ReadInt(elementDict, "randomize_off_width_amount", 0, 0, 1000000);+ element.DetachAfterStep = SourceSettings.ReadInt(elementDict, "detach_after_step", -1, -1, 1000000000);+ elements.Add(element);+ }+ }+ }+ s.Elements = elements;+ s.Normalize();+ return s;+ }++ /// <summary>Reads a value as text (invariant culture); <paramref name="fallback"/> when the key is missing or null.</summary>+ private static string ReadText(Dictionary<string, object> d, string key, string fallback)+ {+ return (d.TryGetValue(key, out object value) && value != null) ? Convert.ToString(value, CultureInfo.InvariantCulture) : fallback;+ }++ /// <summary>Reads a bool; <paramref name="fallback"/> unless the stored value is an actual <see cref="bool"/> (no string parsing).</summary>+ private static bool ReadBool(Dictionary<string, object> d, string key, bool fallback)+ {+ return (d.TryGetValue(key, out object value) && value is bool) ? (bool)value : fallback;+ }++ /// <summary>Reads an int (invariant culture); <paramref name="fallback"/> when the key is missing, not convertible or outside [minValue, maxValue].</summary>+ private static int ReadInt(Dictionary<string, object> d, string key, int fallback, int minValue, int maxValue)+ {+ if (d.TryGetValue(key, out object value) && value != null)+ {+ try+ {+ int parsed = Convert.ToInt32(value, CultureInfo.InvariantCulture);+ if (parsed >= minValue && parsed <= maxValue)+ {+ return parsed;+ }+ }+ catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException)+ {+ }+ }+ return fallback;+ }++ /// <summary>Reads a double (invariant culture); <paramref name="fallback"/> when the key is missing, not convertible or outside [minValue, maxValue].</summary>+ private static double ReadDouble(Dictionary<string, object> d, string key, double fallback, double minValue, double maxValue)+ {+ if (d.TryGetValue(key, out object value) && value != null)+ {+ try+ {+ double parsed = Convert.ToDouble(value, CultureInfo.InvariantCulture);+ if (parsed >= minValue && parsed <= maxValue)+ {+ return parsed;+ }+ }+ catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException)+ {+ }+ }+ return fallback;+ }++ /// <summary>Name of the project config section that holds the source list.</summary>+ public const string SectionName = "object_sources";+ }+}diff --git a/Wave_Dude_2D/WaveEngineFactory.cs b/Wave_Dude_2D/WaveEngineFactory.csnew file mode 100644index 0000000..1134eb0--- /dev/null+++ b/Wave_Dude_2D/WaveEngineFactory.cs@@ -0,0 +1,75 @@+using System;+using System.Collections.Generic;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Picks the wave engine for a run: the GPU (OpenCL) engine when requested and available, otherwise the CPU engine.+ /// Static-only; called by <see cref="SimulationRunner"/> on its worker thread once per run.+ /// </summary>+ internal sealed class WaveEngineFactory+ {+ /// <summary>Not instantiable.</summary>+ private WaveEngineFactory()+ {+ }++ /// <summary>+ /// Creates the engine for <paramref name="scene"/>. With <see cref="SimulationSettings.UseGpu"/> set it first tries+ /// <see cref="GpuWaveSimulator.TryCreate"/>, translating the usual OpenCL loader failures (missing, wrong-bitness or+ /// incomplete OpenCL.dll) into a readable reason; any failure falls back to the CPU <see cref="WaveSimulator"/>.+ /// Never throws for GPU problems, but CPU engine construction may still throw (e.g. out of memory).+ /// </summary>+ /// <param name="scene">Per-pixel speed, damping and image sources of the canvas; the engine copies it into its padded grid.</param>+ /// <param name="settings">Supplies <see cref="SimulationSettings.UseGpu"/> and the physics options passed to the engine (frequency scale, Laplacian order, time decay, intensity scale).</param>+ /// <param name="sourceAmplitude">Amplitude multiplier for the image-defined sources.</param>+ /// <param name="trackIntensity">Whether the engine must accumulate the intensity buffer (needed for intensity video, preview or probes).</param>+ /// <param name="note">+ /// Receives an empty string when the GPU was not requested or the GPU engine was created; "GPU not used: reason" when the GPU+ /// was requested but could not be used (the loader message above, or the per-device errors from <c>TryCreate</c>).+ /// The "the first choice failed - ..." form is only produced if <c>TryCreate</c> ever returns an engine together with a+ /// message, which it does not at present.+ /// </param>+ /// <param name="objectSources">Object sources to drive in addition to the image sources; may be null.</param>+ /// <returns>A ready engine; the caller owns and must dispose it.</returns>+ public static IWaveEngine Create(SceneData scene, SimulationSettings settings, double sourceAmplitude, bool trackIntensity, ref string note, List<SourceElement> objectSources = null)+ {+ note = "";+ if (settings.UseGpu)+ {+ string gpuMessage = "";+ GpuWaveSimulator gpu = null;+ try+ {+ gpu = GpuWaveSimulator.TryCreate(scene, settings.SourceFrequencyScale, sourceAmplitude, trackIntensity, settings.Use4thOrderLaplacian, settings.TimeDecayFactor, settings.IntensityScale, ref gpuMessage, objectSources);+ }+ catch (DllNotFoundException)+ {+ gpuMessage = "no OpenCL driver (OpenCL.dll) found; install the driver of the graphics card";+ }+ catch (BadImageFormatException)+ {+ gpuMessage = "the OpenCL driver does not match this 32/64-bit program";+ }+ catch (EntryPointNotFoundException)+ {+ gpuMessage = "the OpenCL driver is incomplete";+ }+ catch (Exception ex)+ {+ gpuMessage = ex.Message;+ }+ if (gpu != null)+ {+ if (gpuMessage.Length > 0)+ {+ note = "the first choice failed - " + gpuMessage;+ }+ return gpu;+ }+ note = "GPU not used: " + gpuMessage;+ }+ return new WaveSimulator(scene, settings.SourceFrequencyScale, sourceAmplitude, trackIntensity, settings.Use4thOrderLaplacian, settings.TimeDecayFactor, settings.IntensityScale, objectSources);+ }+ }+}diff --git a/Wave_Dude_2D/WaveSimulator.cs b/Wave_Dude_2D/WaveSimulator.csnew file mode 100644index 0000000..b65103d--- /dev/null+++ b/Wave_Dude_2D/WaveSimulator.cs@@ -0,0 +1,769 @@+using System;+using System.Collections.Generic;+using System.Globalization;+using System.Threading.Tasks;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// CPU implementation of <see cref="IWaveEngine"/>: an explicit leapfrog finite-difference solver for the+ /// scalar 2D wave equation on a grid padded by one cell on each side. Created by+ /// <see cref="WaveEngineFactory"/> on the <see cref="SimulationRunner"/> worker thread, which is the only+ /// thread that advances it; the UI thread reads <see cref="FieldData"/> / <see cref="IntensityData"/> only+ /// while the run is paused.+ /// </summary>+ /// <remarks>+ /// Units: grid spacing and time step are both 1, so the wave speed c is in cells (canvas pixels) per step,+ /// the per-cell <c>c2</c> is c² = 1/n² for refractive index n, and <see cref="Time"/> counts steps. Source+ /// frequencies are angular frequencies in radians per step (<see cref="_levelFrequency"/>).+ /// Per step: the sources are blended into the field once (<see cref="ApplySources"/>), then the field is+ /// advanced by <see cref="_subSteps"/> leapfrog sub-steps (<see cref="UpdateField"/>), the last of which also+ /// updates the running intensity. The 4th-order stencil needs a shorter time step to stay stable, hence+ /// the sub-stepping; the 9-point stencil always runs a single sub-step.+ /// </remarks>+ internal sealed class WaveSimulator : IWaveEngine+ {+ /// <summary>+ /// Copies the scene's c² and damping maps into the padded grid, derives the sub-step count (4th order+ /// only) and the matching per-sub-step damping and c² corrections, indexes the image and object sources,+ /// and sets the intensity averaging constant from the slowest source level in use.+ /// </summary>+ /// <param name="scene">Per-cell c² and damping maps plus the image (green-channel) sources.</param>+ /// <param name="sourceFrequencyScale">Multiplier in the level-to-angular-frequency mapping; see <see cref="_levelFrequency"/>.</param>+ /// <param name="sourceAmplitude">Peak amplitude of the image sources (object sources carry their own).</param>+ /// <param name="trackIntensity">Whether to allocate and update the intensity buffers; when false <see cref="IntensityData"/> stays null.</param>+ /// <param name="use4thOrderLaplacian">Use the 4th-order 5-point-per-axis stencil (with sub-stepping) instead of the 9-point one.</param>+ /// <param name="timeDecayFactor">Intensity averaging time in units of 100/level steps; see <see cref="_intensityAlpha"/>.</param>+ /// <param name="intensityScale">Multiplier applied to the intensity output.</param>+ /// <param name="objectSources">Interactive sources; those positioned outside the canvas are dropped.</param>+ public WaveSimulator(SceneData scene, double sourceFrequencyScale, double sourceAmplitude, bool trackIntensity, bool use4thOrderLaplacian, double timeDecayFactor, double intensityScale, List<SourceElement> objectSources = null)+ {+ this._levelFrequency = new double[256];+ this._levelUsed = new bool[256];+ this._levelValue = new float[256];+ this._objRandom = new Random();+ this._probeValues = new List<List<float>>();+ this._sourceAmplitude = sourceAmplitude;+ this._use4thOrderLaplacian = use4thOrderLaplacian;+ this._intensityScale = (float)intensityScale;+ this._width = scene.Width;+ this._height = scene.Height;+ this._stride = this._width + 2;+ int cellCount = this._stride * (this._height + 2);+ this._u = new float[cellCount];+ this._uPrev = new float[cellCount];+ this._c2 = new float[cellCount];+ this._d = new float[cellCount];+ if (trackIntensity)+ {+ this._intensity = new float[cellCount];+ this._intensityStage1 = new float[cellCount];+ this._intensityOut = new float[cellCount];+ }+ for (int y = 0; y < this._height; y++)+ {+ Array.Copy(scene.C2, y * this._width, this._c2, (y + 1) * this._stride + 1, this._width);+ Array.Copy(scene.D, y * this._width, this._d, (y + 1) * this._stride + 1, this._width);+ }+ if (use4thOrderLaplacian)+ {+ float maxC2 = 0f;+ for (int i = 0; i < this._c2.Length; i++)+ {+ if (this._c2[i] > maxC2)+ {+ maxC2 = this._c2[i];+ }+ }+ this._subSteps = WaveSimulator.ComputeSubSteps(maxC2);+ }+ else+ {+ this._subSteps = 1;+ }+ if (this._subSteps > 1)+ {+ // Damping is applied once per sub-step, so take the sub-step root to keep the per-step decay unchanged.+ float[] dEffective = new float[this._d.Length];+ double exponent = 1.0 / this._subSteps;+ for (int i = 0; i < this._d.Length; i++)+ {+ dEffective[i] = (float)Math.Pow(this._d[i], exponent);+ }+ this._dEffective = dEffective;+ // A sub-step is 1/subSteps long, so c²·dt² shrinks by 1/subSteps².+ this._c2Mult = 1f / (float)(this._subSteps * this._subSteps);+ }+ else+ {+ this._dEffective = this._d;+ this._c2Mult = 1f;+ }+ int sourceCount = scene.SourceCount;+ this._sourceIndex = new int[sourceCount];+ this._sourceLevel = new byte[sourceCount];+ for (int i = 0; i < sourceCount; i++)+ {+ this._sourceIndex[i] = (scene.SourceY[i] + 1) * this._stride + scene.SourceX[i] + 1;+ this._sourceLevel[i] = scene.SourceLevel[i];+ this._levelUsed[scene.SourceLevel[i]] = true;+ }+ for (int level = 0; level <= 255; level++)+ {+ this._levelFrequency[level] = level / 255.0 * 0.5 * sourceFrequencyScale;+ }+ if (objectSources == null)+ {+ this._objSources = Array.Empty<SourceElement>();+ this._objIndex = Array.Empty<int>();+ }+ else+ {+ List<SourceElement> insideSources = new List<SourceElement>();+ List<int> insideIndices = new List<int>();+ foreach (SourceElement source in objectSources)+ {+ if (source.PosX >= 0 && source.PosX < this._width && source.PosY >= 0 && source.PosY < this._height)+ {+ insideSources.Add(source);+ insideIndices.Add((source.PosY + 1) * this._stride + source.PosX + 1);+ }+ }+ this._objSources = insideSources.ToArray();+ this._objIndex = insideIndices.ToArray();+ }+ // The intensity decay time is scaled by the lowest (slowest) source level in use.+ int lowestLevel = 0;+ for (int level = 1; level <= 255; level++)+ {+ if (this._levelUsed[level])+ {+ lowestLevel = level;+ break;+ }+ }+ foreach (SourceElement source in this._objSources)+ {+ if (source.Level > 0 && (lowestLevel == 0 || source.Level < lowestLevel))+ {+ lowestLevel = source.Level;+ }+ }+ if (lowestLevel == 0)+ {+ lowestLevel = NominalDecayLevel;+ }+ double decaySteps = Math.Max(1.0, timeDecayFactor * 100.0 / lowestLevel);+ this._intensityAlpha = (float)Math.Exp(-1.0 / decaySteps);+ this._objCycleAnchor = new double[this._objSources.Length];+ this._objCurrentOffWidth = new int[this._objSources.Length];+ for (int i = 0; i < this._objSources.Length; i++)+ {+ this._objCurrentOffWidth[i] = this._objSources[i].OffWidthCycles;+ }+ }++ /// <summary>Scene width in cells (canvas pixels), excluding the padding.</summary>+ public int Width+ {+ get+ {+ return this._width;+ }+ }++ /// <summary>Scene height in cells (canvas pixels), excluding the padding.</summary>+ public int Height+ {+ get+ {+ return this._height;+ }+ }++ /// <summary>Row pitch of the padded buffers: <see cref="Width"/> + 2.</summary>+ public int Stride+ {+ get+ {+ return this._stride;+ }+ }++ /// <summary>+ /// The current field u (padded layout). The array instance changes every sub-step because the two+ /// field buffers are swapped, so callers must re-read this property per frame rather than cache the array.+ /// </summary>+ public float[] FieldData+ {+ get+ {+ return this._u;+ }+ }++ /// <summary>Scaled running intensity (padded layout), or null when the engine was created without intensity tracking.</summary>+ public float[] IntensityData+ {+ get+ {+ return this._intensityOut;+ }+ }++ /// <summary>Engine label for the UI/result: "CPU (n threads)" with the logical processor count.</summary>+ public string Description+ {+ get+ {+ return "CPU (" + Environment.ProcessorCount.ToString(CultureInfo.InvariantCulture) + " threads)";+ }+ }++ /// <summary>No-op: the CPU buffers are always host-resident and up to date.</summary>+ public void PrepareFrame(bool needField, bool needIntensity)+ {+ }++ /// <summary>No-op: the engine owns only managed arrays.</summary>+ public void Dispose()+ {+ }++ /// <summary>+ /// Installs the probe layout (or clears it when <paramref name="sampler"/> is null or empty), discarding any+ /// pending samples and integrated totals, and allocates the per-pixel totals for integrated line probes.+ /// </summary>+ /// <exception cref="InvalidOperationException">The sampler needs intensity but this engine does not track it.</exception>+ public void SetProbes(ProbeSampler sampler)+ {+ this._probeValues.Clear();+ this._profileTotals = null;+ if (sampler == null || sampler.Count == 0)+ {+ this._sampler = null;+ return;+ }+ if (sampler.NeedsIntensity && this._intensityOut == null)+ {+ throw new InvalidOperationException("the intensity is not tracked");+ }+ this._sampler = sampler;+ this._profileTotals = new double[sampler.Count][];+ for (int i = 0; i < sampler.Count; i++)+ {+ this._probeValues.Add(new List<float>());+ if (sampler.Integrate[i])+ {+ this._profileTotals[i] = new double[sampler.Pixels[i].Length];+ }+ }+ }++ /// <summary>+ /// Called by the runner after every step: appends one field or intensity value per point probe, and adds+ /// the current intensity to the per-pixel totals of integrated line probes (once <see cref="Time"/> has+ /// reached their start step). Non-integrated line probes are read live by <see cref="ReadProbeProfiles"/>.+ /// </summary>+ public void SampleProbes()+ {+ if (this._sampler == null)+ {+ return;+ }+ int step = (int)Math.Round(this._time);+ for (int i = 0; i < this._sampler.Count; i++)+ {+ if (!this._sampler.IsProfile[i])+ {+ float[] source = this._sampler.UseIntensity[i] ? this._intensityOut : this._u;+ this._probeValues[i].Add(this._sampler.Compute(i, source));+ }+ else if (this._sampler.Integrate[i])+ {+ if (this._sampler.UseStartAfterStep[i] && step < this._sampler.StartAfterStep[i])+ {+ continue;+ }+ int[] pixels = this._sampler.Pixels[i];+ double[] totals = this._profileTotals[i];+ float[] intensityOut = this._intensityOut;+ for (int j = 0; j < pixels.Length; j++)+ {+ totals[j] += intensityOut[pixels[j]];+ }+ }+ }+ }++ /// <summary>Returns and clears the point-probe values collected since the previous call.</summary>+ /// <returns>One array per probe, one value per step (empty for line probes); an empty outer array when no sampler is set.</returns>+ public float[][] TakeProbeSamples()+ {+ if (this._sampler == null)+ {+ return new float[0][];+ }+ float[][] samples = new float[this._sampler.Count][];+ for (int i = 0; i < this._sampler.Count; i++)+ {+ samples[i] = this._probeValues[i].ToArray();+ this._probeValues[i].Clear();+ }+ return samples;+ }++ /// <summary>Reads the current values along every line probe; nothing is cleared.</summary>+ /// <returns>+ /// One array per probe in pixel order along the line, holding the integrated intensity totals or the live+ /// field/intensity values; null entries for point probes; an empty outer array when no sampler is set.+ /// </returns>+ public float[][] ReadProbeProfiles()+ {+ if (this._sampler == null)+ {+ return new float[0][];+ }+ float[][] profiles = new float[this._sampler.Count][];+ for (int i = 0; i < this._sampler.Count; i++)+ {+ if (!this._sampler.IsProfile[i])+ {+ continue;+ }+ int[] pixels = this._sampler.Pixels[i];+ float[] profile = new float[pixels.Length];+ if (this._sampler.Integrate[i])+ {+ double[] totals = this._profileTotals[i];+ for (int j = 0; j < pixels.Length; j++)+ {+ profile[j] = (float)totals[j];+ }+ }+ else+ {+ float[] source = this._sampler.UseIntensity[i] ? this._intensityOut : this._u;+ for (int j = 0; j < pixels.Length; j++)+ {+ profile[j] = source[pixels[j]];+ }+ }+ profiles[i] = profile;+ }+ return profiles;+ }++ /// <summary>Elapsed simulation time in steps (one per <see cref="AdvanceOneStep"/>).</summary>+ public double Time+ {+ get+ {+ return this._time;+ }+ }++ /// <summary>+ /// Number of sub-steps per time step needed to keep the 4th-order stencil stable for the largest c² in the+ /// scene: the smallest n with c²·λmax/n² ≤ <see cref="SubStepTargetLimit"/>, at least 1.+ /// </summary>+ private static int ComputeSubSteps(float maxC2)+ {+ if (maxC2 <= 0f)+ {+ return 1;+ }+ double subSteps = Math.Ceiling(Math.Sqrt((double)maxC2 * FourthOrderLambdaMax / SubStepTargetLimit));+ return Math.Max(1, (int)Math.Round(subSteps));+ }++ /// <summary>+ /// Advances the simulation by one step: blends the sources in once, runs <see cref="_subSteps"/> leapfrog+ /// sub-steps (the intensity is updated on the last one only) and increments <see cref="Time"/>.+ /// </summary>+ public void AdvanceOneStep()+ {+ this.ApplySources();+ for (int i = 1; i <= this._subSteps; i++)+ {+ this.UpdateField(this._dEffective, this._c2Mult, i == this._subSteps);+ }+ this._time += 1.0;+ }++ /// <summary>+ /// Soft-blends the current source values into the field (<c>u = 0.9·u + 0.1·value</c>, see+ /// <see cref="SourceOpacity"/>): image sources driven by their level's frequency, then object sources+ /// with their own phase, amplitude, pulse envelope and detach fade. Object sources that have been+ /// detached for <see cref="SourceElement.DetachRampSteps"/> steps or longer are skipped.+ /// </summary>+ private void ApplySources()+ {+ float[] u = this._u;+ if (this._sourceIndex.Length > 0)+ {+ for (int level = 1; level <= 255; level++)+ {+ if (this._levelUsed[level])+ {+ this._levelValue[level] = (float)(Math.Sin(this._levelFrequency[level] * this._time) * this._sourceAmplitude);+ }+ }+ for (int i = 0; i < this._sourceIndex.Length; i++)+ {+ int idx = this._sourceIndex[i];+ u[idx] = u[idx] * SourceOpacity + this._levelValue[this._sourceLevel[i]] * (1f - SourceOpacity);+ }+ }+ for (int i = 0; i < this._objSources.Length; i++)+ {+ SourceElement source = this._objSources[i];+ float fade = 1f;+ if (source.DetachAfterStep >= 0)+ {+ // Linear fade to zero over 30 steps (SourceElement.DetachRampSteps) after the detach step.+ double sinceDetach = this._time - source.DetachAfterStep;+ if (sinceDetach >= 30.0)+ {+ continue;+ }+ if (sinceDetach > 0.0)+ {+ fade = (float)(1.0 - sinceDetach / 30.0);+ }+ }+ double freq = this._levelFrequency[source.Level];+ double envelope;+ if (source.Mode == SourceMode.Continuous)+ {+ envelope = 1.0;+ }+ else+ {+ int offWidth = 0;+ bool isFirstCycle = false;+ double pulsePos = this.ComputePulsePosition(i, source, freq, ref offWidth, ref isFirstCycle);+ envelope = this.PulseEnvelope(source, pulsePos, offWidth, isFirstCycle);+ }+ float value = (float)(Math.Sin(source.PhaseRad + freq * this._time) * source.Amplitude * envelope) * fade;+ int idx = this._objIndex[i];+ u[idx] = u[idx] * SourceOpacity + value * (1f - SourceOpacity);+ }+ }++ /// <summary>+ /// Position (in cycles of the source frequency) of a pulsed source within its current on/off period. Also+ /// reports the off-width in effect for that period and whether the source is still in its first period.+ /// With a fixed off-width the period is phase-shifted by the off-width so the on-phase starts at step 0.+ /// With a randomized off-width the position is measured from the anchor of the current period (which+ /// begins with its off-phase); whenever a period completes the anchor moves on and a fresh off-width is+ /// drawn from <c>OffWidthBase ± RandomizeOffWidthAmount</c> (at least 1), at most+ /// <see cref="CycleAdvanceGuard"/> periods at a time.+ /// </summary>+ /// <param name="i">Index of the source in <see cref="_objSources"/> (selects its anchor/off-width slot).</param>+ /// <param name="el">The source whose pulse timing is evaluated.</param>+ /// <param name="freq">Angular frequency of the source in radians per step.</param>+ /// <param name="offWidth">Receives the off-width (cycles) in effect for the current period.</param>+ /// <param name="isFirstCycle">Receives whether the source is still in its first period.</param>+ private double ComputePulsePosition(int i, SourceElement el, double freq, ref int offWidth, ref bool isFirstCycle)+ {+ double cycles = freq * this._time / (2.0 * Math.PI);+ if (el.RandomizeOffWidthAmount <= 0)+ {+ offWidth = el.OffWidthCycles;+ int period = el.OnWidthCycles + offWidth;+ if (period <= 0)+ {+ isFirstCycle = true;+ return 0.0;+ }+ double shifted = cycles + offWidth;+ isFirstCycle = Math.Floor(shifted / period) == 0.0;+ return shifted - period * Math.Floor(shifted / period);+ }+ else+ {+ offWidth = this._objCurrentOffWidth[i];+ int period = el.OnWidthCycles + offWidth;+ if (period <= 0)+ {+ isFirstCycle = true;+ return 0.0;+ }+ double sinceAnchor = cycles - this._objCycleAnchor[i];+ int guard = 0;+ while (sinceAnchor >= period && guard < CycleAdvanceGuard)+ {+ this._objCycleAnchor[i] += period;+ sinceAnchor -= period;+ offWidth = Math.Max(1, el.OffWidthBase + SourceSettings.RandomInt(this._objRandom, el.RandomizeOffWidthAmount));+ this._objCurrentOffWidth[i] = offWidth;+ period = el.OnWidthCycles + offWidth;+ guard++;+ }+ if (sinceAnchor < 0.0)+ {+ sinceAnchor = 0.0;+ }+ isFirstCycle = this._objCycleAnchor[i] == 0.0;+ return sinceAnchor;+ }+ }++ /// <summary>+ /// Amplitude envelope (0..1) of a pulsed source at the given position within its on/off period (a+ /// non-positive period yields 1). Gaussian: zero during the off-phase, then a bell centred in the on-window+ /// with σ = on-width/6. Smoothed square: the product of an arctan rise at the start and an arctan fall at+ /// the end of the on-window (softness 0.35 cycles); positions are wrapped so the tails of neighbouring+ /// periods blend smoothly, except in the first period so the pulse does not start mid-tail.+ /// </summary>+ /// <param name="el">The source; supplies the pulse shape and on-width.</param>+ /// <param name="pos">Position within the period in cycles, as returned by <see cref="ComputePulsePosition"/>.</param>+ /// <param name="offWidth">Off-width (cycles) in effect for this period.</param>+ /// <param name="isFirstCycle">Whether this is the first period (suppresses the tail wrapping of the smoothed square).</param>+ private double PulseEnvelope(SourceElement el, double pos, int offWidth, bool isFirstCycle)+ {+ int onWidthCycles = el.OnWidthCycles;+ int period = onWidthCycles + offWidth;+ if (period <= 0)+ {+ return 1.0;+ }+ if (el.PulseShape == SourcePulseShape.Gaussian)+ {+ if (pos < offWidth)+ {+ return 0.0;+ }+ double onPos = pos - offWidth;+ double center = onWidthCycles / 2.0;+ double sigma = Math.Max(onWidthCycles / 6.0, 1E-06);+ double z = (onPos - center) / sigma;+ return Math.Exp(-0.5 * z * z);+ }+ else+ {+ double onPos = pos - offWidth;+ if (onPos < 0.0 && !isFirstCycle)+ {+ onPos += period;+ }+ double fallArg = onPos - onWidthCycles;+ double riseArg = onPos;+ if (riseArg > period / 2.0)+ {+ riseArg -= period;+ }+ double rise = 0.5 + Math.Atan(riseArg / 0.35) / Math.PI;+ double fall = 0.5 - Math.Atan(fallArg / 0.35) / Math.PI;+ return rise * fall;+ }+ }++ /// <summary>+ /// One leapfrog sub-step over all interior cells, parallelised over row bands:+ /// <c>next = u + (u - uPrev)·d + lap·c2·c2Mult</c>, where d is the per-cell damping (1 = lossless, applied+ /// to the velocity term) and lap is the Laplacian: the 9-point stencil (corners <see cref="KernelCorner"/>,+ /// edges <see cref="KernelEdge"/>, centre -1), or for cells at least two cells away from the border and+ /// when enabled, the 4th-order 5-point-per-axis stencil (<see cref="FourthOrderFar"/>,+ /// <see cref="FourthOrderNear"/>, <see cref="FourthOrderCenter"/>). Each cell reads only <see cref="_u"/>+ /// and overwrites its own slot in <see cref="_uPrev"/>, so the bands do not race; afterwards the two+ /// buffers are swapped. Border cells are never written and stay 0.+ /// When tracking, the intensity is a cascade of two exponential moving averages of u² (retention+ /// <see cref="_intensityAlpha"/>); the output mixes both stages (<see cref="IntensityBlend"/>) times+ /// <see cref="_intensityScale"/>.+ /// </summary>+ /// <param name="dArray">Damping map to use, already corrected for the sub-step length.</param>+ /// <param name="c2Mult">Factor on c² for the sub-step length (1/subSteps²).</param>+ /// <param name="updateIntensity">Whether to update the intensity buffers in this sub-step (last sub-step only).</param>+ private void UpdateField(float[] dArray, float c2Mult, bool updateIntensity)+ {+ float[] u = this._u;+ float[] uPrev = this._uPrev;+ float[] c2 = this._c2;+ float[] d = dArray;+ float[] intensity = this._intensity;+ float[] stage1 = this._intensityStage1;+ float[] intensityOut = this._intensityOut;+ bool track = intensity != null && updateIntensity;+ int stride = this._stride;+ int w = this._width;+ int h = this._height;+ bool use4th = this._use4thOrderLaplacian;+ float mult = c2Mult;+ float alpha = this._intensityAlpha;+ float scale = this._intensityScale;+ int bands = Math.Min(h, Environment.ProcessorCount * 4);++ Parallel.For(0, bands, band =>+ {+ int rowStart = (int)((long)h * band / bands);+ int rowEnd = (int)((long)h * (band + 1) / bands) - 1;+ for (int y = rowStart; y <= rowEnd; y++)+ {+ int idx = (y + 1) * stride + 1;+ // The 4th-order stencil reaches two cells out, but the padding is only one cell wide.+ bool rowAllows4th = use4th && y >= 1 && y <= h - 2;+ for (int x = 0; x < w; x++)+ {+ float center = u[idx];+ float laplacian;+ if (rowAllows4th && x >= 1 && x <= w - 2)+ {+ laplacian = FourthOrderFar * (u[idx - 2] + u[idx + 2] + u[idx - 2 * stride] + u[idx + 2 * stride])+ + FourthOrderNear * (u[idx - 1] + u[idx + 1] + u[idx - stride] + u[idx + stride])+ + FourthOrderCenter * center;+ }+ else+ {+ laplacian = KernelCorner * (u[idx - stride - 1] + u[idx - stride + 1] + u[idx + stride - 1] + u[idx + stride + 1])+ + KernelEdge * (u[idx - 1] + u[idx + 1] + u[idx - stride] + u[idx + stride])+ - center;+ }+ float next = center + (center - uPrev[idx]) * d[idx] + laplacian * c2[idx] * mult;+ uPrev[idx] = next;+ if (track)+ {+ float s1 = stage1[idx] * alpha + next * next * (1f - alpha);+ stage1[idx] = s1;+ float s2 = intensity[idx] * alpha + s1 * (1f - alpha);+ intensity[idx] = s2;+ intensityOut[idx] = (s1 * (1f - IntensityBlend) + s2 * IntensityBlend) * scale;+ }+ idx++;+ }+ }+ });++ // uPrev now holds the new field; swap buffers.+ this._uPrev = u;+ this._u = uPrev;+ }++ /// <summary>Weight of the four diagonal neighbours in the 9-point Laplacian.</summary>+ private const float KernelCorner = 0.066f;++ /// <summary>Weight of the four edge neighbours in the 9-point Laplacian (4·corner + 4·edge = 1 balances the centre weight of -1).</summary>+ private const float KernelEdge = 0.184f;++ /// <summary>Fraction of the old field value kept when a source value is blended in (soft source injection).</summary>+ private const float SourceOpacity = 0.9f;++ /// <summary>Source level assumed for the intensity decay time when no source has a level above 0.</summary>+ private const int NominalDecayLevel = 100;++ /// <summary>Mix of the two intensity averaging stages in the output: 0 = first stage only, 1 = second stage only.</summary>+ private const float IntensityBlend = 0.5f;++ /// <summary>4th-order stencil weight of the nearest neighbours (4/3).</summary>+ private const float FourthOrderNear = 1.3333334f;++ /// <summary>4th-order stencil weight of the second-nearest neighbours (-1/12).</summary>+ private const float FourthOrderFar = -0.083333336f;++ /// <summary>4th-order stencil centre weight (2 × -5/2 for the two axes).</summary>+ private const float FourthOrderCenter = -5f;++ /// <summary>Largest eigenvalue magnitude of the 2D 4th-order stencil (2 × 16/3), for the stability estimate in <see cref="ComputeSubSteps"/>.</summary>+ private const float FourthOrderLambdaMax = 10.666667f;++ /// <summary>Allowed c²·λmax·dt² per sub-step; 2 keeps a margin below the leapfrog stability bound of 4.</summary>+ private const float SubStepTargetLimit = 2f;++ /// <summary>Scene width in cells.</summary>+ private readonly int _width;++ /// <summary>Scene height in cells.</summary>+ private readonly int _height;++ /// <summary>Padded row pitch (<see cref="_width"/> + 2).</summary>+ private readonly int _stride;++ /// <summary>Whether interior cells use the 4th-order stencil.</summary>+ private readonly bool _use4thOrderLaplacian;++ /// <summary>Leapfrog sub-steps per simulation step; 1 unless the 4th-order stencil is on.</summary>+ private readonly int _subSteps;++ /// <summary>Damping map applied per sub-step: <see cref="_d"/> raised to 1/<see cref="_subSteps"/>, or <see cref="_d"/> itself without sub-stepping.</summary>+ private readonly float[] _dEffective;++ /// <summary>1/<see cref="_subSteps"/>², scaling c² for the shorter sub-step.</summary>+ private readonly float _c2Mult;++ /// <summary>Per-step retention of the intensity averages: exp(-1/decaySteps) with decaySteps = timeDecayFactor·100/lowest source level.</summary>+ private readonly float _intensityAlpha;++ /// <summary>Multiplier on the intensity output.</summary>+ private readonly float _intensityScale;++ /// <summary>Current field (padded); exchanged with <see cref="_uPrev"/> after every sub-step.</summary>+ private float[] _u;++ /// <summary>Previous field (padded); receives the new field during a sub-step and then becomes <see cref="_u"/>.</summary>+ private float[] _uPrev;++ /// <summary>Per-cell c² = 1/n² (padded; border cells 0).</summary>+ private readonly float[] _c2;++ /// <summary>Per-cell damping from the scene (padded), 1 = lossless; source of <see cref="_dEffective"/>.</summary>+ private readonly float[] _d;++ /// <summary>Second-stage running average of u² (padded), or null when intensity is not tracked.</summary>+ private readonly float[] _intensity;++ /// <summary>First-stage running average of u² (padded), or null when intensity is not tracked.</summary>+ private readonly float[] _intensityStage1;++ /// <summary>Blended and scaled intensity exposed as <see cref="IntensityData"/>, or null when not tracked.</summary>+ private readonly float[] _intensityOut;++ /// <summary>Padded cell index of every image source.</summary>+ private readonly int[] _sourceIndex;++ /// <summary>Green level (1..255) of every image source, indexing <see cref="_levelFrequency"/>.</summary>+ private readonly byte[] _sourceLevel;++ /// <summary>Angular frequency in radians per step for each level 0..255: level/255 × 0.5 × sourceFrequencyScale.</summary>+ private readonly double[] _levelFrequency;++ /// <summary>Which levels have at least one image source; only those get a value computed per step.</summary>+ private readonly bool[] _levelUsed;++ /// <summary>Image source value for the current step, per level.</summary>+ private readonly float[] _levelValue;++ /// <summary>Peak amplitude of the image sources.</summary>+ private readonly double _sourceAmplitude;++ /// <summary>Object sources that lie inside the canvas.</summary>+ private readonly SourceElement[] _objSources;++ /// <summary>Padded cell index of every entry in <see cref="_objSources"/>.</summary>+ private readonly int[] _objIndex;++ /// <summary>Random generator for randomized off-widths; used on the worker thread only.</summary>+ private readonly Random _objRandom;++ /// <summary>Per object source: start (in cycles) of its current period; used in randomized off-width mode only.</summary>+ private readonly double[] _objCycleAnchor;++ /// <summary>Per object source: off-width (cycles) in effect for its current period.</summary>+ private readonly int[] _objCurrentOffWidth;++ /// <summary>Upper bound on the periods <see cref="ComputePulsePosition"/> advances at once (guards against a tiny period).</summary>+ private const int CycleAdvanceGuard = 1000;++ /// <summary>Elapsed time in steps.</summary>+ private double _time;++ /// <summary>Probe layout in use, or null when no probes are set.</summary>+ private ProbeSampler _sampler;++ /// <summary>Point-probe samples gathered since the last <see cref="TakeProbeSamples"/>, one list per probe.</summary>+ private readonly List<List<float>> _probeValues;++ /// <summary>Running per-pixel intensity sums for integrated line probes (null entries for other probes); null without a sampler.</summary>+ private double[][] _profileTotals;+ }+}diff --git a/Wave_Dude_2D/Wave_Dude_2D.csproj b/Wave_Dude_2D/Wave_Dude_2D.csprojnew file mode 100644index 0000000..9947a98--- /dev/null+++ b/Wave_Dude_2D/Wave_Dude_2D.csproj@@ -0,0 +1,185 @@+<?xml version="1.0" encoding="utf-8"?>+<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">+ <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />+ <PropertyGroup>+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>+ <ProjectGuid>{C3F63FB8-2009-4631-AB8D-4E176E131C5F}</ProjectGuid>+ <OutputType>WinExe</OutputType>+ <RootNamespace>_2D_wave_sim_V01</RootNamespace>+ <AssemblyName>Wave_Dude_2D</AssemblyName>+ <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>+ <FileAlignment>512</FileAlignment>+ <ApplicationIcon>Wave_Dude_2D.ico</ApplicationIcon>+ <StartupObject>_2D_wave_sim_V01.My.MyApplication</StartupObject>+ </PropertyGroup>+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">+ <PlatformTarget>AnyCPU</PlatformTarget>+ <DebugSymbols>true</DebugSymbols>+ <DebugType>full</DebugType>+ <Optimize>false</Optimize>+ <OutputPath>bin\Debug\</OutputPath>+ <DocumentationFile>bin\Debug\Wave_Dude_2D.xml</DocumentationFile>+ <DefineConstants>DEBUG;TRACE</DefineConstants>+ <ErrorReport>prompt</ErrorReport>+ <WarningLevel>4</WarningLevel>+ </PropertyGroup>+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">+ <PlatformTarget>AnyCPU</PlatformTarget>+ <DebugType>pdbonly</DebugType>+ <Optimize>true</Optimize>+ <OutputPath>bin\Release\</OutputPath>+ <DocumentationFile>bin\Release\Wave_Dude_2D.xml</DocumentationFile>+ <DefineConstants>TRACE</DefineConstants>+ <ErrorReport>prompt</ErrorReport>+ <WarningLevel>4</WarningLevel>+ </PropertyGroup>+ <ItemGroup>+ <Reference Include="Microsoft.VisualBasic" />+ <Reference Include="System" />+ <Reference Include="System.Core" />+ <Reference Include="System.Drawing" />+ <Reference Include="System.Web.Extensions" />+ <Reference Include="System.Windows.Forms" />+ </ItemGroup>+ <ItemGroup>+ <AppDesigner Include="Properties\" />+ </ItemGroup>+ <ItemGroup>+ <Compile Include="AboutForm.cs">+ <SubType>Form</SubType>+ </Compile>+ <Compile Include="AboutForm.Designer.cs">+ <DependentUpon>AboutForm.cs</DependentUpon>+ </Compile>+ <Compile Include="AppSettings.cs" />+ <Compile Include="AviFrameSink.cs" />+ <Compile Include="AviMjpegWriter.cs" />+ <Compile Include="ColorLut.cs" />+ <Compile Include="ColorPickerControl.cs" />+ <Compile Include="ColorScheme.cs" />+ <Compile Include="ColorSchemeStore.cs" />+ <Compile Include="Form1.cs">+ <SubType>Form</SubType>+ </Compile>+ <Compile Include="Form1.Designer.cs">+ <DependentUpon>Form1.cs</DependentUpon>+ </Compile>+ <Compile Include="Form1.Projects.cs">+ <DependentUpon>Form1.cs</DependentUpon>+ </Compile>+ <Compile Include="Form1.Output.cs">+ <DependentUpon>Form1.cs</DependentUpon>+ </Compile>+ <Compile Include="Form1.Scene.cs">+ <DependentUpon>Form1.cs</DependentUpon>+ </Compile>+ <Compile Include="Form1.Colors.cs">+ <DependentUpon>Form1.cs</DependentUpon>+ </Compile>+ <Compile Include="Form1.Simulation.cs">+ <DependentUpon>Form1.cs</DependentUpon>+ </Compile>+ <Compile Include="Form1.Probes.cs">+ <DependentUpon>Form1.cs</DependentUpon>+ </Compile>+ <Compile Include="Form1.Sources.cs">+ <DependentUpon>Form1.cs</DependentUpon>+ </Compile>+ <Compile Include="FrameRenderer.cs" />+ <Compile Include="frmDescription.cs">+ <SubType>Form</SubType>+ </Compile>+ <Compile Include="frmDescription.Designer.cs">+ <DependentUpon>frmDescription.cs</DependentUpon>+ </Compile>+ <Compile Include="GpuDeviceInfo.cs" />+ <Compile Include="GpuWaveSimulator.cs" />+ <Compile Include="HelpForm.cs">+ <SubType>Form</SubType>+ </Compile>+ <Compile Include="HelpForm.Designer.cs">+ <DependentUpon>HelpForm.cs</DependentUpon>+ </Compile>+ <Compile Include="IFrameSink.cs" />+ <Compile Include="IMFAttributesNative.cs" />+ <Compile Include="IMFMediaBufferNative.cs" />+ <Compile Include="IMFSampleNative.cs" />+ <Compile Include="IMFSinkWriterNative.cs" />+ <Compile Include="IWaveEngine.cs" />+ <Compile Include="MfVideoWriter.cs" />+ <Compile Include="My\MyApplication.cs" />+ <Compile Include="My\MyComputer.cs" />+ <Compile Include="My\MyProject.cs" />+ <Compile Include="My\MySettings.Designer.cs">+ <DependentUpon>MySettings.settings</DependentUpon>+ <AutoGen>True</AutoGen>+ <DesignTimeSharedInput>True</DesignTimeSharedInput>+ </Compile>+ <Compile Include="My\MySettingsProperty.cs" />+ <Compile Include="My\Resources\_2D_wave_sim_V01.Resources.Designer.cs">+ <DependentUpon>_2D_wave_sim_V01.Resources.resx</DependentUpon>+ <AutoGen>True</AutoGen>+ <DesignTime>True</DesignTime>+ </Compile>+ <Compile Include="OpenClApi.cs" />+ <Compile Include="ProbeBoxSize.cs" />+ <Compile Include="ProbeCollector.cs" />+ <Compile Include="ProbeGraphPainter.cs" />+ <Compile Include="ProbeKind.cs" />+ <Compile Include="ProbeMeasurement.cs" />+ <Compile Include="ProbeOverlay.cs" />+ <Compile Include="ProbePlaceOn.cs" />+ <Compile Include="ProbeSampler.cs" />+ <Compile Include="ProbeScaleMode.cs" />+ <Compile Include="ProbeSeries.cs" />+ <Compile Include="ProbeSettings.cs" />+ <Compile Include="ProbeTrace.cs" />+ <Compile Include="ProbeUpdate.cs" />+ <Compile Include="Project.cs" />+ <Compile Include="ProjectConfig.cs" />+ <Compile Include="ProjectStore.cs" />+ <Compile Include="Properties\AssemblyInfo.cs" />+ <Compile Include="SceneData.cs" />+ <Compile Include="SceneSettings.cs" />+ <Compile Include="SimulationJob.cs" />+ <Compile Include="SimulationResult.cs" />+ <Compile Include="SimulationRunner.cs" />+ <Compile Include="SimulationSettings.cs" />+ <Compile Include="SimulationStatus.cs" />+ <Compile Include="SourceCompositeMode.cs" />+ <Compile Include="SourceElement.cs" />+ <Compile Include="SourceMainType.cs" />+ <Compile Include="SourceMode.cs" />+ <Compile Include="SourcePulseShape.cs" />+ <Compile Include="SourceSettings.cs" />+ <Compile Include="WaveEngineFactory.cs" />+ <Compile Include="WaveSimulator.cs" />+ </ItemGroup>+ <ItemGroup>+ <EmbeddedResource Include="AboutForm.resx">+ <DependentUpon>AboutForm.cs</DependentUpon>+ </EmbeddedResource>+ <EmbeddedResource Include="Form1.resx">+ <DependentUpon>Form1.cs</DependentUpon>+ </EmbeddedResource>+ <EmbeddedResource Include="frmDescription.resx">+ <DependentUpon>frmDescription.cs</DependentUpon>+ </EmbeddedResource>+ <EmbeddedResource Include="HelpForm.resx">+ <DependentUpon>HelpForm.cs</DependentUpon>+ </EmbeddedResource>+ <EmbeddedResource Include="My\Resources\_2D_wave_sim_V01.Resources.resx">+ <Generator>ResXFileCodeGenerator</Generator>+ <LastGenOutput>_2D_wave_sim_V01.Resources.Designer.cs</LastGenOutput>+ </EmbeddedResource>+ </ItemGroup>+ <ItemGroup>+ <None Include="app.config" />+ <None Include="My\MySettings.settings">+ <Generator>SettingsSingleFileGenerator</Generator>+ <LastGenOutput>MySettings.Designer.cs</LastGenOutput>+ </None>+ </ItemGroup>+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />+</Project>\ No newline at end of filediff --git a/Wave_Dude_2D/Wave_Dude_2D.ico b/Wave_Dude_2D/Wave_Dude_2D.iconew file mode 100644index 0000000..daf72c8Binary files /dev/null and b/Wave_Dude_2D/Wave_Dude_2D.ico differdiff --git a/Wave_Dude_2D/app.config b/Wave_Dude_2D/app.confignew file mode 100644index 0000000..b22f757--- /dev/null+++ b/Wave_Dude_2D/app.config@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="utf-8" ?>+<configuration>+ <startup>+ <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />+ </startup>+</configuration>\ No newline at end of filediff --git a/Wave_Dude_2D/frmDescription.Designer.cs b/Wave_Dude_2D/frmDescription.Designer.csnew file mode 100644index 0000000..cd4cee5--- /dev/null+++ b/Wave_Dude_2D/frmDescription.Designer.cs@@ -0,0 +1,76 @@+using System;+using System.ComponentModel;+using System.Windows.Forms;++namespace _2D_wave_sim_V01+{+ public partial class frmDescription : global::System.Windows.Forms.Form+ {+ /// <summary>Releases the designer-managed components when <paramref name="disposing"/> is true, then the form itself.</summary>+ /// <param name="disposing">True when called from <see cref="System.ComponentModel.Component.Dispose()"/>; false from the finalizer.</param>+ [global::System.Diagnostics.DebuggerNonUserCode]+ protected override void Dispose(bool disposing)+ {+ try+ {+ bool flag = disposing && this.components != null;+ if (flag)+ {+ this.components.Dispose();+ }+ }+ finally+ {+ base.Dispose(disposing);+ }+ }++ [global::System.Diagnostics.DebuggerStepThrough]+ private void InitializeComponent()+ {+ this.TextBox1 = new global::System.Windows.Forms.TextBox();+ this.btnSaveDescription = new global::System.Windows.Forms.Button();+ this.btnCancelDescription = new global::System.Windows.Forms.Button();+ base.SuspendLayout();+ this.TextBox1.BorderStyle = global::System.Windows.Forms.BorderStyle.FixedSingle;+ this.TextBox1.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.TextBox1.Location = new global::System.Drawing.Point(22, 23);+ this.TextBox1.Multiline = true;+ this.TextBox1.Name = "TextBox1";+ this.TextBox1.Size = new global::System.Drawing.Size(662, 267);+ this.TextBox1.TabIndex = 0;+ this.btnSaveDescription.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnSaveDescription.Location = new global::System.Drawing.Point(575, 305);+ this.btnSaveDescription.Name = "btnSaveDescription";+ this.btnSaveDescription.Size = new global::System.Drawing.Size(109, 32);+ this.btnSaveDescription.TabIndex = 1;+ this.btnSaveDescription.Text = "OK";+ this.btnSaveDescription.UseVisualStyleBackColor = true;+ this.btnCancelDescription.Font = new global::System.Drawing.Font("Microsoft Sans Serif", 11.25f, global::System.Drawing.FontStyle.Regular, global::System.Drawing.GraphicsUnit.Point, 0);+ this.btnCancelDescription.Location = new global::System.Drawing.Point(460, 305);+ this.btnCancelDescription.Name = "btnCancelDescription";+ this.btnCancelDescription.Size = new global::System.Drawing.Size(109, 32);+ this.btnCancelDescription.TabIndex = 1;+ this.btnCancelDescription.Text = "Cancel";+ this.btnCancelDescription.UseVisualStyleBackColor = true;+ // event wiring (was VB WithEvents/Handles)+ this.btnSaveDescription.Click += new EventHandler(this.btnSaveDescription_Click);+ this.btnCancelDescription.Click += new EventHandler(this.btnCancelDescription_Click);+ base.AutoScaleDimensions = new global::System.Drawing.SizeF(6f, 13f);+ base.AutoScaleMode = global::System.Windows.Forms.AutoScaleMode.Font;+ base.ClientSize = new global::System.Drawing.Size(705, 349);+ base.Controls.Add(this.btnCancelDescription);+ base.Controls.Add(this.btnSaveDescription);+ base.Controls.Add(this.TextBox1);+ base.Name = "frmDescription";+ this.Text = "Edit project description";+ base.ResumeLayout(false);+ base.PerformLayout();+ }++ private TextBox TextBox1;+ private Button btnSaveDescription;+ private Button btnCancelDescription;+ private global::System.ComponentModel.IContainer components;+ }+}diff --git a/Wave_Dude_2D/frmDescription.cs b/Wave_Dude_2D/frmDescription.csnew file mode 100644index 0000000..a396054--- /dev/null+++ b/Wave_Dude_2D/frmDescription.cs@@ -0,0 +1,46 @@+using System;+using System.Windows.Forms;++namespace _2D_wave_sim_V01+{+ /// <summary>+ /// Small modal dialog for editing a project's free-text description. <see cref="Form1"/>+ /// opens it from the "Description" button, pre-fills <see cref="DescriptionText"/> and reads+ /// it back when the dialog closes with <see cref="DialogResult.OK"/>.+ /// </summary>+ public partial class frmDescription : Form+ {+ /// <summary>Creates the dialog with an empty description.</summary>+ public frmDescription()+ {+ this.InitializeComponent();+ }++ /// <summary>Gets or sets the description text shown in the text box.</summary>+ public string DescriptionText+ {+ get+ {+ return this.TextBox1.Text;+ }+ set+ {+ this.TextBox1.Text = value;+ }+ }++ /// <summary>Closes the dialog with <see cref="DialogResult.OK"/>; the edited text stays in <see cref="DescriptionText"/>.</summary>+ private void btnSaveDescription_Click(object sender, EventArgs e)+ {+ base.DialogResult = DialogResult.OK;+ base.Close();+ }++ /// <summary>Closes the dialog with <see cref="DialogResult.Cancel"/>; the caller discards the edit.</summary>+ private void btnCancelDescription_Click(object sender, EventArgs e)+ {+ base.DialogResult = DialogResult.Cancel;+ base.Close();+ }+ }+}diff --git a/Wave_Dude_2D/frmDescription.resx b/Wave_Dude_2D/frmDescription.resxnew file mode 100644index 0000000..7c72981--- /dev/null+++ b/Wave_Dude_2D/frmDescription.resx@@ -0,0 +1,61 @@+<?xml version="1.0" encoding="utf-8"?>+<root>+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />+ <xsd:element name="root" msdata:IsDataSet="true">+ <xsd:complexType>+ <xsd:choice maxOccurs="unbounded">+ <xsd:element name="metadata">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" />+ </xsd:sequence>+ <xsd:attribute name="name" use="required" type="xsd:string" />+ <xsd:attribute name="type" type="xsd:string" />+ <xsd:attribute name="mimetype" type="xsd:string" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="assembly">+ <xsd:complexType>+ <xsd:attribute name="alias" type="xsd:string" />+ <xsd:attribute name="name" type="xsd:string" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="data">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="resheader">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" />+ </xsd:complexType>+ </xsd:element>+ </xsd:choice>+ </xsd:complexType>+ </xsd:element>+ </xsd:schema>+ <resheader name="resmimetype">+ <value>text/microsoft-resx</value>+ </resheader>+ <resheader name="version">+ <value>2.0</value>+ </resheader>+ <resheader name="reader">+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <resheader name="writer">+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+</root>\ No newline at end of filediff --git a/_tools/CLEANUP_GUIDE.md b/_tools/CLEANUP_GUIDE.mdnew file mode 100644index 0000000..9b73e78--- /dev/null+++ b/_tools/CLEANUP_GUIDE.md@@ -0,0 +1,85 @@+# Decompiled-code cleanup guide (phase 2)++The C# in `Wave_Dude_2D/` is ILSpy output from a VB.NET binary. Your job is to make the+files assigned to you read like hand-written C# **without changing behaviour**. The project+compiles right now; it must still compile when you are done.++## Hard rules++1. **Behaviour-preserving only.** No feature changes, no "improvements" to logic, no reordering+ of side effects. If you are unsure whether a rewrite is equivalent, leave the original.+2. **Do not change the signature, name, accessibility or type of any member** (method, property,+ field, event, constant, nested type). Other agents are editing other files in parallel and+ call into yours. This includes `ref` parameters — leave them `ref` for now.+3. **Only edit the files assigned to you.** Never touch `*.Designer.cs`, `My/*`, `*.resx`,+ `*.csproj`, or any other file.+4. Keep the file format: **tab indentation, Allman braces**,+ `this.` prefixes as they are. Do not reflow or reformat code you are not otherwise changing.+5. Keep `using` directives that are still needed; drop ones that become unused+ (`Microsoft.VisualBasic.CompilerServices`, `System.Runtime.CompilerServices` usually do).++## What to fix++### Names+Decompiler placeholders → descriptive names based on what the value *is*:+`num`, `num2`, … `flag`, `flag3`, … `text`, `text2`, … `array`, `list`, `list2`, `obj`,+`item`, `ex2`, `dictionary`, `bitmap2`, `graphics`, `stringBuilder`, `result`, `enumerator`…+- A loop bound `int num = x.Length - 1; for (int i = 0; i <= num; i++)` becomes+ `for (int i = 0; i < x.Length; i++)` (drop the temp).+- A hoisted `bool flag = <cond>;` used once in an `if` is inlined (see control flow).+- Unused catch variables: `catch (Exception ex) { }` → `catch (Exception) { }`+ (or `catch { }` when the type is `Exception`). Keep the variable if it is used.+- Keep names already meaningful (`stride`, `width`, `probe`, `scheme`...).+- Naming style: camelCase locals, no Hungarian, no `_` prefix for locals.++### Control flow+- `bool flag = cond; if (flag) {…}` → `if (cond) {…}`; `if (!flag)` → `if (!cond)`.+- `if (!cond) { <whole rest of method> }` → `if (cond) return;` + flat body (guard clauses),+ when it removes a nesting level and the method has no other tail code.+- `T result; if (c) { result = a; } else { result = b; } return result;` →+ `return c ? a : b;` for simple expressions, otherwise two `return`s.+- `do { … num++; } while (num <= 255);` counting loops → `for`.+- `for (;;) { … if (x) break; … }` → `while (!x)` when it reads naturally; otherwise leave.+- `foreach (object obj in coll) { T t = (T)obj; … }` → `foreach (T t in coll) { … }`.+- `checked { … }` blocks and `checked(...)`/`unchecked(...)` expression wrappers: remove.+ Keep `unchecked` only where it is needed to compile a constant/cast+ (e.g. `unchecked((int)0xFF000000)`).+- `RuntimeHelpers.GetObjectValue(x)` → `x`.+- VB runtime helpers → C#, preserving semantics:+ - `Conversions.ToString(x)` → `x.ToString()` (for numbers use the same culture the original+ would have used: VB uses the current culture → `x.ToString(CultureInfo.CurrentCulture)`,+ or keep `CultureInfo.InvariantCulture` when the surrounding code already uses it).+ - `Conversions.ToInteger(s)` / `ToDouble(s)` → `int.Parse` / `double.Parse` with+ `CultureInfo.CurrentCulture`; if the original was wrapped in try/catch keep it.+ - `Conversions.ToBoolean`, `ToInteger(bool)` etc. → plain C# casts/expressions.+ - `Operators.CompareString(a, b, false) == 0` → `string.CompareOrdinal(a, b) == 0`+ (or `a == b` when neither side can be null-vs-empty sensitive — if unsure use `CompareOrdinal`).+ - `Strings.Len(s)` → `s.Length`; `Strings.Trim` → `.Trim()`; `Interaction.MsgBox` → `MessageBox.Show`.+- Redundant casts the decompiler added (`(int)c.R`, `(double)intValue * 1.0`, `(long)` widening+ in index arithmetic) → remove where the result type is unchanged.+- Empty `try { } finally { }` leftovers, dead `if (true)`, duplicated null checks → remove.++### Comments / attributes+- Delete every `// Token: …`, `// (get) Token…`, `// (set) Token…`, `// RVA…` comment.+- Delete decompiler attributes `[CompilerGenerated]`, `[DebuggerStepThrough]`,+ `[MethodImpl(MethodImplOptions.Synchronized)]`, `[DesignerGenerated]`, `[GeneratedCode(...)]`+ when they sit on ordinary members. Keep `[DllImport]`, `[StructLayout]`, `[STAThread]`,+ `[DesignerCategory]`, `[Serializable]` and anything with runtime meaning.+- You may add a short `///` summary on a class and on methods whose purpose is not obvious from+ the name. Keep it sparse — the surrounding code has few comments; do not comment every line.++## Verify before you finish++Run the standalone compiler check (does not touch `bin/obj`, safe in parallel):++```+cd /c/Work/WaveDude/Wave_Dude_2D && "/c/Program Files/Microsoft Visual Studio/18/Community/MSBuild/Current/Bin/Roslyn/csc.exe" -nologo -target:winexe -out:"$(cygpath -w /tmp/check_<yourname>.exe)" -langversion:7.3 -r:System.dll -r:System.Core.dll -r:System.Drawing.dll -r:System.Windows.Forms.dll -r:Microsoft.VisualBasic.dll -r:System.Web.Extensions.dll -nowarn:0168,0649,0414,0675 *.cs My/*.cs My/Resources/*.cs Properties/*.cs+```++- Errors in **your** files: fix them.+- Errors in other files: another agent is mid-edit; wait ~30 s and re-run. Ignore if they persist+ and your files are clean (report it).+++Finish with a 5-line report: files touched, approximate number of renames, anything you left+alone because you were unsure, and the csc result.diff --git a/_tools/DOC_GUIDE.md b/_tools/DOC_GUIDE.mdnew file mode 100644index 0000000..8bca643--- /dev/null+++ b/_tools/DOC_GUIDE.md@@ -0,0 +1,64 @@+# Documentation + final cleanup guide (phase 3)++The code in `Wave_Dude_2D/` has been cleaned from decompiler output into readable C#. This pass+adds proper XML documentation and finishes any cleanup still left. All the **hard rules** of+`CLEANUP_GUIDE.md` still apply (behaviour-preserving, no signature/name/accessibility changes,+only your assigned files, tabs + Allman, verify with `csc`). Read that file first. Do not touch, check or mention file encodings or line endings; `.editorconfig` handles that.++## XML documentation — what is required++Every **type** (class, struct, interface, enum, delegate, nested type) gets a `/// <summary>` that+says what it is *for* and how it fits in (who creates it, who consumes it, which thread it lives+on if that matters).++Every **member** gets a `/// <summary>`:+- public/internal methods, properties, fields, events, constants: always, with `<param>` for every+ parameter whose meaning is not obvious from its name and type, `<returns>` when the return value+ needs explanation (what null/empty/-1 means, units, ranges), `<exception>` when the method throws+ deliberately.+- enum members: always, one line each.+- private fields: one line each (what it holds, units, when it is null, which thread touches it).+- private methods: a summary; `<param>`/`<returns>` only where they add information.+- WinForms event handlers (`btnX_Click`, `numY_ValueChanged`, …): one line saying what the user+ action results in — not "handles the click event".+- Constructors: only if they do more than assign parameters.++Quality bar:+- Write from the *code*, not from the name. Read the body before writing the summary. If the code+ does something surprising (side effects, re-entrancy guards like `_loadingScene`, swapping buffers,+ clamping, culture-specific parsing, COM late binding), say so.+- State units and coordinate systems: canvas pixels vs. picture-box pixels vs. screen; steps vs.+ seconds; refractive index vs. speed; 0..1 vs 0..255; radians vs degrees.+- State threading: anything called from `SimulationRunner`'s worker thread, anything that must+ run on the UI thread, anything marshalled through `PostToUi`.+- State ownership/disposal for `Bitmap`, `Graphics`, OpenCL and Media Foundation handles.+- Do not pad. "Gets or sets the width." is fine for a trivial property. Do not write a paragraph+ for a one-line getter. Do not restate parameter names as prose.+- Keep summaries that already exist if they are accurate; sharpen them if not.+- Use `<see cref="..."/>` for references to other members/types; `<paramref name="..."/>` for+ parameters. Standard XML doc syntax only (`<summary>`, `<param>`, `<returns>`, `<remarks>`,+ `<exception>`, `<see>`, `<paramref>`, `<c>`, `<list>`). Escape `<`, `>` and `&` in prose as+ `<`, `>`, `&`.+- Inline `//` comments: add them where a non-obvious line needs one (magic numbers, why a+ workaround exists); do not comment every line.++## Final cleanup — whatever is still left++While you are reading each method anyway, finish the cleanup from `CLEANUP_GUIDE.md` where the+previous pass missed something: leftover placeholder names, `bool x = cond; if (x)` temps used+once, redundant casts, `string.Concat(new string[] {...})` → `+`, dead code, duplicated+null-checks, empty handlers that are never wired, unused `using`s, `catch (Exception ex)` with+unused `ex`. Still no signature or behaviour changes.++Also fix obvious typos in **identifiers you own privately** is NOT allowed (names are frozen);+typos in **comments** and in **existing string literals** are also off-limits (strings are UI+behaviour). Just document.++## Verify++Run the csc check from `CLEANUP_GUIDE.md` (use your own check exe name), **adding `-doc:"$(cygpath -w /tmp/check_<yourname>.xml)" -warnaserror+:1570,1572,1573,1574,1580,1584,1587,1589,1590,1591,1710`** so malformed+XML or wrong `<param>` names fail the build. Fix every such error in your files.++Finish with a 5-line report: files touched, number of members documented, anything you could not+understand well enough to document confidently (list them — a wrong comment is worse than none),+cleanup done beyond docs, csc result.diff --git a/_tools/fix_designer_generated.py b/_tools/fix_designer_generated.pynew file mode 100644index 0000000..c1da0a7--- /dev/null+++ b/_tools/fix_designer_generated.py@@ -0,0 +1,31 @@+"""Remove VB [DesignerGenerated] attributes and replace the _rootBlinkTimer WithEvents property with a field."""+import glob, re++def rw(path, fn):+ raw = open(path, 'rb').read()+ bom = raw.startswith(b'\xef\xbb\xbf')+ text = raw.decode('utf-8-sig')+ new = fn(text)+ if new != text:+ open(path, 'wb').write((b'\xef\xbb\xbf' if bom else b'') + new.encode('utf-8'))+ print('patched', path)++for p in glob.glob('Wave_Dude_2D/*.cs'):+ rw(p, lambda t: re.sub(r'^\t\[(global::Microsoft\.VisualBasic\.CompilerServices\.)?DesignerGenerated\]\r\n', '', t, flags=re.M))++def fix_timer(t):+ # property -> field+ t, n = re.subn(+ r'(\t\t// Token:[^\r\n]*\r\n)*\t\tprivate virtual global::System\.Windows\.Forms\.Timer _rootBlinkTimer\r\n\t\t\{.*?\r\n\t\t\}\r\n',+ '\t\tprivate readonly global::System.Windows.Forms.Timer _rootBlinkTimer;\r\n', t, count=1, flags=re.S)+ assert n == 1, 'timer property not found'+ # drop backing field+ t, n = re.subn(r'(\t\t// Token:[^\r\n]*\r\n)*\t\tprivate global::System\.Windows\.Forms\.Timer __rootBlinkTimer;\r\n\r\n?', '', t, count=1)+ # (the decompiler never emitted the backing field, so n may be 0)+ # wire the Tick handler where the timer is created+ t, n = re.subn(r'(\t\t\tthis\._rootBlinkTimer = new global::System\.Windows\.Forms\.Timer\r\n\t\t\t\{\r\n\t\t\t\tInterval = 700\r\n\t\t\t\};\r\n)',+ r'\1\t\t\tthis._rootBlinkTimer.Tick += this.RootBlinkTimer_Tick;\r\n', t, count=1)+ assert n == 1, 'timer construction not found'+ return t++rw('Wave_Dude_2D/Form1.cs', fix_timer)diff --git a/_tools/fix_semantic.py b/_tools/fix_semantic.pynew file mode 100644index 0000000..2d32b55--- /dev/null+++ b/_tools/fix_semantic.py@@ -0,0 +1,191 @@+"""Second-pass fixes for decompiled-VB residue that is syntactically valid but does not compile.++Order matters: step 1 uses line numbers from the current build log (/tmp/build.log),+so it runs before anything that shifts lines.++ 1. CS0165 ByRef locals : `double num;` passed as `ref num` -> `double num = default(double);`+ 2. bogus try/finally : `finally { List<T>.Enumerator enumerator; ((IDisposable)enumerator).Dispose(); }`+ -> drop the finally, unwrap the try+ 3. VB event backing refs: `this.FooEvent` -> `this.Foo`+ 4. AviMjpegWriter : two mis-decompiled unsigned constants+ 5. WithEvents properties: `internal virtual T name { get{return this._name;} set{...hook events...} }`+ -> `private T name;` in the Designer + `this.name.Event += handler;` in InitializeComponent+"""+import re, sys, os++SRC = 'Wave_Dude_2D'++def read(path):+ raw = open(path, 'rb').read()+ return raw.startswith(b'\xef\xbb\xbf'), raw.decode('utf-8-sig').split('\r\n')++def write(path, bom, lines):+ open(path, 'wb').write((b'\xef\xbb\xbf' if bom else b'') + '\r\n'.join(lines).encode('utf-8'))++def indent_of(line):+ return len(line) - len(line.lstrip('\t'))++# ---------------------------------------------------------------- 1. ByRef locals+def fix_byref_locals(log_path):+ sites = {}+ for m in re.finditer(r'\\([A-Za-z0-9_.]+\.cs)\((\d+),\d+\): error CS0165: Use of unassigned local variable \'(\w+)\'', open(log_path, encoding='utf-8', errors='replace').read()):+ f, line, var = m.group(1), int(m.group(2)), m.group(3)+ if var.startswith('enumerator'):+ continue+ sites.setdefault(f, set()).add((line, var))+ for f, items in sites.items():+ path = os.path.join(SRC, f)+ bom, lines = read(path)+ for line, var in sorted(items):+ i = line - 1+ decl = re.compile(r'^(\t+)([A-Za-z0-9_<>\[\].]+) ' + re.escape(var) + r';$')+ while i >= 0 and not decl.match(lines[i]):+ i -= 1+ if i < 0:+ sys.exit('decl of %s not found near %s:%d' % (var, f, line))+ m = decl.match(lines[i])+ lines[i] = '%s%s %s = default(%s);' % (m.group(1), m.group(2), var, m.group(2))+ write(path, bom, lines)+ print('byref locals: %s (%d)' % (f, len(items)))++# ---------------------------------------------------------------- 2. bogus try/finally+BOGUS = [re.compile(p) for p in (+ r'^\t+[A-Za-z0-9_<>.\[\]]*Enumerator enumerator\d*;$',+ r'^\t+\(\(IDisposable\)enumerator\d*\)\.Dispose\(\);$',+ r'^\t+if \(enumerator\d* is IDisposable\)$',+ r'^\t+\(enumerator\d* as IDisposable\)\.Dispose\(\);$',+ r'^\t+[{}]$',+)]++def fix_bogus_finally(path):+ bom, lines = read(path)+ changed = 0+ i = 0+ while i < len(lines):+ if lines[i].lstrip('\t') == 'finally' and lines[i].startswith('\t'):+ k = indent_of(lines[i])+ close = i + 2+ while close < len(lines) and lines[close] != '\t' * k + '}':+ close += 1+ body = lines[i + 2:close]+ if body and all(any(p.match(l) for p in BOGUS) for l in body) and any('numerator' in l for l in body):+ # block directly before `finally` is `{ ... }` at indent k; find its opening brace+ j = i - 1+ assert lines[j] == '\t' * k + '}', (path, i)+ depth = 0+ while True:+ s = lines[j].strip()+ if s == '}':+ depth += 1+ elif s == '{':+ depth -= 1+ if depth == 0:+ break+ j -= 1+ head = lines[j - 1].strip()+ del lines[i:close + 1] # drop finally block+ if head == 'try':+ inner = [l[1:] if l.startswith('\t') else l for l in lines[j + 1:i - 1]]+ lines[j - 1:i] = inner # unwrap try { ... }+ i = j - 1 + len(inner)+ else:+ # try/catch/finally: keep try/catch, finally alone is dropped+ i = i+ changed += 1+ continue+ i += 1+ if changed:+ write(path, bom, lines)+ print('bogus finally: %s (%d)' % (path, changed))++# ---------------------------------------------------------------- 3. event backing refs+def fix_event_refs(path):+ bom, lines = read(path)+ new = [re.sub(r'this\.(ColorChanged|EngineReady|ProgressChanged|PreviewReady|ProbesUpdated|Finished)Event\b', r'this.\1', l) for l in lines]+ if new != lines:+ write(path, bom, new)+ print('event refs:', path)++# ---------------------------------------------------------------- 4. AVI constants+def fix_avi():+ path = os.path.join(SRC, 'AviMjpegWriter.cs')+ bom, lines = read(path)+ text = '\r\n'.join(lines)+ a = text.replace('this._writer.Write((uint)((unchecked((long)width) * unchecked((long)height) * 3L) & (long)(unchecked((ulong)(-1)))));',+ 'this._writer.Write((uint)(((long)width * height * 3L) & 0xFFFFFFFFL));')+ b = a.replace('+ 64L > (long)(unchecked((ulong)(-394967296)))', '+ 64L > MaxAviBytes')+ assert a != text and b != a, 'AVI constants not found'+ b = b.replace('\t\tpublic void AddFrame(byte[] data, int length)',+ '\t\t// stay safely below the 4 GB RIFF limit\r\n\t\tprivate const long MaxAviBytes = 3900000000L;\r\n\r\n\t\tpublic void AddFrame(byte[] data, int length)', 1)+ write(path, bom, b.split('\r\n'))+ print('avi constants fixed')++# ---------------------------------------------------------------- 5. WithEvents properties+PROP = re.compile(r'^\t\tinternal virtual ([A-Za-z0-9_<>.:]+) ([A-Za-z0-9_]+)$')+HANDLER = re.compile(r'^\t{4}([A-Za-z0-9_.]+) ([A-Za-z0-9_]+) = new ([A-Za-z0-9_.]+)\(this\.([A-Za-z0-9_]+)\);$')+HOOK = re.compile(r'^\t{5}([A-Za-z0-9_]+)\.([A-Za-z0-9_]+) \+= ([A-Za-z0-9_]+);$')++def fix_withevents(code_path, designer_path):+ bom, lines = read(code_path)+ fields = [] # (type, name)+ wiring = [] # (control, event, delegateType, handlerMethod)+ i = 0+ out = []+ while i < len(lines):+ m = PROP.match(lines[i])+ if not m:+ out.append(lines[i]); i += 1; continue+ typ, name = m.group(1), m.group(2)+ # strip preceding decompiler comments already emitted to out+ while out and out[-1].strip().startswith('// '):+ out.pop()+ end = i + 1+ while lines[end] != '\t\t}':+ end += 1+ block = lines[i:end + 1]+ delegates = {}+ for l in block:+ h = HANDLER.match(l)+ if h:+ delegates[h.group(2)] = (h.group(3), h.group(4))+ k = HOOK.match(l)+ if k:+ dt, method = delegates[k.group(3)]+ wiring.append((name, k.group(2), dt, method))+ fields.append((typ, name))+ i = end + 1+ # drop one trailing blank line+ if i < len(lines) and lines[i] == '' and out and out[-1] == '':+ i += 1+ # sanity: no stray references to the backing fields remain+ leftover = [n for _, n in fields if re.search(r'\b_' + re.escape(n) + r'\b', '\r\n'.join(out))]+ assert not leftover, ('backing field refs remain', code_path, leftover[:5])+ write(code_path, bom, out)++ dbom, dlines = read(designer_path)+ comp = next(j for j, l in enumerate(dlines) if l.strip().startswith('private global::System.ComponentModel.IContainer components;'))+ # drop the Token comment above `components`+ if dlines[comp - 1].strip().startswith('// Token'):+ del dlines[comp - 1]; comp -= 1+ decls = ['\t\tprivate %s %s;' % (t.replace('global::', ''), n) for t, n in fields]+ dlines[comp:comp] = decls+ if wiring:+ created = set(re.findall(r'this\.([A-Za-z0-9_]+) = new ', '\r\n'.join(dlines)))+ missing = sorted({c for c, _, _, _ in wiring if c not in created})+ assert not missing, ('wired controls not created in InitializeComponent', designer_path, missing)+ anchor = next(j for j, l in enumerate(dlines) if re.match(r'^\t\t\t(base|this)\.(AutoScaleDimensions|ResumeLayout)', l))+ hooks = ['\t\t\tthis.%s.%s += new %s(this.%s);' % w for w in wiring]+ dlines[anchor:anchor] = ['\t\t\t// event wiring (was VB WithEvents/Handles)'] + hooks+ write(designer_path, dbom, dlines)+ print('withevents: %s -> %d fields, %d event hooks' % (code_path, len(fields), len(wiring)))++if __name__ == '__main__':+ fix_byref_locals('/tmp/build.log' if os.path.exists('/tmp/build.log') else sys.argv[1])+ for f in sorted(os.listdir(SRC)):+ if f.endswith('.cs'):+ fix_bogus_finally(os.path.join(SRC, f))+ fix_event_refs(os.path.join(SRC, 'ColorPickerControl.cs'))+ fix_event_refs(os.path.join(SRC, 'SimulationRunner.cs'))+ fix_avi()+ for form in ('Form1', 'frmDescription', 'AboutForm', 'HelpForm'):+ fix_withevents(os.path.join(SRC, form + '.cs'), os.path.join(SRC, form + '.Designer.cs'))diff --git a/_tools/fix_static_lambdas.py b/_tools/fix_static_lambdas.pynew file mode 100644index 0000000..7dfc527--- /dev/null+++ b/_tools/fix_static_lambdas.py@@ -0,0 +1,27 @@+"""Replace the two decompiled cached-static-lambda Sort calls with plain lambdas."""+import re++def patch(path, pattern, replacement):+ raw = open(path, 'rb').read()+ text = raw.decode('utf-8-sig')+ new, n = re.subn(pattern, replacement, text, flags=re.S)+ if n != 1:+ raise SystemExit('%s: expected 1 match, got %d' % (path, n))+ open(path, 'wb').write(b'\xef\xbb\xbf' + new.encode('utf-8'))+ print(path, 'patched')++patch('Wave_Dude_2D/GpuDeviceInfo.cs',+ r'list\.Sort\(\(GpuDeviceInfo\._Closure\$__\.\$I9-0 == null\) \? \(GpuDeviceInfo\._Closure\$__\.\$I9-0 = delegate\(GpuDeviceInfo a, GpuDeviceInfo b\)\r\n(\t+)\{.*?\}\) : GpuDeviceInfo\._Closure\$__\.\$I9-0\);',+ lambda m: ('list.Sort((a, b) =>\r\n'+ + m.group(1) + '{\r\n'+ + m.group(1) + '\t// discrete GPUs first, then by score descending\r\n'+ + m.group(1) + '\tif (a.Discrete != b.Discrete)\r\n'+ + m.group(1) + '\t{\r\n'+ + m.group(1) + '\t\treturn a.Discrete ? -1 : 1;\r\n'+ + m.group(1) + '\t}\r\n'+ + m.group(1) + '\treturn b.Score.CompareTo(a.Score);\r\n'+ + m.group(1) + '});'))++patch('Wave_Dude_2D/ProjectStore.cs',+ r'list\.Sort\(\(ProjectStore\._Closure\$__\.\$I14-0 == null\) \? \(ProjectStore\._Closure\$__\.\$I14-0 = \(string a, string b\) => string\.Compare\(a, b, StringComparison\.OrdinalIgnoreCase\)\) : ProjectStore\._Closure\$__\.\$I14-0\);',+ 'list.Sort((a, b) => string.Compare(a, b, StringComparison.OrdinalIgnoreCase));')diff --git a/_tools/replace_method.py b/_tools/replace_method.pynew file mode 100644index 0000000..4d4c8c0--- /dev/null+++ b/_tools/replace_method.py@@ -0,0 +1,32 @@+"""Replace one method body in a decompiled .cs file, preserving BOM + CRLF.++usage: replace_method.py <file.cs> <signature-substring> <replacement.txt>++The method is located by the first line containing <signature-substring>;+the replaced range runs from any directly preceding '// Token:' comment lines+to the closing brace at the same indentation as the signature line.+"""+import sys++path, sig, repl_path = sys.argv[1:4]+raw = open(path, 'rb').read()+bom = raw.startswith(b'\xef\xbb\xbf')+text = raw.decode('utf-8-sig')+lines = text.split('\r\n')++start = next(i for i, l in enumerate(lines) if sig in l)+indent = lines[start][:len(lines[start]) - len(lines[start].lstrip('\t'))]+# swallow preceding decompiler comment lines+while start > 0 and lines[start - 1].strip().startswith('//'):+ start -= 1+end = start+while end < len(lines) and lines[end] != indent + '}':+ end += 1+if end == len(lines):+ sys.exit('closing brace not found for ' + sig)++repl = open(repl_path, 'rb').read().decode('utf-8-sig').replace('\r\n', '\n').rstrip('\n').split('\n')+lines[start:end + 1] = repl+out = '\r\n'.join(lines).encode('utf-8')+open(path, 'wb').write((b'\xef\xbb\xbf' if bom else b'') + out)+print('%s: replaced lines %d-%d with %d lines' % (path, start + 1, end + 1, len(repl)))diff --git a/_tools/split_form1.py b/_tools/split_form1.pynew file mode 100644index 0000000..4024530--- /dev/null+++ b/_tools/split_form1.py@@ -0,0 +1,64 @@+"""Split Form1.cs into partial-class files along its feature seams (no code changes).++Each section starts at the named method (including the decompiler comment lines+directly above it) and runs to the line before the next section. The Sources+section ends before the first field token comment (`// Token: 0x04...`).+Fields and nested types stay in Form1.cs. Adds the new files to the csproj.+"""+import re++SRC = 'Wave_Dude_2D/'+SECTIONS = [+ ('Form1.Projects.cs', 'BuildProjectEntries'),+ ('Form1.Output.cs', 'InitializeOutputsTab'),+ ('Form1.Scene.cs', 'InitializeSceneControls'),+ ('Form1.Colors.cs', 'btbChooseFFolder_Click'),+ ('Form1.Simulation.cs', 'InitializeSimulationControls'),+ ('Form1.Probes.cs', 'ProbeUi'),+ ('Form1.Sources.cs', 'InitializeSourceControls'),+]++raw = open(SRC + 'Form1.cs', 'rb').read()+lines = raw.decode('utf-8-sig').split('\r\n')++def method_start(name):+ sig = re.compile(r'^\t\t(private|public|internal|protected)[^=]*\b' + re.escape(name) + r'\(')+ i = next(i for i, l in enumerate(lines) if sig.match(l))+ while lines[i - 1].strip().startswith('//'):+ i -= 1+ return i++starts = [method_start(m) for _, m in SECTIONS]+last_method = starts[-1]+fields_start = next(i for i in range(last_method, len(lines)) if re.match(r'^\t\t// Token: 0x04', lines[i]))+bounds = starts + [fields_start]++header_end = next(i for i, l in enumerate(lines) if l.startswith('namespace '))+usings = lines[:header_end]++def wrap(body):+ out = list(usings) + ['namespace _2D_wave_sim_V01', '{', '\tpublic partial class Form1', '\t{']+ # trim leading/trailing blank lines of the body+ while body and body[0] == '':+ body.pop(0)+ while body and body[-1] == '':+ body.pop()+ out += body + ['\t}', '}', '']+ return out++for (fname, _), a, b in zip(SECTIONS, bounds, bounds[1:]):+ open(SRC + fname, 'wb').write(b'\xef\xbb\xbf' + '\r\n'.join(wrap(lines[a:b])).encode('utf-8'))+ print('%-22s lines %5d-%5d (%d)' % (fname, a + 1, b, b - a))++core = lines[:starts[0]] + lines[fields_start:]+open(SRC + 'Form1.cs', 'wb').write(b'\xef\xbb\xbf' + '\r\n'.join(core).encode('utf-8'))+print('Form1.cs now %d lines' % len(core))++proj = SRC + 'Wave_Dude_2D.csproj'+p = open(proj, 'rb').read().decode('utf-8-sig')+items = ''.join(' <Compile Include="%s">\r\n <DependentUpon>Form1.cs</DependentUpon>\r\n </Compile>\r\n' % f for f, _ in SECTIONS)+anchor = ' <Compile Include="Form1.Designer.cs">\r\n <DependentUpon>Form1.cs</DependentUpon>\r\n </Compile>\r\n'+assert anchor in p+p = p.replace(anchor, anchor + items, 1)+open(proj, 'wb').write(b'\xef\xbb\xbf' + p.encode('utf-8'))+print('csproj updated')