Skip to content

Interactive 2D wave optics simulator. Turn any image into a refractive scene, add sources, watch waves refract, diffract and interfere. Probes, intensity maps, video export.

C#

Open edges: a wave leaves the grid; a damping edge outside the canvas as an option; version 2 project files

Alexander Graefb59d3eca299b
diff --git a/CLAUDE.md b/CLAUDE.md
index fdac53b..59fed15 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -91,7 +91,12 @@ ExportJob (own STA thread): CopyLayer -> FrameRenderer -> outline -> probe boxes
FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDATA%\WaveDudeNext\cache, DeleteOnClose)
```
-- **Engine contract**: padded grid (`Stride = Width + 2`), one driver thread at a time, no locking; captures
+- **Engine contract**: padded grid (`Stride = Width + 2 + 2 × Rim`: a negative damping edge is a rim of that many cells
+ outside the canvas, simulated and never shown, the canvas starting at (Rim, Rim); `Scene.Edges` Open puts Mur's
+ first-order absorbing condition on the ring, Reflective is Jeroen's wall; a new project is Open with no damping edge
+ (2026-10-19, the user's choice: measured on a pulse, the open ring alone returns 0.05 to 0.09 % of the amplitude, a
+ rim at its best the same, a rim damped to a standstill 1 %, the reflective box 72 %); a version-1 file loads as
+ Reflective, an import as Reflective with his band; one driver thread at a time, no locking; captures
deliver planes in the spec's `FrameShape` (halves or palette index bytes, the GPU converting on the card);
`Reset`, `SetEmitters`, `SetProbes`. Numerics are Jeroen's (dx = dt = 1, leapfrog, 9-point or 4th-order
Laplacian, soft sources, EMA intensity; a scene pixel with red 0 is a mirror, n = 1000, his V0.30 rule,
@@ -192,7 +197,7 @@ numbers: no GPU JPEG, no OpenCL colouring at presentation, no `Vector256`, no Di
## Harnesses
-`library_check` (100+ checks: engines, store, renderer, schemes, probes, scratch, reduced preview, importer, export, parts, group move).
+`library_check` (100+ checks: engines, store, renderer, schemes, probes, scratch, reduced preview, importer, export, parts, group move, open edges).
UI, all on `Common.ps1`, with their check counts: `PreviewCheck` 43, `RunCheck` 71, `LanguageCheck` 11,
`ProbeGraphCheck` 39, `ImportCheck` 10, `ExportCheck` 38, `PreviewQualityCheck` 35, `SceneImageCheck` 8,
`ColorPickerCheck` 13, `KeyboardCheck` 13, `AboutCheck` 18, `SelectionCheck` 10. Test projects `tiny*.wdproj` sit beside them. A harness
diff --git a/WaveDudeNext.WPF/Strings/Strings.DE.xaml b/WaveDudeNext.WPF/Strings/Strings.DE.xaml
index c7dc351..d6da445 100644
--- a/WaveDudeNext.WPF/Strings/Strings.DE.xaml
+++ b/WaveDudeNext.WPF/Strings/Strings.DE.xaml
@@ -404,7 +404,9 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<s:String x:Key="Label.Scene.Height">Höhe</s:String>
<s:String x:Key="Hint.Scene.Height">Höhe einer leeren Leinwand in Pixeln.</s:String>
<s:String x:Key="Label.Scene.DampingEdge">Dämpfungsrand</s:String>
- <s:String x:Key="Hint.Scene.DampingEdge">Dicke des absorbierenden Rahmens um die Leinwand in Pixeln. 0 schaltet ihn ab.</s:String>
+ <s:String x:Key="Hint.Scene.DampingEdge">Dicke des absorbierenden Rahmens in Pixeln: positiv innerhalb der Leinwand, wo er als dunkler Rand sichtbar ist; negativ außerhalb, simuliert, aber nie gezeigt. 0 schaltet ihn ab.</s:String>
+ <s:String x:Key="Label.Scene.Edges">Ränder</s:String>
+ <s:String x:Key="Hint.Scene.Edges">Offen lässt eine Welle das Gitter verlassen, als läge die Leinwand im freien Raum; Reflektierend ist eine harte Wand wie in Wave Dude 2D.</s:String>
<s:String x:Key="Label.Scene.RefractiveIndex">Brechungsindex</s:String>
<s:String x:Key="Hint.Scene.RefractiveIndex">Brechungsindex einer leeren Leinwand, 1,0 bis 2,55. Die Wellengeschwindigkeit beträgt 1/n Zellen pro Schritt.</s:String>
<s:String x:Key="Label.Scene.ImageSources">Bildquellen</s:String>
@@ -500,6 +502,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<s:String x:Key="Enum.ProbeScaleMode.Full">Ganzer Lauf</s:String>
<s:String x:Key="Enum.SceneMode.Canvas">Leinwand</s:String>
<s:String x:Key="Enum.SceneMode.Image">Bild</s:String>
+ <s:String x:Key="Enum.EdgeMode.Open">Offen</s:String>
+ <s:String x:Key="Enum.EdgeMode.Reflective">Reflektierend</s:String>
<s:String x:Key="Enum.SourceMode.Continuous">Durchgehend</s:String>
<s:String x:Key="Enum.SourceMode.Pulsed">Gepulst</s:String>
<s:String x:Key="Enum.PulseShape.Gaussian">Gaußsch</s:String>
diff --git a/WaveDudeNext.WPF/Strings/Strings.EN.xaml b/WaveDudeNext.WPF/Strings/Strings.EN.xaml
index 5aa348e..c3fdd6c 100644
--- a/WaveDudeNext.WPF/Strings/Strings.EN.xaml
+++ b/WaveDudeNext.WPF/Strings/Strings.EN.xaml
@@ -406,7 +406,9 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<s:String x:Key="Label.Scene.Height">Height</s:String>
<s:String x:Key="Hint.Scene.Height">Height of a blank canvas in pixels.</s:String>
<s:String x:Key="Label.Scene.DampingEdge">Damping edge</s:String>
- <s:String x:Key="Hint.Scene.DampingEdge">Thickness in pixels of the absorbing frame around the canvas. 0 turns it off.</s:String>
+ <s:String x:Key="Hint.Scene.DampingEdge">Thickness in pixels of the absorbing frame: positive inside the canvas, where it shows as a dark margin; negative outside it, simulated but never shown. 0 turns it off.</s:String>
+ <s:String x:Key="Label.Scene.Edges">Edges</s:String>
+ <s:String x:Key="Hint.Scene.Edges">Open lets a wave leave the grid, as if the canvas sat in open space; Reflective is a hard wall, as in Wave Dude 2D.</s:String>
<s:String x:Key="Label.Scene.RefractiveIndex">Refractive index</s:String>
<s:String x:Key="Hint.Scene.RefractiveIndex">Refractive index of a blank canvas, 1.0 to 2.55. The wave speed is 1/n cells per step.</s:String>
<s:String x:Key="Label.Scene.ImageSources">Image sources</s:String>
@@ -502,6 +504,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<s:String x:Key="Enum.ProbeScaleMode.Full">Full</s:String>
<s:String x:Key="Enum.SceneMode.Canvas">Canvas</s:String>
<s:String x:Key="Enum.SceneMode.Image">Image</s:String>
+ <s:String x:Key="Enum.EdgeMode.Open">Open</s:String>
+ <s:String x:Key="Enum.EdgeMode.Reflective">Reflective</s:String>
<s:String x:Key="Enum.SourceMode.Continuous">Continuous</s:String>
<s:String x:Key="Enum.SourceMode.Pulsed">Pulsed</s:String>
<s:String x:Key="Enum.PulseShape.Gaussian">Gaussian</s:String>
diff --git a/WaveDudeNext.WPF/Strings/Strings.FR.xaml b/WaveDudeNext.WPF/Strings/Strings.FR.xaml
index 413601f..22f447a 100644
--- a/WaveDudeNext.WPF/Strings/Strings.FR.xaml
+++ b/WaveDudeNext.WPF/Strings/Strings.FR.xaml
@@ -404,7 +404,9 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<s:String x:Key="Label.Scene.Height">Hauteur</s:String>
<s:String x:Key="Hint.Scene.Height">Hauteur d'une toile vierge en pixels.</s:String>
<s:String x:Key="Label.Scene.DampingEdge">Bord amortissant</s:String>
- <s:String x:Key="Hint.Scene.DampingEdge">Épaisseur en pixels du cadre absorbant autour de la toile. 0 le désactive.</s:String>
+ <s:String x:Key="Hint.Scene.DampingEdge">Épaisseur en pixels du cadre absorbant : positive à l'intérieur de la toile, où il apparaît comme une marge sombre ; négative à l'extérieur, simulée mais jamais affichée. 0 le désactive.</s:String>
+ <s:String x:Key="Label.Scene.Edges">Bords</s:String>
+ <s:String x:Key="Hint.Scene.Edges">Ouvert laisse l'onde quitter la grille, comme si la toile était dans l'espace libre ; Réfléchissant est un mur dur, comme dans Wave Dude 2D.</s:String>
<s:String x:Key="Label.Scene.RefractiveIndex">Indice de réfraction</s:String>
<s:String x:Key="Hint.Scene.RefractiveIndex">Indice de réfraction d'une toile vierge, 1,0 à 2,55. La vitesse d'onde est de 1/n cellules par pas.</s:String>
<s:String x:Key="Label.Scene.ImageSources">Sources de l'image</s:String>
@@ -500,6 +502,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<s:String x:Key="Enum.ProbeScaleMode.Full">Toute l'exécution</s:String>
<s:String x:Key="Enum.SceneMode.Canvas">Toile</s:String>
<s:String x:Key="Enum.SceneMode.Image">Image</s:String>
+ <s:String x:Key="Enum.EdgeMode.Open">Ouvert</s:String>
+ <s:String x:Key="Enum.EdgeMode.Reflective">Réfléchissant</s:String>
<s:String x:Key="Enum.SourceMode.Continuous">Continu</s:String>
<s:String x:Key="Enum.SourceMode.Pulsed">Pulsé</s:String>
<s:String x:Key="Enum.PulseShape.Gaussian">Gaussienne</s:String>
diff --git a/WaveDudeNext.WPF/Strings/Strings.NL.xaml b/WaveDudeNext.WPF/Strings/Strings.NL.xaml
index a7e2ea7..1a946fb 100644
--- a/WaveDudeNext.WPF/Strings/Strings.NL.xaml
+++ b/WaveDudeNext.WPF/Strings/Strings.NL.xaml
@@ -404,7 +404,9 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<s:String x:Key="Label.Scene.Height">Hoogte</s:String>
<s:String x:Key="Hint.Scene.Height">Hoogte van een leeg canvas in pixels.</s:String>
<s:String x:Key="Label.Scene.DampingEdge">Dempingsrand</s:String>
- <s:String x:Key="Hint.Scene.DampingEdge">Dikte in pixels van de absorberende rand rond het canvas. 0 schakelt hem uit.</s:String>
+ <s:String x:Key="Hint.Scene.DampingEdge">Dikte in pixels van de absorberende rand: positief binnen het canvas, waar hij als donkere marge zichtbaar is; negatief erbuiten, gesimuleerd maar nooit getoond. 0 schakelt hem uit.</s:String>
+ <s:String x:Key="Label.Scene.Edges">Randen</s:String>
+ <s:String x:Key="Hint.Scene.Edges">Open laat een golf het raster verlaten, alsof het canvas in de vrije ruimte ligt; Reflecterend is een harde wand, zoals in Wave Dude 2D.</s:String>
<s:String x:Key="Label.Scene.RefractiveIndex">Brekingsindex</s:String>
<s:String x:Key="Hint.Scene.RefractiveIndex">Brekingsindex van een leeg canvas, 1,0 tot 2,55. De golfsnelheid is 1/n cellen per stap.</s:String>
<s:String x:Key="Label.Scene.ImageSources">Afbeeldingsbronnen</s:String>
@@ -500,6 +502,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<s:String x:Key="Enum.ProbeScaleMode.Full">Hele run</s:String>
<s:String x:Key="Enum.SceneMode.Canvas">Canvas</s:String>
<s:String x:Key="Enum.SceneMode.Image">Afbeelding</s:String>
+ <s:String x:Key="Enum.EdgeMode.Open">Open</s:String>
+ <s:String x:Key="Enum.EdgeMode.Reflective">Reflecterend</s:String>
<s:String x:Key="Enum.SourceMode.Continuous">Continu</s:String>
<s:String x:Key="Enum.SourceMode.Pulsed">Gepulst</s:String>
<s:String x:Key="Enum.PulseShape.Gaussian">Gaussisch</s:String>
diff --git a/WaveDudeNext.WPF/Views/SceneView.xaml b/WaveDudeNext.WPF/Views/SceneView.xaml
index 0c8cf54..8adffa0 100644
--- a/WaveDudeNext.WPF/Views/SceneView.xaml
+++ b/WaveDudeNext.WPF/Views/SceneView.xaml
@@ -76,8 +76,12 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Scene.Height}" />
<controls:NumberBox Style="{StaticResource CanvasOnly}" Text="{Binding Height}" Minimum="8" Maximum="16384" ToolTip="{meta:Hint model:Scene.Height}" />
+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Scene.Edges}" />
+ <ComboBox Style="{StaticResource EnumComboBox}" ItemsSource="{meta:EnumValues model:EdgeMode}"
+ SelectedItem="{Binding Edges}" ToolTip="{meta:Hint model:Scene.Edges}" AutomationProperties.AutomationId="SceneEdges" />
+
<TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Scene.DampingEdge}" />
- <controls:NumberBox Text="{Binding DampingEdge}" Minimum="0" Maximum="8192" ToolTip="{meta:Hint model:Scene.DampingEdge}" />
+ <controls:NumberBox Text="{Binding DampingEdge}" Minimum="-8192" Maximum="8192" ToolTip="{meta:Hint model:Scene.DampingEdge}" />
<TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Scene.RefractiveIndex}" />
<controls:NumberBox Text="{Binding RefractiveIndex}" Minimum="1" Maximum="2.55" Increment="0.01" ToolTip="{meta:Hint model:Scene.RefractiveIndex}" />
diff --git a/WaveDudeNext/Engine/GpuWaveSimulator.cs b/WaveDudeNext/Engine/GpuWaveSimulator.cs
index 03c8cd6..3fa2ee1 100644
--- a/WaveDudeNext/Engine/GpuWaveSimulator.cs
+++ b/WaveDudeNext/Engine/GpuWaveSimulator.cs
@@ -135,6 +135,10 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
_device = device;
_width = scene.Width;
_height = scene.Height;
+ _rim = scene.Rim;
+ _canvasWidth = scene.CanvasWidth;
+ _canvasHeight = scene.CanvasHeight;
+ _openEdges = scene.OpenEdges;
_stride = _width + 2;
_cells = _stride * (_height + 2);
_track = options.TrackIntensity;
@@ -170,7 +174,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
{
foreach (Emitter source in emitters)
{
- if (source.X >= 0 && source.X < _width && source.Y >= 0 && source.Y < _height)
+ if (source.X >= 0 && source.X < _canvasWidth && source.Y >= 0 && source.Y < _canvasHeight)
{
sourcesInScene.Add(source);
}
@@ -218,7 +222,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
public void CaptureFrame(FrameSnapshot snapshot, bool needIntensity)
{
FrameShape shape = snapshot.Shape;
- if (shape.CanvasWidth != _width || shape.CanvasHeight != _height)
+ if (shape.CanvasWidth != _canvasWidth || shape.CanvasHeight != _canvasHeight)
{
throw new ArgumentException("The snapshot's canvas does not match the engine's size.", nameof(snapshot));
}
@@ -230,16 +234,19 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
{
// lazily: most engines never capture (the harness, the probes-only paths). The staging planes have room
// for any shape: a plane is at most the whole canvas as halves
- _stagingField = CreateBuffer((long)_width * _height * 2, _scene);
- _stagingIntensity = _track ? CreateBuffer((long)_width * _height * 2, _scene) : IntPtr.Zero;
+ _stagingField = CreateBuffer((long)_canvasWidth * _canvasHeight * 2, _scene);
+ _stagingIntensity = _track ? CreateBuffer((long)_canvasWidth * _canvasHeight * 2, _scene) : IntPtr.Zero;
_captureHalfKernel = CreateKernel(_scene, _scene.Program, "capture_half");
_captureIndexKernel = CreateKernel(_scene, _scene.Program, "capture_index");
foreach (IntPtr kernel in new[] { _captureHalfKernel, _captureIndexKernel })
{
- SetInt(kernel, 2U, _width);
- SetInt(kernel, 3U, _height);
+ // the canvas, which the captures cover, and where it starts in the grid
+ SetInt(kernel, 2U, _canvasWidth);
+ SetInt(kernel, 3U, _canvasHeight);
SetInt(kernel, 4U, _stride);
}
+ SetInt(_captureHalfKernel, 8U, _rim);
+ SetInt(_captureIndexKernel, 10U, _rim);
}
if (_captureShape == null || _captureShape.Divisor != shape.Divisor || !_captureShape.SameLayoutAs(shape))
{
@@ -414,7 +421,20 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
SetMem(step, 11U, intensityStage1Buffer);
SetMem(step, 12U, _intensityOutBuffer);
SetFloat(step, 13U, intensityScale);
+ if (_openEdges)
+ {
+ // the ring after the step, reading the field the step read and writing the one it wrote
+ IntPtr edges = _edgeKernel[k] = CreateKernel(_scene, "open_edges");
+ SetMem(edges, 0U, _field[k]);
+ SetMem(edges, 1U, _field[1 - k]);
+ SetMem(edges, 2U, c2Buffer);
+ SetInt(edges, 3U, _width);
+ SetInt(edges, 4U, _height);
+ SetInt(edges, 5U, _stride);
+ SetFloat(edges, 6U, c2Mult);
+ }
}
+ _edgeGrid1D = [new IntPtr(_width + 2 + _height)];
if (_sourceCount > 0)
{
IntPtr indexBuffer = CreateBuffer(indices, _scene);
@@ -451,7 +471,7 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
for (int i = 0; i < n; i++)
{
Emitter source = objectSources[i];
- index[i] = (source.Y + 1) * _stride + source.X + 1;
+ index[i] = (source.Y + 1 + _rim) * _stride + source.X + 1 + _rim;
omega[i] = (float)(source.Level / 255.0 * 0.5 * _sourceFrequencyScale);
amplitude[i] = (float)source.Amplitude;
phase[i] = (float)source.PhaseRadians;
@@ -726,24 +746,24 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
// right and bottom edges, averaged into one sample, stored as a half or as the palette index the renderer
// would compute at the given brightness; so a frame crosses the bus at half the size or less and the host
// converts nothing. vstore_half is core OpenCL C; only half arithmetic would need cl_khr_fp16.
- source.AppendLine("float capture_sample(__global const float* src, const int w, const int h, const int stride, const int div, const int x, const int y)");
+ source.AppendLine("float capture_sample(__global const float* src, const int w, const int h, const int stride, const int div, const int rim, const int x, const int y)");
source.AppendLine("{");
- source.AppendLine(" if (div == 1) return src[(y + 1) * stride + x + 1];");
+ source.AppendLine(" if (div == 1) return src[(y + 1 + rim) * stride + x + 1 + rim];");
source.AppendLine(" int x0 = x * div, y0 = y * div;");
source.AppendLine(" int x1 = min(w, x0 + div), y1 = min(h, y0 + div);");
source.AppendLine(" float sum = 0.0f;");
source.AppendLine(" for (int cy = y0; cy < y1; cy++)");
source.AppendLine(" for (int cx = x0; cx < x1; cx++)");
- source.AppendLine(" sum += src[(cy + 1) * stride + cx + 1];");
+ source.AppendLine(" sum += src[(cy + 1 + rim) * stride + cx + 1 + rim];");
source.AppendLine(" return sum / (float)((y1 - y0) * (x1 - x0));");
source.AppendLine("}");
source.AppendLine();
- source.AppendLine("__kernel void capture_half(__global const float* src, __global half* dst, const int w, const int h, const int stride, const int div, const int fw, const int fh)");
+ source.AppendLine("__kernel void capture_half(__global const float* src, __global half* dst, const int w, const int h, const int stride, const int div, const int fw, const int fh, const int rim)");
source.AppendLine("{");
source.AppendLine(" int x = get_global_id(0);");
source.AppendLine(" int y = get_global_id(1);");
source.AppendLine(" if (x >= fw || y >= fh) return;");
- source.AppendLine(" vstore_half(capture_sample(src, w, h, stride, div, x, y), y * fw + x, dst);");
+ source.AppendLine(" vstore_half(capture_sample(src, w, h, stride, div, rim, x, y), y * fw + x, dst);");
source.AppendLine("}");
source.AppendLine();
// the index mapping of ColorLut.FieldIndex / IntensityIndex: a NaN field gives the centre, a NaN or
@@ -770,12 +790,12 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
source.AppendLine("}");
source.AppendLine();
source.AppendLine("#pragma OPENCL FP_CONTRACT OFF");
- source.AppendLine("__kernel void capture_index(__global const float* src, __global uchar* dst, const int w, const int h, const int stride, const int div, const int fw, const int fh, const float brightness, const int intensity)");
+ source.AppendLine("__kernel void capture_index(__global const float* src, __global uchar* dst, const int w, const int h, const int stride, const int div, const int fw, const int fh, const float brightness, const int intensity, const int rim)");
source.AppendLine("{");
source.AppendLine(" int x = get_global_id(0);");
source.AppendLine(" int y = get_global_id(1);");
source.AppendLine(" if (x >= fw || y >= fh) return;");
- source.AppendLine(" float v = round_to_half(capture_sample(src, w, h, stride, div, x, y));");
+ source.AppendLine(" float v = round_to_half(capture_sample(src, w, h, stride, div, rim, x, y));");
source.AppendLine(" int index;");
source.AppendLine(" if (intensity)");
source.AppendLine(" index = v > 0.0f ? (int)(fmin(sqrt(v) * brightness, 1.0f) * 254.0f) : 0;");
@@ -785,6 +805,32 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
source.AppendLine(" }");
source.AppendLine(" dst[y * fw + x] = (uchar)index;");
source.AppendLine("}");
+ source.AppendLine();
+ // open_edges: Mur's first-order absorbing condition on the ring, WaveSimulator.ApplyOpenEdges cell for cell and
+ // operation for operation (no contraction, see above): one work item per column of the top and bottom rows
+ // (corners take their diagonal neighbour), then one per row of the left and right columns
+ source.AppendLine("void absorb(__global const float* u, __global float* up, __global const float* c2, const float c2Scale, const int ring, const int inner)");
+ source.AppendLine("{");
+ source.AppendLine(" float s = sqrt(c2[inner] * c2Scale) * " + EdgeSpeedFactorLiteral + ";");
+ source.AppendLine(" float k = (s - 1.0f) / (s + 1.0f);");
+ source.AppendLine(" up[ring] = u[inner] + k * (up[inner] - u[ring]);");
+ source.AppendLine("}");
+ source.AppendLine();
+ source.AppendLine("__kernel void open_edges(__global const float* u, __global float* up, __global const float* c2, const int w, const int h, const int stride, const float c2Scale)");
+ source.AppendLine("{");
+ source.AppendLine(" int id = get_global_id(0);");
+ source.AppendLine(" if (id < w + 2) {");
+ source.AppendLine(" int x = id;");
+ source.AppendLine(" int ix = clamp(x, 1, w);");
+ source.AppendLine(" absorb(u, up, c2, c2Scale, x, stride + ix);");
+ source.AppendLine(" absorb(u, up, c2, c2Scale, (h + 1) * stride + x, h * stride + ix);");
+ source.AppendLine(" } else {");
+ source.AppendLine(" int y = id - (w + 2) + 1;");
+ source.AppendLine(" if (y > h) return;");
+ source.AppendLine(" absorb(u, up, c2, c2Scale, y * stride, y * stride + 1);");
+ source.AppendLine(" absorb(u, up, c2, c2Scale, y * stride + w + 1, y * stride + w);");
+ source.AppendLine(" }");
+ source.AppendLine("}");
return source.ToString();
}
@@ -892,10 +938,13 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
public GpuDeviceInfo Device => _device;
/// <summary>Scene width in cells (canvas pixels), excluding the padding.</summary>
- public int Width => _width;
+ public int Width => _canvasWidth;
+
+ /// <inheritdoc/>
+ public int Rim => _rim;
/// <summary>Scene height in cells (canvas pixels), excluding the padding.</summary>
- public int Height => _height;
+ public int Height => _canvasHeight;
/// <summary>Row pitch of the padded buffers: <see cref="Width"/> + 2.</summary>
public int Stride => _stride;
@@ -942,6 +991,10 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
SetInt(_stepKernel[current], 8U, subStep == _subSteps && _track ? 1 : 0);
}
Enqueue(_stepKernel[current], _grid2D, "step");
+ if (_openEdges)
+ {
+ Enqueue(_edgeKernel[current], _edgeGrid1D, "edges");
+ }
current = 1 - current;
}
// the buffer that received the new values is now the current field
@@ -1442,6 +1495,15 @@ public sealed class GpuWaveSimulator : IWaveEngine, IDisposable
/// <summary>The device the context lives on; needed again to build the probe program.</summary>
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
private readonly GpuDeviceInfo _device;
+ private readonly int _rim;
+ private readonly int _canvasWidth;
+ private readonly int _canvasHeight;
+ private readonly bool _openEdges;
+ private readonly IntPtr[] _edgeKernel = new IntPtr[2];
+ private IntPtr[] _edgeGrid1D = [new IntPtr(1)];
+
+ /// <summary><see cref="WaveSimulator.EdgeSpeedFactor"/> as the kernel source spells it, so both engines use the same float.</summary>
+ private static readonly string EdgeSpeedFactorLiteral = WaveSimulator.EdgeSpeedFactor.ToString("R", System.Globalization.CultureInfo.InvariantCulture) + "f";
/// <summary>Scene width in cells (canvas pixels), without padding.</summary>
private readonly int _width;
diff --git a/WaveDudeNext/Engine/IWaveEngine.cs b/WaveDudeNext/Engine/IWaveEngine.cs
index 7a7594f..f7cfae2 100644
--- a/WaveDudeNext/Engine/IWaveEngine.cs
+++ b/WaveDudeNext/Engine/IWaveEngine.cs
@@ -22,7 +22,8 @@ namespace WaveDudeNext.Engine;
/// <summary>
/// A wave-field solver (CPU <see cref="WaveSimulator"/> or OpenCL <see cref="GpuWaveSimulator"/>), created by
/// <see cref="WaveEngineFactory"/> and driven by the run on its worker task. 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.
+/// are padded by one cell on each side of the grid, and the grid may carry a rim of <see cref="Rim"/> cells around the
+/// canvas (<see cref="SceneData.Rim"/>), so canvas row y starts at index (y + 1 + Rim) * Stride + 1 + Rim.
/// Exactly one thread drives an engine at a time and nothing else reads it; the engines have no internal
/// synchronisation and no thread affinity. Implementations that own native resources are <see cref="IDisposable"/>;
/// the interface deliberately is not, the driver disposes through <c>(engine as IDisposable)?.Dispose()</c>.
@@ -38,11 +39,14 @@ public interface IWaveEngine
/// <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. Pixel (x, y) is at (y + 1) * Stride + x + 1.</summary>
+ /// <summary>Row pitch of <see cref="FieldData"/> and <see cref="IntensityData"/>: <see cref="Width"/> + 2 + 2 × <see cref="Rim"/>. Canvas pixel (x, y) is at (y + 1 + Rim) * Stride + x + 1 + Rim.</summary>
int Stride { get; }
+ /// <summary>Cells simulated beyond each side of the canvas (a damping edge outside it); 0 when the grid is the canvas.</summary>
+ int Rim { get; }
+
/// <summary>
- /// The field of the last completed step, <see cref="Stride"/> * (<see cref="Height"/> + 2) floats. Valid for
+ /// The field of the last completed step, <see cref="Stride"/> * (<see cref="Height"/> + 2 + 2 × <see cref="Rim"/>) floats. Valid for
/// reading after <see cref="PrepareFrame"/>(true, ...); 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.
/// Do not change.
diff --git a/WaveDudeNext/Engine/SceneData.cs b/WaveDudeNext/Engine/SceneData.cs
index 318d461..579ae90 100644
--- a/WaveDudeNext/Engine/SceneData.cs
+++ b/WaveDudeNext/Engine/SceneData.cs
@@ -32,7 +32,11 @@ namespace WaveDudeNext.Engine;
/// Created by the run on its worker from the decoded scene pixels (<see cref="FromBgra"/>) 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, so any thread may read them.
+/// not modified after construction, so any thread may read them. The grid may be larger than the canvas: a
+/// negative damping edge puts the absorbing band in a rim of <see cref="Rim"/> cells outside the canvas, which the
+/// engines simulate and never show (2026-10-19, the user's request: waves leave the picture, no visible margin);
+/// the canvas then starts at (<see cref="Rim"/>, <see cref="Rim"/>) of the grid, the rim continues the canvas's
+/// edge cells, and <see cref="OpenEdges"/> says whether the ring beyond the grid absorbs or reflects.
/// </summary>
public sealed class SceneData
{
@@ -43,10 +47,12 @@ public sealed class SceneData
/// </summary>
public const double MirrorRefractiveIndex = 1000.0;
- private SceneData(int w, int h, float[] c2, float[] d, int[] srcX, int[] srcY, byte[] srcLevel)
+ private SceneData(int w, int h, int rim, bool openEdges, float[] c2, float[] d, int[] srcX, int[] srcY, byte[] srcLevel)
{
Width = w;
Height = h;
+ Rim = rim;
+ OpenEdges = openEdges;
C2 = c2;
D = d;
SourceX = srcX;
@@ -54,6 +60,18 @@ public sealed class SceneData
SourceLevel = srcLevel;
}
+ /// <summary>Cells of the grid beyond each side of the canvas (a damping edge outside the canvas); 0 when the grid is the canvas.</summary>
+ public int Rim { get; }
+
+ /// <summary>Whether the ring beyond the grid lets a wave leave (Mur's first-order condition) rather than reflecting it.</summary>
+ public bool OpenEdges { get; }
+
+ /// <summary>Width of the canvas in cells: <see cref="Width"/> less the rim on both sides.</summary>
+ public int CanvasWidth => Width - 2 * Rim;
+
+ /// <summary>Height of the canvas in cells.</summary>
+ public int CanvasHeight => Height - 2 * Rim;
+
/// <summary>Number of image-defined source pixels (length of <see cref="SourceX"/>, <see cref="SourceY"/> and <see cref="SourceLevel"/>).</summary>
public int SourceCount => SourceX.Length;
@@ -68,8 +86,9 @@ public sealed class SceneData
/// <param name="height">Canvas height in pixels.</param>
/// <param name="strideBytes">Bytes per row (at least 4 × <paramref name="width"/>).</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 FromBgra(ReadOnlySpan<byte> bgra, int width, int height, int strideBytes, bool useSources, int dampingEdge)
+ /// <param name="dampingEdge">Thickness of the absorbing border in pixels: positive inside the canvas, negative outside it (the rim), 0 for none.</param>
+ /// <param name="openEdges">Whether the ring beyond the grid absorbs a wave rather than reflecting it.</param>
+ public static SceneData FromBgra(ReadOnlySpan<byte> bgra, int width, int height, int strideBytes, bool useSources, int dampingEdge, bool openEdges = false)
{
float[] c2 = new float[width * height];
float[] d = new float[width * height];
@@ -98,8 +117,51 @@ public sealed class SceneData
}
}
}
- ApplyBorder(d, width, height, dampingEdge);
- return new SceneData(width, height, c2, d, sourceX.ToArray(), sourceY.ToArray(), sourceLevel.ToArray());
+ return WithRim(width, height, dampingEdge, openEdges, c2, d, sourceX.ToArray(), sourceY.ToArray(), sourceLevel.ToArray());
+ }
+
+ /// <summary>
+ /// The scene as the engines take it: for a damping edge inside the canvas the canvas itself with the band applied; for one
+ /// outside it a grid grown by that many cells on each side, the rim continuing the canvas's edge cells, with the band in
+ /// the rim, and the sources moved into grid coordinates.
+ /// </summary>
+ private static SceneData WithRim(int width, int height, int dampingEdge, bool openEdges, float[] c2, float[] d, int[] sourceX, int[] sourceY, byte[] sourceLevel)
+ {
+ int rim = Math.Max(0, -dampingEdge);
+ if (rim == 0)
+ {
+ ApplyBorder(d, width, height, dampingEdge);
+ return new SceneData(width, height, 0, openEdges, c2, d, sourceX, sourceY, sourceLevel);
+ }
+ int gridWidth = width + 2 * rim;
+ int gridHeight = height + 2 * rim;
+ float[] gridC2 = Grow(c2, width, height, rim);
+ float[] gridD = Grow(d, width, height, rim);
+ ApplyRim(gridD, gridWidth, gridHeight, rim);
+ for (int i = 0; i < sourceX.Length; i++)
+ {
+ sourceX[i] += rim;
+ sourceY[i] += rim;
+ }
+ return new SceneData(gridWidth, gridHeight, rim, openEdges, gridC2, gridD, sourceX, sourceY, sourceLevel);
+ }
+
+ /// <summary>A <paramref name="w"/> × <paramref name="h"/> array embedded in one grown by <paramref name="rim"/> cells on each side, the rim repeating the nearest edge cell.</summary>
+ private static float[] Grow(float[] values, int w, int h, int rim)
+ {
+ int gw = w + 2 * rim;
+ int gh = h + 2 * rim;
+ var grid = new float[gw * gh];
+ for (int gy = 0; gy < gh; gy++)
+ {
+ int y = Math.Clamp(gy - rim, 0, h - 1);
+ for (int gx = 0; gx < gw; gx++)
+ {
+ int x = Math.Clamp(gx - rim, 0, w - 1);
+ grid[gy * gw + gx] = values[y * w + x];
+ }
+ }
+ return grid;
}
/// <summary>
@@ -109,17 +171,17 @@ public sealed class SceneData
/// </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="dampingEdge">Thickness of the absorbing border in pixels: positive inside the canvas, negative outside it (the rim), 0 for none.</param>
/// <param name="refractiveIndex">Background refractive index (1.0 by default, the same rule as a scene image's red channel: index = red / 100).</param>
- public static SceneData Empty(int w, int h, int dampingEdge, double refractiveIndex = 1.0)
+ /// <param name="openEdges">Whether the ring beyond the grid absorbs a wave rather than reflecting it.</param>
+ public static SceneData Empty(int w, int h, int dampingEdge, double refractiveIndex = 1.0, bool openEdges = false)
{
float speed = (float)(1.0 / Math.Clamp(refractiveIndex, 1.0, 10.0));
float[] c2 = new float[w * h];
float[] d = new float[w * h];
Array.Fill(c2, speed * speed);
Array.Fill(d, 1f);
- ApplyBorder(d, w, h, dampingEdge);
- return new SceneData(w, h, c2, d, [], [], []);
+ return WithRim(w, h, dampingEdge, openEdges, c2, d, [], [], []);
}
/// <summary>
@@ -147,6 +209,37 @@ public sealed class SceneData
return count;
}
+ /// <summary>
+ /// The damping of a rim outside the canvas: the loss of velocity per step rises linearly from nothing at the
+ /// canvas's edge to a tenth at the outer ring. Measured on a pulse (2026-10-19): a rim damped to a standstill, as
+ /// Jeroen's square-root band is, sent about 1 % of the pulse back, since cells whose velocity is wiped keep their
+ /// displacement and let it creep back; this mild ramp sends back 0.1 to 0.2 % at 32 cells and 0.06 % at 64, while
+ /// the open ring alone (<see cref="OpenEdges"/>) returns 0.05 to 0.09 %, so a rim is an option, not the default.
+ /// </summary>
+ /// <param name="d">Damping array of the whole grid, row-major, modified in place.</param>
+ /// <param name="w">Grid width in cells.</param>
+ /// <param name="h">Grid height in cells.</param>
+ /// <param name="rim">Cells of the rim on each side.</param>
+ internal static void ApplyRim(float[] d, int w, int h, int rim)
+ {
+ for (int i = 0; i < rim; i++)
+ {
+ // i cells from the outer ring: (rim - i) / rim of the way into the rim, a tenth of that lost per step
+ double into = (double)(rim - i) / rim;
+ float factor = (float)(1.0 - 0.1 * into);
+ 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>
/// Damping edge, as in <c>StaticDampening</c>: overwrites the damping factor in a frame of
/// <paramref name="thickness"/> pixels (capped at half the smaller side) around the edge of the
diff --git a/WaveDudeNext/Engine/WaveSimulator.cs b/WaveDudeNext/Engine/WaveSimulator.cs
index 00bab06..1c564bf 100644
--- a/WaveDudeNext/Engine/WaveSimulator.cs
+++ b/WaveDudeNext/Engine/WaveSimulator.cs
@@ -107,6 +107,10 @@ public sealed class WaveSimulator : IWaveEngine, IDisposable
_intensityScale = (float)options.IntensityScale;
_width = scene.Width;
_height = scene.Height;
+ _rim = scene.Rim;
+ _canvasWidth = scene.CanvasWidth;
+ _canvasHeight = scene.CanvasHeight;
+ _openEdges = scene.OpenEdges;
_stride = _width + 2;
int cellCount = _stride * (_height + 2);
_u = new float[cellCount];
@@ -177,10 +181,10 @@ public sealed class WaveSimulator : IWaveEngine, IDisposable
{
foreach (Emitter source in emitters)
{
- if (source.X >= 0 && source.X < _width && source.Y >= 0 && source.Y < _height)
+ if (source.X >= 0 && source.X < _canvasWidth && source.Y >= 0 && source.Y < _canvasHeight)
{
insideSources.Add(source);
- insideIndices.Add((source.Y + 1) * _stride + source.X + 1);
+ insideIndices.Add((source.Y + 1 + _rim) * _stride + source.X + 1 + _rim);
}
}
}
@@ -232,11 +236,11 @@ public sealed class WaveSimulator : IWaveEngine, IDisposable
/// </summary>
public void CaptureFrame(FrameSnapshot snapshot, bool needIntensity)
{
- if (snapshot.Shape.CanvasWidth != _width || snapshot.Shape.CanvasHeight != _height)
+ if (snapshot.Shape.CanvasWidth != _canvasWidth || snapshot.Shape.CanvasHeight != _canvasHeight)
{
throw new ArgumentException("The snapshot's canvas does not match the engine's size.", nameof(snapshot));
}
- int cells = _width * _height;
+ int cells = _canvasWidth * _canvasHeight;
snapshot.FieldFloats ??= new float[cells];
CopyInterior(_u, snapshot.FieldFloats);
snapshot.HasIntensity = needIntensity && _intensityOut != null && snapshot.IntensityBytes != null;
@@ -257,26 +261,30 @@ public sealed class WaveSimulator : IWaveEngine, IDisposable
}
snapshot.PendingConversion = false;
// the shape's shrinking and format (FrameConversion), on the awaiting thread
- FrameConversion.Convert(snapshot.FieldFloats!, 0, _width, snapshot.Shape, false, snapshot.FieldBytes);
+ FrameConversion.Convert(snapshot.FieldFloats!, 0, _canvasWidth, snapshot.Shape, false, snapshot.FieldBytes);
if (snapshot.HasIntensity)
{
- FrameConversion.Convert(snapshot.IntensityFloats!, 0, _width, snapshot.Shape, true, snapshot.IntensityBytes!);
+ FrameConversion.Convert(snapshot.IntensityFloats!, 0, _canvasWidth, snapshot.Shape, true, snapshot.IntensityBytes!);
}
}
/// <summary>The interior rows of a padded buffer into a tightly packed plane.</summary>
private void CopyInterior(float[] source, float[] target)
{
- int width = _width;
+ int width = _canvasWidth;
int stride = _stride;
- Parallel.For(0, _height, y => source.AsSpan((y + 1) * stride + 1, width).CopyTo(target.AsSpan(y * width, width)));
+ int rim = _rim;
+ Parallel.For(0, _canvasHeight, y => source.AsSpan((y + 1 + rim) * stride + 1 + rim, width).CopyTo(target.AsSpan(y * width, width)));
}
- /// <summary>Scene width in cells (canvas pixels), excluding the padding.</summary>
- public int Width => _width;
+ /// <summary>Canvas width in cells, excluding the padding and the rim.</summary>
+ public int Width => _canvasWidth;
+
+ /// <inheritdoc/>
+ public int Rim => _rim;
/// <summary>Scene height in cells (canvas pixels), excluding the padding.</summary>
- public int Height => _height;
+ public int Height => _canvasHeight;
/// <summary>Row pitch of the padded buffers: <see cref="Width"/> + 2. Pixel (x, y) is at (y + 1) * Stride + x + 1.</summary>
public int Stride => _stride;
@@ -803,11 +811,58 @@ public sealed class WaveSimulator : IWaveEngine, IDisposable
}
});
+ if (_openEdges)
+ {
+ ApplyOpenEdges(u, uPrev, c2, mult, w, h, stride);
+ }
// the array that received the new values is now the current field
_uPrev = u;
_u = uPrev;
}
+ /// <summary>
+ /// The phase speed of the 9-point stencil for a wave of c² = 1 in cells per step: a plane wave of small k sees
+ /// lap ≈ −(0.184 + 2 × 0.066) k² = −0.316 k², so the speed is √0.316 (Jeroen's c of 0.563). The cell next to the
+ /// ring always uses that stencil, so the open edge is tuned to it in both stencil modes.
+ /// </summary>
+ internal const float EdgeSpeedFactor = 0.56213877f;
+
+ /// <summary>
+ /// Mur's first-order absorbing condition on the ring outside the grid, after a sub-step (2026-10-19): each ring cell
+ /// takes what a wave travelling straight out would leave behind, u_ring' = u_in + k (u_in' − u_ring) with
+ /// k = (s − 1) / (s + 1) and s the local speed in cells per sub-step, so a head-on wave walks off the grid; an
+ /// oblique one partly returns, which the damping rim in front of the ring takes care of. A corner takes its
+ /// diagonal neighbour. The GPU kernel <c>open_edges</c> does the same operations in the same order.
+ /// </summary>
+ /// <param name="old">The field before the sub-step.</param>
+ /// <param name="next">The field after it, whose ring this writes.</param>
+ /// <param name="c2">Squared speed per cell (the padded layout).</param>
+ /// <param name="mult">The sub-step's c² scale.</param>
+ /// <param name="w">Grid width without padding.</param>
+ /// <param name="h">Grid height without padding.</param>
+ /// <param name="stride">Row pitch.</param>
+ internal static void ApplyOpenEdges(float[] old, float[] next, float[] c2, float mult, int w, int h, int stride)
+ {
+ for (int x = 0; x <= w + 1; x++)
+ {
+ int ix = Math.Clamp(x, 1, w);
+ Absorb(old, next, c2, mult, x, stride + ix);
+ Absorb(old, next, c2, mult, (h + 1) * stride + x, h * stride + ix);
+ }
+ for (int y = 1; y <= h; y++)
+ {
+ Absorb(old, next, c2, mult, y * stride, y * stride + 1);
+ Absorb(old, next, c2, mult, y * stride + w + 1, y * stride + w);
+ }
+ }
+
+ private static void Absorb(float[] old, float[] next, float[] c2, float mult, int ring, int inner)
+ {
+ float s = MathF.Sqrt(c2[inner] * mult) * EdgeSpeedFactor;
+ float k = (s - 1f) / (s + 1f);
+ next[ring] = old[inner] + k * (next[inner] - old[ring]);
+ }
+
/// <summary>Weight of the four diagonal neighbours in the 9-point Laplacian.</summary>
private const float KernelCorner = 0.066f;
@@ -884,6 +939,10 @@ public sealed class WaveSimulator : IWaveEngine, IDisposable
/// otherwise a separate array of it raised to the power 1/<see cref="_subSteps"/>.
/// </summary>
private readonly float[] _damping;
+ private readonly int _rim;
+ private readonly int _canvasWidth;
+ private readonly int _canvasHeight;
+ private readonly bool _openEdges;
/// <summary>1/<see cref="_subSteps"/>², scaling c² for the shorter sub-step (or exactly 1.0F when _subSteps = 1, a bit-for-bit no-op multiply).</summary>
private readonly float _c2Mult;
diff --git a/WaveDudeNext/Model/LegacyProject.cs b/WaveDudeNext/Model/LegacyProject.cs
index b20810e..6d35558 100644
--- a/WaveDudeNext/Model/LegacyProject.cs
+++ b/WaveDudeNext/Model/LegacyProject.cs
@@ -115,7 +115,9 @@ public static class LegacyProject
scene.Mode = Text(section, "mode", "user_defined") == "image" ? SceneMode.Image : SceneMode.Canvas;
scene.Width = Int(section, "user_width", Scene.DefaultWidth);
scene.Height = Int(section, "user_height", Scene.DefaultHeight);
- scene.DampingEdge = Bool(section, "damping_edge_enabled", false) ? Int(section, "damping_edge_size_px", Scene.DefaultDampingEdge) : 0;
+ // his program has walls, with his band in front of them when enabled (64 px when the size is missing, his default)
+ scene.Edges = EdgeMode.Reflective;
+ scene.DampingEdge = Bool(section, "damping_edge_enabled", false) ? Math.Abs(Int(section, "damping_edge_size_px", 64)) : 0;
scene.ImageSources = Bool(section, "use_sources", false);
scene.ImageSourceScale = Double(section, "image_source_scale", Scene.DefaultImageSourceScale);
scene.ObjectSources = Bool(section, "use_object_sources", false);
diff --git a/WaveDudeNext/Model/Project.cs b/WaveDudeNext/Model/Project.cs
index 96d88fc..8fd484c 100644
--- a/WaveDudeNext/Model/Project.cs
+++ b/WaveDudeNext/Model/Project.cs
@@ -35,7 +35,7 @@ namespace WaveDudeNext.Model;
public sealed class Project : ObservableObject
{
/// <summary>Format version written to new files; bump when the layout changes incompatibly.</summary>
- public const int CurrentVersion = 1;
+ public const int CurrentVersion = 2;
private int _version = CurrentVersion;
private int _seed = NewSeed();
@@ -534,6 +534,13 @@ public sealed class Project : ObservableObject
{
Logger.Warn("Project file version {Version} is newer than the supported {Supported}; unknown settings are ignored", project.Version, CurrentVersion);
}
+ if (project.Version < 2)
+ {
+ // version 1 (until 2026-10-19) knew only reflective edges; the open edges that are the default since must not
+ // reach an old file, which keeps the walls it was made with
+ project.Scene.Edges = EdgeMode.Reflective;
+ project.Version = CurrentVersion;
+ }
project.Normalize();
Logger.Debug("Loaded project: version {Version}, seed {Seed}, {Sources} sources, {Parts} parts, {Probes} probes", project.Version, project.Seed, project.Sources.Count, project.Parts.Count, project.Probes.Count);
return project;
diff --git a/WaveDudeNext/Model/Scene.cs b/WaveDudeNext/Model/Scene.cs
index a7b4438..0608a12 100644
--- a/WaveDudeNext/Model/Scene.cs
+++ b/WaveDudeNext/Model/Scene.cs
@@ -29,6 +29,15 @@ public enum SceneMode
Image,
}
+/// <summary>What the outermost cells of the grid do with a wave that reaches them (2026-10-19, the user's request).</summary>
+public enum EdgeMode
+{
+ /// <summary>The wave walks off the grid (Mur's first-order absorbing condition on the ring outside the canvas): a pulse returns well under a tenth of a percent, as good as a void.</summary>
+ Open,
+ /// <summary>A hard wall: the wave comes back in full, as in Wave Dude 2D; a damping edge in front of it softens that.</summary>
+ Reflective,
+}
+
/// <summary>
/// The simulation canvas: its origin (blank or image), the damping border and the options for
/// sources painted into the image. Positions throughout the project are canvas pixels with the
@@ -46,7 +55,7 @@ public sealed class Scene : ObservableObject
/// <summary>Largest accepted canvas width or height in pixels.</summary>
public const int MaxSize = 16384;
/// <summary>Damping frame thickness the editor proposes when the frame is switched on.</summary>
- public const int DefaultDampingEdge = 64;
+ public const int DefaultDampingEdge = 0;
/// <summary>Largest accepted <see cref="DampingEdge"/> in pixels.</summary>
public const int MaxDampingEdge = 8192;
/// <summary>Default <see cref="ImageSourceScale"/>.</summary>
@@ -65,7 +74,8 @@ public sealed class Scene : ObservableObject
private string _imagePath = "";
private int _width = DefaultWidth;
private int _height = DefaultHeight;
- private int _dampingEdge;
+ private int _dampingEdge = DefaultDampingEdge;
+ private EdgeMode _edges = EdgeMode.Open;
private double _refractiveIndex = DefaultRefractiveIndex;
private bool _imageSources;
private double _imageSourceScale = DefaultImageSourceScale;
@@ -189,18 +199,34 @@ public sealed class Scene : ObservableObject
set => SetProperty(ref _height, value);
}
- /// <summary>Thickness of the absorbing frame around the canvas in pixels; 0 turns it off.</summary>
+ /// <summary>
+ /// Thickness of the absorbing frame in pixels: positive inside the canvas, where it shows as a dark margin (Jeroen's
+ /// band), negative outside the canvas, where the engine simulates that much more and shows none of it (2026-10-19,
+ /// the user's rule for the sign); 0 turns it off.
+ /// </summary>
[XmlAttribute]
- [DefaultValue(0)]
+ [DefaultValue(DefaultDampingEdge)]
[Category("Canvas")]
[DisplayName("Damping edge")]
- [Description("Thickness in pixels of the absorbing frame around the canvas. 0 turns it off.")]
+ [Description("Thickness in pixels of the absorbing frame: positive inside the canvas, where it is visible, negative outside it, where it is not. 0 turns it off.")]
public int DampingEdge
{
get => _dampingEdge;
set => SetProperty(ref _dampingEdge, value);
}
+ /// <summary>What the edge of the grid does with a wave: lets it leave, or reflects it.</summary>
+ [XmlAttribute]
+ [DefaultValue(EdgeMode.Open)]
+ [Category("Canvas")]
+ [DisplayName("Edges")]
+ [Description("Open lets a wave leave the grid; Reflective is a hard wall, as in Wave Dude 2D.")]
+ public EdgeMode Edges
+ {
+ get => _edges;
+ set => SetProperty(ref _edges, value);
+ }
+
/// <summary>Refractive index of a blank canvas, 1.0 to 2.55; the wave speed is 1/n cells per step.</summary>
[XmlAttribute]
[DefaultValue(DefaultRefractiveIndex)]
@@ -254,7 +280,7 @@ public sealed class Scene : ObservableObject
[Browsable(false)]
public bool IsDefault =>
Mode == SceneMode.Canvas && Image.Length == 0 && ImagePath.Length == 0 && ImageData == null && Width == DefaultWidth && Height == DefaultHeight
- && DampingEdge == 0 && RefractiveIndex == DefaultRefractiveIndex && !ImageSources
+ && DampingEdge == DefaultDampingEdge && Edges == EdgeMode.Open && RefractiveIndex == DefaultRefractiveIndex && !ImageSources
&& ImageSourceScale == DefaultImageSourceScale && ObjectSources;
/// <summary>Clamps every value into its valid range.</summary>
@@ -264,7 +290,7 @@ public sealed class Scene : ObservableObject
ImagePath ??= "";
Width = Math.Clamp(Width, MinSize, MaxSize);
Height = Math.Clamp(Height, MinSize, MaxSize);
- DampingEdge = Math.Clamp(DampingEdge, 0, MaxDampingEdge);
+ DampingEdge = Math.Clamp(DampingEdge, -MaxDampingEdge, MaxDampingEdge);
RefractiveIndex = Math.Clamp(RefractiveIndex, MinRefractiveIndex, MaxRefractiveIndex);
ImageSourceScale = Math.Clamp(ImageSourceScale, 0, MaxImageSourceScale);
}
diff --git a/WaveDudeNext/Probes/ProbeSampler.cs b/WaveDudeNext/Probes/ProbeSampler.cs
index 9648103..023e05e 100644
--- a/WaveDudeNext/Probes/ProbeSampler.cs
+++ b/WaveDudeNext/Probes/ProbeSampler.cs
@@ -73,7 +73,8 @@ public sealed class ProbeSampler
/// <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(IReadOnlyList<ProbeSpec> probes, int w, int h)
+ /// <param name="rim">Cells of the engine's grid beyond each side of the canvas (<see cref="Engine.SceneData.Rim"/>); the indices are moved into the grid.</param>
+ public static ProbeSampler Build(IReadOnlyList<ProbeSpec> probes, int w, int h, int rim = 0)
{
int count = probes.Count;
int[][] pixels = new int[count][];
@@ -84,7 +85,8 @@ public sealed class ProbeSampler
double[] lengths = new double[count];
bool[] useStartAfterStep = new bool[count];
int[] startAfterStep = new int[count];
- int stride = w + 2;
+ int stride = w + 2 + 2 * rim;
+ int shift = rim * stride + rim; // the canvas starts that far into a grid with a rim (SceneData.Rim)
for (int i = 0; i < count; i++)
{
ProbeSpec probe = probes[i];
@@ -112,6 +114,13 @@ public sealed class ProbeSampler
useStartAfterStep[i] = probe.StartAfter > 0;
startAfterStep[i] = probe.StartAfter;
}
+ if (shift > 0)
+ {
+ foreach (int[] indices in pixels)
+ {
+ Shift(indices, shift);
+ }
+ }
return new ProbeSampler(pixels, isProfile, useIntensity, cumulative, integrate, lengths, useStartAfterStep, startAfterStep);
}
@@ -129,12 +138,21 @@ public sealed class ProbeSampler
return value;
}
+ /// <summary>Moves every index by <paramref name="shift"/>: the rim's offset into the grid.</summary>
+ private static void Shift(int[] indices, int shift)
+ {
+ for (int i = 0; i < indices.Length; i++)
+ {
+ indices[i] += shift;
+ }
+ }
+
/// <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>
+ /// <param name="stride">Row length of the padded grid (canvas width + 2, plus twice the rim).</param>
private static int[] LinePixels(int x0, int y0, int x1, int y1, int stride)
{
var indices = new List<int>();
diff --git a/WaveDudeNext/Runs/FrameStore.cs b/WaveDudeNext/Runs/FrameStore.cs
index 9c1b222..90bb6b0 100644
--- a/WaveDudeNext/Runs/FrameStore.cs
+++ b/WaveDudeNext/Runs/FrameStore.cs
@@ -302,20 +302,21 @@ public sealed unsafe class FrameStore : IFrameSource, IDisposable
/// <param name="frame">Index of the frame; must equal <see cref="Count"/>.</param>
/// <param name="field">Padded field buffer, <c>stride × (canvas height + 2)</c> floats.</param>
/// <param name="intensity">Padded intensity buffer, or null when the store has no intensity plane.</param>
- /// <param name="stride">Row pitch of the padded buffers (<see cref="CanvasWidth"/> + 2).</param>
+ /// <param name="stride">Row pitch of the padded buffers (<see cref="CanvasWidth"/> + 2, plus twice the rim).</param>
+ /// <param name="rim">Cells of the grid beyond each side of the canvas (<see cref="Engine.IWaveEngine.Rim"/>): the canvas starts that far into the padded rows.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="frame"/> is not the next frame or beyond <see cref="Capacity"/>.</exception>
/// <exception cref="ArgumentNullException">The store has an intensity plane but <paramref name="intensity"/> is null.</exception>
/// <exception cref="ObjectDisposedException">The store is disposed.</exception>
- public void Write(int frame, float[] field, float[]? intensity, int stride)
+ public void Write(int frame, float[] field, float[]? intensity, int stride, int rim = 0)
{
byte[] fieldPlane = _staging;
- FrameConversion.Convert(field, stride + 1, stride, Shape, false, fieldPlane);
+ FrameConversion.Convert(field, (rim + 1) * stride + rim + 1, stride, Shape, false, fieldPlane);
byte[]? intensityPlane = null;
if (Has(FrameLayer.Intensity))
{
ArgumentNullException.ThrowIfNull(intensity);
intensityPlane = _staging2 ??= new byte[Shape.PlaneBytes];
- FrameConversion.Convert(intensity, stride + 1, stride, Shape, true, intensityPlane);
+ FrameConversion.Convert(intensity, (rim + 1) * stride + rim + 1, stride, Shape, true, intensityPlane);
}
Write(frame, fieldPlane, intensityPlane);
}
diff --git a/WaveDudeNext/Runs/RunSpec.cs b/WaveDudeNext/Runs/RunSpec.cs
index 432f66e..147e48e 100644
--- a/WaveDudeNext/Runs/RunSpec.cs
+++ b/WaveDudeNext/Runs/RunSpec.cs
@@ -53,6 +53,7 @@ public sealed class RunSpec
Width = width;
Height = height;
DampingEdge = project.Scene.DampingEdge;
+ Edges = project.Scene.Edges;
RefractiveIndex = project.Scene.RefractiveIndex;
// a canvas scene with painted parts has pixels too, but no green to emit from (the parts never touch green)
ImageSources = project.Scene.Mode == SceneMode.Image && image != null && project.Scene.ImageSources;
@@ -118,6 +119,12 @@ public sealed class RunSpec
/// <summary>Thickness of the absorbing border in pixels; 0 for none.</summary>
public int DampingEdge { get; }
+ /// <summary>What the grid's edge does with a wave (<see cref="Scene.Edges"/>).</summary>
+ public EdgeMode Edges { get; }
+
+ /// <summary>Cells the engine simulates beyond each side of the canvas: a damping edge outside the canvas (a negative <see cref="DampingEdge"/>), else 0.</summary>
+ public int Rim => Math.Max(0, -DampingEdge);
+
/// <summary>Background refractive index of a blank canvas.</summary>
public double RefractiveIndex { get; }
@@ -181,7 +188,7 @@ public sealed class RunSpec
/// damping, refractive index, image sources), the same solver options and engine choice. The emitters may differ.
/// </summary>
public bool SameSceneAs(RunSpec other) =>
- Width == other.Width && Height == other.Height && ReferenceEquals(Image, other.Image) && DampingEdge == other.DampingEdge
+ Width == other.Width && Height == other.Height && ReferenceEquals(Image, other.Image) && DampingEdge == other.DampingEdge && Edges == other.Edges
&& RefractiveIndex == other.RefractiveIndex && ImageSources == other.ImageSources && Engine == other.Engine && PreferGpu == other.PreferGpu;
/// <summary>Whether the object sources are the same emitters, value for value.</summary>
@@ -189,6 +196,6 @@ public sealed class RunSpec
/// <summary>Builds the engine's scene input from the snapshot. Worker; allocates the per-pixel maps.</summary>
internal SceneData BuildScene() => Image is { } image
- ? SceneData.FromBgra(image.Bgra, image.Width, image.Height, image.StrideBytes, ImageSources, DampingEdge)
- : SceneData.Empty(Width, Height, DampingEdge, RefractiveIndex);
+ ? SceneData.FromBgra(image.Bgra, image.Width, image.Height, image.StrideBytes, ImageSources, DampingEdge, Edges == EdgeMode.Open)
+ : SceneData.Empty(Width, Height, DampingEdge, RefractiveIndex, Edges == EdgeMode.Open);
}
diff --git a/WaveDudeNext/Runs/ScratchRunner.cs b/WaveDudeNext/Runs/ScratchRunner.cs
index 29a7122..3e56c44 100644
--- a/WaveDudeNext/Runs/ScratchRunner.cs
+++ b/WaveDudeNext/Runs/ScratchRunner.cs
@@ -174,7 +174,7 @@ public sealed class ScratchRunner : IDisposable
int steps = frame * spec.VisualizeEvery + 1;
IWaveEngine engine = EngineFor(spec);
// the spec's probes, installed per request (Reset removes them; a fresh engine has none)
- ProbeSampler? sampler = spec.Probes.Length > 0 ? ProbeSampler.Build(spec.Probes, spec.Width, spec.Height) : null;
+ ProbeSampler? sampler = spec.Probes.Length > 0 ? ProbeSampler.Build(spec.Probes, spec.Width, spec.Height, spec.Rim) : null;
engine.SetProbes(sampler);
var clock = Stopwatch.StartNew();
for (int i = 0; i < steps; i++)
diff --git a/WaveDudeNext/Runs/SimulationRun.cs b/WaveDudeNext/Runs/SimulationRun.cs
index 65e3148..80c7054 100644
--- a/WaveDudeNext/Runs/SimulationRun.cs
+++ b/WaveDudeNext/Runs/SimulationRun.cs
@@ -248,7 +248,7 @@ public sealed class SimulationRun : INotifyPropertyChanged, IDisposable
{
CancellationToken token = _cancel.Token;
SceneData scene = Spec.BuildScene();
- ProbeSampler? sampler = Spec.Probes.Length > 0 ? ProbeSampler.Build(Spec.Probes, scene.Width, scene.Height) : null;
+ ProbeSampler? sampler = Spec.Probes.Length > 0 ? ProbeSampler.Build(Spec.Probes, scene.CanvasWidth, scene.CanvasHeight, scene.Rim) : null;
ProbeCollector? collector = sampler != null ? new ProbeCollector(sampler) : null;
engine = WaveEngineFactory.Create(scene, Spec.Engine, Spec.PreferGpu, Spec.Emitters, out string note);
Logger.Info("Engine: {0}", engine.Description);
diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.cs
index ecdc41c..c81f6f0 100644
--- a/_tools/library_check/Program.cs
+++ b/_tools/library_check/Program.cs
@@ -257,6 +257,7 @@ internal static class Program
CheckMirror(W, H);
CheckDecimalLevels(W, H);
CheckMovable();
+ CheckOpenEdges(W, H);
CheckFrameStore(scene);
CheckPreviewQuality(scene, W, H);
CheckRenderer();
@@ -712,6 +713,94 @@ internal static class Program
Check(probe.Anchors.SequenceEqual([(8, 7)]), "a point probe anchors at point A alone");
}
+ private static void CheckOpenEdges(int W, int H)
+ {
+ Console.WriteLine("--- open edges and the damping rim");
+ // a scene image with a green pixel: a negative damping edge grows the grid, moves the source into grid coordinates
+ // and continues the canvas's edge cells into the rim
+ var bgra = new byte[8 * 8 * 4];
+ for (int i = 0; i < 64; i++)
+ {
+ bgra[i * 4 + 2] = 100;
+ bgra[i * 4 + 3] = 255;
+ }
+ bgra[(3 * 8 + 2) * 4 + 1] = 120; // a source at (2, 3)
+ bgra[2] = 200; // index 2 at the corner (0, 0)
+ SceneData rimmed = SceneData.FromBgra(bgra, 8, 8, 32, true, -4, true);
+ Check(rimmed.Width == 16 && rimmed.Height == 16 && rimmed.Rim == 4 && rimmed.CanvasWidth == 8 && rimmed.CanvasHeight == 8 && rimmed.OpenEdges,
+ "a damping edge of -4 grows an 8x8 scene to a 16x16 grid with a rim of 4, open");
+ Check(rimmed.SourceCount == 1 && rimmed.SourceX[0] == 6 && rimmed.SourceY[0] == 7, "the image source moved into grid coordinates");
+ Check(rimmed.D[0] == 0.9f && rimmed.D[4 * 16 + 4] == 1f && rimmed.C2[0] == rimmed.C2[4 * 16 + 4] && rimmed.C2[0] == 0.25f,
+ "the rim loses a tenth per step at its outer ring, the canvas nothing, and the rim repeats the canvas's corner cell");
+ SceneData plain = SceneData.Empty(W, H, 8);
+ Check(plain.Rim == 0 && plain.Width == W && !plain.OpenEdges && plain.D[0] == 0f && plain.D[8 * W + 8] == 1f, "a positive damping edge stays inside the canvas, reflective by default");
+ // what comes back: a Gaussian pulse from the centre, its peak amplitude on the way out against the largest
+ // amplitude found in the canvas once it has had time to leave (steps 300 to 700)
+ (string Name, int Edge, bool Open)[] configs = [("reflective, no damping", 0, false), ("reflective, a 24 px band inside", 24, false), ("open, no damping", 0, true), ("open, a 32 px rim outside", -32, true)];
+ double[] back = new double[configs.Length];
+ for (int c = 0; c < configs.Length; c++)
+ {
+ SceneData scene = SceneData.Empty(W, H, configs[c].Edge, 1.0, configs[c].Open);
+ var pulse = new List<Emitter> { Make(W / 2, H / 2, 120, 1.0) with { Mode = SourceMode.Pulsed, PulseShape = PulseShape.Gaussian, OnWidthCycles = 3, OffWidthCycles = 100000, OffWidthBase = 100000 } };
+ var cpu = new WaveSimulator(scene, new EngineOptions(1.0, 1.0, false, false, 10.0, 1.0), pulse);
+ double peak = 0, returned = 0;
+ for (int step = 1; step <= 700; step++)
+ {
+ cpu.AdvanceOneStep();
+ if (step % 5 == 0)
+ {
+ double amplitude = CanvasPeak(cpu);
+ if (step <= 150)
+ {
+ peak = Math.Max(peak, amplitude);
+ }
+ else if (step >= 300)
+ {
+ returned = Math.Max(returned, amplitude);
+ }
+ }
+ }
+ back[c] = returned / peak;
+ Console.WriteLine($" {configs[c].Name}: {back[c] * 100:0.000} % of the pulse's amplitude is back in the canvas between steps 300 and 700");
+ }
+ Check(back[2] < 0.002, "open edges alone: under 0.2 % of the amplitude comes back");
+ Check(back[3] < 0.005, "open edges with a 32 px rim outside: under half a percent comes back");
+ Check(back[0] > 0.5, "a reflective box without damping sends it all back");
+ // CPU = GPU with the rim and the open edge
+ SceneData openScene = SceneData.Empty(W, H, -32, 1.0, true);
+ var wave = new List<Emitter> { Make(W / 2, H / 2, 120, 1.0) };
+ float[] cpuField = RunCpu(openScene, wave, 300);
+ Check(cpuField.Length == (W + 66) * (H + 66), "the engine's buffer holds the grid with its rim and padding");
+ GpuWaveSimulator? gpu = GpuWaveSimulator.TryCreate(openScene, new EngineOptions(1.0, 1.0, false, false, 10.0, 1.0), wave, out string problems);
+ if (gpu == null)
+ {
+ Console.WriteLine(" skip GPU: " + problems);
+ return;
+ }
+ using (gpu)
+ {
+ Run(gpu, 300);
+ float diff = MaxDiff(cpuField, gpu.FieldData);
+ Check(gpu.Rim == 32 && gpu.Width == W && gpu.Stride == W + 66 && diff < 1e-3f * Math.Max(1f, MaxAbs(cpuField)), "GPU agrees with the CPU on the rim and the open edge (max diff " + diff + ")");
+ }
+ }
+
+ /// <summary>Max |u| over the canvas cells of an engine's field (the rim and padding left out).</summary>
+ private static double CanvasPeak(IWaveEngine engine)
+ {
+ float[] u = engine.FieldData;
+ double peak = 0;
+ for (int y = 0; y < engine.Height; y++)
+ {
+ int row = (y + 1 + engine.Rim) * engine.Stride + 1 + engine.Rim;
+ for (int x = 0; x < engine.Width; x++)
+ {
+ peak = Math.Max(peak, Math.Abs(u[row + x]));
+ }
+ }
+ return peak;
+ }
+
/// <summary>Max |u| over the canvas columns <paramref name="x0"/>..<paramref name="x1"/> of a padded field.</summary>
private static float MaxAbsColumns(float[] padded, int W, int H, int x0, int x1)
{
@@ -1228,7 +1317,7 @@ internal static class Program
"a run in that quality completes with 50 stored frames of 32x24 index bytes covering all 100 timeline frames");
// stored frame 49 is timeline frame 98, step 196: an engine stepped 197 times and captured in the shape gives the same bytes,
// and timeline frame 99 (not stored) reads the same stored frame
- IWaveEngine reference = WaveEngineFactory.Create(SceneData.Empty(W, H, spec.DampingEdge, spec.RefractiveIndex), spec.Engine, false, spec.Emitters, out _);
+ IWaveEngine reference = WaveEngineFactory.Create(SceneData.Empty(W, H, spec.DampingEdge, spec.RefractiveIndex, spec.Edges == EdgeMode.Open), spec.Engine, false, spec.Emitters, out _);
Run(reference, 197);
var expected = new FrameSnapshot(spec.Shape, spec.TrackIntensity);
reference.CaptureFrame(expected, spec.TrackIntensity);