From e87dcc9ec5866d78f3cf4ac94d0ff900862f519e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 26 Sep 2026 02:36:52 +0200 Subject: [PATCH 01/10] cultmath: add snoise_grad, fbm_grad, ridged_grad to C# math (cut 2a-ii-a) Analytic-gradient simplex noise, ported from webgl-noise's noise3Dgrad.glsl differentiation but retargeted onto this repo's own snoise(float3) constants (0.6 falloff radius, +1 permute offset, 42 scale) so snoise_grad.w stays exactly snoise's own field. fbm_grad and ridged_grad are octave sums with per-octave frequency/amplitude compounding (invariant 8). octaves is clamped to [0, 16] so the HLSL mirror test's full-int32-range oracle cannot turn a garbage octave count into a multi-billion-iteration loop. Co-Authored-By: Claude Opus 5.5 --- packages/cultmath/src/CultMath/math.cs | 132 +++++++++++++++++++++++++ 1 file changed, 132 insertions(+) diff --git a/packages/cultmath/src/CultMath/math.cs b/packages/cultmath/src/CultMath/math.cs index 1b03f4ed..168868c6 100644 --- a/packages/cultmath/src/CultMath/math.cs +++ b/packages/cultmath/src/CultMath/math.cs @@ -693,6 +693,138 @@ public static partial class math private static float3 snoise_permute(float3 value) => snoise_mod289(((value * 34.0f) + 1.0f) * value); private static float4 snoise_permute(float4 value) => snoise_mod289(((value * 34.0f) + 1.0f) * value); + // Ashima Arts / Ian McEwan 3D simplex noise with analytic gradient (invariant 8), following the + // differentiation in webgl-noise src/noise3Dgrad.glsl (Ashima Arts / McEwan, MIT; confirmed at + // stegu/webgl-noise today), retargeted onto THIS file's own snoise(float3) constants: upstream's + // noise3Dgrad.glsl uses a 0.5 falloff radius, permute(x) = mod289((34x+10)x) and an overall scale + // of 105, while this repo's existing snoise(float3) (and cultmath_snoise) use 0.6, permute(x) = + // mod289((34x+1)x) and scale 42 (Ashima's alternate, second-order-artifact-reduced noise3D.glsl + // constants, already load-bearing here and pinned by the existing snoise tests): every local up + // through p0..p3 and x0..x3 below is snoise(float3)'s own derivation verbatim, unchanged, so .w + // stays that same field (SnoiseGradTests pins the two within 1e-6 and reports whether they are + // bit-equal). The differentiation itself carries over unchanged from upstream, because it never + // depends on the threshold or permutation constants: per corner, m0 = max(radius - dot(x,x), 0), + // so dm0/dx = -2x, and d(m0^4 * dot(p,x))/dx = 4*m0^3*(-2x)*dot(p,x) + m0^4*p + // = -8*m0^3*dot(p,x)*x + m0^4*p (p is that corner's own gradient constant, independent of x, so + // only the dot(p,x) factor contributes there); summed over the four corners and scaled by the + // same 42 as the value. + public static float4 snoise_grad(float3 value) + { + const float cx = 1.0f / 6.0f; + const float cy = 1.0f / 3.0f; + var i = floor(value + dot(value, new float3(cy, cy, cy))); + var x0 = value - i + dot(i, new float3(cx, cx, cx)); + var g = step(new float3(x0.y, x0.z, x0.x), x0); + var l = 1.0f - g; + var lzxy = new float3(l.z, l.x, l.y); + var i1 = min(g, lzxy); + var i2 = max(g, lzxy); + var x1 = x0 - i1 + cx; + var x2 = x0 - i2 + cy; + var x3 = x0 - 0.5f; + + i = snoise_mod289(i); + var p = snoise_permute(snoise_permute(snoise_permute( + i.z + new float4(0.0f, i1.z, i2.z, 1.0f)) + i.y + new float4(0.0f, i1.y, i2.y, 1.0f)) + i.x + new float4(0.0f, i1.x, i2.x, 1.0f)); + + const float n = 0.142857142857f; + var ns = new float3(2.0f * n, 0.5f * n - 1.0f, n); + var j = p - 49.0f * floor(p * ns.z * ns.z); + var xs = floor(j * ns.z); + var ys = floor(j - 7.0f * xs); + var x = xs * ns.x + ns.y; + var y = ys * ns.x + ns.y; + var h = 1.0f - abs(x) - abs(y); + + var b0 = new float4(x.x, x.y, y.x, y.y); + var b1 = new float4(x.z, x.w, y.z, y.w); + var s0 = floor(b0) * 2.0f + 1.0f; + var s1 = floor(b1) * 2.0f + 1.0f; + var sh = -step(h, 0.0f); + var a0 = new float4(b0.x, b0.z, b0.y, b0.w) + new float4(s0.x, s0.z, s0.y, s0.w) * new float4(sh.x, sh.x, sh.y, sh.y); + var a1 = new float4(b1.x, b1.z, b1.y, b1.w) + new float4(s1.x, s1.z, s1.y, s1.w) * new float4(sh.z, sh.z, sh.w, sh.w); + + var p0 = new float3(a0.x, a0.y, h.x); + var p1 = new float3(a0.z, a0.w, h.y); + var p2 = new float3(a1.x, a1.y, h.z); + var p3 = new float3(a1.z, a1.w, h.w); + var norm = 1.79284291400159f - 0.85373472095314f * new float4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)); + p0 *= norm.x; + p1 *= norm.y; + p2 *= norm.z; + p3 *= norm.w; + + var m0 = max(0.6f - new float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0f); + var m2 = m0 * m0; + var m3 = m2 * m0; + var m4 = m2 * m2; + + var px = new float4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)); + var value2 = 42.0f * dot(m4, px); + var grad = -8.0f * m3.x * x0 * px.x + m4.x * p0 + + -8.0f * m3.y * x1 * px.y + m4.y * p1 + + -8.0f * m3.z * x2 * px.z + m4.z * p2 + + -8.0f * m3.w * x3 * px.w + m4.w * p3; + grad *= 42.0f; + + return new float4(grad, value2); + } + + // Octave sum of snoise_grad (invariant 8). Each octave samples snoise_grad at p scaled by the + // running frequency, so by the chain rule its gradient scales by that same frequency + // (d/dp[n(f*p)] = f * grad_n(f*p)); amplitude and frequency both compound per octave (gain, + // lacunarity respectively), not applied once for the whole sum, so with 1 octave this is exactly + // snoise_grad (FbmGradTests). octaves is clamped to [0, 16]: HlslSourceCompatibilityTests' + // bit-parity oracle drives every mirrored int parameter across the full int32 range, which is + // the right domain for pcg3d/pcg4d's O(1) hash inputs but would turn an unclamped octave count + // into a multi-billion-iteration loop for this mirror. + public static float4 fbm_grad(float3 p, int octaves, float lacunarity, float gain) + { + octaves = clamp(octaves, 0, 16); + var amplitude = 1.0f; + var frequency = 1.0f; + var value = 0.0f; + var gradient = new float3(0.0f, 0.0f, 0.0f); + for (var i = 0; i < octaves; i++) + { + var n = snoise_grad(p * frequency); + value += amplitude * n.w; + gradient += amplitude * frequency * new float3(n.x, n.y, n.z); + frequency *= lacunarity; + amplitude *= gain; + } + + return new float4(gradient, value); + } + + // Ridged multifractal noise (Musgrave, Texturing and Modeling, ch. 16; the operator's dune term, + // 2026-09-25): each octave folds snoise_grad about zero, value = Sum a_i*(1 - |n_i|), gradient = + // -Sum a_i*f_i*sign(n_i)*grad(n_i), the same per-octave frequency scaling as fbm_grad's chain + // rule plus the fold's sign flip (d|n|/dp = sign(n)*dn/dp). The crease at n_i = 0 is real and + // deliberate, not a bug: RidgedGradTests exclude a band around it, the same way cellular excludes + // its F1 = F2 seam. sign follows this codebase's HLSL-matching convention (design.md: sign + // returns int, 0 at exactly 0), so the crease itself contributes no gradient rather than an + // arbitrary one. Same octave clamp as fbm_grad, for the same bit-parity-oracle reason. + public static float4 ridged_grad(float3 p, int octaves, float lacunarity, float gain) + { + octaves = clamp(octaves, 0, 16); + var amplitude = 1.0f; + var frequency = 1.0f; + var value = 0.0f; + var gradient = new float3(0.0f, 0.0f, 0.0f); + for (var i = 0; i < octaves; i++) + { + var n = snoise_grad(p * frequency); + var s = (float)sign(n.w); + value += amplitude * (1.0f - abs(n.w)); + gradient += -amplitude * frequency * s * new float3(n.x, n.y, n.z); + frequency *= lacunarity; + amplitude *= gain; + } + + return new float4(gradient, value); + } + // Inigo Quilez, "smooth minimum" (https://iquilezles.org/articles/smin/): the quadratic-polynomial // smin, carried to value-and-gradient form (invariant 8). h is affine in (b.w - a.w) inside the // smoothing band, so differentiating value = lerp(b.w, a.w, h) - k*h*(1-h) with respect to From 1249167989d095f40730ffda62bd3d9df08fd98c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 26 Sep 2026 02:36:59 +0200 Subject: [PATCH 02/10] cultmath: mirror snoise_grad, fbm_grad, ridged_grad to HLSL (cut 2a-ii-a) cultmath_snoise_grad/fbm_grad/ridged_grad mirror the new C# math functions in both tracked CultMath.hlsl copies, which stay one blob. Extends the existing Ashima notice entry in both THIRD-PARTY-NOTICES.md copies to cover the ported differentiation. Co-Authored-By: Claude Opus 5.5 --- packages/cultmath/THIRD-PARTY-NOTICES.md | 6 + packages/cultmath/shaders/CultMath.hlsl | 109 ++++++++++++++++++ .../Shaders/CultMath.hlsl | 109 ++++++++++++++++++ .../THIRD-PARTY-NOTICES.md | 6 + 4 files changed, 230 insertions(+) diff --git a/packages/cultmath/THIRD-PARTY-NOTICES.md b/packages/cultmath/THIRD-PARTY-NOTICES.md index 06ebb6c3..2b4f2acd 100644 --- a/packages/cultmath/THIRD-PARTY-NOTICES.md +++ b/packages/cultmath/THIRD-PARTY-NOTICES.md @@ -6,6 +6,12 @@ simplex-noise functions by Ian McEwan and Ashima Arts, as distributed by Stefan Gustavson's `webgl-noise` project and Unity Mathematics. +`math.snoise_grad`/`cultmath_snoise_grad` (and the `fbm_grad`/`ridged_grad` +octave sums built on them) follow the analytic-gradient differentiation from +the same project's `src/noise3Dgrad.glsl`, retargeted onto this file's own +`snoise(float3)` falloff radius, permutation, and scale constants (see the +`math.snoise_grad` doc comment). + - Copyright 2011 Ashima Arts. - Upstream: - License: MIT. diff --git a/packages/cultmath/shaders/CultMath.hlsl b/packages/cultmath/shaders/CultMath.hlsl index 5c00bda0..b7cb69ca 100644 --- a/packages/cultmath/shaders/CultMath.hlsl +++ b/packages/cultmath/shaders/CultMath.hlsl @@ -162,6 +162,115 @@ float cultmath_snoise(float2 value) return 130.0 * dot(m, g); } +// Ashima Arts / Ian McEwan 3D simplex noise with analytic gradient (invariant 8), following the +// differentiation in webgl-noise src/noise3Dgrad.glsl (Ashima Arts / McEwan, MIT; confirmed at +// stegu/webgl-noise today), retargeted onto cultmath_snoise(float3)'s own constants (0.6 falloff +// radius, permute(x) = mod289((34x+1)x), scale 42; see the C# math.snoise_grad comment for the full +// derivation and why the differentiation itself is unaffected by that retargeting). Every local up +// through p0..p3 and x0..x3 is cultmath_snoise(float3)'s own derivation verbatim. +float4 cultmath_snoise_grad(float3 value) +{ + float2 c = float2(1.0 / 6.0, 1.0 / 3.0); + float3 i = floor(value + dot(value, c.yyy)); + float3 x0 = value - i + dot(i, c.xxx); + float3 g = step(x0.yzx, x0.xyz); + float3 l = 1.0 - g; + float3 i1 = min(g.xyz, l.zxy); + float3 i2 = max(g.xyz, l.zxy); + float3 x1 = x0 - i1 + c.xxx; + float3 x2 = x0 - i2 + c.yyy; + float3 x3 = x0 - 0.5; + + i = cultmath_snoise_mod289(i); + float4 p = cultmath_snoise_permute(cultmath_snoise_permute(cultmath_snoise_permute( + i.z + float4(0.0, i1.z, i2.z, 1.0)) + i.y + float4(0.0, i1.y, i2.y, 1.0)) + i.x + float4(0.0, i1.x, i2.x, 1.0)); + + const float n_ = 0.142857142857; + float3 ns = float3(2.0 * n_, 0.5 * n_ - 1.0, n_); + float4 j = p - 49.0 * floor(p * ns.z * ns.z); + float4 x_ = floor(j * ns.z); + float4 y_ = floor(j - 7.0 * x_); + float4 x = x_ * ns.x + ns.yyyy; + float4 y = y_ * ns.x + ns.yyyy; + float4 h = 1.0 - abs(x) - abs(y); + + float4 b0 = float4(x.xy, y.xy); + float4 b1 = float4(x.zw, y.zw); + float4 s0 = floor(b0) * 2.0 + 1.0; + float4 s1 = floor(b1) * 2.0 + 1.0; + float4 sh = -step(h, 0.0); + float4 a0 = b0.xzyw + s0.xzyw * sh.xxyy; + float4 a1 = b1.xzyw + s1.xzyw * sh.zzww; + + float3 p0 = float3(a0.xy, h.x); + float3 p1 = float3(a0.zw, h.y); + float3 p2 = float3(a1.xy, h.z); + float3 p3 = float3(a1.zw, h.w); + float4 norm = 1.79284291400159 - 0.85373472095314 * float4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)); + p0 *= norm.x; + p1 *= norm.y; + p2 *= norm.z; + p3 *= norm.w; + + float4 m0 = max(0.6 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); + float4 m2 = m0 * m0; + float4 m3 = m2 * m0; + float4 m4 = m2 * m2; + + float4 px = float4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)); + float value2 = 42.0 * dot(m4, px); + float3 grad = -8.0 * m3.x * x0 * px.x + m4.x * p0 + + -8.0 * m3.y * x1 * px.y + m4.y * p1 + + -8.0 * m3.z * x2 * px.z + m4.z * p2 + + -8.0 * m3.w * x3 * px.w + m4.w * p3; + grad *= 42.0; + + return float4(grad, value2); +} + +// Octave sum of cultmath_snoise_grad (invariant 8); see the C# math.fbm_grad comment for the +// per-octave frequency/amplitude derivation and why octaves is clamped. +float4 cultmath_fbm_grad(float3 p, int octaves, float lacunarity, float gain) +{ + octaves = clamp(octaves, 0, 16); + float amplitude = 1.0; + float frequency = 1.0; + float value = 0.0; + float3 gradient = float3(0.0, 0.0, 0.0); + for (int i = 0; i < octaves; i++) + { + float4 n = cultmath_snoise_grad(p * frequency); + value += amplitude * n.w; + gradient += amplitude * frequency * n.xyz; + frequency *= lacunarity; + amplitude *= gain; + } + + return float4(gradient, value); +} + +// Ridged multifractal noise (Musgrave, Texturing and Modeling, ch. 16); see the C# math.ridged_grad +// comment for the fold/sign derivation, the deliberate crease at n = 0, and why octaves is clamped. +float4 cultmath_ridged_grad(float3 p, int octaves, float lacunarity, float gain) +{ + octaves = clamp(octaves, 0, 16); + float amplitude = 1.0; + float frequency = 1.0; + float value = 0.0; + float3 gradient = float3(0.0, 0.0, 0.0); + for (int i = 0; i < octaves; i++) + { + float4 n = cultmath_snoise_grad(p * frequency); + float s = sign(n.w); + value += amplitude * (1.0 - abs(n.w)); + gradient += -amplitude * frequency * s * n.xyz; + frequency *= lacunarity; + amplitude *= gain; + } + + return float4(gradient, value); +} + float cultmath_lengthsq(float2 value) { return dot(value, value); } float cultmath_lengthsq(float3 value) { return dot(value, value); } float cultmath_lengthsq(float4 value) { return dot(value, value); } diff --git a/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.hlsl b/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.hlsl index 5c00bda0..b7cb69ca 100644 --- a/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.hlsl +++ b/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.hlsl @@ -162,6 +162,115 @@ float cultmath_snoise(float2 value) return 130.0 * dot(m, g); } +// Ashima Arts / Ian McEwan 3D simplex noise with analytic gradient (invariant 8), following the +// differentiation in webgl-noise src/noise3Dgrad.glsl (Ashima Arts / McEwan, MIT; confirmed at +// stegu/webgl-noise today), retargeted onto cultmath_snoise(float3)'s own constants (0.6 falloff +// radius, permute(x) = mod289((34x+1)x), scale 42; see the C# math.snoise_grad comment for the full +// derivation and why the differentiation itself is unaffected by that retargeting). Every local up +// through p0..p3 and x0..x3 is cultmath_snoise(float3)'s own derivation verbatim. +float4 cultmath_snoise_grad(float3 value) +{ + float2 c = float2(1.0 / 6.0, 1.0 / 3.0); + float3 i = floor(value + dot(value, c.yyy)); + float3 x0 = value - i + dot(i, c.xxx); + float3 g = step(x0.yzx, x0.xyz); + float3 l = 1.0 - g; + float3 i1 = min(g.xyz, l.zxy); + float3 i2 = max(g.xyz, l.zxy); + float3 x1 = x0 - i1 + c.xxx; + float3 x2 = x0 - i2 + c.yyy; + float3 x3 = x0 - 0.5; + + i = cultmath_snoise_mod289(i); + float4 p = cultmath_snoise_permute(cultmath_snoise_permute(cultmath_snoise_permute( + i.z + float4(0.0, i1.z, i2.z, 1.0)) + i.y + float4(0.0, i1.y, i2.y, 1.0)) + i.x + float4(0.0, i1.x, i2.x, 1.0)); + + const float n_ = 0.142857142857; + float3 ns = float3(2.0 * n_, 0.5 * n_ - 1.0, n_); + float4 j = p - 49.0 * floor(p * ns.z * ns.z); + float4 x_ = floor(j * ns.z); + float4 y_ = floor(j - 7.0 * x_); + float4 x = x_ * ns.x + ns.yyyy; + float4 y = y_ * ns.x + ns.yyyy; + float4 h = 1.0 - abs(x) - abs(y); + + float4 b0 = float4(x.xy, y.xy); + float4 b1 = float4(x.zw, y.zw); + float4 s0 = floor(b0) * 2.0 + 1.0; + float4 s1 = floor(b1) * 2.0 + 1.0; + float4 sh = -step(h, 0.0); + float4 a0 = b0.xzyw + s0.xzyw * sh.xxyy; + float4 a1 = b1.xzyw + s1.xzyw * sh.zzww; + + float3 p0 = float3(a0.xy, h.x); + float3 p1 = float3(a0.zw, h.y); + float3 p2 = float3(a1.xy, h.z); + float3 p3 = float3(a1.zw, h.w); + float4 norm = 1.79284291400159 - 0.85373472095314 * float4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)); + p0 *= norm.x; + p1 *= norm.y; + p2 *= norm.z; + p3 *= norm.w; + + float4 m0 = max(0.6 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); + float4 m2 = m0 * m0; + float4 m3 = m2 * m0; + float4 m4 = m2 * m2; + + float4 px = float4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)); + float value2 = 42.0 * dot(m4, px); + float3 grad = -8.0 * m3.x * x0 * px.x + m4.x * p0 + + -8.0 * m3.y * x1 * px.y + m4.y * p1 + + -8.0 * m3.z * x2 * px.z + m4.z * p2 + + -8.0 * m3.w * x3 * px.w + m4.w * p3; + grad *= 42.0; + + return float4(grad, value2); +} + +// Octave sum of cultmath_snoise_grad (invariant 8); see the C# math.fbm_grad comment for the +// per-octave frequency/amplitude derivation and why octaves is clamped. +float4 cultmath_fbm_grad(float3 p, int octaves, float lacunarity, float gain) +{ + octaves = clamp(octaves, 0, 16); + float amplitude = 1.0; + float frequency = 1.0; + float value = 0.0; + float3 gradient = float3(0.0, 0.0, 0.0); + for (int i = 0; i < octaves; i++) + { + float4 n = cultmath_snoise_grad(p * frequency); + value += amplitude * n.w; + gradient += amplitude * frequency * n.xyz; + frequency *= lacunarity; + amplitude *= gain; + } + + return float4(gradient, value); +} + +// Ridged multifractal noise (Musgrave, Texturing and Modeling, ch. 16); see the C# math.ridged_grad +// comment for the fold/sign derivation, the deliberate crease at n = 0, and why octaves is clamped. +float4 cultmath_ridged_grad(float3 p, int octaves, float lacunarity, float gain) +{ + octaves = clamp(octaves, 0, 16); + float amplitude = 1.0; + float frequency = 1.0; + float value = 0.0; + float3 gradient = float3(0.0, 0.0, 0.0); + for (int i = 0; i < octaves; i++) + { + float4 n = cultmath_snoise_grad(p * frequency); + float s = sign(n.w); + value += amplitude * (1.0 - abs(n.w)); + gradient += -amplitude * frequency * s * n.xyz; + frequency *= lacunarity; + amplitude *= gain; + } + + return float4(gradient, value); +} + float cultmath_lengthsq(float2 value) { return dot(value, value); } float cultmath_lengthsq(float3 value) { return dot(value, value); } float cultmath_lengthsq(float4 value) { return dot(value, value); } diff --git a/packages/cultmath/unity/org.gamecult.cultmath/THIRD-PARTY-NOTICES.md b/packages/cultmath/unity/org.gamecult.cultmath/THIRD-PARTY-NOTICES.md index 06ebb6c3..2b4f2acd 100644 --- a/packages/cultmath/unity/org.gamecult.cultmath/THIRD-PARTY-NOTICES.md +++ b/packages/cultmath/unity/org.gamecult.cultmath/THIRD-PARTY-NOTICES.md @@ -6,6 +6,12 @@ simplex-noise functions by Ian McEwan and Ashima Arts, as distributed by Stefan Gustavson's `webgl-noise` project and Unity Mathematics. +`math.snoise_grad`/`cultmath_snoise_grad` (and the `fbm_grad`/`ridged_grad` +octave sums built on them) follow the analytic-gradient differentiation from +the same project's `src/noise3Dgrad.glsl`, retargeted onto this file's own +`snoise(float3)` falloff radius, permutation, and scale constants (see the +`math.snoise_grad` doc comment). + - Copyright 2011 Ashima Arts. - Upstream: - License: MIT. From 03f0ed7a0a15085fb1fe35bcae48fbc6f47ffaf6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 26 Sep 2026 02:37:05 +0200 Subject: [PATCH 03/10] docs: describe snoise_grad, fbm_grad, ridged_grad in cultmath design.md Extends the invariant-8 primitives list with the new gradient-noise family: the constant-retargeting for snoise_grad, the per-octave frequency/amplitude chain rule, ridged_grad's deliberate zero crease, and the octave clamp's reason (the HLSL mirror test's bit-parity oracle). Co-Authored-By: Claude Opus 5.5 --- packages/cultmath/docs/design.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/packages/cultmath/docs/design.md b/packages/cultmath/docs/design.md index 30cef06c..408a49a3 100644 --- a/packages/cultmath/docs/design.md +++ b/packages/cultmath/docs/design.md @@ -233,6 +233,28 @@ together, laid out as `float4(gradient.xyz, value.w)`, with no value-only twin paths are proven bit-identical (`PrunedSearchIsBitIdenticalToTheUnprunedFiveCubedSearch`, which samples `[-50, 50]^3`, is comfortably inside that domain). +- `snoise_grad(float3 p)` carries `snoise(float3)` to value-and-gradient form, + following the differentiation in webgl-noise `src/noise3Dgrad.glsl` (Ashima + Arts / Ian McEwan, MIT) but retargeted onto `snoise(float3)`'s own falloff + radius (`0.6`), permutation (`mod289((34x+1)x)`), and scale (`42`) rather + than upstream's `0.5`/`mod289((34x+10)x)`/`105`: the differentiation itself + does not depend on those constants (per corner, `m0 = max(radius - + dot(x,x), 0)`, so `d(m0^4 * dot(p,x))/dx = -8*m0^3*dot(p,x)*x + m0^4*p`, + summed over the four corners and scaled by the same constant as the value), + so `.w` stays exactly `snoise(float3)`'s own field. `fbm_grad` and + `ridged_grad` are octave sums of `snoise_grad`: each octave samples at + `p * frequency`, so by the chain rule its gradient scales by that same + frequency, and both amplitude (`gain`) and frequency (`lacunarity`) compound + per octave rather than applying once to the whole sum. `ridged_grad` folds + each octave about zero (`Σ aᵢ(1 − |nᵢ|)`, gradient `−Σ aᵢfᵢ sign(nᵢ)∇nᵢ`, + Musgrave's ridged multifractal, *Texturing and Modeling* ch. 16); the crease + at `nᵢ = 0` is deliberate (the operator's dune term, 2026-09-25), not a bug. + Both clamp `octaves` to `[0, 16]`: `HlslSourceCompatibilityTests`'s bit-parity + oracle drives every mirrored `int` parameter across the full int32 range, + which is the right domain for `pcg3d`/`pcg4d`'s O(1) hash inputs but would + turn an unclamped octave count into a multi-billion-iteration loop for these + two mirrors. + Integer hashing uses the PCG hashes from Jarzynski and Olano, "Hash Functions for GPU Rendering" (JCGT 9(3), 2020): `pcg(uint)` is O'Neill's RXS-M-XS 32/32 permutation over one LCG step, and `pcg3d`/`pcg4d` are the paper's (3 → 3) and From 256f8e20be690b55b88ebee97c54023ae6f8a379 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 26 Sep 2026 02:54:17 +0200 Subject: [PATCH 04/10] tests: cover snoise_grad, fbm_grad, ridged_grad mirrors in HLSL compat test Adds explicit function-presence assertions and bumps the reflective bit-parity oracle's expected mirror count from 30 to 33 now that the three new cultmath_ mirrors are covered automatically. Co-Authored-By: Claude Opus 5.5 --- .../tests/CultMath.Tests/HlslSourceCompatibilityTests.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs b/packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs index fb269ee2..be8a3df4 100644 --- a/packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs +++ b/packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs @@ -27,6 +27,9 @@ public sealed class HlslSourceCompatibilityTests Assert.NotNull(ShaderFunction(shader, "cultmath_value_noise_bicubic", typeof(float2))); Assert.NotNull(ShaderFunction(shader, "cultmath_smin_grad", typeof(float4), typeof(float4), typeof(float))); Assert.NotNull(ShaderFunction(shader, "cultmath_cellular", typeof(float3))); + Assert.NotNull(ShaderFunction(shader, "cultmath_snoise_grad", typeof(float3))); + Assert.NotNull(ShaderFunction(shader, "cultmath_fbm_grad", typeof(float3), typeof(int), typeof(float), typeof(float))); + Assert.NotNull(ShaderFunction(shader, "cultmath_ridged_grad", typeof(float3), typeof(int), typeof(float), typeof(float))); } // HLSL functions carry no access modifier, so they compile as private instance methods. @@ -127,7 +130,7 @@ public sealed class HlslSourceCompatibilityTests } Assert.True(mismatches.Count == 0, $"{mismatches.Count} mismatches:{Environment.NewLine}{string.Join(Environment.NewLine, mismatches.Take(12))}"); - Assert.Equal(30, compared.Count); + Assert.Equal(33, compared.Count); } /// From bbf00394deb09fcc9dacd96ec98581268d74cfd5 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 26 Sep 2026 02:54:17 +0200 Subject: [PATCH 05/10] tests: behavioural coverage for snoise_grad, fbm_grad, ridged_grad snoise_grad.w is bit-equal to snoise (stronger than the spec's 1e-6 floor, measured over 20,000 points). fbm_grad/ridged_grad with 1/3 octaves are pinned bit-exact against a closed form built with the same incremental gain/lacunarity multiply chain the production loop uses, catching both a swapped-argument mutant and an applied-once mutant. The shared invariant-8 property harness central-differences all three functions' own .w, filtering simplex-lattice seam flukes by comparing the estimate at two step sizes (measured tolerances and detection floor in the harness comment). A dedicated fixture bisects to a snoise zero crossing and pins that ridged_grad's two one-sided gradients there have opposite sign. Co-Authored-By: Claude Opus 5.5 --- .../tests/CultMath.Tests/NoiseGradTests.cs | 351 ++++++++++++++++++ 1 file changed, 351 insertions(+) create mode 100644 packages/cultmath/tests/CultMath.Tests/NoiseGradTests.cs diff --git a/packages/cultmath/tests/CultMath.Tests/NoiseGradTests.cs b/packages/cultmath/tests/CultMath.Tests/NoiseGradTests.cs new file mode 100644 index 00000000..e548c970 --- /dev/null +++ b/packages/cultmath/tests/CultMath.Tests/NoiseGradTests.cs @@ -0,0 +1,351 @@ +using System; +using CultMath; +using Xunit; + +namespace CultMath.Tests; + +public sealed class NoiseGradTests +{ + // ---- Invariant-8 property harness (shared by snoise_grad, fbm_grad, ridged_grad) ---- + // + // eps=0.0001f: a sweep at {0.001, 0.0005, 0.0002, 0.0001, 0.00005} against a self-consistency + // filter (below) found the clean central-difference error bottoming out at 0.0001 for all three + // functions (0.008 for snoise_grad, 0.034 for fbm_grad at 4 octaves, 0.107 for ridged_grad at 3 + // octaves), then rising again at 0.00005 as float32 rounding noise starts to dominate: this is + // the same "eps too large -> curvature error, eps too small -> rounding noise" shape as + // CellularAndSminGradTests, just with the sweet spot an order of magnitude smaller than + // cellular's 0.0005f, because snoise's simplex lattice has real curvature at a finer length + // scale than cellular's Euclidean distance field. Each tolerance below keeps roughly 4-5x + // headroom over its own measured clean floor (Hands, cut 2a-ii-a, seeds 0xA11CE/0xA11CF/0xA11D0, + // 50,000-80,000 samples in [-3, 3]^3 per function). + // + // Self-consistency filter: snoise_grad's simplex lattice has internal corner-selection + // boundaries (where two of x0's components tie) that are exactly smooth in real arithmetic but, + // at specific eps values, a float32-precision coincidence can put one of the two central- + // difference sample points close enough to such a boundary to spike the finite-difference + // estimate by orders of magnitude (confirmed by hand: at one such point central differences at + // eps=1e-5 and 1e-6 agreed with the analytic gradient to within noise, while eps=1e-4 alone was + // off by 8+, i.e. a fluke tied to that one step size, not a real gradient error). Comparing the + // central difference at eps against the same estimate at 4*eps and skipping the point when they + // disagree by more than consistencyThreshold catches these flukes without needing an analytic + // description of every lattice seam (cellular's F1=F2 seam has one; the simplex lattice's + // corner-tie seams do not have as clean a closed form here). This plays the same role as + // cellular's F1=F2/F2=F3 band exclusion in CellularAndSminGradTests. + private const float PropertyEps = 0.0001f; + private const float PropertyCoarseEps = PropertyEps * 4.0f; + private const float ConsistencyThreshold = 0.02f; + private const float SnoiseGradTolerance = 0.04f; + private const float FbmGradTolerance = 0.15f; + private const float RidgedGradTolerance = 0.5f; + + // Detection floor (Hands, cut 2a-ii-a, snoise_grad harness, 1000 clean points, seed 0xDE7EC7, + // PropertyEps/SnoiseGradTolerance above): a uniform multiplicative scale on the returned gradient + // is caught at 1.01x, survives at 1.005x; a uniform additive offset is caught at 0.035, survives + // at 0.03. fbm_grad and ridged_grad share the same central-difference harness and per-octave + // scaling by snoise_grad's gradient, so a mutant of the same shape in either is caught at a + // similar or tighter scale (their tolerances have comparable headroom over their own floors). + [Fact] + public void SnoiseGradGradientMatchesCentralDifferencesOfItsOwnValue() + { + var random = new System.Random(0xA11CE); + var tested = 0; + var attempts = 0; + while (tested < 200 && attempts < 20000) + { + attempts++; + var p = RandomPoint(random); + var g = math.snoise_grad(p); + float F(float3 q) => math.snoise_grad(q).w; + var fine = CentralDifference(F, p, PropertyEps); + var coarse = CentralDifference(F, p, PropertyCoarseEps); + if (ChebyshevDistance(fine, coarse) > ConsistencyThreshold) + continue; + + tested++; + AssertGradientWithinTolerance(fine, g, SnoiseGradTolerance); + } + + Assert.True(tested >= 150, $"only {tested} of {attempts} points were clean of a lattice seam"); + } + + [Fact] + public void FbmGradGradientMatchesCentralDifferencesOfItsOwnValue() + { + const int octaves = 4; + const float lacunarity = 2.0f; + const float gain = 0.5f; + var random = new System.Random(0xA11CF); + var tested = 0; + var attempts = 0; + while (tested < 200 && attempts < 40000) + { + attempts++; + var p = RandomPoint(random); + var g = math.fbm_grad(p, octaves, lacunarity, gain); + float F(float3 q) => math.fbm_grad(q, octaves, lacunarity, gain).w; + var fine = CentralDifference(F, p, PropertyEps); + var coarse = CentralDifference(F, p, PropertyCoarseEps); + if (ChebyshevDistance(fine, coarse) > ConsistencyThreshold) + continue; + + tested++; + AssertGradientWithinTolerance(fine, g, FbmGradTolerance); + } + + Assert.True(tested >= 150, $"only {tested} of {attempts} points were clean of a lattice seam"); + } + + [Fact] + public void RidgedGradGradientMatchesCentralDifferencesExcludingAnyOctavesZeroBand() + { + // ridged_grad's own crease (any octave's n_i = 0) is a real, deliberate discontinuity + // (design.md, "the operator's dune term"), not a numerical artifact: exclude a band around it + // for every octave, the same way cellular excludes its F1 = F2 seam. + const float zeroBand = 0.1f; + const int octaves = 3; + const float lacunarity = 2.0f; + const float gain = 0.5f; + var random = new System.Random(0xA11D0); + var tested = 0; + var attempts = 0; + while (tested < 200 && attempts < 80000) + { + attempts++; + var p = RandomPoint(random); + if (AnyOctaveNearZero(p, octaves, lacunarity, zeroBand)) + continue; + + var g = math.ridged_grad(p, octaves, lacunarity, gain); + float F(float3 q) => math.ridged_grad(q, octaves, lacunarity, gain).w; + var fine = CentralDifference(F, p, PropertyEps); + var coarse = CentralDifference(F, p, PropertyCoarseEps); + if (ChebyshevDistance(fine, coarse) > ConsistencyThreshold) + continue; + + tested++; + AssertGradientWithinTolerance(fine, g, RidgedGradTolerance); + } + + Assert.True(tested >= 150, $"only {tested} of {attempts} points were clean of a zero band or lattice seam"); + } + + private static bool AnyOctaveNearZero(float3 p, int octaves, float lacunarity, float band) + { + var frequency = 1.0f; + for (var i = 0; i < octaves; i++) + { + if (MathF.Abs(math.snoise_grad(p * frequency).w) < band) + return true; + frequency *= lacunarity; + } + + return false; + } + + private static float3 RandomPoint(System.Random random) => new( + random.NextSingle() * 6.0f - 3.0f, random.NextSingle() * 6.0f - 3.0f, random.NextSingle() * 6.0f - 3.0f); + + private static float3 CentralDifference(Func f, float3 p, float eps) => new( + (f(p + new float3(eps, 0.0f, 0.0f)) - f(p - new float3(eps, 0.0f, 0.0f))) / (2.0f * eps), + (f(p + new float3(0.0f, eps, 0.0f)) - f(p - new float3(0.0f, eps, 0.0f))) / (2.0f * eps), + (f(p + new float3(0.0f, 0.0f, eps)) - f(p - new float3(0.0f, 0.0f, eps))) / (2.0f * eps)); + + private static double ChebyshevDistance(float3 a, float3 b) => + Math.Max(Math.Abs(a.x - b.x), Math.Max(Math.Abs(a.y - b.y), Math.Abs(a.z - b.z))); + + private static void AssertGradientWithinTolerance(float3 numeric, float4 analytic, float tolerance) + { + AssertWithinTolerance(numeric.x, analytic.x, tolerance); + AssertWithinTolerance(numeric.y, analytic.y, tolerance); + AssertWithinTolerance(numeric.z, analytic.z, tolerance); + } + + private static void AssertWithinTolerance(float expected, float actual, float tolerance) => + Assert.True(MathF.Abs(expected - actual) <= tolerance, $"expected {expected}, actual {actual}, tolerance {tolerance}"); + + // ---- snoise_grad.w vs snoise ---- + + [Fact] + public void SnoiseGradValueIsBitEqualToSnoise() + { + // Both compute 42 * dot(m4, px) via the exact same operation order (math.cs comment on + // snoise_grad); measured bit-equal on 20,000 random points in [-100, 100]^3 (Hands, cut + // 2a-ii-a, seed 0x50F2, maxDiff 0), so this asserts the stronger bit-exact claim rather than + // only the spec's 1e-6 floor. + var random = new System.Random(0x50F2); + for (var i = 0; i < 5000; i++) + { + var p = new float3( + random.NextSingle() * 200.0f - 100.0f, random.NextSingle() * 200.0f - 100.0f, random.NextSingle() * 200.0f - 100.0f); + var expected = math.snoise(p); + var actual = math.snoise_grad(p).w; + Assert.Equal(BitConverter.SingleToInt32Bits(expected), BitConverter.SingleToInt32Bits(actual)); + } + } + + // ---- fbm_grad / ridged_grad: per-octave gain and lacunarity ---- + + [Fact] + public void FbmGradWithOneOctaveEqualsSnoiseGrad() + { + var random = new System.Random(0xF6B10); + for (var i = 0; i < 64; i++) + { + var p = RandomPoint(random); + var lacunarity = 1.0f + random.NextSingle() * 3.0f; + var gain = 0.1f + random.NextSingle() * 0.8f; + + var expected = math.snoise_grad(p); + var actual = math.fbm_grad(p, 1, lacunarity, gain); + + Assert.Equal(expected.x, actual.x); + Assert.Equal(expected.y, actual.y); + Assert.Equal(expected.z, actual.z); + Assert.Equal(expected.w, actual.w); + } + } + + [Fact] + public void FbmGradCompoundsGainAndLacunarityPerOctaveNotOnce() + { + // Falsifies two mutant shapes at once: applying gain/lacunarity once for the whole sum + // instead of compounding per octave, and swapping which argument drives amplitude versus + // frequency. lacunarity != gain and both != 1 so a swap changes the result, and 3 octaves + // gives amplitude/frequency three distinct compounded values (1, gain, gain^2 and + // 1, lacunarity, lacunarity^2) so "applied once" mutants cannot coincidentally match. + // The expected value is built by the same incremental multiply chain fbm_grad itself uses + // (frequency *= lacunarity, amplitude *= gain, one step at a time, not lacunarity*lacunarity + // or MathF.Pow), so this asserts bit-exact equality rather than needing a tolerance. + const float lacunarity = 2.5f; + const float gain = 0.6f; + var random = new System.Random(0xF6B11); + for (var i = 0; i < 32; i++) + { + var p = RandomPoint(random); + + var frequency = 1.0f; + var amplitude = 1.0f; + var n0 = math.snoise_grad(p * frequency); + var expectedValue = amplitude * n0.w; + var expectedGradient = amplitude * frequency * new float3(n0.x, n0.y, n0.z); + frequency *= lacunarity; + amplitude *= gain; + + var n1 = math.snoise_grad(p * frequency); + expectedValue += amplitude * n1.w; + expectedGradient += amplitude * frequency * new float3(n1.x, n1.y, n1.z); + frequency *= lacunarity; + amplitude *= gain; + + var n2 = math.snoise_grad(p * frequency); + expectedValue += amplitude * n2.w; + expectedGradient += amplitude * frequency * new float3(n2.x, n2.y, n2.z); + + var actual = math.fbm_grad(p, 3, lacunarity, gain); + + Assert.Equal(expectedValue, actual.w); + Assert.Equal(expectedGradient.x, actual.x); + Assert.Equal(expectedGradient.y, actual.y); + Assert.Equal(expectedGradient.z, actual.z); + } + } + + [Fact] + public void RidgedGradCompoundsGainAndLacunarityPerOctaveNotOnce() + { + // Same construction as FbmGradCompoundsGainAndLacunarityPerOctaveNotOnce, folded: value is + // Sum a_i*(1-|n_i|), gradient is -Sum a_i*f_i*sign(n_i)*grad(n_i) (math.cs comment on + // ridged_grad). p is offset away from the origin and re-tried on a near-zero octave so no + // octave's n_i lands in the fold's own zero band, which would make the closed form's sign() + // ambiguous between runs. + const float lacunarity = 2.5f; + const float gain = 0.6f; + var random = new System.Random(0xF6B12); + var tested = 0; + while (tested < 32) + { + var p = RandomPoint(random); + if (AnyOctaveNearZero(p, 3, lacunarity, 0.1f)) + continue; + tested++; + + var frequency = 1.0f; + var amplitude = 1.0f; + var n0 = math.snoise_grad(p * frequency); + var s0 = (float)MathF.Sign(n0.w); + var expectedValue = amplitude * (1.0f - MathF.Abs(n0.w)); + var expectedGradient = -amplitude * frequency * s0 * new float3(n0.x, n0.y, n0.z); + frequency *= lacunarity; + amplitude *= gain; + + var n1 = math.snoise_grad(p * frequency); + var s1 = (float)MathF.Sign(n1.w); + expectedValue += amplitude * (1.0f - MathF.Abs(n1.w)); + expectedGradient += -amplitude * frequency * s1 * new float3(n1.x, n1.y, n1.z); + frequency *= lacunarity; + amplitude *= gain; + + var n2 = math.snoise_grad(p * frequency); + var s2 = (float)MathF.Sign(n2.w); + expectedValue += amplitude * (1.0f - MathF.Abs(n2.w)); + expectedGradient += -amplitude * frequency * s2 * new float3(n2.x, n2.y, n2.z); + + var actual = math.ridged_grad(p, 3, lacunarity, gain); + + Assert.Equal(expectedValue, actual.w); + Assert.Equal(expectedGradient.x, actual.x); + Assert.Equal(expectedGradient.y, actual.y); + Assert.Equal(expectedGradient.z, actual.z); + } + } + + // ---- ridged_grad's deliberate crease at n = 0 ---- + + [Fact] + public void RidgedGradOneSidedGradientsAcrossAZeroCrossingDifferInSign() + { + // 1 octave: ridged_grad(p) = 1 - |snoise(p)|, gradient = -sign(snoise(p)) * grad(snoise)(p). + // Bisect along a fixed direction from a random start point to find a tight straddle of a + // snoise zero crossing, then check the two ridged_grad gradients just either side of it point + // in near-opposite directions (their dot product is negative): the crease is real, not a + // numerical accident (design.md, "the operator's dune term"). + var random = new System.Random(0xC2E55); + for (var attempt = 0; attempt < 200; attempt++) + { + var origin = RandomPoint(random); + var direction = new float3(random.NextSingle() - 0.5f, random.NextSingle() - 0.5f, random.NextSingle() - 0.5f); + if (math.length(direction) < 1.0e-3f) + continue; + + float NoiseAt(float t) => math.snoise(origin + direction * t); + + var lo = -3.0f; + var hi = 3.0f; + if (Math.Sign(NoiseAt(lo)) == Math.Sign(NoiseAt(hi))) + continue; + + for (var step = 0; step < 40; step++) + { + var mid = (lo + hi) * 0.5f; + if (Math.Sign(NoiseAt(lo)) == Math.Sign(NoiseAt(mid))) lo = mid; else hi = mid; + } + + // lo and hi now straddle the crossing within about 3 * 2^-40 of parameter t; step off by + // a small margin either side so each sample is cleanly on one side, not exactly on it. + const float margin = 1.0e-4f; + var minusSide = origin + direction * (lo - margin); + var plusSide = origin + direction * (hi + margin); + if (MathF.Sign(NoiseAt(lo - margin)) == MathF.Sign(NoiseAt(hi + margin))) + continue; // margin stepped back across the crossing; try another direction. + + var gradMinus = math.ridged_grad(minusSide, 1, 2.0f, 0.5f); + var gradPlus = math.ridged_grad(plusSide, 1, 2.0f, 0.5f); + var dot = gradMinus.x * gradPlus.x + gradMinus.y * gradPlus.y + gradMinus.z * gradPlus.z; + + Assert.True(dot < 0.0f, $"one-sided gradients did not differ in sign: minus=({gradMinus.x},{gradMinus.y},{gradMinus.z}) plus=({gradPlus.x},{gradPlus.y},{gradPlus.z}) dot={dot}"); + return; + } + + Assert.Fail("did not find a snoise zero crossing to straddle"); + } +} From c9dabbeef6b6c02b5609e2fa3a22a1ec32452068 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 26 Sep 2026 03:05:08 +0200 Subject: [PATCH 06/10] cultmath: fix stale test-name references in snoise_grad/fbm_grad/ridged_grad comments The doc comments named test classes/methods (SnoiseGradTests, FbmGradTests, RidgedGradTests) that were never committed under those names; the actual coverage lives in NoiseGradTests. Point the comments at the real methods. Co-Authored-By: Claude Opus 5.5 --- packages/cultmath/src/CultMath/math.cs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/cultmath/src/CultMath/math.cs b/packages/cultmath/src/CultMath/math.cs index 168868c6..380267c8 100644 --- a/packages/cultmath/src/CultMath/math.cs +++ b/packages/cultmath/src/CultMath/math.cs @@ -701,8 +701,9 @@ public static partial class math // mod289((34x+1)x) and scale 42 (Ashima's alternate, second-order-artifact-reduced noise3D.glsl // constants, already load-bearing here and pinned by the existing snoise tests): every local up // through p0..p3 and x0..x3 below is snoise(float3)'s own derivation verbatim, unchanged, so .w - // stays that same field (SnoiseGradTests pins the two within 1e-6 and reports whether they are - // bit-equal). The differentiation itself carries over unchanged from upstream, because it never + // stays that same field (NoiseGradTests.SnoiseGradValueIsBitEqualToSnoise pins the two bit-equal + // over a random sweep, stronger than the spec's 1e-6 floor). The differentiation itself carries + // over unchanged from upstream, because it never // depends on the threshold or permutation constants: per corner, m0 = max(radius - dot(x,x), 0), // so dm0/dx = -2x, and d(m0^4 * dot(p,x))/dx = 4*m0^3*(-2x)*dot(p,x) + m0^4*p // = -8*m0^3*dot(p,x)*x + m0^4*p (p is that corner's own gradient constant, independent of x, so @@ -774,10 +775,10 @@ public static partial class math // running frequency, so by the chain rule its gradient scales by that same frequency // (d/dp[n(f*p)] = f * grad_n(f*p)); amplitude and frequency both compound per octave (gain, // lacunarity respectively), not applied once for the whole sum, so with 1 octave this is exactly - // snoise_grad (FbmGradTests). octaves is clamped to [0, 16]: HlslSourceCompatibilityTests' - // bit-parity oracle drives every mirrored int parameter across the full int32 range, which is - // the right domain for pcg3d/pcg4d's O(1) hash inputs but would turn an unclamped octave count - // into a multi-billion-iteration loop for this mirror. + // snoise_grad (NoiseGradTests.FbmGradWithOneOctaveEqualsSnoiseGrad). octaves is clamped to + // [0, 16]: HlslSourceCompatibilityTests' bit-parity oracle drives every mirrored int parameter + // across the full int32 range, which is the right domain for pcg3d/pcg4d's O(1) hash inputs but + // would turn an unclamped octave count into a multi-billion-iteration loop for this mirror. public static float4 fbm_grad(float3 p, int octaves, float lacunarity, float gain) { octaves = clamp(octaves, 0, 16); @@ -801,7 +802,7 @@ public static partial class math // 2026-09-25): each octave folds snoise_grad about zero, value = Sum a_i*(1 - |n_i|), gradient = // -Sum a_i*f_i*sign(n_i)*grad(n_i), the same per-octave frequency scaling as fbm_grad's chain // rule plus the fold's sign flip (d|n|/dp = sign(n)*dn/dp). The crease at n_i = 0 is real and - // deliberate, not a bug: RidgedGradTests exclude a band around it, the same way cellular excludes + // deliberate, not a bug: NoiseGradTests excludes a band around it, the same way cellular excludes // its F1 = F2 seam. sign follows this codebase's HLSL-matching convention (design.md: sign // returns int, 0 at exactly 0), so the crease itself contributes no gradient rather than an // arbitrary one. Same octave clamp as fbm_grad, for the same bit-parity-oracle reason. From 4ca1cf388adbd3dfdefb17a58c0932f841265efb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 11:10:18 +0200 Subject: [PATCH 07/10] CultMath: continuity probe for snoise across simplex-cell boundaries (red on the 0.6 kernel) Co-Authored-By: Claude Sonnet 5 --- .../tests/CultMath.Tests/NoiseGradTests.cs | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/packages/cultmath/tests/CultMath.Tests/NoiseGradTests.cs b/packages/cultmath/tests/CultMath.Tests/NoiseGradTests.cs index e548c970..e12cdfe0 100644 --- a/packages/cultmath/tests/CultMath.Tests/NoiseGradTests.cs +++ b/packages/cultmath/tests/CultMath.Tests/NoiseGradTests.cs @@ -163,6 +163,70 @@ public sealed class NoiseGradTests private static void AssertWithinTolerance(float expected, float actual, float tolerance) => Assert.True(MathF.Abs(expected - actual) <= tolerance, $"expected {expected}, actual {actual}, tolerance {tolerance}"); + // ---- snoise is continuous across simplex-cell boundaries ---- + + // The simplex corner set (i, i1, i2) summed by snoise(float3), derived the same way snoise does. + private static (float3 i, float3 i1, float3 i2) SimplexCell(float3 p) + { + var i = math.floor(p + math.dot(p, new float3(1.0f / 3.0f, 1.0f / 3.0f, 1.0f / 3.0f))); + var x0 = p - i + math.dot(i, new float3(1.0f / 6.0f, 1.0f / 6.0f, 1.0f / 6.0f)); + var g = math.step(new float3(x0.y, x0.z, x0.x), x0); + var l = 1.0f - g; + var lzxy = new float3(l.z, l.x, l.y); + return (i, math.min(g, lzxy), math.max(g, lzxy)); + } + + [Fact] + public void SnoiseAndItsGradientAreContinuousAcrossSimplexCellBoundaries() + { + // March random lines in steps of 1e-3 until the corner set changes, bisect the crossing to + // float precision, and compare the two sides. With a kernel radius^2 above 0.5 a lattice + // vertex outside the four summed corners can lie inside the kernel, which leaves a value + // jump at the boundary (stegu/webgl-noise fixed it in 21d9fe23d7); at 0.5 the jump is float + // noise. A value jump below 1e-5 and a gradient jump below 1e-4 is float noise on both sides. + const int lines = 400; + const int maxSteps = 20000; + const float dt = 1.0e-3f; + var random = new System.Random(0x5EA4); + var crossings = 0; + var maxValueJump = 0.0f; + var maxGradientJump = 0.0f; + for (var line = 0; line < lines; line++) + { + var origin = RandomPoint(random); + var direction = math.normalize(new float3( + random.NextSingle() - 0.5f, random.NextSingle() - 0.5f, random.NextSingle() - 0.5f)); + var start = SimplexCell(origin); + var t = 0.0f; + var found = false; + for (var step = 0; step < maxSteps && !found; step++) + { + t += dt; + found = !SimplexCell(origin + direction * t).Equals(start); + } + + Assert.True(found, $"line {line} never left its simplex cell in {maxSteps} steps"); + + double lo = t - dt; + double hi = t; + for (var bisect = 0; bisect < 60; bisect++) + { + var mid = 0.5 * (lo + hi); + if (SimplexCell(origin + direction * (float)mid).Equals(start)) lo = mid; else hi = mid; + } + + var a = math.snoise_grad(origin + direction * (float)lo); + var b = math.snoise_grad(origin + direction * (float)hi); + crossings++; + maxValueJump = MathF.Max(maxValueJump, MathF.Abs(a.w - b.w)); + maxGradientJump = MathF.Max(maxGradientJump, MathF.Max(MathF.Abs(a.x - b.x), MathF.Max(MathF.Abs(a.y - b.y), MathF.Abs(a.z - b.z)))); + } + + Assert.Equal(lines, crossings); + Assert.True(maxValueJump < 1.0e-5f, $"value jump {maxValueJump} across a simplex boundary"); + Assert.True(maxGradientJump < 1.0e-4f, $"gradient jump {maxGradientJump} across a simplex boundary"); + } + // ---- snoise_grad.w vs snoise ---- [Fact] From 8703b44636d1de6ca86a0df2c7f3cb6e5a1db335 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 11:13:34 +0200 Subject: [PATCH 08/10] CultMath: snoise(float3) takes the upstream simplex-boundary fix Kernel radius^2 0.6 -> 0.5, scale 42 -> 105, permute (34x+1)x -> (34x+10)x, per stegu/webgl-noise 22434e04d7 (fix 21d9fe23d7, scale ff3b5d34ea, permute a3e6d57095). snoise_grad, fbm_grad, ridged_grad follow. C#, both HLSL copies, design.md and THIRD-PARTY-NOTICES.md change together. The 2D snoise shares the permute helper, so its values change too. Golden values are regenerated in the next commit. Co-Authored-By: Claude Sonnet 5 --- packages/cultmath/THIRD-PARTY-NOTICES.md | 10 +++-- packages/cultmath/docs/design.md | 24 +++++++--- packages/cultmath/shaders/CultMath.hlsl | 25 +++++------ packages/cultmath/src/CultMath/math.cs | 44 +++++++++---------- .../Shaders/CultMath.hlsl | 25 +++++------ .../THIRD-PARTY-NOTICES.md | 10 +++-- 6 files changed, 75 insertions(+), 63 deletions(-) diff --git a/packages/cultmath/THIRD-PARTY-NOTICES.md b/packages/cultmath/THIRD-PARTY-NOTICES.md index 2b4f2acd..1de744a7 100644 --- a/packages/cultmath/THIRD-PARTY-NOTICES.md +++ b/packages/cultmath/THIRD-PARTY-NOTICES.md @@ -6,11 +6,15 @@ simplex-noise functions by Ian McEwan and Ashima Arts, as distributed by Stefan Gustavson's `webgl-noise` project and Unity Mathematics. +`math.snoise(float3)` and `cultmath_snoise(float3)` follow `src/noise3D.glsl` and +`math.snoise(float2)` follows `src/noise2D.glsl` of stegu/webgl-noise at commit +`22434e04d7753f7e949e8d724ab3da2864c17a0f` (the simplex-boundary fix is +`21d9fe23d7`, scale `ff3b5d34ea`, permutation `a3e6d57095`). + `math.snoise_grad`/`cultmath_snoise_grad` (and the `fbm_grad`/`ridged_grad` octave sums built on them) follow the analytic-gradient differentiation from -the same project's `src/noise3Dgrad.glsl`, retargeted onto this file's own -`snoise(float3)` falloff radius, permutation, and scale constants (see the -`math.snoise_grad` doc comment). +the same project's `src/noise3Dgrad.glsl`, with the same kernel radius, +permutation and scale as `snoise(float3)`. - Copyright 2011 Ashima Arts. - Upstream: diff --git a/packages/cultmath/docs/design.md b/packages/cultmath/docs/design.md index 408a49a3..e14927fe 100644 --- a/packages/cultmath/docs/design.md +++ b/packages/cultmath/docs/design.md @@ -233,15 +233,25 @@ together, laid out as `float4(gradient.xyz, value.w)`, with no value-only twin paths are proven bit-identical (`PrunedSearchIsBitIdenticalToTheUnprunedFiveCubedSearch`, which samples `[-50, 50]^3`, is comfortably inside that domain). +- `snoise(float3)` follows webgl-noise `src/noise3D.glsl` as of + stegu/webgl-noise `22434e04d7`: kernel radius squared `0.5`, output scale + `105`, permutation `mod289((34x+10)x)`. Upstream's `21d9fe23d7` (2020-10-14, + "an age-old bug that caused slight discontinuities along simplex + boundaries") moved the radius from `0.6` to `0.5`; at `0.6` a lattice vertex + outside the four summed corners can lie inside the kernel, leaving a value + jump at the cell boundary (3.1e-3 over the committed probe's 400 lines). `ff3b5d34ea` set the scale + to `105` and `a3e6d57095` (2021-06-30) the permutation; the 2D `snoise` shares + that permutation helper, so its values changed too, while its own kernel + (`0.5`) and scale (`130`) already matched upstream. + `NoiseGradTests.SnoiseAndItsGradientAreContinuousAcrossSimplexCellBoundaries` + pins the continuity. - `snoise_grad(float3 p)` carries `snoise(float3)` to value-and-gradient form, following the differentiation in webgl-noise `src/noise3Dgrad.glsl` (Ashima - Arts / Ian McEwan, MIT) but retargeted onto `snoise(float3)`'s own falloff - radius (`0.6`), permutation (`mod289((34x+1)x)`), and scale (`42`) rather - than upstream's `0.5`/`mod289((34x+10)x)`/`105`: the differentiation itself - does not depend on those constants (per corner, `m0 = max(radius - - dot(x,x), 0)`, so `d(m0^4 * dot(p,x))/dx = -8*m0^3*dot(p,x)*x + m0^4*p`, - summed over the four corners and scaled by the same constant as the value), - so `.w` stays exactly `snoise(float3)`'s own field. `fbm_grad` and + Arts / Ian McEwan, MIT), which uses the same radius, permutation and scale as + `snoise(float3)`: per corner, `m0 = max(0.5 - dot(x,x), 0)`, so + `d(m0^4 * dot(p,x))/dx = -8*m0^3*dot(p,x)*x + m0^4*p`, summed over the four + corners and scaled by the same constant as the value, so `.w` is exactly + `snoise(float3)`. `fbm_grad` and `ridged_grad` are octave sums of `snoise_grad`: each octave samples at `p * frequency`, so by the chain rule its gradient scales by that same frequency, and both amplitude (`gain`) and frequency (`lacunarity`) compound diff --git a/packages/cultmath/shaders/CultMath.hlsl b/packages/cultmath/shaders/CultMath.hlsl index b7cb69ca..50c5a746 100644 --- a/packages/cultmath/shaders/CultMath.hlsl +++ b/packages/cultmath/shaders/CultMath.hlsl @@ -76,8 +76,8 @@ float cultmath_smootherstep(float value) float2 cultmath_snoise_mod289(float2 value) { return value - floor(value * (1.0 / 289.0)) * 289.0; } float3 cultmath_snoise_mod289(float3 value) { return value - floor(value * (1.0 / 289.0)) * 289.0; } float4 cultmath_snoise_mod289(float4 value) { return value - floor(value * (1.0 / 289.0)) * 289.0; } -float3 cultmath_snoise_permute(float3 value) { return cultmath_snoise_mod289(((value * 34.0) + 1.0) * value); } -float4 cultmath_snoise_permute(float4 value) { return cultmath_snoise_mod289(((value * 34.0) + 1.0) * value); } +float3 cultmath_snoise_permute(float3 value) { return cultmath_snoise_mod289(((value * 34.0) + 10.0) * value); } +float4 cultmath_snoise_permute(float4 value) { return cultmath_snoise_mod289(((value * 34.0) + 10.0) * value); } // Ashima Arts / Ian McEwan 3D simplex noise (MIT), same float32 evaluation // order as the C# math.snoise(float3) mirror. @@ -125,9 +125,9 @@ float cultmath_snoise(float3 value) p2 *= norm.z; p3 *= norm.w; - float4 m = max(0.6 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); + float4 m = max(0.5 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); m = m * m; - return 42.0 * dot(m * m, float4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3))); + return 105.0 * dot(m * m, float4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3))); } float cultmath_snoise(float2 value) @@ -162,12 +162,11 @@ float cultmath_snoise(float2 value) return 130.0 * dot(m, g); } -// Ashima Arts / Ian McEwan 3D simplex noise with analytic gradient (invariant 8), following the -// differentiation in webgl-noise src/noise3Dgrad.glsl (Ashima Arts / McEwan, MIT; confirmed at -// stegu/webgl-noise today), retargeted onto cultmath_snoise(float3)'s own constants (0.6 falloff -// radius, permute(x) = mod289((34x+1)x), scale 42; see the C# math.snoise_grad comment for the full -// derivation and why the differentiation itself is unaffected by that retargeting). Every local up -// through p0..p3 and x0..x3 is cultmath_snoise(float3)'s own derivation verbatim. +// Analytic gradient of cultmath_snoise(float3) (invariant 8), following webgl-noise +// src/noise3Dgrad.glsl (Ashima Arts / McEwan, MIT); same kernel, permutation and scale as +// cultmath_snoise(float3) (stegu/webgl-noise 22434e04d7). See the C# math.snoise_grad comment for the +// derivation. Every local up through p0..p3 and x0..x3 is cultmath_snoise(float3)'s own derivation +// verbatim. float4 cultmath_snoise_grad(float3 value) { float2 c = float2(1.0 / 6.0, 1.0 / 3.0); @@ -212,18 +211,18 @@ float4 cultmath_snoise_grad(float3 value) p2 *= norm.z; p3 *= norm.w; - float4 m0 = max(0.6 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); + float4 m0 = max(0.5 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); float4 m2 = m0 * m0; float4 m3 = m2 * m0; float4 m4 = m2 * m2; float4 px = float4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)); - float value2 = 42.0 * dot(m4, px); + float value2 = 105.0 * dot(m4, px); float3 grad = -8.0 * m3.x * x0 * px.x + m4.x * p0 + -8.0 * m3.y * x1 * px.y + m4.y * p1 + -8.0 * m3.z * x2 * px.z + m4.z * p2 + -8.0 * m3.w * x3 * px.w + m4.w * p3; - grad *= 42.0; + grad *= 105.0; return float4(grad, value2); } diff --git a/packages/cultmath/src/CultMath/math.cs b/packages/cultmath/src/CultMath/math.cs index 380267c8..23916b6b 100644 --- a/packages/cultmath/src/CultMath/math.cs +++ b/packages/cultmath/src/CultMath/math.cs @@ -595,7 +595,10 @@ public static partial class math } // Ashima Arts / Ian McEwan 3D simplex noise (MIT), mirrored by cultmath_snoise(float3) - // in shaders/CultMath.hlsl with the same float32 evaluation order. + // in shaders/CultMath.hlsl with the same float32 evaluation order. Follows stegu/webgl-noise + // src/noise3D.glsl at 22434e04d7 (kernel radius^2 0.5, scale 105, permute (34x+10)x); see + // THIRD-PARTY-NOTICES.md. Continuous across simplex-cell boundaries + // (NoiseGradTests.SnoiseAndItsGradientAreContinuousAcrossSimplexCellBoundaries). public static float snoise(float3 value) { const float cx = 1.0f / 6.0f; @@ -642,9 +645,9 @@ public static partial class math p2 *= norm.z; p3 *= norm.w; - var m = max(0.6f - new float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0f); + var m = max(0.5f - new float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0f); m = m * m; - return 42.0f * dot(m * m, new float4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3))); + return 105.0f * dot(m * m, new float4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3))); } // Ashima Arts / Ian McEwan 2D simplex noise, kept component-explicit so @@ -690,25 +693,18 @@ public static partial class math private static float2 snoise_mod289(float2 value) => value - floor(value * (1.0f / 289.0f)) * 289.0f; private static float3 snoise_mod289(float3 value) => value - floor(value * (1.0f / 289.0f)) * 289.0f; private static float4 snoise_mod289(float4 value) => value - floor(value * (1.0f / 289.0f)) * 289.0f; - private static float3 snoise_permute(float3 value) => snoise_mod289(((value * 34.0f) + 1.0f) * value); - private static float4 snoise_permute(float4 value) => snoise_mod289(((value * 34.0f) + 1.0f) * value); + private static float3 snoise_permute(float3 value) => snoise_mod289(((value * 34.0f) + 10.0f) * value); + private static float4 snoise_permute(float4 value) => snoise_mod289(((value * 34.0f) + 10.0f) * value); - // Ashima Arts / Ian McEwan 3D simplex noise with analytic gradient (invariant 8), following the - // differentiation in webgl-noise src/noise3Dgrad.glsl (Ashima Arts / McEwan, MIT; confirmed at - // stegu/webgl-noise today), retargeted onto THIS file's own snoise(float3) constants: upstream's - // noise3Dgrad.glsl uses a 0.5 falloff radius, permute(x) = mod289((34x+10)x) and an overall scale - // of 105, while this repo's existing snoise(float3) (and cultmath_snoise) use 0.6, permute(x) = - // mod289((34x+1)x) and scale 42 (Ashima's alternate, second-order-artifact-reduced noise3D.glsl - // constants, already load-bearing here and pinned by the existing snoise tests): every local up - // through p0..p3 and x0..x3 below is snoise(float3)'s own derivation verbatim, unchanged, so .w - // stays that same field (NoiseGradTests.SnoiseGradValueIsBitEqualToSnoise pins the two bit-equal - // over a random sweep, stronger than the spec's 1e-6 floor). The differentiation itself carries - // over unchanged from upstream, because it never - // depends on the threshold or permutation constants: per corner, m0 = max(radius - dot(x,x), 0), - // so dm0/dx = -2x, and d(m0^4 * dot(p,x))/dx = 4*m0^3*(-2x)*dot(p,x) + m0^4*p - // = -8*m0^3*dot(p,x)*x + m0^4*p (p is that corner's own gradient constant, independent of x, so - // only the dot(p,x) factor contributes there); summed over the four corners and scaled by the - // same 42 as the value. + // Analytic gradient of snoise(float3) (invariant 8), following the differentiation in + // webgl-noise src/noise3Dgrad.glsl (Ashima Arts / McEwan, MIT), which uses the same kernel + // radius^2 0.5, permutation (34x+10)x and scale 105 as snoise(float3) (stegu/webgl-noise + // 22434e04d7). Every local up through p0..p3 and x0..x3 below is snoise(float3)'s own derivation + // verbatim, so .w is that same field (NoiseGradTests.SnoiseGradValueIsBitEqualToSnoise pins the + // two bit-equal over a random sweep). Per corner, m0 = max(0.5 - dot(x,x), 0), so dm0/dx = -2x, + // and d(m0^4 * dot(p,x))/dx = 4*m0^3*(-2x)*dot(p,x) + m0^4*p = -8*m0^3*dot(p,x)*x + m0^4*p (p is + // that corner's own gradient constant, independent of x); summed over the four corners and + // scaled by the same 105 as the value. public static float4 snoise_grad(float3 value) { const float cx = 1.0f / 6.0f; @@ -755,18 +751,18 @@ public static partial class math p2 *= norm.z; p3 *= norm.w; - var m0 = max(0.6f - new float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0f); + var m0 = max(0.5f - new float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0f); var m2 = m0 * m0; var m3 = m2 * m0; var m4 = m2 * m2; var px = new float4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)); - var value2 = 42.0f * dot(m4, px); + var value2 = 105.0f * dot(m4, px); var grad = -8.0f * m3.x * x0 * px.x + m4.x * p0 + -8.0f * m3.y * x1 * px.y + m4.y * p1 + -8.0f * m3.z * x2 * px.z + m4.z * p2 + -8.0f * m3.w * x3 * px.w + m4.w * p3; - grad *= 42.0f; + grad *= 105.0f; return new float4(grad, value2); } diff --git a/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.hlsl b/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.hlsl index b7cb69ca..50c5a746 100644 --- a/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.hlsl +++ b/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.hlsl @@ -76,8 +76,8 @@ float cultmath_smootherstep(float value) float2 cultmath_snoise_mod289(float2 value) { return value - floor(value * (1.0 / 289.0)) * 289.0; } float3 cultmath_snoise_mod289(float3 value) { return value - floor(value * (1.0 / 289.0)) * 289.0; } float4 cultmath_snoise_mod289(float4 value) { return value - floor(value * (1.0 / 289.0)) * 289.0; } -float3 cultmath_snoise_permute(float3 value) { return cultmath_snoise_mod289(((value * 34.0) + 1.0) * value); } -float4 cultmath_snoise_permute(float4 value) { return cultmath_snoise_mod289(((value * 34.0) + 1.0) * value); } +float3 cultmath_snoise_permute(float3 value) { return cultmath_snoise_mod289(((value * 34.0) + 10.0) * value); } +float4 cultmath_snoise_permute(float4 value) { return cultmath_snoise_mod289(((value * 34.0) + 10.0) * value); } // Ashima Arts / Ian McEwan 3D simplex noise (MIT), same float32 evaluation // order as the C# math.snoise(float3) mirror. @@ -125,9 +125,9 @@ float cultmath_snoise(float3 value) p2 *= norm.z; p3 *= norm.w; - float4 m = max(0.6 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); + float4 m = max(0.5 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); m = m * m; - return 42.0 * dot(m * m, float4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3))); + return 105.0 * dot(m * m, float4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3))); } float cultmath_snoise(float2 value) @@ -162,12 +162,11 @@ float cultmath_snoise(float2 value) return 130.0 * dot(m, g); } -// Ashima Arts / Ian McEwan 3D simplex noise with analytic gradient (invariant 8), following the -// differentiation in webgl-noise src/noise3Dgrad.glsl (Ashima Arts / McEwan, MIT; confirmed at -// stegu/webgl-noise today), retargeted onto cultmath_snoise(float3)'s own constants (0.6 falloff -// radius, permute(x) = mod289((34x+1)x), scale 42; see the C# math.snoise_grad comment for the full -// derivation and why the differentiation itself is unaffected by that retargeting). Every local up -// through p0..p3 and x0..x3 is cultmath_snoise(float3)'s own derivation verbatim. +// Analytic gradient of cultmath_snoise(float3) (invariant 8), following webgl-noise +// src/noise3Dgrad.glsl (Ashima Arts / McEwan, MIT); same kernel, permutation and scale as +// cultmath_snoise(float3) (stegu/webgl-noise 22434e04d7). See the C# math.snoise_grad comment for the +// derivation. Every local up through p0..p3 and x0..x3 is cultmath_snoise(float3)'s own derivation +// verbatim. float4 cultmath_snoise_grad(float3 value) { float2 c = float2(1.0 / 6.0, 1.0 / 3.0); @@ -212,18 +211,18 @@ float4 cultmath_snoise_grad(float3 value) p2 *= norm.z; p3 *= norm.w; - float4 m0 = max(0.6 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); + float4 m0 = max(0.5 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); float4 m2 = m0 * m0; float4 m3 = m2 * m0; float4 m4 = m2 * m2; float4 px = float4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)); - float value2 = 42.0 * dot(m4, px); + float value2 = 105.0 * dot(m4, px); float3 grad = -8.0 * m3.x * x0 * px.x + m4.x * p0 + -8.0 * m3.y * x1 * px.y + m4.y * p1 + -8.0 * m3.z * x2 * px.z + m4.z * p2 + -8.0 * m3.w * x3 * px.w + m4.w * p3; - grad *= 42.0; + grad *= 105.0; return float4(grad, value2); } diff --git a/packages/cultmath/unity/org.gamecult.cultmath/THIRD-PARTY-NOTICES.md b/packages/cultmath/unity/org.gamecult.cultmath/THIRD-PARTY-NOTICES.md index 2b4f2acd..1de744a7 100644 --- a/packages/cultmath/unity/org.gamecult.cultmath/THIRD-PARTY-NOTICES.md +++ b/packages/cultmath/unity/org.gamecult.cultmath/THIRD-PARTY-NOTICES.md @@ -6,11 +6,15 @@ simplex-noise functions by Ian McEwan and Ashima Arts, as distributed by Stefan Gustavson's `webgl-noise` project and Unity Mathematics. +`math.snoise(float3)` and `cultmath_snoise(float3)` follow `src/noise3D.glsl` and +`math.snoise(float2)` follows `src/noise2D.glsl` of stegu/webgl-noise at commit +`22434e04d7753f7e949e8d724ab3da2864c17a0f` (the simplex-boundary fix is +`21d9fe23d7`, scale `ff3b5d34ea`, permutation `a3e6d57095`). + `math.snoise_grad`/`cultmath_snoise_grad` (and the `fbm_grad`/`ridged_grad` octave sums built on them) follow the analytic-gradient differentiation from -the same project's `src/noise3Dgrad.glsl`, retargeted onto this file's own -`snoise(float3)` falloff radius, permutation, and scale constants (see the -`math.snoise_grad` doc comment). +the same project's `src/noise3Dgrad.glsl`, with the same kernel radius, +permutation and scale as `snoise(float3)`. - Copyright 2011 Ashima Arts. - Upstream: From 641041822d247a375cd7c3459f8d65bd94788bb4 Mon Sep 17 00:00:00 2001 From: x Date: Tue, 29 Sep 2026 12:04:08 +0200 Subject: [PATCH 09/10] CultMath: noise gradient tests carry only numbers the harness produces Drops the unreproducible floors and detection-scale claims, and the seam-fluke consistency filter (the spikes it hid were the snoise seam, now fixed and pinned by the continuity probe). Tightens the tolerances to at least 5x the harness maximum (ridged 0.5 -> 0.05), corrects the point count in the bit-equality test, and caps the ridged compounding loop so a mutant fails loudly instead of hanging. Co-Authored-By: Claude Sonnet 5 --- .../tests/CultMath.Tests/NoiseGradTests.cs | 73 +++++-------------- 1 file changed, 19 insertions(+), 54 deletions(-) diff --git a/packages/cultmath/tests/CultMath.Tests/NoiseGradTests.cs b/packages/cultmath/tests/CultMath.Tests/NoiseGradTests.cs index e12cdfe0..77ec4819 100644 --- a/packages/cultmath/tests/CultMath.Tests/NoiseGradTests.cs +++ b/packages/cultmath/tests/CultMath.Tests/NoiseGradTests.cs @@ -8,42 +8,17 @@ public sealed class NoiseGradTests { // ---- Invariant-8 property harness (shared by snoise_grad, fbm_grad, ridged_grad) ---- // - // eps=0.0001f: a sweep at {0.001, 0.0005, 0.0002, 0.0001, 0.00005} against a self-consistency - // filter (below) found the clean central-difference error bottoming out at 0.0001 for all three - // functions (0.008 for snoise_grad, 0.034 for fbm_grad at 4 octaves, 0.107 for ridged_grad at 3 - // octaves), then rising again at 0.00005 as float32 rounding noise starts to dominate: this is - // the same "eps too large -> curvature error, eps too small -> rounding noise" shape as - // CellularAndSminGradTests, just with the sweet spot an order of magnitude smaller than - // cellular's 0.0005f, because snoise's simplex lattice has real curvature at a finer length - // scale than cellular's Euclidean distance field. Each tolerance below keeps roughly 4-5x - // headroom over its own measured clean floor (Hands, cut 2a-ii-a, seeds 0xA11CE/0xA11CF/0xA11D0, - // 50,000-80,000 samples in [-3, 3]^3 per function). - // - // Self-consistency filter: snoise_grad's simplex lattice has internal corner-selection - // boundaries (where two of x0's components tie) that are exactly smooth in real arithmetic but, - // at specific eps values, a float32-precision coincidence can put one of the two central- - // difference sample points close enough to such a boundary to spike the finite-difference - // estimate by orders of magnitude (confirmed by hand: at one such point central differences at - // eps=1e-5 and 1e-6 agreed with the analytic gradient to within noise, while eps=1e-4 alone was - // off by 8+, i.e. a fluke tied to that one step size, not a real gradient error). Comparing the - // central difference at eps against the same estimate at 4*eps and skipping the point when they - // disagree by more than consistencyThreshold catches these flukes without needing an analytic - // description of every lattice seam (cellular's F1=F2 seam has one; the simplex lattice's - // corner-tie seams do not have as clean a closed form here). This plays the same role as - // cellular's F1=F2/F2=F3 band exclusion in CellularAndSminGradTests. + // Each test compares a function's analytic gradient with central differences of its own .w at + // random points in [-3, 3]^3. eps trades curvature error (eps too large) against float32 + // rounding noise (eps too small). snoise is continuous across simplex-cell boundaries (the + // continuity test below), so no point needs excluding for a seam; ridged_grad excludes a band + // around its own deliberate crease. Each tolerance is at least 5x the largest error the harness + // itself produces at its seed. private const float PropertyEps = 0.0001f; - private const float PropertyCoarseEps = PropertyEps * 4.0f; - private const float ConsistencyThreshold = 0.02f; - private const float SnoiseGradTolerance = 0.04f; - private const float FbmGradTolerance = 0.15f; - private const float RidgedGradTolerance = 0.5f; + private const float SnoiseGradTolerance = 0.03f; + private const float FbmGradTolerance = 0.05f; + private const float RidgedGradTolerance = 0.05f; - // Detection floor (Hands, cut 2a-ii-a, snoise_grad harness, 1000 clean points, seed 0xDE7EC7, - // PropertyEps/SnoiseGradTolerance above): a uniform multiplicative scale on the returned gradient - // is caught at 1.01x, survives at 1.005x; a uniform additive offset is caught at 0.035, survives - // at 0.03. fbm_grad and ridged_grad share the same central-difference harness and per-octave - // scaling by snoise_grad's gradient, so a mutant of the same shape in either is caught at a - // similar or tighter scale (their tolerances have comparable headroom over their own floors). [Fact] public void SnoiseGradGradientMatchesCentralDifferencesOfItsOwnValue() { @@ -57,15 +32,12 @@ public sealed class NoiseGradTests var g = math.snoise_grad(p); float F(float3 q) => math.snoise_grad(q).w; var fine = CentralDifference(F, p, PropertyEps); - var coarse = CentralDifference(F, p, PropertyCoarseEps); - if (ChebyshevDistance(fine, coarse) > ConsistencyThreshold) - continue; tested++; AssertGradientWithinTolerance(fine, g, SnoiseGradTolerance); } - Assert.True(tested >= 150, $"only {tested} of {attempts} points were clean of a lattice seam"); + Assert.True(tested >= 150, $"only {tested} of {attempts} points were usable"); } [Fact] @@ -84,15 +56,12 @@ public sealed class NoiseGradTests var g = math.fbm_grad(p, octaves, lacunarity, gain); float F(float3 q) => math.fbm_grad(q, octaves, lacunarity, gain).w; var fine = CentralDifference(F, p, PropertyEps); - var coarse = CentralDifference(F, p, PropertyCoarseEps); - if (ChebyshevDistance(fine, coarse) > ConsistencyThreshold) - continue; tested++; AssertGradientWithinTolerance(fine, g, FbmGradTolerance); } - Assert.True(tested >= 150, $"only {tested} of {attempts} points were clean of a lattice seam"); + Assert.True(tested >= 150, $"only {tested} of {attempts} points were usable"); } [Fact] @@ -118,15 +87,12 @@ public sealed class NoiseGradTests var g = math.ridged_grad(p, octaves, lacunarity, gain); float F(float3 q) => math.ridged_grad(q, octaves, lacunarity, gain).w; var fine = CentralDifference(F, p, PropertyEps); - var coarse = CentralDifference(F, p, PropertyCoarseEps); - if (ChebyshevDistance(fine, coarse) > ConsistencyThreshold) - continue; tested++; AssertGradientWithinTolerance(fine, g, RidgedGradTolerance); } - Assert.True(tested >= 150, $"only {tested} of {attempts} points were clean of a zero band or lattice seam"); + Assert.True(tested >= 150, $"only {tested} of {attempts} points were outside the zero band"); } private static bool AnyOctaveNearZero(float3 p, int octaves, float lacunarity, float band) @@ -150,9 +116,6 @@ public sealed class NoiseGradTests (f(p + new float3(0.0f, eps, 0.0f)) - f(p - new float3(0.0f, eps, 0.0f))) / (2.0f * eps), (f(p + new float3(0.0f, 0.0f, eps)) - f(p - new float3(0.0f, 0.0f, eps))) / (2.0f * eps)); - private static double ChebyshevDistance(float3 a, float3 b) => - Math.Max(Math.Abs(a.x - b.x), Math.Max(Math.Abs(a.y - b.y), Math.Abs(a.z - b.z))); - private static void AssertGradientWithinTolerance(float3 numeric, float4 analytic, float tolerance) { AssertWithinTolerance(numeric.x, analytic.x, tolerance); @@ -232,10 +195,8 @@ public sealed class NoiseGradTests [Fact] public void SnoiseGradValueIsBitEqualToSnoise() { - // Both compute 42 * dot(m4, px) via the exact same operation order (math.cs comment on - // snoise_grad); measured bit-equal on 20,000 random points in [-100, 100]^3 (Hands, cut - // 2a-ii-a, seed 0x50F2, maxDiff 0), so this asserts the stronger bit-exact claim rather than - // only the spec's 1e-6 floor. + // Both compute 105 * dot(m4, px) via the exact same operation order (math.cs comment on + // snoise_grad), so this asserts bit equality over 5,000 random points in [-100, 100]^3. var random = new System.Random(0x50F2); for (var i = 0; i < 5000; i++) { @@ -326,8 +287,10 @@ public sealed class NoiseGradTests const float gain = 0.6f; var random = new System.Random(0xF6B12); var tested = 0; - while (tested < 32) + var attempts = 0; + while (tested < 32 && attempts < 4000) { + attempts++; var p = RandomPoint(random); if (AnyOctaveNearZero(p, 3, lacunarity, 0.1f)) continue; @@ -361,6 +324,8 @@ public sealed class NoiseGradTests Assert.Equal(expectedGradient.y, actual.y); Assert.Equal(expectedGradient.z, actual.z); } + + Assert.True(tested == 32, $"only {tested} of {attempts} points were outside the zero band"); } // ---- ridged_grad's deliberate crease at n = 0 ---- From 0a5f4bf571dd0a0b73950be6345976eeeb2f6904 Mon Sep 17 00:00:00 2001 From: x Date: Tue, 29 Sep 2026 12:09:43 +0200 Subject: [PATCH 10/10] CultMath: regenerate snoise golden values for the upstream kernel Seven values change: four snoise(float3) in HlslSemanticsTests and three snoise(float2) in MathTests (the 2D (0,0) golden is 0 either way). Regenerated from the code after the continuity probe passed. The tests no longer claim to match Unity.Mathematics, whose snoise keeps the old constants. Co-Authored-By: Claude Sonnet 5 --- .../tests/CultMath.Tests/HlslSemanticsTests.cs | 10 +++++----- packages/cultmath/tests/CultMath.Tests/MathTests.cs | 8 ++++---- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/cultmath/tests/CultMath.Tests/HlslSemanticsTests.cs b/packages/cultmath/tests/CultMath.Tests/HlslSemanticsTests.cs index 954c4375..c6bac266 100644 --- a/packages/cultmath/tests/CultMath.Tests/HlslSemanticsTests.cs +++ b/packages/cultmath/tests/CultMath.Tests/HlslSemanticsTests.cs @@ -444,11 +444,11 @@ public sealed class HlslSemanticsTests } [Theory] - [InlineData(0.0f, 0.0f, 0.0f, -0.41219875f)] - [InlineData(0.25f, -0.5f, 1.75f, 0.5250269f)] - [InlineData(12.25f, -4.5f, 3.125f, 0.008141451f)] - [InlineData(-7.3f, 2.9f, 101.4f, 0.578015f)] - public void Snoise3MatchesUnityMathematicsReference(float x, float y, float z, float expected) + [InlineData(0.0f, 0.0f, 0.0f, -0.435872972f)] + [InlineData(0.25f, -0.5f, 1.75f, 0.0492948629f)] + [InlineData(12.25f, -4.5f, 3.125f, 0.443114728f)] + [InlineData(-7.3f, 2.9f, 101.4f, -0.10221792f)] + public void Snoise3MatchesGoldenValues(float x, float y, float z, float expected) { Assert.Equal(expected, math.snoise(new float3(x, y, z)), precision: 5); } diff --git a/packages/cultmath/tests/CultMath.Tests/MathTests.cs b/packages/cultmath/tests/CultMath.Tests/MathTests.cs index b47a389e..3dc374bf 100644 --- a/packages/cultmath/tests/CultMath.Tests/MathTests.cs +++ b/packages/cultmath/tests/CultMath.Tests/MathTests.cs @@ -307,10 +307,10 @@ public sealed class MathTests [Theory] [InlineData(0.0f, 0.0f, 0.0f)] - [InlineData(0.25f, -0.5f, -0.425866783f)] - [InlineData(12.25f, -4.5f, 0.258312f)] - [InlineData(536.5106f, 536.5106f, -0.6901103f)] - public void SimplexNoiseMatchesUnityMathematics(float x, float y, float expected) + [InlineData(0.25f, -0.5f, 0.225074813f)] + [InlineData(12.25f, -4.5f, -0.388599217f)] + [InlineData(536.5106f, 536.5106f, 0.538390875f)] + public void SimplexNoiseMatchesGoldenValues(float x, float y, float expected) { Assert.Equal(expected, math.snoise(new float2(x, y)), precision: 6); }