diff --git a/packages/cultmath/shaders/CultMath.hlsl b/packages/cultmath/shaders/CultMath.hlsl
index 50c5a746..d0dd22ae 100644
--- a/packages/cultmath/shaders/CultMath.hlsl
+++ b/packages/cultmath/shaders/CultMath.hlsl
@@ -503,6 +503,92 @@ CultCellular cultmath_cellular(float3 p)
return result;
}
+// Invariant 8's struct return shape for cultmath_phacelle, compared field by field and bit for bit
+// against CultMath.CultPhasor, same field order.
+struct CultPhasor
+{
+ float4 cos;
+ float4 sin;
+};
+
+// Johansen's Phacelle noise on 3D cells. See math.phacelle's comment (math.cs) for the stripe wave
+// vector, the weight, the normalization, the exact gradient and why the prune is exact. Mirrors
+// the C# body operation for operation; the C#-only internal overload that switches the prune off
+// has no shader twin.
+CultPhasor cultmath_phacelle(float3 p, float3 side, float offset, float normalization)
+{
+ float3 cell = floor(p);
+ float3 local = p - cell;
+ float phaseOffset = offset * CULTMATH_TAU;
+ float sumW = 0.0;
+ float sumCos = 0.0;
+ float sumSin = 0.0;
+ float3 gradW = float3(0.0, 0.0, 0.0);
+ float3 gradCos = float3(0.0, 0.0, 0.0);
+ float3 gradSin = float3(0.0, 0.0, 0.0);
+
+ for (int dz = -1; dz <= 2; dz++)
+ {
+ float gz = max(0.0, abs(local.z - (float)dz) - 0.5);
+ for (int dy = -1; dy <= 2; dy++)
+ {
+ float gy = max(0.0, abs(local.y - (float)dy) - 0.5);
+ for (int dx = -1; dx <= 2; dx++)
+ {
+ float gx = max(0.0, abs(local.x - (float)dx) - 0.5);
+ if (gx * gx + gy * gy + gz * gz >= 2.25)
+ continue;
+
+ float3 gridStep = float3(dx, dy, dz);
+ int3 hash = cultmath_pcg3d(int3(cell + gridStep));
+ float3 jitter = float3(
+ ((uint)hash.x >> 8) * (1.0 / 16777216.0) - 0.5,
+ ((uint)hash.y >> 8) * (1.0 / 16777216.0) - 0.5,
+ ((uint)hash.z >> 8) * (1.0 / 16777216.0) - 0.5);
+ float3 v = local - gridStep - jitter;
+ float falloff = exp(-2.0 * dot(v, v));
+ float w = max(0.0, falloff - 0.01111);
+ float3 dw = w > 0.0 ? (-4.0 * falloff) * v : float3(0.0, 0.0, 0.0);
+ float phase = dot(v, side) + phaseOffset;
+ float c = cos(phase);
+ float s = sin(phase);
+
+ sumW += w;
+ sumCos += w * c;
+ sumSin += w * s;
+ gradW += dw;
+ gradCos += dw * c - (w * s) * side;
+ gradSin += dw * s + (w * c) * side;
+ }
+ }
+ }
+
+ float invW = 1.0 / sumW;
+ float rawCos = sumCos * invW;
+ float rawSin = sumSin * invW;
+ float3 gradRawCos = (gradCos - rawCos * gradW) * invW;
+ float3 gradRawSin = (gradSin - rawSin * gradW) * invW;
+ float rawLength = sqrt(rawCos * rawCos + rawSin * rawSin);
+ float floorLength = 1.0 - normalization;
+
+ CultPhasor result;
+ if (rawLength > floorLength)
+ {
+ float outCos = rawCos / rawLength;
+ float outSin = rawSin / rawLength;
+ float3 gradLength = (rawCos * gradRawCos + rawSin * gradRawSin) / rawLength;
+ result.cos = float4((gradRawCos - outCos * gradLength) / rawLength, outCos);
+ result.sin = float4((gradRawSin - outSin * gradLength) / rawLength, outSin);
+ }
+ else
+ {
+ result.cos = float4(gradRawCos / floorLength, rawCos / floorLength);
+ result.sin = float4(gradRawSin / floorLength, rawSin / floorLength);
+ }
+
+ return result;
+}
+
float cultmath_value_noise(float2 position)
{
float2 cell = floor(position);
diff --git a/packages/cultmath/src/CultMath/CultPhasor.cs b/packages/cultmath/src/CultMath/CultPhasor.cs
new file mode 100644
index 00000000..0a28faa8
--- /dev/null
+++ b/packages/cultmath/src/CultMath/CultPhasor.cs
@@ -0,0 +1,21 @@
+namespace CultMath;
+
+///
+/// The value-and-gradient result of
+/// (invariant 8's struct return shape). Both fields use the float4(gradient.xyz, value.w)
+/// layout of a bare value-and-gradient return.
+///
+public struct CultPhasor
+{
+ /// (∇cos, cos): the normalized cosine wave and its gradient.
+ public float4 cos;
+
+ /// (∇sin, sin): the normalized sine wave and its gradient.
+ public float4 sin;
+
+ public CultPhasor(float4 cos, float4 sin)
+ {
+ this.cos = cos;
+ this.sin = sin;
+ }
+}
diff --git a/packages/cultmath/src/CultMath/CultPhasor.cs.meta b/packages/cultmath/src/CultMath/CultPhasor.cs.meta
new file mode 100644
index 00000000..d586aa3f
--- /dev/null
+++ b/packages/cultmath/src/CultMath/CultPhasor.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 807ae2c8a758cf31896da12f1e5047bd
diff --git a/packages/cultmath/src/CultMath/math.cs b/packages/cultmath/src/CultMath/math.cs
index 23916b6b..430325ea 100644
--- a/packages/cultmath/src/CultMath/math.cs
+++ b/packages/cultmath/src/CultMath/math.cs
@@ -968,6 +968,104 @@ public static partial class math
// dxc and C#, bit-exact on both sides.
internal static float cellular_unit(int bits) => ((uint)bits >> 8) * (1.0f / 16777216.0f);
+ // Johansen's Phacelle noise (phase + cell), generalised to 3D cells with a caller-supplied
+ // stripe wave vector. Each of the 4x4x4 cells around p carries one jittered feature point
+ // (jitter in [-0.5, 0.5) per axis, from pcg3d over the integer cell coordinate, the same
+ // integer-hashing rule as cellular) and one cosine/sine wave that runs along `side` (the wave
+ // vector: its length is 2*pi times the stripe frequency, and the caller chooses which
+ // perpendicular it is; on a unit sphere that is cross(p_hat, flow)). The waves are blended with
+ // the bell weight max(0, exp(-2 d^2) - 0.01111) (exactly 0 at distance 1.5, the nearest a
+ // feature outside the 4x4x4 block can be in 2D, which is what keeps cell-grid lines out), and
+ // the blended phasor is normalized: its length is stretched to 1 wherever the raw length is at
+ // least 1 - normalization, and scaled by 1 / (1 - normalization) below that. `offset` is the
+ // phase in cycles (1 is a full turn). Value and normalization follow Johansen's
+ // PhacelleNoise as ported in lpmitchell/AdvancedTerrainErosion.
+ //
+ // The gradient is exact: it carries the weight derivative (grad w = -4 v exp(-2 |v|^2) where
+ // w > 0) and the normalization, not upstream's convention grad(cos) ~ -sin * side, which
+ // ignores the weight gradient (Asura probe: 16.8 deg off at the median, 97.8 at the 95th
+ // percentile; the exact form is 0.00 and 0.03). With P = sum(w * (cos, sin)) and W = sum(w),
+ // I = P / W has grad I = (grad P - I * grad W) / W; above the threshold the output is I / |I|
+ // with gradient (grad I - out * grad|I|) / |I|, below it grad I / (1 - normalization). The
+ // gradient is discontinuous where |I| crosses the threshold, and where a cell's weight leaves
+ // its support (distance 1.4998): there grad w jumps from -4 * 0.01111 * v (length about 0.067) to 0. The value is
+ // continuous at both.
+ //
+ // Pruning is exact: per axis, |local - g| - 0.5 (floored at 0) lower-bounds |v| for any jitter,
+ // so a cell whose summed square is at least 2.25 has weight exactly 0 (exp(-4.5) = 0.011109 <
+ // 0.01111) and contributes nothing to any sum. Only the internal overload can switch the prune
+ // off; PhacelleTests uses it to pin bit equality. About 14 of 64 cells survive on average.
+ public static CultPhasor phacelle(float3 p, float3 side, float offset, float normalization) =>
+ phacelle(p, side, offset, normalization, true);
+
+ internal static CultPhasor phacelle(float3 p, float3 side, float offset, float normalization, bool prune)
+ {
+ var cell = floor(p);
+ var local = p - cell;
+ var phaseOffset = offset * TAU;
+ var sumW = 0.0f;
+ var sumCos = 0.0f;
+ var sumSin = 0.0f;
+ var gradW = new float3(0.0f, 0.0f, 0.0f);
+ var gradCos = new float3(0.0f, 0.0f, 0.0f);
+ var gradSin = new float3(0.0f, 0.0f, 0.0f);
+
+ for (var dz = -1; dz <= 2; dz++)
+ {
+ var gz = max(0.0f, abs(local.z - (float)dz) - 0.5f);
+ for (var dy = -1; dy <= 2; dy++)
+ {
+ var gy = max(0.0f, abs(local.y - (float)dy) - 0.5f);
+ for (var dx = -1; dx <= 2; dx++)
+ {
+ var gx = max(0.0f, abs(local.x - (float)dx) - 0.5f);
+ if (prune && gx * gx + gy * gy + gz * gz >= 2.25f)
+ continue;
+
+ var gridStep = new float3(dx, dy, dz);
+ var hash = pcg3d(int3(cell + gridStep));
+ var jitter = new float3(cellular_unit(hash.x) - 0.5f, cellular_unit(hash.y) - 0.5f, cellular_unit(hash.z) - 0.5f);
+ var v = local - gridStep - jitter;
+ var falloff = exp(-2.0f * dot(v, v));
+ var w = max(0.0f, falloff - 0.01111f);
+ var dw = w > 0.0f ? (-4.0f * falloff) * v : new float3(0.0f, 0.0f, 0.0f);
+ var phase = dot(v, side) + phaseOffset;
+ var c = cos(phase);
+ var s = sin(phase);
+
+ sumW += w;
+ sumCos += w * c;
+ sumSin += w * s;
+ gradW += dw;
+ gradCos += dw * c - (w * s) * side;
+ gradSin += dw * s + (w * c) * side;
+ }
+ }
+ }
+
+ var invW = 1.0f / sumW;
+ var rawCos = sumCos * invW;
+ var rawSin = sumSin * invW;
+ var gradRawCos = (gradCos - rawCos * gradW) * invW;
+ var gradRawSin = (gradSin - rawSin * gradW) * invW;
+ var rawLength = sqrt(rawCos * rawCos + rawSin * rawSin);
+ var floorLength = 1.0f - normalization;
+
+ if (rawLength > floorLength)
+ {
+ var outCos = rawCos / rawLength;
+ var outSin = rawSin / rawLength;
+ var gradLength = (rawCos * gradRawCos + rawSin * gradRawSin) / rawLength;
+ return new CultPhasor(
+ new float4((gradRawCos - outCos * gradLength) / rawLength, outCos),
+ new float4((gradRawSin - outSin * gradLength) / rawLength, outSin));
+ }
+
+ return new CultPhasor(
+ new float4(gradRawCos / floorLength, rawCos / floorLength),
+ new float4(gradRawSin / floorLength, rawSin / floorLength));
+ }
+
public static float value_noise(float2 position)
{
var cell = floor(position);
diff --git a/packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs b/packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs
index be8a3df4..ad690759 100644
--- a/packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs
+++ b/packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs
@@ -30,6 +30,7 @@ public sealed class HlslSourceCompatibilityTests
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)));
+ Assert.NotNull(ShaderFunction(shader, "cultmath_phacelle", typeof(float3), typeof(float3), typeof(float), typeof(float)));
}
// HLSL functions carry no access modifier, so they compile as private instance methods.
@@ -130,7 +131,7 @@ public sealed class HlslSourceCompatibilityTests
}
Assert.True(mismatches.Count == 0, $"{mismatches.Count} mismatches:{Environment.NewLine}{string.Join(Environment.NewLine, mismatches.Take(12))}");
- Assert.Equal(33, compared.Count);
+ Assert.Equal(34, compared.Count);
}
///
diff --git a/packages/cultmath/tests/CultMath.Tests/PhacelleTests.cs b/packages/cultmath/tests/CultMath.Tests/PhacelleTests.cs
new file mode 100644
index 00000000..15d1a89a
--- /dev/null
+++ b/packages/cultmath/tests/CultMath.Tests/PhacelleTests.cs
@@ -0,0 +1,275 @@
+using System;
+using CultMath;
+using Xunit;
+
+namespace CultMath.Tests;
+
+public sealed class PhacelleTests
+{
+ // Every tolerance below is at least 5x the largest error the same test measures at its seed.
+ private const float GradientEps = 1.0e-3f;
+ private const float GradientTolerance = 5.0e-3f;
+ private const double ValueTolerance = 1.6e-5;
+ private const double ThresholdBand = 0.02;
+
+ private static float3 RandomPoint(System.Random random, float extent = 3.0f) => new(
+ (random.NextSingle() * 2.0f - 1.0f) * extent, (random.NextSingle() * 2.0f - 1.0f) * extent, (random.NextSingle() * 2.0f - 1.0f) * extent);
+
+ // A wave vector of length 2*pi times a stripe frequency in [0.5, 1.5], in a random direction.
+ private static float3 RandomSide(System.Random random)
+ {
+ float3 direction;
+ do
+ {
+ direction = new float3(random.NextSingle() - 0.5f, random.NextSingle() - 0.5f, random.NextSingle() - 0.5f);
+ }
+ while (math.length(direction) < 0.1f);
+
+ return math.normalize(direction) * (math.TAU * (0.5f + random.NextSingle()));
+ }
+
+ // ---- An independent double-precision evaluation: all 64 cells, no prune, no gradient. ----
+ //
+ // It shares only the hash (pcg3d over the integer cell coordinate, top 24 bits) and the constants
+ // the function is specified by: weight max(0, exp(-2 d^2) - 0.01111), jitter in [-0.5, 0.5).
+
+ private readonly record struct Reference(double Cos, double Sin, double RawLength, double SupportEdgeGap);
+
+ private static Reference Evaluate(float3 p, float3 side, float offset, float normalization)
+ {
+ double fx = Math.Floor(p.x), fy = Math.Floor(p.y), fz = Math.Floor(p.z);
+ double lx = p.x - fx, ly = p.y - fy, lz = p.z - fz;
+ double sumW = 0.0, sumCos = 0.0, sumSin = 0.0, edgeGap = double.MaxValue;
+ var supportRadius = Math.Sqrt(Math.Log(1.0 / 0.01111) / 2.0);
+ for (var dz = -1; dz <= 2; dz++)
+ for (var dy = -1; dy <= 2; dy++)
+ for (var dx = -1; dx <= 2; dx++)
+ {
+ var hash = math.pcg3d(new int3((int)fx + dx, (int)fy + dy, (int)fz + dz));
+ double vx = lx - dx - (math.cellular_unit(hash.x) - 0.5);
+ double vy = ly - dy - (math.cellular_unit(hash.y) - 0.5);
+ double vz = lz - dz - (math.cellular_unit(hash.z) - 0.5);
+ var d2 = vx * vx + vy * vy + vz * vz;
+ edgeGap = Math.Min(edgeGap, Math.Abs(Math.Sqrt(d2) - supportRadius));
+ var w = Math.Max(0.0, Math.Exp(-2.0 * d2) - 0.01111);
+ var phase = vx * side.x + vy * side.y + vz * side.z + (double)offset * math.TAU;
+ sumW += w;
+ sumCos += w * Math.Cos(phase);
+ sumSin += w * Math.Sin(phase);
+ }
+
+ double rawCos = sumCos / sumW, rawSin = sumSin / sumW;
+ var raw = Math.Sqrt(rawCos * rawCos + rawSin * rawSin);
+ var length = Math.Max(1.0 - normalization, raw);
+ return new Reference(rawCos / length, rawSin / length, raw, edgeGap);
+ }
+
+ 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 float MaxComponentError(float3 numeric, float4 analytic) => MathF.Max(
+ MathF.Abs(numeric.x - analytic.x), MathF.Max(MathF.Abs(numeric.y - analytic.y), MathF.Abs(numeric.z - analytic.z)));
+
+ // ---- Value: the function is Johansen's, on 3D cells ----
+
+ [Theory]
+ [InlineData(0.0f)]
+ [InlineData(0.5f)]
+ [InlineData(0.9f)]
+ [InlineData(1.0f)]
+ public void ValueMatchesTheIndependentReferenceAndNormalizesAboveTheThreshold(float normalization)
+ {
+ var random = new System.Random(0x7ACE1 + (int)(normalization * 10.0f));
+ var maxError = 0.0;
+ var above = 0;
+ var below = 0;
+ for (var i = 0; i < 3000; i++)
+ {
+ var p = RandomPoint(random, 40.0f);
+ var side = RandomSide(random);
+ var offset = random.NextSingle();
+ var actual = math.phacelle(p, side, offset, normalization);
+ var expected = Evaluate(p, side, offset, normalization);
+
+ maxError = Math.Max(maxError, Math.Max(Math.Abs(actual.cos.w - expected.Cos), Math.Abs(actual.sin.w - expected.Sin)));
+ if (expected.RawLength >= 1.0 - normalization + ThresholdBand)
+ {
+ // The output magnitude is 1 wherever the raw magnitude reaches 1 - normalization.
+ above++;
+ var magnitude = Math.Sqrt((double)actual.cos.w * actual.cos.w + (double)actual.sin.w * actual.sin.w);
+ Assert.True(Math.Abs(magnitude - 1.0) < ValueTolerance, $"magnitude {magnitude} above the threshold at {p}");
+ }
+ else if (expected.RawLength <= 1.0 - normalization - ThresholdBand)
+ {
+ below++;
+ }
+ }
+
+ Assert.True(maxError < ValueTolerance, $"max value error against the reference {maxError}");
+ if (normalization > 0.0f)
+ Assert.True(above >= 500, $"only {above} points above the threshold");
+ if (normalization is > 0.0f and < 1.0f)
+ Assert.True(below >= 50, $"only {below} points below the threshold");
+ }
+
+ [Fact]
+ public void ValueIsPeriodicInOffsetAndAQuarterCycleRotatesCosIntoSin()
+ {
+ // offset is in cycles: a quarter turn maps cos to -sin and sin to cos, and a whole turn is the
+ // identity. The weights and the normalization do not depend on the phase, so this is exact
+ // up to float rounding.
+ var random = new System.Random(0x7ACE2);
+ for (var i = 0; i < 200; i++)
+ {
+ var p = RandomPoint(random);
+ var side = RandomSide(random);
+ var offset = random.NextSingle();
+ var basePhasor = math.phacelle(p, side, offset, 0.5f);
+ var quarter = math.phacelle(p, side, offset + 0.25f, 0.5f);
+ var whole = math.phacelle(p, side, offset + 1.0f, 0.5f);
+
+ Assert.True(MathF.Abs(quarter.cos.w + basePhasor.sin.w) < 2.0e-5f);
+ Assert.True(MathF.Abs(quarter.sin.w - basePhasor.cos.w) < 2.0e-5f);
+ Assert.True(MathF.Abs(whole.cos.w - basePhasor.cos.w) < 2.0e-5f);
+ Assert.True(MathF.Abs(whole.sin.w - basePhasor.sin.w) < 2.0e-5f);
+ }
+ }
+
+ // ---- Invariant 8: the gradient is exact ----
+
+ [Fact]
+ public void GradientOfCosAndSinMatchesCentralDifferencesOnBothSidesOfTheNormalizationThreshold()
+ {
+ // Above the threshold the output is I / |I|; below it, I / (1 - normalization). The gradient
+ // is discontinuous where |I| crosses the threshold, and at the edge of each cell's weight support
+ // (distance 1.4998, where max(0, ...) starts: a jump of about 4 d 0.01111 in grad w), so a band
+ // around each is excluded (by the
+ // reference's raw length, since the output alone cannot say how close it is).
+ const float normalization = 0.5f;
+ var random = new System.Random(0x7ACE3);
+ var above = 0;
+ var below = 0;
+ var maxError = 0.0f;
+ for (var attempts = 0; attempts < 20000 && (above < 150 || below < 150); attempts++)
+ {
+ var p = RandomPoint(random);
+ var side = RandomSide(random);
+ var offset = random.NextSingle();
+ var reference = Evaluate(p, side, offset, normalization);
+ var distance = reference.RawLength - (1.0 - normalization);
+ if (Math.Abs(distance) < ThresholdBand || reference.SupportEdgeGap < 3.0 * GradientEps)
+ continue;
+ if (distance > 0.0 ? above >= 150 : below >= 150)
+ continue;
+ if (distance > 0.0) above++; else below++;
+
+ var analytic = math.phacelle(p, side, offset, normalization);
+ var numericCos = CentralDifference(q => math.phacelle(q, side, offset, normalization).cos.w, p, GradientEps);
+ var numericSin = CentralDifference(q => math.phacelle(q, side, offset, normalization).sin.w, p, GradientEps);
+ maxError = MathF.Max(maxError, MathF.Max(MaxComponentError(numericCos, analytic.cos), MaxComponentError(numericSin, analytic.sin)));
+ }
+
+ Assert.True(above >= 150 && below >= 150, $"{above} points above and {below} below the threshold");
+ Assert.True(maxError < GradientTolerance, $"max gradient error against central differences {maxError}");
+ }
+
+ // ---- Stripes run along the flow ----
+
+ [Fact]
+ public void OnTheUnitSphereStripesRunAlongTheFlow()
+ {
+ // side = cross(p_hat, flow) * 2*pi is tangent to the sphere and perpendicular to the flow, so the
+ // cosine should change across the stripes (along side) and hardly at all along them (along
+ // flow). Asura's probe measured 0.212 for this ratio, against 0.202 for the planar upstream.
+ const float radiusInCells = 10.0f;
+ var random = new System.Random(0x7ACE4);
+ var reference = math.normalize(new float3(0.3f, 0.5f, 0.8f));
+ var alongFlow = 0.0;
+ var acrossFlow = 0.0;
+ var used = 0;
+ while (used < 2000)
+ {
+ var hat = math.normalize(new float3(random.NextSingle() - 0.5f, random.NextSingle() - 0.5f, random.NextSingle() - 0.5f));
+ var tangent = reference - hat * math.dot(hat, reference);
+ if (math.length(tangent) < 0.2f)
+ continue;
+
+ var flow = math.normalize(tangent);
+ var sideDirection = math.cross(hat, flow);
+ var phasor = math.phacelle(hat * radiusInCells, sideDirection * math.TAU, 0.25f, 0.5f);
+ var gradient = new float3(phasor.cos.x, phasor.cos.y, phasor.cos.z);
+ alongFlow += Math.Abs(math.dot(gradient, flow));
+ acrossFlow += Math.Abs(math.dot(gradient, sideDirection));
+ used++;
+ }
+
+ var ratio = alongFlow / acrossFlow;
+ Assert.True(ratio <= 0.25, $"mean|d cos/d flow| / mean|d cos/d side| = {ratio}");
+ }
+
+ // ---- Continuity ----
+
+ [Fact]
+ public void ValueStepDifferenceShrinksTenfoldPerTenfoldStepIncludingAcrossCellPlanes()
+ {
+ // Pairs straddle an integer plane on each axis (where the 4x4x4 window moves by one cell and a
+ // weight that did not vanish at the window edge would jump) and also start at random points.
+ // Lipschitz continuity means the largest difference over a step scales with the step.
+ var random = new System.Random(0x7ACE5);
+ var steps = new[] { 1.0e-3f, 1.0e-4f, 1.0e-5f };
+ var maxDifference = new float[steps.Length];
+ for (var i = 0; i < 3000; i++)
+ {
+ var p = RandomPoint(random);
+ var side = RandomSide(random);
+ var offset = random.NextSingle();
+ var axis = i % 3;
+ if (i % 2 == 0)
+ p = SetAxis(p, axis, MathF.Round(GetAxis(p, axis)));
+ for (var k = 0; k < steps.Length; k++)
+ {
+ var low = math.phacelle(SetAxis(p, axis, GetAxis(p, axis) - steps[k] * 0.5f), side, offset, 0.5f);
+ var high = math.phacelle(SetAxis(p, axis, GetAxis(p, axis) + steps[k] * 0.5f), side, offset, 0.5f);
+ maxDifference[k] = MathF.Max(maxDifference[k], MathF.Max(MathF.Abs(low.cos.w - high.cos.w), MathF.Abs(low.sin.w - high.sin.w)));
+ }
+ }
+
+ Assert.True(maxDifference[1] * 8.0f <= maxDifference[0], $"1e-3: {maxDifference[0]}, 1e-4: {maxDifference[1]}");
+ Assert.True(maxDifference[2] * 8.0f <= maxDifference[1], $"1e-4: {maxDifference[1]}, 1e-5: {maxDifference[2]}");
+ }
+
+ private static float GetAxis(float3 v, int axis) => axis == 0 ? v.x : axis == 1 ? v.y : v.z;
+
+ private static float3 SetAxis(float3 v, int axis, float value) =>
+ axis == 0 ? new float3(value, v.y, v.z) : axis == 1 ? new float3(v.x, value, v.z) : new float3(v.x, v.y, value);
+
+ // ---- Exact pruning ----
+
+ [Fact]
+ public void PrunedOutputIsBitEqualToTheUnprunedSum()
+ {
+ var random = new System.Random(0x7ACE6);
+ for (var i = 0; i < 20000; i++)
+ {
+ var p = RandomPoint(random, 50.0f);
+ var side = RandomSide(random);
+ var offset = random.NextSingle();
+ var normalization = random.NextSingle();
+ var pruned = math.phacelle(p, side, offset, normalization);
+ var unpruned = math.phacelle(p, side, offset, normalization, false);
+
+ AssertBitEqual(unpruned.cos, pruned.cos);
+ AssertBitEqual(unpruned.sin, pruned.sin);
+ }
+ }
+
+ private static void AssertBitEqual(float4 expected, float4 actual)
+ {
+ Assert.Equal(BitConverter.SingleToInt32Bits(expected.x), BitConverter.SingleToInt32Bits(actual.x));
+ Assert.Equal(BitConverter.SingleToInt32Bits(expected.y), BitConverter.SingleToInt32Bits(actual.y));
+ Assert.Equal(BitConverter.SingleToInt32Bits(expected.z), BitConverter.SingleToInt32Bits(actual.z));
+ Assert.Equal(BitConverter.SingleToInt32Bits(expected.w), BitConverter.SingleToInt32Bits(actual.w));
+ }
+}
diff --git a/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.hlsl b/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.hlsl
index 50c5a746..d0dd22ae 100644
--- a/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.hlsl
+++ b/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.hlsl
@@ -503,6 +503,92 @@ CultCellular cultmath_cellular(float3 p)
return result;
}
+// Invariant 8's struct return shape for cultmath_phacelle, compared field by field and bit for bit
+// against CultMath.CultPhasor, same field order.
+struct CultPhasor
+{
+ float4 cos;
+ float4 sin;
+};
+
+// Johansen's Phacelle noise on 3D cells. See math.phacelle's comment (math.cs) for the stripe wave
+// vector, the weight, the normalization, the exact gradient and why the prune is exact. Mirrors
+// the C# body operation for operation; the C#-only internal overload that switches the prune off
+// has no shader twin.
+CultPhasor cultmath_phacelle(float3 p, float3 side, float offset, float normalization)
+{
+ float3 cell = floor(p);
+ float3 local = p - cell;
+ float phaseOffset = offset * CULTMATH_TAU;
+ float sumW = 0.0;
+ float sumCos = 0.0;
+ float sumSin = 0.0;
+ float3 gradW = float3(0.0, 0.0, 0.0);
+ float3 gradCos = float3(0.0, 0.0, 0.0);
+ float3 gradSin = float3(0.0, 0.0, 0.0);
+
+ for (int dz = -1; dz <= 2; dz++)
+ {
+ float gz = max(0.0, abs(local.z - (float)dz) - 0.5);
+ for (int dy = -1; dy <= 2; dy++)
+ {
+ float gy = max(0.0, abs(local.y - (float)dy) - 0.5);
+ for (int dx = -1; dx <= 2; dx++)
+ {
+ float gx = max(0.0, abs(local.x - (float)dx) - 0.5);
+ if (gx * gx + gy * gy + gz * gz >= 2.25)
+ continue;
+
+ float3 gridStep = float3(dx, dy, dz);
+ int3 hash = cultmath_pcg3d(int3(cell + gridStep));
+ float3 jitter = float3(
+ ((uint)hash.x >> 8) * (1.0 / 16777216.0) - 0.5,
+ ((uint)hash.y >> 8) * (1.0 / 16777216.0) - 0.5,
+ ((uint)hash.z >> 8) * (1.0 / 16777216.0) - 0.5);
+ float3 v = local - gridStep - jitter;
+ float falloff = exp(-2.0 * dot(v, v));
+ float w = max(0.0, falloff - 0.01111);
+ float3 dw = w > 0.0 ? (-4.0 * falloff) * v : float3(0.0, 0.0, 0.0);
+ float phase = dot(v, side) + phaseOffset;
+ float c = cos(phase);
+ float s = sin(phase);
+
+ sumW += w;
+ sumCos += w * c;
+ sumSin += w * s;
+ gradW += dw;
+ gradCos += dw * c - (w * s) * side;
+ gradSin += dw * s + (w * c) * side;
+ }
+ }
+ }
+
+ float invW = 1.0 / sumW;
+ float rawCos = sumCos * invW;
+ float rawSin = sumSin * invW;
+ float3 gradRawCos = (gradCos - rawCos * gradW) * invW;
+ float3 gradRawSin = (gradSin - rawSin * gradW) * invW;
+ float rawLength = sqrt(rawCos * rawCos + rawSin * rawSin);
+ float floorLength = 1.0 - normalization;
+
+ CultPhasor result;
+ if (rawLength > floorLength)
+ {
+ float outCos = rawCos / rawLength;
+ float outSin = rawSin / rawLength;
+ float3 gradLength = (rawCos * gradRawCos + rawSin * gradRawSin) / rawLength;
+ result.cos = float4((gradRawCos - outCos * gradLength) / rawLength, outCos);
+ result.sin = float4((gradRawSin - outSin * gradLength) / rawLength, outSin);
+ }
+ else
+ {
+ result.cos = float4(gradRawCos / floorLength, rawCos / floorLength);
+ result.sin = float4(gradRawSin / floorLength, rawSin / floorLength);
+ }
+
+ return result;
+}
+
float cultmath_value_noise(float2 position)
{
float2 cell = floor(position);