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#
The painter settles runs of pixels and a fibre runs its chords once; the glowing edges and the CPU stencil in lanes
Alexander Graefac210ef36da5
diff --git a/CLAUDE.md b/CLAUDE.mdindex db88887..3ba4ef5 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -182,7 +182,12 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDAmore rebuilds), the tables holding the CPU's floats, so the arithmetic is unchanged; and the intensity's blend of itstwo stages is made where it is read (the captures, the probes, `PrepareFrame`), not written every step: 69 bytes acell, the step 0.47 → 0.38 ms at full HD and 4th order, 0.25 → 0.21 at 9-point. `PrepareFrame`, which no path of the- app uses, reads both stages and blends on the host. Numerics are Jeroen's (dx = dt = 1, leapfrog, 9-point or 4th-order+ app uses, reads both stages and blends on the host. **Measured against the engine before these commits** (2026-11-04,+ the user's question whether the day's engine work changed a result: the library at d0a42e3 built from a `git archive`+ export under %TEMP%, both stepping the same painted scene with two sources 200 steps, a 32 px rim, open edges, both+ stencils): the field bit for bit the same, through `PrepareFrame` and through a capture; the captured intensity, the+ app's path, bit for bit the same, 0 of 2,073,600 halves differing; `PrepareFrame`'s host blend alone differs in about+ a thousand values of two million by one ulp at 1e-45, where the card flushes subnormals and the host does not. Numerics are Jeroen's (dx = dt = 1, leapfrog, 9-point or 4th-orderLaplacian, soft sources, EMA intensity; a scene pixel with red 0 is a mirror, n = 1000, his V0.30 rule,2026-10-18), verified CPU = GPU by the harness; seeds from `Pcg32` make CPU = GPUbit for bit on random gaps. A source's frequency level, amplitude and phase take decimals (2026-10-19, Jeroen's point 10); the@@ -485,7 +490,7 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDA## Numbers (workstation: 10-core Xeon without AVX2, RTX 2080, 64 GB)GPU step at 1080p 0.21 ms (9-point) to 0.38 ms (4th order, three sub-steps; 0.25–0.47 before the compact maps and the-deferred intensity blend of 2026-11-03), CPU 6–14 ms; OpenCL build 0.3 s; a full-HD frame's capture (both planes as halves, 8.3 MB)+deferred intensity blend of 2026-11-03), CPU 5.3 ms (9-point) to 8.7 (4th order) in lanes since 2026-11-04 (6.2 and 13.2 cell by cell); OpenCL build 0.3 s; a full-HD frame's capture (both planes as halves, 8.3 MB)0.9 ms on top of its two steps since the page-locked snapshots (2026-11-03; 2.1 ms before, the stepping thread blocked inthe driver's copy; `bench 1920 1080`: 1.50 → 0.65 ms a step with captures every 2 steps at 4th order, the DMA on its ownqueue), the DMA itself 0.63 ms at 13 GB/s. In the app the default project's run (2500 steps, 1250 frames, 16-bit, both@@ -505,8 +510,11 @@ table lookup per pixel): 16-bit 0.5 ms,Example 7 (2880×1080 in a 458×172 picture, both layers, playing): 16-bit 7.3–8.5 ms a frame, dithered 7.7–9.1, 8-bit10–11 (its bitmaps are canvas-sized). Presenter about 7 ms a frame quiet, 20 during a run. JPEG 1080p at 4:4:4: WIC 26 ms a framesingle-threaded (9 ms a frame in a sequence job on half the cores), in-house 9.8 ms on ten cores (15 in a job);-MP4 job 16 ms a frame. Part painter on a Full HD canvas (ten cores): a 400 × 330 outline 30 ms, a 400 px lens 5, a hexagon 8, an S-bent fibre across the canvas 51 (156 chords on the cell grid; 1.3 s without it);-the glowing edges 22 ms; the preview's scene pictures about 100 ms more, so the scene rebuild is coalesced at background priority.+MP4 job 16 ms a frame. Part painter on a Full HD canvas (ten cores, the bench's figures less its 3 ms canvas, 2026-11-04):+a 400 × 330 outline 0.8 ms (30 on 2026-10-19, 3.6 before the runs), a 400 px lens 0.6, a hexagon 0.7 (was 2.3), an S-bent+fibre across the canvas 9.6 (51 on 2026-10-22, 19 before the runs and the one chord pass; 156 chords on the cell grid, 1.3 s+without it); the glowing edges 8.8 ms on noise and 4.5 on Example 16's scene (12.7 and 6.2 cell by cell; 2.1 of each the+result's allocation); the preview's scene pictures about 100 ms more, so the scene rebuild is coalesced at background priority.**The composition runs on a worker since 2026-11-03** (the user's choice, after the log of a drag in Example 16: everycoalesced update repainted all four rectangles, one the whole canvas, "composed in 115–270 ms" on the UI thread, then20–30 ms of pictures, and the handle jumped): `MainWindow.ComposeScene` clones the parts (`OpticalPart.Clone` copies the@@ -525,18 +533,27 @@ edge is within reach** — the outline, the coating band's, or an inner edge thefibre's core boundary, a Bragg stack's layer boundaries; the logic gate still says 0, every inside pixel sampled) — whereevery pixel of a fibre had been (2026-11-03, after the user's drag of a fibre node: Example 23's three fibres 138/163/398 →43/50/96 ms, its composition 731 → 218 ms; a graded band's pixels are the centre sample now, as every other coated shape's,-within 0.01 of index where the band curves inside a pixel). A fibre pixel still runs four chord loops (depth, body index,-face, inner edge), sharable for about another factor of two. Left for later, if wanted: a Lipschitz skip-in the rows (the depth is a lower bound on the distance to the outline, so a pixel at depth *d* settles the next-⌈|*d*| − 0.6⌉ pixels: ~20 evaluations a row instead of 600 for a box, the arithmetic itself then a few milliseconds),-and the pictures' glowing edges, now the larger share of the UI thread's time during a drag; not an incremental-painter, since a coating's band rises from the index beneath it. Laptop (2 cores, HD 520, HDD): iGPU 4.3 ms a step against CPU 14.7; the ball+within 0.01 of index where the band curves inside a pixel). **The painter settles runs** (2026-11-04, the user's+request, "all of them to the best of abilities"; the rules and the figures are in `OpticalParts.md` under Rasterisation):+where a shape's depths are distances (`PartShape.DepthIsDistance`), one pixel centre settles the next+floor(e − 0.6 − allowance) pixels of its row, e the nearest edge's distance, as outside or as body (`BodyIndexAt`), so a+box costs a handful of depth evaluations a row; the lens and the gate are not distances and stay pixel by pixel; a fibre+sample runs its chords once for depth, index and face (`Evaluate`), its wedge jump at a bent flat end covered by a computed+`SkipAllowance`. Proven byte for byte against the pixel-by-pixel painting over every example and every kind at four+angles (`library_check`, "painter runs"); the proof of any later painter change is that check. **Lanes** (`Vector<T>`, 4+floats on this Xeon, 8 with AVX2): the glowing edges (the Sobel sums as 16-bit integers, the root in double, the bytes the+scalar's, proven on noise and a painted scene) and the CPU engine's stencil (each lane the scalar arithmetic in its+order, the field and intensity bit for bit the committed engine's after 100 steps of a painted scene with two sources:+6.2 → 5.3 ms a step at 9-point, 13.2 → 8.7 at 4th order on 1920 × 1080 with a 32 px rim, the rest the memory bus). The+screen path keeps its loops: a two-to-three-term dot product a pixel and a table gather, which lanes do not help. Not an+incremental painter, since a coating's band rises from the index beneath it. Laptop (2 cores, HD 520, HDD): iGPU 4.3 ms a step against CPU 14.7; the balllens run 105 s full quality (disk-bound), 61 s at half resolution with every second frame, in RAM. Settled by these-numbers: no GPU JPEG, no OpenCL colouring at presentation, no `Vector256`, no Direct3D display path.+numbers: no GPU JPEG, no OpenCL colouring at presentation, no explicit `Vector256` paths (`Vector<T>` takes the width the+machine has), no Direct3D display path.## Harnesses-`library_check` (100+ checks: engines, store, renderer, half tables, screen path, schemes, probes, scratch, reduced preview, importer, export, parts, group move, open edges, work groups on a prime grid, ranges, XOR gate, zone plate, gate port follower, history, clipboard, the project file's DTD, the first start's tiers, the engine's page-locked snapshots, scene replacement, the memory warning's store bytes).+`library_check` (100+ checks: engines, store, renderer, half tables, screen path, schemes, probes, scratch, reduced preview, importer, export, parts, group move, open edges, work groups on a prime grid, ranges, XOR gate, zone plate, gate port follower, history, clipboard, the project file's DTD, the first start's tiers, the engine's page-locked snapshots, scene replacement, the memory warning's store bytes, the painter's runs and the glowing edges' lanes byte for byte against pixel by pixel).UI, all on `Common.ps1`, with their check counts: `PreviewCheck` 43, `RunCheck` 71, `LanguageCheck` 11,`ProbeGraphCheck` 39, `ImportCheck` 10, `ExportCheck` 44, `PreviewQualityCheck` 35, `SceneImageCheck` 8,`ColorPickerCheck` 13, `KeyboardCheck` 13, `AboutCheck` 18, `SelectionCheck` 10. Test projects `tiny*.wdproj` sit beside them. Thediff --git a/OpticalParts.md b/OpticalParts.mdindex a492a95..3ff4b51 100644--- a/OpticalParts.md+++ b/OpticalParts.md@@ -17,7 +17,9 @@ The class is the kind (2026-10-22: the `PartKind` enum was removed).get (a fibre's default path: `XmlSerializer` appends a file's items to the list it finds), and its properties under`CLAUDE.md`'s model conventions (`[Range]` beside every clamp in `Normalize()`).2. Its shape in `Parts/PartShape.cs` (`PartShape.For`) and, if it has one, its size grip in `SceneOverlay.GripOf` and- `SetGrip`.+ `SetGrip`. A shape whose `Depth` and `InnerEdgeDistance` are true distances (they change by at most the distance+ moved) says so with `DepthIsDistance`, and the painter settles runs of pixels from one centre's depths; one that is+ not stays pixel by pixel, which is always right.3. An `[XmlElement("Name", typeof(…))]` line on `Project.Parts`: one element name per kind.4. Its entry in `PartMenuEntries` (`Panes/ProjectTree.xaml`), where the app decides which kinds it offers and in whichorder; both menus take their entries from there.@@ -48,7 +50,21 @@ checked.body, a fibre's or GRIN lens's zone) and the indices averaged (an existing red 0 counting as index 1), rounded to red.A mirror uses the pixel-centre test alone and writes red 0: a half-covered mirror pixel would otherwise round to anindex and be transparent. A part's centre is the corner of pixel (X, Y), so even sizes, every default, cover whole- pixels. A part whose index is not painted (`PaintsIndex` false, the zone plate) writes blue alone.+ pixels. A part whose index is not painted (`PaintsIndex` false, the zone plate) writes blue alone. Only pixels near+ an edge are supersampled: the shape's depth at the pixel centre is a distance, so a pixel farther than a sample's+ reach (0.6 px) from the outline, the coating band's inner edge and every inner edge (a fibre's core, a stack's layers)+ takes its centre's index in one go. And where the shape says its depths are distances (`PartShape.DepthIsDistance`:+ the polygon shapes, the fibre, the Bragg stack, the GRIN lens, the zone plate; not the lens, whose surface depth is+ the radius beyond a convex surface's centre and minus infinity beyond a concave one's, nor the gate's first-order arm+ distance), one pixel centre settles a run of the pixels after it along the row (2026-11-04): a centre k pixels on is+ at most k nearer to every edge, so the next floor(e − 0.6 − allowance) pixels, e the nearest edge's distance, are+ outside too or body too, and only the body index is asked of them (`BodyIndexAt`); a fibre's `SkipAllowance` covers+ the one place its depth jumps, the wedge between a flat face's plane and the end chord's perpendicular at a bent end,+ by (R + margin) tan²φ / 2 per end, φ the angle between the face's tangent and the chord. `library_check` paints every+ example's parts and every kind at four angles both ways, with runs and pixel by pixel, and the bytes must agree. A+ fibre sample runs its chords once for depth, index and face together (`Evaluate`), with each chord's run and length+ precomputed; on a blank Full HD canvas the painting of a 400 × 330 outline went 3.6 → 0.8 ms, a hexagon 2.3 → 0.7, an+ S-bent fibre across the canvas 19 → 9.6.- **The angle** is in degrees, counter-clockwise on the screen, 0 pointing the part's axis x' along +x (the compositesource's convention); y' is across. Shapes face a source on the left (-x').- **The AR coating** (`CoatedPart`: lens, shapes, GRIN lens) is a band of `Coating` pixels just inside the outline: withdiff --git a/WaveDudeNext/Engine/WaveSimulator.cs b/WaveDudeNext/Engine/WaveSimulator.csindex 410fd7d..e81ae7b 100644--- a/WaveDudeNext/Engine/WaveSimulator.cs+++ b/WaveDudeNext/Engine/WaveSimulator.cs@@ -16,6 +16,7 @@// <https://www.gnu.org/licenses/>.using System.Globalization;+using System.Numerics;using System.Numerics.Tensors;using WaveDudeNext.Model;using WaveDudeNext.Probes;@@ -800,48 +801,45 @@ public sealed class WaveSimulator : IWaveEngine, IDisposablefloat scale = _intensityScale;int bands = Math.Min(h, Environment.ProcessorCount * 4);+ // the cells go through the stencil in lanes of Vector<float> (4 on SSE, 8 with AVX2; 2026-11-04), each lane the+ // scalar arithmetic in the scalar order, so the field is the same bit for bit as cell by cell (and as the GPU's,+ // which library_check proves); the columns the lanes do not cover and the first and last column of a 4th-order+ // row, which take the 9-point stencil, go cell by cell+ int lanes = Vector<float>.Count;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;+ int row = (y + 1) * stride + 1;// the 4th order stencil reaches 2 cells away, so it is only safe for domain rows/columns that// have that much room before the (1 cell wide) border - the outermost ring of the domain (y = 0,// y = h - 1, and, per column below, x = 0, x = w - 1) falls back to the original 3x3 kernelbool rowAllows4th = use4th && y >= 1 && y <= h - 2;- for (int x = 0; x < w; x++)+ int x = 0;+ if (rowAllows4th){- float center = u[idx];- float laplacian;- if (rowAllows4th && x >= 1 && x <= w - 2)+ StepCell9(u, uPrev, c2, d, stage1, intensity, intensityOut, track, mult, alpha, scale, stride, row);+ int end = w - 1;+ for (x = 1; x + lanes <= end; x += lanes){- 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;+ StepLanes4(u, uPrev, c2, d, stage1, intensity, intensityOut, track, mult, alpha, scale, stride, row + x);}- else+ for (; x < end; x++){- 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;+ StepCell4(u, uPrev, c2, d, stage1, intensity, intensityOut, track, mult, alpha, scale, stride, row + x);}- // the new value replaces the previous one (each cell only reads its own previous value)- float next = center + (center - uPrev[idx]) * d[idx] + laplacian * c2[idx] * mult;- uPrev[idx] = next;- if (track)- {- // two cascaded one-pole stages (see the class remarks), blended with the 1-stage- // result (IntensityBlend) for the shown/exported intensity rather than using the full- // 2-stage cascade outright- 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++;+ StepCell9(u, uPrev, c2, d, stage1, intensity, intensityOut, track, mult, alpha, scale, stride, row + w - 1);+ continue;+ }+ for (; x + lanes <= w; x += lanes)+ {+ StepLanes9(u, uPrev, c2, d, stage1, intensity, intensityOut, track, mult, alpha, scale, stride, row + x);+ }+ for (; x < w; x++)+ {+ StepCell9(u, uPrev, c2, d, stage1, intensity, intensityOut, track, mult, alpha, scale, stride, row + x);}}});@@ -855,6 +853,81 @@ public sealed class WaveSimulator : IWaveEngine, IDisposable_u = uPrev;}+ /// <summary>One cell of <see cref="UpdateField"/> with the 9-point stencil: the Laplacian, then <see cref="FinishCell"/>.</summary>+ private static void StepCell9(float[] u, float[] uPrev, float[] c2, float[] d, float[]? stage1, float[]? intensity, float[]? intensityOut, bool track, float mult, float alpha, float scale, int stride, int idx)+ {+ float center = u[idx];+ float 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;+ FinishCell(uPrev, c2, d, stage1, intensity, intensityOut, track, mult, alpha, scale, idx, center, laplacian);+ }++ /// <summary>One cell of <see cref="UpdateField"/> with the 4th-order stencil: the Laplacian, then <see cref="FinishCell"/>.</summary>+ private static void StepCell4(float[] u, float[] uPrev, float[] c2, float[] d, float[]? stage1, float[]? intensity, float[]? intensityOut, bool track, float mult, float alpha, float scale, int stride, int idx)+ {+ float center = u[idx];+ float 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;+ FinishCell(uPrev, c2, d, stage1, intensity, intensityOut, track, mult, alpha, scale, idx, center, laplacian);+ }++ /// <summary>+ /// The leapfrog update of one cell from its Laplacian, <c>next = u + (u − uPrev)·d + lap·c²·mult</c>, written over+ /// its previous value, and when tracking the intensity's two cascaded one-pole stages (see the class remarks),+ /// blended with the 1-stage result (<see cref="IntensityBlend"/>) for the shown/exported intensity rather than+ /// using the full 2-stage cascade outright.+ /// </summary>+ private static void FinishCell(float[] uPrev, float[] c2, float[] d, float[]? stage1, float[]? intensity, float[]? intensityOut, bool track, float mult, float alpha, float scale, int idx, float center, float laplacian)+ {+ 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;+ }+ }++ /// <summary><see cref="StepCell9"/> for <see cref="Vector{T}.Count"/> cells from <paramref name="idx"/> on, each lane the scalar's arithmetic in its order.</summary>+ private static void StepLanes9(float[] u, float[] uPrev, float[] c2, float[] d, float[]? stage1, float[]? intensity, float[]? intensityOut, bool track, float mult, float alpha, float scale, int stride, int idx)+ {+ var center = new Vector<float>(u, idx);+ Vector<float> laplacian = KernelCorner * (new Vector<float>(u, idx - stride - 1) + new Vector<float>(u, idx - stride + 1) + new Vector<float>(u, idx + stride - 1) + new Vector<float>(u, idx + stride + 1))+ + KernelEdge * (new Vector<float>(u, idx - 1) + new Vector<float>(u, idx + 1) + new Vector<float>(u, idx - stride) + new Vector<float>(u, idx + stride))+ - center;+ FinishLanes(uPrev, c2, d, stage1, intensity, intensityOut, track, mult, alpha, scale, idx, center, laplacian);+ }++ /// <summary><see cref="StepCell4"/> for <see cref="Vector{T}.Count"/> cells from <paramref name="idx"/> on, each lane the scalar's arithmetic in its order.</summary>+ private static void StepLanes4(float[] u, float[] uPrev, float[] c2, float[] d, float[]? stage1, float[]? intensity, float[]? intensityOut, bool track, float mult, float alpha, float scale, int stride, int idx)+ {+ var center = new Vector<float>(u, idx);+ Vector<float> laplacian = FourthOrderFar * (new Vector<float>(u, idx - 2) + new Vector<float>(u, idx + 2) + new Vector<float>(u, idx - 2 * stride) + new Vector<float>(u, idx + 2 * stride))+ + FourthOrderNear * (new Vector<float>(u, idx - 1) + new Vector<float>(u, idx + 1) + new Vector<float>(u, idx - stride) + new Vector<float>(u, idx + stride))+ + FourthOrderCenter * center;+ FinishLanes(uPrev, c2, d, stage1, intensity, intensityOut, track, mult, alpha, scale, idx, center, laplacian);+ }++ /// <summary><see cref="FinishCell"/> for <see cref="Vector{T}.Count"/> cells from <paramref name="idx"/> on.</summary>+ private static void FinishLanes(float[] uPrev, float[] c2, float[] d, float[]? stage1, float[]? intensity, float[]? intensityOut, bool track, float mult, float alpha, float scale, int idx, Vector<float> center, Vector<float> laplacian)+ {+ Vector<float> next = center + (center - new Vector<float>(uPrev, idx)) * new Vector<float>(d, idx) + laplacian * new Vector<float>(c2, idx) * mult;+ next.CopyTo(uPrev, idx);+ if (track)+ {+ Vector<float> s1 = new Vector<float>(stage1!, idx) * alpha + next * next * (1f - alpha);+ s1.CopyTo(stage1!, idx);+ Vector<float> s2 = new Vector<float>(intensity!, idx) * alpha + s1 * (1f - alpha);+ s2.CopyTo(intensity!, idx);+ ((s1 * (1f - IntensityBlend) + s2 * IntensityBlend) * scale).CopyTo(intensityOut!, idx);+ }+ }+/// <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 thediff --git a/WaveDudeNext/Parts/PartPainter.cs b/WaveDudeNext/Parts/PartPainter.csindex dc1a849..8fd2555 100644--- a/WaveDudeNext/Parts/PartPainter.cs+++ b/WaveDudeNext/Parts/PartPainter.cs@@ -33,7 +33,12 @@ namespace WaveDudeNext.Parts;/// tests the pixel centre alone and writes red 0, since an averaged mirror edge would/// clamp to glass. Only pixels near an edge (the outline, the coating band's inner edge, a Bragg layer) are/// supersampled: the shape's depth at the pixel centre is an exact distance, so a pixel farther than a sample's-/// reach from every edge takes its centre's index in one go (2026-10-19, a drag of a part was sluggish).+/// reach from every edge takes its centre's index in one go (2026-10-19, a drag of a part was sluggish). And where the+/// shape's depths are distances (<see cref="PartShape.DepthIsDistance"/>), one pixel centre settles a run of the pixels+/// after it along the row (<see cref="Settled"/>): a centre k pixels on is at most k nearer to every edge, so the pixels+/// within the nearest edge's distance less the reach are outside too, or body too, and only the body index is asked of+/// them (2026-11-04: a box of 600 pixels a row takes a handful of depth evaluations instead of 600; proven byte for byte+/// against the pixel-by-pixel painting by <c>library_check</c>)./// Pure geometry, no UI; any thread. The per-kind tests are in <see cref="PartShape"/> so the/// harness can check them./// </summary>@@ -47,6 +52,28 @@ public static class PartPainter/// <summary>How far a sample can lie from the pixel centre, with a margin: beyond this depth from an edge, every sample falls on the same side.</summary>private const double SampleReach = 0.6;+ /// <summary>Taken off a run's reach for the rounding of the depths' arithmetic, in pixels.</summary>+ private const double Epsilon = 1e-6;++ /// <summary>+ /// How many pixels after one along a row its depths settle: with the nearest edge <paramref name="edge"/> pixels from+ /// the centre and the shape's depths distances, the next floor(edge − <paramref name="reach"/> − allowance − ε) centres+ /// are still farther than <paramref name="reach"/> from every edge, on the same side; 0 for a shape whose depths are+ /// not distances, which is sampled pixel by pixel.+ /// </summary>+ /// <param name="shape">The shape.</param>+ /// <param name="edge">The distance from this pixel's centre to the nearest edge, positive.</param>+ /// <param name="reach">The samples' reach to stay clear of, <see cref="SampleReach"/> for the refractive painting, 0 for a mirror's centre test.</param>+ private static int Settled(PartShape shape, double edge, double reach)+ {+ if (!shape.DepthIsDistance)+ {+ return 0;+ }+ double pixels = edge - reach - shape.SkipAllowance - Epsilon;+ return pixels >= 1.0 ? (int)pixels : 0;+ }+/// <summary>/// The scene pixels with the enabled parts painted in: <paramref name="image"/> itself (the same reference, so/// callers comparing by reference see no change) when no part is enabled, else a copy of the image, or a blank@@ -133,12 +160,25 @@ public static class PartPainterParallel.For(y0, y1 + 1, (int y) =>{int row = y * stride;- for (int x = x0; x <= x1; x++)+ double cy = y + 0.5;+ for (int x = x0; x <= x1;){- if (shape.IndexAt(x + 0.5, y + 0.5) is not null)+ // the centre test: inside at a depth of 0 and more; the run its depth settles is on the same side+ double depth = shape.DepthAt(x + 0.5, cy);+ int run;+ if (depth >= 0.0){- bgra[row + x * 4 + 2] = 0;+ run = Math.Min(Settled(shape, depth, 0.0), x1 - x);+ for (int k = 0; k <= run; k++)+ {+ bgra[row + (x + k) * 4 + 2] = 0;+ }}+ else+ {+ run = Math.Min(Settled(shape, -depth, 0.0), x1 - x);+ }+ x += run + 1;}});return;@@ -149,13 +189,16 @@ public static class PartPainterParallel.For(y0, y1 + 1, (int y) =>{int row = y * stride;- for (int x = x0; x <= x1; x++)+ double cy = y + 0.5;+ for (int x = x0; x <= x1;){int offset = row + x * 4 + 2;- (double depth, double inner) = shape.DepthsAt(x + 0.5, y + 0.5);+ (double depth, double inner) = shape.DepthsAt(x + 0.5, cy);if (depth < -SampleReach){- continue; // every sample outside+ // every sample outside: this pixel and the run its depth settles+ x += Math.Min(Settled(shape, -depth, SampleReach), x1 - x) + 1;+ continue;}int red = bgra[offset];// red 0 is a mirror the engine reads as index 1000; averaging it in as glass of index 1 is the user's rule,@@ -165,10 +208,19 @@ public static class PartPainter{// every sample inside and no edge within reach, neither the outline, an inner edge (a fibre's core, a// stack's layer) nor the coating band's: the centre's index stands for the pixel- if (shape.IndexAt(x + 0.5, y + 0.5, existing) is { } whole)+ if (shape.IndexAt(x + 0.5, cy, existing) is { } whole){bgra[offset] = (byte)Math.Clamp((int)Math.Round(whole * 100.0), 1, 255);}+ // deeper than the band, or without one: the run the depths settle is body too, clear of the outline, the+ // band's inner edge and every inner edge, and the body index alone is its pixels' index+ double body = coating == 0 ? depth : depth - coating;+ int run = body > SampleReach ? Math.Min(Settled(shape, Math.Min(body, inner), SampleReach), x1 - x) : 0;+ for (int k = 1; k <= run; k++)+ {+ bgra[offset + k * 4] = (byte)Math.Clamp((int)Math.Round(shape.BodyIndexAt(x + k + 0.5, cy) * 100.0), 1, 255);+ }+ x += run + 1;continue;}double sum = 0.0;@@ -193,6 +245,7 @@ public static class PartPainter{bgra[offset] = (byte)Math.Clamp((int)Math.Round(sum / (Supersample * Supersample) * 100.0), 1, 255);}+ x++;}});}@@ -215,11 +268,19 @@ public static class PartPainterParallel.For(y0, y1 + 1, () => 0.0, (int y, ParallelLoopState _, double local) =>{int row = (y - y0) * columns;- for (int x = x0; x <= x1; x++)+ double cy = y + 0.5;+ for (int x = x0; x <= x1;){- double depth = shape.DepthAt(x + 0.5, y + 0.5);+ double depth = shape.DepthAt(x + 0.5, cy);depths[row + x - x0] = (float)depth;local = Math.Max(local, depth);+ // outside: the run its depth settles is outside too, and only its sign is read+ int run = depth < 0.0 ? Math.Min(Settled(shape, -depth, 0.0), x1 - x) : 0;+ for (int k = 1; k <= run; k++)+ {+ depths[row + x + k - x0] = -1f;+ }+ x += run + 1;}return local;}, local =>diff --git a/WaveDudeNext/Parts/PartShape.cs b/WaveDudeNext/Parts/PartShape.csindex c9990ff..b86bb95 100644--- a/WaveDudeNext/Parts/PartShape.cs+++ b/WaveDudeNext/Parts/PartShape.cs@@ -81,9 +81,14 @@ public abstract class PartShape/// </summary>protected virtual Face FaceAt(double x, double y) => Face.Front;+ /// <summary>Whether every face carries the band, so the band needs no face search.</summary>+ protected bool AllFacesCoated => _frontCoated && _backCoated && _sidesCoated;++ /// <summary>Whether <paramref name="face"/> carries the band.</summary>+ protected bool FaceCoated(Face face) => face switch { Face.Front => _frontCoated, Face.Back => _backCoated, _ => _sidesCoated };+/// <summary>Whether the band at (x', y') is painted: the flag of the nearest face, without the search when every face is coated.</summary>- private bool Coated(double x, double y) =>- _frontCoated && _backCoated && _sidesCoated || FaceAt(x, y) switch { Face.Front => _frontCoated, Face.Back => _backCoated, _ => _sidesCoated };+ private bool Coated(double x, double y) => AllFacesCoated || FaceCoated(FaceAt(x, y));/// <summary>/// The share of the index step a graded band has reached at <paramref name="t"/>, the depth inside the outline over the@@ -187,9 +192,39 @@ public abstract class PartShapepublic (double Depth, double InnerEdge) DepthsAt(double canvasX, double canvasY){(double x, double y) = ToFrame(canvasX, canvasY);- return (Depth(x, y), InnerEdgeDistance(x, y));+ return Depths(x, y);+ }++ /// <summary><see cref="Depth"/> and <see cref="InnerEdgeDistance"/> of a part-frame point; a shape whose two share their work (the fibre's chords) overrides it with one pass.</summary>+ protected virtual (double Depth, double InnerEdge) Depths(double x, double y) => (Depth(x, y), InnerEdgeDistance(x, y));++ /// <summary>+ /// The body index at a canvas point the painter knows to lie inside the outline and deeper than the coating band:+ /// <see cref="BodyIndex"/> alone, what <see cref="IndexAt(double, double, double)"/> returns there, without the depth.+ /// </summary>+ public double BodyIndexAt(double canvasX, double canvasY)+ {+ (double x, double y) = ToFrame(canvasX, canvasY);+ return BodyIndex(x, y);}+ /// <summary>+ /// Whether <see cref="Depth"/> and <see cref="InnerEdgeDistance"/> change by at most the distance moved, as a true+ /// distance to an edge does (1-Lipschitz), so that from one pixel centre's depths the painter can settle the pixels+ /// after it whose every sample lies on the same side of every edge as that centre's, less <see cref="SkipAllowance"/>+ /// (2026-11-04). The polygon's signed distance, the fibre's tube, the stack's, the GRIN lens's and the zone plate's+ /// rectangles say yes. The lens does not: beyond a convex surface's centre its surface depth is the radius, beyond a+ /// concave one's minus infinity, and only the rim's depth covers the jumps; nor the gate, whose arm distance is first+ /// order. Both are sampled pixel by pixel.+ /// </summary>+ public virtual bool DepthIsDistance => false;++ /// <summary>+ /// By how many pixels <see cref="Depth"/> may jump where it departs from a distance although <see cref="DepthIsDistance"/>+ /// holds otherwise (a fibre's flat face at a bent end): the painter settles that many pixels fewer per run. 0 by default.+ /// </summary>+ public virtual double SkipAllowance => 0.0;+/// <summary>Maps a canvas point into the part frame: the inverse of the composite source's turn (x = dx cos + dy sin, y = dy cos - dx sin), the transpose.</summary>private (double X, double Y) ToFrame(double canvasX, double canvasY){@@ -233,6 +268,12 @@ public abstract class PartShapepublic double? IndexAt(double canvasX, double canvasY, double outside){(double x, double y) = ToFrame(canvasX, canvasY);+ return IndexInFrame(x, y, outside);+ }++ /// <summary><see cref="IndexAt(double, double, double)"/> of a part-frame point; a shape whose depth, body index and face share their work (the fibre's chords) overrides it with one pass.</summary>+ protected virtual double? IndexInFrame(double x, double y, double outside)+ {double depth = Depth(x, y);if (depth < 0.0){@@ -247,9 +288,13 @@ public abstract class PartShape{return index;}- return _profile == CoatingProfile.Graded ? outside + (index - outside) * GradedProfile(depth / Coating) : Math.Round(Math.Sqrt(index), 2);+ return BandIndex(depth, index, outside);}+ /// <summary>The index inside the band, <paramref name="depth"/> in over a coated face: for a graded band the index risen from <paramref name="outside"/> toward the body's <paramref name="index"/> by <see cref="GradedProfile"/> of the depth over the thickness, for a layer √n rounded to 0.01.</summary>+ protected double BandIndex(double depth, double index, double outside) =>+ _profile == CoatingProfile.Graded ? outside + (index - outside) * GradedProfile(depth / Coating) : Math.Round(Math.Sqrt(index), 2);+/// <summary>A refractive index within the part range.</summary>protected static double GuardIndex(double index) => double.IsFinite(index) ? Math.Clamp(index, OpticalPart.MinIndex, OpticalPart.MaxIndex) : OpticalPart.MinIndex;@@ -289,7 +334,12 @@ public abstract class PartShape{double dx = bx - ax;double dy = by - ay;- double length2 = dx * dx + dy * dy;+ return SegmentDistance(ax, ay, dx, dy, dx * dx + dy * dy, x, y);+ }++ /// <summary>Distance from (x, y) to the segment from a along (<paramref name="dx"/>, <paramref name="dy"/>), whose squared length is <paramref name="length2"/>: the same arithmetic as the four-point form, for a caller that keeps the segments' geometry.</summary>+ protected static double SegmentDistance(double ax, double ay, double dx, double dy, double length2, double x, double y)+ {double t = length2 > 0.0 ? Math.Clamp(((x - ax) * dx + (y - ay) * dy) / length2, 0.0, 1.0) : 0.0;double px = ax + t * dx - x;double py = ay + t * dy - y;@@ -435,6 +485,8 @@ public abstract class PartShapepublic override int Absorption { get; }public override int AbsorptionRamp { get; }protected override double Extent => _extent;+ /// <summary>The signed distance to the polygon: a distance.</summary>+ public override bool DepthIsDistance => true;protected override double Depth(double x, double y) => PolygonDepth(_vertices, x, y);protected override double BodyIndex(double x, double y) => _index;}@@ -475,10 +527,30 @@ public abstract class PartShapeprivate readonly int[] _cellChords;private readonly int _startZone;private readonly int _endZone;+ private readonly double _allowance;+ private readonly double[] _chordDx;+ private readonly double[] _chordDy;+ private readonly double[] _chordLength;+ private readonly double[] _chordLength2;public FiberShape(FiberPart fiber, (double X, double Y)[] path) : base(fiber){_path = path;+ // each chord's run and length once, instead of a square root per chord per sample (2026-11-04); the same+ // expressions as the loops had, so the numbers are the same+ _chordDx = new double[path.Length];+ _chordDy = new double[path.Length];+ _chordLength = new double[path.Length];+ _chordLength2 = new double[path.Length];+ for (int i = 1; i < path.Length; i++)+ {+ double dx = path[i].X - path[i - 1].X;+ double dy = path[i].Y - path[i - 1].Y;+ _chordDx[i] = dx;+ _chordDy[i] = dy;+ _chordLength2[i] = dx * dx + dy * dy;+ _chordLength[i] = Math.Sqrt(dx * dx + dy * dy);+ }_flat = fiber.Ends == FiberEnds.Flat;FiberNode first = fiber.Nodes[0];FiberNode last = fiber.Nodes[^1];@@ -494,6 +566,15 @@ public abstract class PartShapeAbsorption = fiber.CladdingThickness > 0 ? GuardAbsorption(fiber.Absorption) : 0;_band = Math.Min(GuardAbsorptionRamp(fiber.AbsorptionRamp), Math.Max(0, fiber.CladdingThickness) / 2.0);_extent = _path.Max(v => Math.Sqrt(v.X * v.X + v.Y * v.Y)) + _outerRadius;+ // the one place the depth is not a distance (see SkipAllowance): with flat ends, in the wedge between a face's+ // plane and the end chord's perpendicular through its end point, the chord's round joint (the distance to that+ // point) stands in for the tube's line, and the depth jumps across the plane. A point of the wedge lies within+ // φ of that perpendicular, φ the angle between the face's tangent and the chord, so at ρ from the end point its+ // way along the chord is at most ρ sin φ and its distance from the line at least ρ cos φ; the jump is along² over+ // the two distances' sum, at most ρ sin²φ / (2 cos φ); and a point whose depth from the chord is above −Margin+ // (below it the clamp hides the jump) has ρ cos φ ≤ R + Margin. So the jump is at most (R + Margin) tan²φ / 2+ // per end, and a run of settled pixels can cross both ends.+ _allowance = _flat ? WedgeJump(_startTangent, path[1].X - path[0].X, path[1].Y - path[0].Y) + WedgeJump(_endTangent, path[^1].X - path[^2].X, path[^1].Y - path[^2].Y) : 0.0;// the chords a flat face cuts: every chord is a capsule, and one starting within the outer radius of an// end (twice that, for a bend) reaches past the face with its round cap_startZone = 1;@@ -544,10 +625,26 @@ public abstract class PartShape}}}++ // (R + Margin) tan²φ / 2 for the angle φ between a face's tangent and its chord; infinite past 90°, which no flattened curve reaches+ double WedgeJump((double X, double Y) tangent, double dx, double dy)+ {+ double length = Math.Sqrt(dx * dx + dy * dy);+ double cos = length > 0.0 ? Math.Clamp((tangent.X * dx + tangent.Y * dy) / length, -1.0, 1.0) : 1.0;+ if (cos <= 0.0)+ {+ return double.PositiveInfinity;+ }+ double tan2 = (1.0 - cos * cos) / (cos * cos);+ return (_outerRadius + Margin) * tan2 / 2.0;+ }}public override bool IsMirror => false;protected override int Coating { get; }+ /// <summary>The largest over the chords of a tube's depth, each cut by the end planes and clamped at −Margin: a distance but for the wedges <see cref="SkipAllowance"/> covers.</summary>+ public override bool DepthIsDistance => true;+ public override double SkipAllowance => _allowance;private readonly double _band;public override int Absorption { get; }public override int AbsorptionRamp => Math.Max(1, (int)Math.Ceiling(_band));@@ -580,15 +677,26 @@ public abstract class PartShape/// the point is nearest to inside; with round ends, the caps before the start and beyond the end./// </summary>protected override Face FaceAt(double x, double y)+ {+ (double startDepth, double endDepth) = FaceDepths(x, y);+ return FaceOf(startDepth, endDepth, PathDistance(x, y));+ }++ /// <summary>How far past the start, and how far short of the end, the point lies along the tangents there.</summary>+ private (double Start, double End) FaceDepths(double x, double y){int last = _path.Length - 1;- double startDepth = (x - _path[0].X) * _startTangent.X + (y - _path[0].Y) * _startTangent.Y;- double endDepth = (_path[last].X - x) * _endTangent.X + (_path[last].Y - y) * _endTangent.Y;+ return ((x - _path[0].X) * _startTangent.X + (y - _path[0].Y) * _startTangent.Y, (_path[last].X - x) * _endTangent.X + (_path[last].Y - y) * _endTangent.Y);+ }++ /// <summary>The face by the face depths and the distance <paramref name="path"/> from the path (see <see cref="FaceAt"/>).</summary>+ private Face FaceOf(double startDepth, double endDepth, double path)+ {if (!_flat){return startDepth < 0.0 ? Face.Front : endDepth < 0.0 ? Face.Back : Face.Sides;}- double side = _outerRadius - PathDistance(x, y);+ double side = _outerRadius - path;return startDepth <= endDepth && startDepth <= side ? Face.Front : endDepth <= side ? Face.Back : Face.Sides;}@@ -600,27 +708,60 @@ public abstract class PartShapeprotected override double Extent => _extent;protected override double BodyIndex(double x, double y) => PathDistance(x, y) <= _coreRadius ? _coreIndex : _claddingIndex;- protected override double Depth(double x, double y)+ protected override double Depth(double x, double y) => Evaluate(x, y).Depth;++ /// <summary>The depth and the core edge's distance from one pass over the chords.</summary>+ protected override (double Depth, double InnerEdge) Depths(double x, double y)+ {+ (double depth, double path, _, _) = Evaluate(x, y);+ return (depth, HasInnerEdges ? Math.Abs(path - _coreRadius) : double.PositiveInfinity);+ }++ /// <summary>The index from one pass over the chords: the depth, the core or the cladding by the distance from the path, and the face by the same numbers (a fibre is never a mirror).</summary>+ protected override double? IndexInFrame(double x, double y, double outside){+ (double depth, double path, double startDepth, double endDepth) = Evaluate(x, y);+ if (depth < 0.0)+ {+ return null;+ }+ double index = path <= _coreRadius ? _coreIndex : _claddingIndex;+ if (Coating <= 0 || depth >= Coating || !(AllFacesCoated || FaceCoated(FaceOf(startDepth, endDepth, path))))+ {+ return index;+ }+ return BandIndex(depth, index, outside);+ }++ /// <summary>+ /// One pass over the chords listed for (x', y'): the depth, the distance to the path (<see cref="PathDistance"/>, infinite+ /// where no chord is listed) and the face depths (<see cref="FaceDepths"/>). A sample of the painter had run the chords+ /// for its depth, again for its index and a third time for its face (2026-11-04).+ /// </summary>+ private (double Depth, double Path, double StartDepth, double EndDepth) Evaluate(double x, double y)+ {+ (double startRaw, double endRaw) = FaceDepths(x, y);(int from, int to) = ChordsNear(x, y);if (from == to){- return -Margin;+ return (-Margin, double.PositiveInfinity, startRaw, endRaw);}int last = _path.Length - 1;// depth from the end faces: how far past the start, and how far short of the end, along the tangents there- double startDepth = _flat ? (x - _path[0].X) * _startTangent.X + (y - _path[0].Y) * _startTangent.Y : double.PositiveInfinity;- double endDepth = _flat ? (_path[last].X - x) * _endTangent.X + (_path[last].Y - y) * _endTangent.Y : double.PositiveInfinity;+ double startDepth = _flat ? startRaw : double.PositiveInfinity;+ double endDepth = _flat ? endRaw : double.PositiveInfinity;double best = double.NegativeInfinity;+ double nearest = double.PositiveInfinity;for (int k = from; k < to; k++){int i = _cellChords[k];(double ax, double ay) = _path[i - 1];- (double bx, double by) = _path[i];- double dx = bx - ax;- double dy = by - ay;- double length = Math.Sqrt(dx * dx + dy * dy);+ double dx = _chordDx[i];+ double dy = _chordDy[i];+ double length = _chordLength[i];double along = ((x - ax) * dx + (y - ay) * dy) / length; // from a, in pixels+ double segment = SegmentDistance(ax, ay, dx, dy, _chordLength2[i], x, y);+ nearest = Math.Min(nearest, segment);double depth;if (along >= 0.0 && along <= length || i == 1 && startDepth < 0.0 || i == last && endDepth < 0.0){@@ -631,7 +772,7 @@ public abstract class PartShapeelse{// beyond a chord's end inside the path: the round joint to the next chord, or a round end- depth = _outerRadius - SegmentDistance(ax, ay, bx, by, x, y);+ depth = _outerRadius - segment;}if (i <= _startZone){@@ -644,7 +785,7 @@ public abstract class PartShapebest = Math.Max(best, depth);}// a chord the cell does not list is more than the margin outside, so it never sets the maximum- return Math.Max(best, -Margin);+ return (Math.Max(best, -Margin), nearest, startRaw, endRaw);}/// <summary>Distance to the nearest chord of the path among those listed for the point's cell (exact within the tube, where the nearest chord is always listed).</summary>@@ -655,7 +796,7 @@ public abstract class PartShapefor (int k = from; k < to; k++){int i = _cellChords[k];- nearest = Math.Min(nearest, SegmentDistance(_path[i - 1].X, _path[i - 1].Y, _path[i].X, _path[i].Y, x, y));+ nearest = Math.Min(nearest, SegmentDistance(_path[i - 1].X, _path[i - 1].Y, _chordDx[i], _chordDy[i], _chordLength2[i], x, y));}return nearest;}@@ -709,6 +850,8 @@ public abstract class PartShapepublic override bool IsMirror => false;protected override int Coating => 0;public override bool HasInnerEdges => true;+ /// <summary>A rectangle's depth and the distance to the nearest layer boundary: distances.</summary>+ public override bool DepthIsDistance => true;protected override double Extent => Math.Sqrt(_halfLength * _halfLength + _halfWidth * _halfWidth);/// <summary>The nearest layer boundary along x': a pair's edges at 0, its first thickness and the period.</summary>@@ -746,6 +889,8 @@ public abstract class PartShapepublic override bool IsMirror => false;protected override int Coating { get; }protected override double Extent => Math.Sqrt(_halfLength * _halfLength + _halfDiameter * _halfDiameter);+ /// <summary>A rectangle's depth: a distance.</summary>+ public override bool DepthIsDistance => true;protected override double Depth(double x, double y) => Math.Min(_halfLength - Math.Abs(x), _halfDiameter - Math.Abs(y));/// <summary>The end faces across the axis are the front (−x') and the back, the long sides the sides.</summary>@@ -790,6 +935,8 @@ public abstract class PartShapepublic override int Absorption => ZonePlatePart.BlockAbsorption;public override int AbsorptionRamp => Math.Max(1, (int)Math.Ceiling(_ramp));protected override double Extent => Math.Sqrt(_halfThickness * _halfThickness + _outerHalfWidth * _outerHalfWidth);+ /// <summary>A rectangle's depth: a distance.</summary>+ public override bool DepthIsDistance => true;protected override double Depth(double x, double y) => Math.Min(_halfThickness - Math.Abs(x), _outerHalfWidth - Math.Abs(y));protected override double BodyIndex(double x, double y) => 1.0;diff --git a/WaveDudeNext/Rendering/GlowingEdges.cs b/WaveDudeNext/Rendering/GlowingEdges.csindex b9b2eb5..6025fef 100644--- a/WaveDudeNext/Rendering/GlowingEdges.cs+++ b/WaveDudeNext/Rendering/GlowingEdges.cs@@ -15,6 +15,8 @@// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or// <https://www.gnu.org/licenses/>.+using System.Numerics;+using System.Runtime.InteropServices;namespace WaveDudeNext.Rendering;@@ -46,47 +48,126 @@ public static class GlowingEdgespublic static byte[] Compute(byte[] bgra, int width, int height, int strideBytes){var result = new byte[width * height * 4];- for (int i = 3; i < result.Length; i += 4)- {- result[i] = 255;- }+ // black with alpha 255: the pixel as a little-endian int, filled in lanes+ MemoryMarshal.Cast<byte, int>(result.AsSpan()).Fill(unchecked((int)0xFF000000));if (width < 3 || height < 3){return result;}- // rows are independent: a Full HD canvas took 60 ms on one core (2026-10-19)- Parallel.For(1, height - 1, (int y) =>+ // rows are independent: a Full HD canvas took 60 ms on one core (2026-10-19). A row goes through the Sobel in+ // lanes over all four channels at once (2026-11-04): first the column sums up + 2 mid + down and the differences+ // down − up as 16-bit integers, then per lane the gradients as ints, their squares summed (at most 2 × 1020²,+ // exact in single precision), the root, the scale and the clamp in double as the scalar loop had them and the+ // floor, so the bytes are the same; the alpha lanes ride along and are put back to 255+ int n = width * 4;+ Parallel.For(1, height - 1, () => new Rows(n), (int y, ParallelLoopState _, Rows rows) =>{- int rowUp = (y - 1) * strideBytes;- int rowMid = y * strideBytes;- int rowDown = (y + 1) * strideBytes;- int dstRow = y * width * 4;- for (int x = 1; x < width - 1; x++)+ ReadOnlySpan<byte> up = bgra.AsSpan((y - 1) * strideBytes, n);+ ReadOnlySpan<byte> mid = bgra.AsSpan(y * strideBytes, n);+ ReadOnlySpan<byte> down = bgra.AsSpan((y + 1) * strideBytes, n);+ Span<ushort> sum = rows.Sum;+ Span<short> diff = rows.Difference;+ int bytes = Vector<byte>.Count;+ int half = Vector<ushort>.Count;+ int i = 0;+ for (; i + bytes <= n; i += bytes)+ {+ Vector.Widen(new Vector<byte>(up.Slice(i)), out Vector<ushort> u0, out Vector<ushort> u1);+ Vector.Widen(new Vector<byte>(mid.Slice(i)), out Vector<ushort> m0, out Vector<ushort> m1);+ Vector.Widen(new Vector<byte>(down.Slice(i)), out Vector<ushort> d0, out Vector<ushort> d1);+ (u0 + m0 + m0 + d0).CopyTo(sum.Slice(i));+ (u1 + m1 + m1 + d1).CopyTo(sum.Slice(i + half));+ // the wrapped unsigned difference reinterpreted is the signed one+ Vector.AsVectorInt16(d0 - u0).CopyTo(diff.Slice(i));+ Vector.AsVectorInt16(d1 - u1).CopyTo(diff.Slice(i + half));+ }+ for (; i < n; i++)+ {+ sum[i] = (ushort)(up[i] + 2 * mid[i] + down[i]);+ diff[i] = (short)(down[i] - up[i]);+ }+ Span<byte> row = result.AsSpan(y * n, n);+ int end = n - 4;+ int x = 4;+ for (; x + bytes <= end; x += bytes)+ {+ Edges(sum, diff, x).CopyTo(row.Slice(x));+ }+ for (; x < end; x++){- int cUp = rowUp + (x - 1) * 4;- int cMid = rowMid + (x - 1) * 4;- int cDown = rowDown + (x - 1) * 4;- int dst = dstRow + x * 4;- for (int channel = 0; channel < 3; channel++)+ if ((x & 3) == 3){- int p00 = bgra[cUp + channel];- int p01 = bgra[cUp + 4 + channel];- int p02 = bgra[cUp + 8 + channel];- int p10 = bgra[cMid + channel];- int p12 = bgra[cMid + 8 + channel];- int p20 = bgra[cDown + channel];- int p21 = bgra[cDown + 4 + channel];- int p22 = bgra[cDown + 8 + channel];- int gx = (p02 + 2 * p12 + p22) - (p00 + 2 * p10 + p20);- int gy = (p20 + 2 * p21 + p22) - (p00 + 2 * p01 + p02);- double magnitude = Math.Sqrt((double)gx * gx + (double)gy * gy) * Scale;- result[dst + channel] = (byte)Math.Min(255.0, magnitude);+ continue; // alpha stays 255}+ int gx = sum[x + 4] - sum[x - 4];+ int gy = diff[x - 4] + 2 * diff[x] + diff[x + 4];+ row[x] = (byte)Math.Min(255.0, Math.Sqrt((double)gx * gx + (double)gy * gy) * Scale);}- });+ return rows;+ }, _ => { });return result;}+ /// <summary>The alpha lanes of a byte vector of pixels, every fourth from the fourth.</summary>+ private static readonly Vector<byte> AlphaLanes = MakeAlphaLanes();++ private static Vector<byte> MakeAlphaLanes()+ {+ var lanes = new byte[Vector<byte>.Count];+ for (int i = 3; i < lanes.Length; i += 4)+ {+ lanes[i] = 255;+ }+ return new Vector<byte>(lanes);+ }++ /// <summary>One vector of edge bytes for the positions from <paramref name="x"/> on, alpha 255, from the column sums and differences at x − 4, x and x + 4.</summary>+ private static Vector<byte> Edges(ReadOnlySpan<ushort> sum, ReadOnlySpan<short> diff, int x)+ {+ int half = Vector<ushort>.Count;+ Vector<float> f0 = Magnitudes(sum, diff, x, out Vector<float> f1);+ Vector<float> f2 = Magnitudes(sum, diff, x + half, out Vector<float> f3);+ Vector<short> s0 = Vector.Narrow(Vector.ConvertToInt32(f0), Vector.ConvertToInt32(f1));+ Vector<short> s1 = Vector.Narrow(Vector.ConvertToInt32(f2), Vector.ConvertToInt32(f3));+ return Vector.ConditionalSelect(AlphaLanes, AlphaLanes, Vector.AsVectorByte(Vector.Narrow(s0, s1)));+ }++ /// <summary>The whole magnitudes of the positions from <paramref name="p"/> on, a vector of 16-bit sums wide, as two single vectors.</summary>+ private static Vector<float> Magnitudes(ReadOnlySpan<ushort> sum, ReadOnlySpan<short> diff, int p, out Vector<float> second)+ {+ // gx: the sum a pixel to the right less the sum a pixel to the left; gy: the difference a pixel to the left, twice here, a pixel to the right+ Vector.Widen(new Vector<ushort>(sum.Slice(p + 4)), out Vector<uint> r0, out Vector<uint> r1);+ Vector.Widen(new Vector<ushort>(sum.Slice(p - 4)), out Vector<uint> l0, out Vector<uint> l1);+ Vector.Widen(new Vector<short>(diff.Slice(p - 4)), out Vector<int> a0, out Vector<int> a1);+ Vector.Widen(new Vector<short>(diff.Slice(p)), out Vector<int> b0, out Vector<int> b1);+ Vector.Widen(new Vector<short>(diff.Slice(p + 4)), out Vector<int> c0, out Vector<int> c1);+ second = Magnitude(Vector.AsVectorInt32(r1) - Vector.AsVectorInt32(l1), a1 + b1 + b1 + c1);+ return Magnitude(Vector.AsVectorInt32(r0) - Vector.AsVectorInt32(l0), a0 + b0 + b0 + c0);+ }++ /// <summary>floor(min(255, √(gx² + gy²) × <see cref="Scale"/>)) per lane: the squares' sum exact in single precision, the rest in double.</summary>+ private static Vector<float> Magnitude(Vector<int> gx, Vector<int> gy)+ {+ Vector.Widen(Vector.ConvertToSingle(gx * gx + gy * gy), out Vector<double> low, out Vector<double> high);+ return Vector.Narrow(Clamp(low), Clamp(high));+ }++ private static Vector<double> Clamp(Vector<double> squares) => Vector.Floor(Vector.Min(Vector.SquareRoot(squares) * Scale, new Vector<double>(255.0)));++ /// <summary>A worker's scratch rows for <see cref="Compute"/>: the column sums and differences of a row, all four channels.</summary>+ private sealed class Rows+ {+ public Rows(int n)+ {+ Sum = new ushort[n];+ Difference = new short[n];+ }++ public ushort[] Sum { get; }+ public short[] Difference { get; }+ }++/// <summary>/// Bakes the edge picture into a rendered frame the author's way: each channel becomes/// min(255, frame + edge × <paramref name="gain"/>), so black edge pixels leave the frame alone at anydiff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.csindex eb12f6b..442eda3 100644--- a/_tools/library_check/Program.cs+++ b/_tools/library_check/Program.cs@@ -284,6 +284,7 @@ internal static class ProgramCheckProbeGraph();CheckImport();CheckParts();+ CheckPainterRuns();CheckAbsorbingParts();CheckXorGate();CheckGatePortFollower();@@ -2782,6 +2783,288 @@ internal static class ProgramCheck(refused, "a newer format version is refused");}+ /// <summary>+ /// The painter's runs (2026-11-04: where a shape's depths are distances, one pixel centre settles the pixels after it+ /// along the row) against the pixel-by-pixel painting they replaced, kept here as <see cref="PaintPixelByPixel"/>: every+ /// example's parts, and every kind at several angles with coatings of both profiles, bare faces, mirrors, absorption,+ /// both fibre ends and a fibre bent sharply at its flat start face (the wedge the allowance covers), painted both ways+ /// onto a canvas whose red and blue vary and that holds mirror pixels, must come out byte for byte the same.+ /// </summary>+ private static void CheckPainterRuns()+ {+ var cases = new List<(string Name, int Width, int Height, IReadOnlyList<OpticalPart> Parts)>();+ string? root = FindRepoRoot();+ if (root != null)+ {+ foreach (string file in Directory.GetFiles(Path.Combine(root, "Examples"), "*.wdproj").Order())+ {+ Project example = Project.Load(file);+ if (example.Parts.Any(part => part.Enabled))+ {+ cases.Add((Path.GetFileNameWithoutExtension(file), Math.Max(64, example.Scene.Width), Math.Max(64, example.Scene.Height), example.Parts));+ }+ }+ }+ foreach (double angle in new[] { 0.0, 17.0, 90.0, -123.0 })+ {+ var project = new Project();+ project.Scene.Width = 520;+ project.Scene.Height = 360;+ var lens = project.AddPart<LensPart>();+ lens.X = 110; lens.Y = 90; lens.Angle = angle; lens.Diameter = 120; lens.Thickness = 30;+ lens.Coating = 5; lens.CoatingProfile = CoatingProfile.Graded; lens.BackCoated = false; lens.Absorption = 40;+ var mirror = project.AddPart<LensPart>();+ mirror.X = 260; mirror.Y = 90; mirror.Angle = angle; mirror.Diameter = 100; mirror.Thickness = 10; mirror.Mirror = true;+ var slab = project.AddPart<RectanglePart>();+ slab.X = 410; slab.Y = 90; slab.Angle = angle; slab.Length = 140; slab.Width = 50;+ slab.Coating = 4; slab.SidesCoated = false; slab.RefractiveIndex = 2.25; slab.Absorption = 120; slab.AbsorptionRamp = 12;+ var wall = project.AddPart<RectanglePart>();+ wall.X = 60; wall.Y = 230; wall.Angle = angle; wall.Length = 90; wall.Width = 6; wall.Mirror = true;+ var polygon = project.AddPart<PolygonPart>();+ polygon.X = 170; polygon.Y = 230; polygon.Angle = angle; polygon.Side = 40;+ polygon.Coating = 3; polygon.CoatingProfile = CoatingProfile.Layer; polygon.FrontCoated = false;+ var disc = project.AddPart<EllipsePart>();+ disc.X = 290; disc.Y = 230; disc.Angle = angle; disc.Length = 80; disc.Width = 50;+ disc.Absorption = 200; disc.AbsorptionRamp = 60; disc.Coating = 6; disc.CoatingProfile = CoatingProfile.Graded;+ var triangle = project.AddPart<TrianglePart>();+ triangle.X = 400; triangle.Y = 230; triangle.Angle = angle; triangle.Base = 70;+ var outline = project.AddPart<OutlinePart>();+ outline.X = 470; outline.Y = 300; outline.Angle = angle;+ foreach ((int px, int py) in new[] { (-40, -30), (30, -40), (45, 10), (0, 45), (-35, 20), (-10, 0) })+ {+ outline.Points.Add(new PartPoint { X = px, Y = py });+ }+ var fiber = project.AddPart<FiberPart>();+ fiber.X = 130; fiber.Y = 320; fiber.Angle = angle; fiber.CoreDiameter = 12; fiber.CladdingThickness = 8;+ fiber.Coating = 3; fiber.FrontCoated = false; fiber.Absorption = 90; fiber.AbsorptionRamp = 3; fiber.Ends = FiberEnds.Flat;+ fiber.Nodes[0].X = -100; fiber.Nodes[0].Y = 0; fiber.Nodes[0].SetHandle(true, 8, 40);+ fiber.Nodes[1].X = 100; fiber.Nodes[1].Y = 10; fiber.Nodes[1].SetHandle(false, -60, 30);+ var bare = project.AddPart<FiberPart>();+ bare.X = 380; bare.Y = 320; bare.Angle = angle; bare.CoreDiameter = 16; bare.CladdingThickness = 0;+ bare.Ends = FiberEnds.Round; bare.Coating = 4; bare.CoatingProfile = CoatingProfile.Graded;+ bare.Nodes[0].X = -70; bare.Nodes[1].X = 70; bare.Nodes[1].Y = -20;+ var bragg = project.AddPart<BraggReflectorPart>();+ bragg.X = 60; bragg.Y = 90; bragg.Angle = angle; bragg.Pairs = 4; bragg.Thickness1 = 5; bragg.Thickness2 = 7; bragg.Width = 60;+ var grin = project.AddPart<GrinLensPart>();+ grin.X = 190; grin.Y = 160; grin.Angle = angle; grin.Length = 60; grin.Diameter = 50;+ grin.Coating = 6; grin.CoatingProfile = CoatingProfile.Graded; grin.SidesCoated = false;+ var plate = project.AddPart<ZonePlatePart>();+ plate.X = 330; plate.Y = 160; plate.Angle = angle; plate.Diameter = 120; plate.Thickness = 20; plate.Coating = 6; plate.Mount = true; plate.MountWidth = 20;+ var gate = project.AddPart<XorGatePart>();+ gate.X = 450; gate.Y = 160; gate.Angle = angle;+ cases.Add(($"every kind at {angle}°", project.Scene.Width, project.Scene.Height, project.Parts));+ }+ int compared = 0;+ foreach ((string name, int width, int height, IReadOnlyList<OpticalPart> parts) in cases)+ {+ // red and blue vary over the canvas, with a column of mirror pixels every 50, so graded bands rise from every+ // medium and absorption meets blue already there+ var bgra = new byte[width * height * 4];+ for (int y = 0; y < height; y++)+ {+ for (int x = 0; x < width; x++)+ {+ int i = (y * width + x) * 4;+ bgra[i] = (byte)(y % 90);+ bgra[i + 2] = (byte)(x % 50 == 0 ? 0 : 100 + (x / 7 + y / 5) % 150);+ bgra[i + 3] = 255;+ }+ }+ var image = new ScenePixels(width, height, width * 4, bgra);+ ScenePixels expected = PaintPixelByPixel(image, parts);+ ScenePixels actual = PartPainter.Paint(image, width, height, 1.0, parts)!;+ int first = expected.Bgra.AsSpan().CommonPrefixLength(actual.Bgra);+ compared++;+ Check(first == expected.Bgra.Length, first == expected.Bgra.Length+ ? $"painter runs: {name} comes out byte for byte as pixel by pixel ({parts.Count} parts, {width}×{height})"+ : $"painter runs: {name} differs at ({first / 4 % width}, {first / 4 / width}) channel {first % 4}: {expected.Bgra[first]} pixel by pixel, {actual.Bgra[first]} with runs");+ }+ Check(compared >= 14, $"the runs were compared on {compared} projects");++ // the glowing edges in lanes (2026-11-04) against the pixel-by-pixel Sobel they replaced: a painted scene and noise+ var noise = new Random(7);+ foreach ((string name, ScenePixels pixels) in new[]+ {+ ("Example 16 painted", PartPainter.Paint(null, 1500, 900, 1.0, cases.First(c => c.Name.StartsWith("Example16")).Parts)!),+ ("noise 1920 × 1080", new ScenePixels(1920, 1080, 1920 * 4, Enumerable.Range(0, 1920 * 1080 * 4).Select(_ => (byte)noise.Next(256)).ToArray())),+ ("noise 5 × 3", new ScenePixels(5, 3, 20, Enumerable.Range(0, 60).Select(_ => (byte)noise.Next(256)).ToArray())),+ })+ {+ byte[] expected = GlowingEdgesPixelByPixel(pixels.Bgra, pixels.Width, pixels.Height, pixels.StrideBytes);+ byte[] actual = GlowingEdges.Compute(pixels.Bgra, pixels.Width, pixels.Height, pixels.StrideBytes);+ int first = expected.AsSpan().CommonPrefixLength(actual);+ Check(first == expected.Length, first == expected.Length+ ? $"glowing edges in lanes: {name} comes out byte for byte as pixel by pixel"+ : $"glowing edges in lanes: {name} differs at byte {first}: {expected[first]} pixel by pixel, {actual[first]} in lanes");+ }+ }++ /// <summary>The glowing edges as they stood before the lanes (2026-11-04): the Sobel magnitude per pixel and channel in double.</summary>+ private static byte[] GlowingEdgesPixelByPixel(byte[] bgra, int width, int height, int strideBytes)+ {+ var result = new byte[width * height * 4];+ for (int i = 3; i < result.Length; i += 4)+ {+ result[i] = 255;+ }+ if (width < 3 || height < 3)+ {+ return result;+ }+ for (int y = 1; y < height - 1; y++)+ {+ int rowUp = (y - 1) * strideBytes;+ int rowMid = y * strideBytes;+ int rowDown = (y + 1) * strideBytes;+ int dstRow = y * width * 4;+ for (int x = 1; x < width - 1; x++)+ {+ int cUp = rowUp + (x - 1) * 4;+ int cMid = rowMid + (x - 1) * 4;+ int cDown = rowDown + (x - 1) * 4;+ int dst = dstRow + x * 4;+ for (int channel = 0; channel < 3; channel++)+ {+ int p00 = bgra[cUp + channel];+ int p01 = bgra[cUp + 4 + channel];+ int p02 = bgra[cUp + 8 + channel];+ int p10 = bgra[cMid + channel];+ int p12 = bgra[cMid + 8 + channel];+ int p20 = bgra[cDown + channel];+ int p21 = bgra[cDown + 4 + channel];+ int p22 = bgra[cDown + 8 + channel];+ int gx = (p02 + 2 * p12 + p22) - (p00 + 2 * p10 + p20);+ int gy = (p20 + 2 * p21 + p22) - (p00 + 2 * p01 + p02);+ double magnitude = Math.Sqrt((double)gx * gx + (double)gy * gy) * GlowingEdges.Scale;+ result[dst + channel] = (byte)Math.Min(255.0, magnitude);+ }+ }+ }+ return result;+ }++ /// <summary>The painting as it stood before the runs (2026-11-03): every pixel of a part's rectangle evaluated on its own.</summary>+ private static ScenePixels PaintPixelByPixel(ScenePixels image, IReadOnlyList<OpticalPart> parts)+ {+ int width = image.Width;+ int height = image.Height;+ int stride = width * 4;+ var bgra = new byte[stride * height];+ for (int y = 0; y < height; y++)+ {+ Buffer.BlockCopy(image.Bgra, y * image.StrideBytes, bgra, y * stride, stride);+ }+ const double reach = 0.6;+ const double step = 1.0 / PartPainter.Supersample;+ const double half = step / 2.0;+ foreach (OpticalPart part in parts)+ {+ if (!part.Enabled || PartShape.For(part) is not { } shape)+ {+ continue;+ }+ (int x0, int y0, int x1, int y1) = shape.Bounds(width, height);+ if (x0 > x1 || y0 > y1)+ {+ continue;+ }+ if (shape.Absorption > 0)+ {+ int columns = x1 - x0 + 1;+ var depths = new float[columns * (y1 - y0 + 1)];+ double deepest = 0.0;+ for (int y = y0; y <= y1; y++)+ {+ for (int x = x0; x <= x1; x++)+ {+ double depth = shape.DepthAt(x + 0.5, y + 0.5);+ depths[(y - y0) * columns + x - x0] = (float)depth;+ deepest = Math.Max(deepest, depth);+ }+ }+ double ramp = Math.Min(shape.AbsorptionRamp, deepest);+ int full = shape.Absorption;+ for (int y = y0; y <= y1; y++)+ {+ for (int x = x0; x <= x1; x++)+ {+ float depth = depths[(y - y0) * columns + x - x0];+ if (depth >= 0f)+ {+ int offset = y * stride + x * 4;+ int blue = (int)Math.Round(full * shape.AbsorptionShareAt(x + 0.5, y + 0.5, depth, ramp));+ bgra[offset] = (byte)Math.Max(bgra[offset], blue);+ }+ }+ }+ }+ if (!shape.PaintsIndex)+ {+ continue;+ }+ if (shape.IsMirror)+ {+ for (int y = y0; y <= y1; y++)+ {+ for (int x = x0; x <= x1; x++)+ {+ if (shape.IndexAt(x + 0.5, y + 0.5) is not null)+ {+ bgra[y * stride + x * 4 + 2] = 0;+ }+ }+ }+ continue;+ }+ int coating = shape.CoatingWidth;+ for (int y = y0; y <= y1; y++)+ {+ for (int x = x0; x <= x1; x++)+ {+ int offset = y * stride + x * 4 + 2;+ (double depth, double inner) = shape.DepthsAt(x + 0.5, y + 0.5);+ if (depth < -reach)+ {+ continue;+ }+ int red = bgra[offset];+ double existing = red == 0 ? 1.0 : red / 100.0;+ if (depth > reach && inner > reach && (coating == 0 || Math.Abs(depth - coating) > reach))+ {+ if (shape.IndexAt(x + 0.5, y + 0.5, existing) is { } whole)+ {+ bgra[offset] = (byte)Math.Clamp((int)Math.Round(whole * 100.0), 1, 255);+ }+ continue;+ }+ double sum = 0.0;+ int inside = 0;+ for (int sy = 0; sy < PartPainter.Supersample; sy++)+ {+ for (int sx = 0; sx < PartPainter.Supersample; sx++)+ {+ double? index = shape.IndexAt(x + half + sx * step, y + half + sy * step, existing);+ if (index is { } n)+ {+ sum += n;+ inside++;+ }+ else+ {+ sum += existing;+ }+ }+ }+ if (inside > 0)+ {+ bgra[offset] = (byte)Math.Clamp((int)Math.Round(sum / (PartPainter.Supersample * PartPainter.Supersample) * 100.0), 1, 255);+ }+ }+ }+ }+ return new ScenePixels(width, height, stride, bgra);+ }+/// <summary>Red at canvas pixel (x, y) of a painted scene.</summary>private static int RedAt(ScenePixels pixels, int x, int y) => pixels.Bgra[y * pixels.StrideBytes + x * 4 + 2];