Research: variable-length shader inputs (array+count vs macro vs constants), for shader-lattice-loop; map section shader-lattice-loop

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-17 15:55:03 +02:00
commit 3cd6815575
12 changed files with 395 additions and 0 deletions

View file

@ -0,0 +1,15 @@
// Probe C: a compute entry passing a constant-buffer array, and one passing a StructuredBuffer copied to a local array.
#include "lattice-array.hlsl"
cbuffer Zone : register(b0) { float4 zoneBodies[CULTMATH_MAX_SITES]; int zoneCount; };
StructuredBuffer<float4> bufferBodies : register(t1);
RWStructuredBuffer<float4> result : register(u2);
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID)
{
float2 p = float2(id.x * 7.0, id.y * 11.0);
float4 local[CULTMATH_MAX_SITES];
for (int i = 0; i < CULTMATH_MAX_SITES; i++)
local[i] = i < zoneCount ? bufferBodies[i] : float4(0.0, 0.0, 0.0, 1.0);
result[id.x] = cultmath_weighted_lattice_cells(p, 1.0, zoneBodies, zoneCount, 260.0, 0.3, 1.6, 120.0, 0.35, float2(1.0, 2.0), 1.5)
+ cultmath_weighted_lattice_cells(p, 1.0, local, zoneCount, 260.0, 0.3, 1.6, 120.0, 0.35, float2(1.0, 2.0), 1.5);
}

View file

@ -0,0 +1,16 @@
layout(local_size_x = 64) in;
layout(std430, binding = 0) readonly buffer IB { uint a[]; } In;
layout(std430, binding = 1) buffer OB { uint a[]; } Out;
void main()
{
uint i = gl_GlobalInvocationID.x; if (i >= NCASES) return; uint b = i * 76u;
vec4 bodies[CULTMATH_MAX_SITES];
for (int k = 0; k < CULTMATH_MAX_SITES; k++)
bodies[k] = uintBitsToFloat(uvec4(In.a[b + 2u + 4u * uint(k)], In.a[b + 3u + 4u * uint(k)], In.a[b + 4u + 4u * uint(k)], In.a[b + 5u + 4u * uint(k)]));
uint c = b + 67u;
vec4 r = cultmath_weighted_lattice_cells(uintBitsToFloat(uvec2(In.a[b], In.a[b + 1u])), uintBitsToFloat(In.a[c]), bodies, int(In.a[b + 66u]),
uintBitsToFloat(In.a[c + 1u]), uintBitsToFloat(In.a[c + 2u]), uintBitsToFloat(In.a[c + 3u]), uintBitsToFloat(In.a[c + 4u]),
uintBitsToFloat(In.a[c + 5u]), uintBitsToFloat(uvec2(In.a[c + 6u], In.a[c + 7u])), uintBitsToFloat(In.a[c + 8u]));
uvec4 w = floatBitsToUint(r);
Out.a[i * 4u] = w.x; Out.a[i * 4u + 1u] = w.y; Out.a[i * 4u + 2u] = w.z; Out.a[i * 4u + 3u] = w.w;
}

View file

@ -0,0 +1,16 @@
// Probe compute entry (HLSL route): 76 words in per case (p, 16 bodies, count, 9 parameters), 4 words out.
#include "CultMath.hlsl"
[[vk::binding(0)]] StructuredBuffer<uint> In;
[[vk::binding(1)]] RWStructuredBuffer<uint> Out;
[numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID)
{
uint i = id.x; if (i >= NCASES) return; uint b = i * 76u;
float4 bodies[CULTMATH_MAX_SITES];
for (int k = 0; k < CULTMATH_MAX_SITES; k++)
bodies[k] = float4(asfloat(In[b + 2 + 4 * k]), asfloat(In[b + 3 + 4 * k]), asfloat(In[b + 4 + 4 * k]), asfloat(In[b + 5 + 4 * k]));
uint c = b + 67u;
float4 r = cultmath_weighted_lattice_cells(float2(asfloat(In[b]), asfloat(In[b + 1])), asfloat(In[c]), bodies, asint(In[b + 66]),
asfloat(In[c + 1]), asfloat(In[c + 2]), asfloat(In[c + 3]), asfloat(In[c + 4]), asfloat(In[c + 5]),
float2(asfloat(In[c + 6]), asfloat(In[c + 7])), asfloat(In[c + 8]));
Out[i * 4] = asuint(r.x); Out[i * 4 + 1] = asuint(r.y); Out[i * 4 + 2] = asuint(r.z); Out[i * 4 + 3] = asuint(r.w);
}

View file

@ -0,0 +1,14 @@
#!/usr/bin/env python3
"""Compare a device output with C#'s reference bits: cases over the lavapipe bound 2.2e-6 max(|v|, 1), and the largest.
usage: judge.py <ref.bin> <out.bin> <label>"""
import math, struct, sys
ref, out = open(sys.argv[1], 'rb').read(), open(sys.argv[2], 'rb').read()
n = len(ref) // 16
r, o = struct.unpack('<%df' % (4 * n), ref), struct.unpack('<%df' % (4 * n), out)
over, exact, worst = 0, 0, 0.0
for i in range(n):
s = max((abs(o[4*i+j] - r[4*i+j]) / max(abs(r[4*i+j]), 1.0) if math.isfinite(o[4*i+j]) else math.inf) for j in range(4))
exact += ref[16*i:16*i+16] == out[16*i:16*i+16]
over += s > 2.2e-6
worst = max(worst, s)
print('%s: cases %d, bit-exact %d, over 2.2e-6 %d, worst %.3g' % (sys.argv[3], n, exact, over, worst))

View file

@ -0,0 +1,7 @@
// Probe A (local dxc): the prototype as a lib_6_3 SPIR-V library export, bodies as a fixed-size array parameter plus a count.
#include "CultMath.hlsl"
#include "prototype.hlsl"
export float4 probe_lattice(float2 p, float4 bodies[CULTMATH_MAX_SITES], int count)
{
return cultmath_weighted_lattice_cells(p, 1.0, bodies, count, 260.0, 0.3, 1.6, 120.0, 0.35, float2(1.0, 2.0), 1.5);
}

View file

@ -0,0 +1,12 @@
// Probe B: bodies through a caller-supplied accessor macro. The library build defines no accessor.
#include "CultMath.hlsl"
#ifdef CULTMATH_BODY
float4 cultmath_power_border_m(float3 p)
{
float4 border = float4(0.0, 0.0, 0.0, 1.0e30);
for (int k = 1; k < CULTMATH_BODY_COUNT; k++)
border = cultmath_power_border_step(p, CULTMATH_BODY(0), CULTMATH_BODY(k), border);
return border;
}
#endif
export float4 probe_macro(float3 p) { return cultmath_power_border_m(p); }

View file

@ -0,0 +1,55 @@
#!/usr/bin/env bash
# Probe for shader-weighted-lattice-loop: the prototype through the dxc + SPIRV-Cross build and on lavapipe, against C#.
# Run from a CultLib clone at a revision with packages/cultmath/tools/glsl/build-glsl.sh (hands/cultmath-glsl-build-dxc
# 23ac4e89), inside mcr.microsoft.com/dotnet/sdk:10.0, with this directory at $P. The clone is disposable: the
# prototype is appended to its CultMath.hlsl, and two build-tool lines are patched (array arguments, int constants).
set -euo pipefail
P=${P:-/tmp/probe}; ROOT=$(pwd); CM=$ROOT/packages/cultmath; W=/tmp/pw; mkdir -p $W
apt-get update -qq >/dev/null && apt-get install -y -qq --no-install-recommends python3 >/dev/null
cat $P/prototype.hlsl >> $CM/shaders/CultMath.hlsl
python3 - $CM/tools/glsl/wrappers.py <<'PY'
import sys; f = sys.argv[1]; t = open(f).read()
t = t.replace(r"args = [re.split(r'\s+', p)[-1] for p in params]", r"args = [re.split(r'\s+', re.sub(r'\[.*\]', '', p))[-1] for p in params]")
open(f, 'w').write(t)
PY
grep -c "re.sub(r'" $CM/tools/glsl/wrappers.py
python3 - $CM/tools/glsl/partition.py <<'PY'
import sys; f = sys.argv[1]; t = open(f).read()
t = t.replace(r"r'^static const float (CULTMATH_\w+) = (-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?);$'", r"r'^static const (float|int) (CULTMATH_\w+) = (-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?);$'")
t = t.replace("consts[o].append('const float %s = %s;' % m.groups())", "consts[o].append('const %s %s = %s;' % m.groups())")
open(f, 'w').write(t)
PY
grep -c "(float|int)" $CM/tools/glsl/partition.py
echo "== build"
bash $CM/tools/glsl/build-glsl.sh $W/built 2>&1 | tail -12
echo "== array functions in the built core.glsl"
grep -nE "^(const int CULTMATH_MAX_SITES|vec4 cultmath_power_border\(|float cultmath_lattice_cell_distance\(|vec4 cultmath_weighted_lattice_cells\()" $W/built/core.glsl
echo "== ES 3.00 fragment consumer passing a uniform array"
{ printf '#version 300 es\nprecision highp float;\nprecision highp int;\n'; cat $W/built/core.glsl
printf 'uniform vec4 zone[CULTMATH_MAX_SITES];\nuniform int zoneCount;\nout highp vec4 c;\nvoid main() { c = cultmath_weighted_lattice_cells(gl_FragCoord.xy, 1.0, zone, zoneCount, 260.0, 0.7, 1.6, 120.0, 0.35, vec2(0.6, 0.8), 1.5); }\n'; } > $W/consumer.frag
glslangValidator $W/consumer.frag && echo "consumer ES 3.00 ok"
echo "== lavapipe"
apt-get install -y -qq --no-install-recommends mesa-vulkan-drivers libvulkan-dev gcc libc6-dev >/dev/null
gcc -O2 -o $W/vkrun $CM/tools/device/vkrun.c -lvulkan
cp -r $P/ref $W/ref && sed -i 's#../../../../packages#'"$CM"'/..#' $W/ref/Ref.csproj
N=$(dotnet run --project $W/ref -c Release -- $W/in.bin $W/ref.bin | tail -1); echo "cases $N"
DXC=$(find $CM/.tools/glsl/dxc -name dxc -type f | head -1); export LD_LIBRARY_PATH=$(dirname $DXC)/../lib:$(dirname $DXC)
{ printf '#version 310 es\nprecision highp float;\nprecision highp int;\n#define NCASES %su\n' $N; cat $W/built/core.glsl $P/entry.comp.tail; } > $W/e.comp
glslangValidator -V --target-env vulkan1.2 -o $W/g.spv $W/e.comp >$W/g.log || { head $W/g.log; exit 1; }
$W/vkrun $W/g.spv $W/in.bin $W/g.out $N 4
python3 $P/judge.py $W/ref.bin $W/g.out built-glsl
run_hlsl() { # $1 label, $2 sed expression applied to a copy of the shaders
rm -rf $W/s && cp -r $CM/shaders $W/s && sed -i "$2" $W/s/CultMath.hlsl
$DXC -T cs_6_0 -E main -HV 2021 -spirv -fspv-target-env=vulkan1.2 -D NCASES=${N}u -I $W/s $P/entry.hlsl -Fo $W/h.spv >$W/h.log 2>&1 || { head -5 $W/h.log; exit 1; }
$W/vkrun $W/h.spv $W/in.bin $W/h.out $N 4 >/dev/null
python3 $P/judge.py $W/ref.bin $W/h.out "$1"
}
run_hlsl hlsl 's/^$//'
cmp $W/h.out $W/g.out && echo "hlsl equals built glsl bit for bit" || echo "hlsl and built glsl differ (plain form; the gate is strict form)"
run_hlsl "M1 exit at 0.5k" 's/0\.5 \* (k - 1) >= max/0.5 * k >= max/'
run_hlsl "M2 exit ignores the smooth band" 's/>= max(f2, f1 + 2\.0 \* smoothing))$/>= f2)/'
run_hlsl "M3 normaliser drops the pre-scale" 's/normal = stretchNormal \/ scale;/normal = stretchNormal;/'
run_hlsl "M4 normaliser drops the length" 's/normal = normal \/ length(normal);//'
run_hlsl "M5 smooth step loses its cap" 's/return min(next, f1 + smoothing);/return next;/'
run_hlsl "M6 box pass skips its first row" 's/for (int dz = -reach; dz <= reach; dz++)/for (int dz = -reach + 1; dz <= reach; dz++)/'
run_hlsl "M7 late exit (equivalent: window-independent)" 's/0\.5 \* (k - 1) >= max/0.5 * (k - 2) >= max/'

View file

@ -0,0 +1,75 @@
// The prototype, appended to CultMath.hlsl by probe.sh: the whole weighted_lattice_cells with bodies as a fixed-size array and a count.
static const int CULTMATH_MAX_SITES = 16;
float4 cultmath_power_border(float3 p, float4 sites[CULTMATH_MAX_SITES], int count)
{
CultSiteCells cells = cultmath_site_cells_empty();
for (int i = 0; i < count; i++)
cells = cultmath_site_cells_insert(cells, cultmath_power_score(p, sites[i]), i);
float4 border = float4(0.0, 0.0, 0.0, 1.0e30);
int owner = (int)cells.nearestSite;
if (owner < 0)
return border;
for (int k = 0; k < count; k++)
if (k != owner)
border = cultmath_power_border_step(p, sites[owner], sites[k], border);
return border;
}
float cultmath_lattice_cell_distance(float2 q, float2 cell, float time, float drift, float4 bodies[CULTMATH_MAX_SITES], int count,
float cellSize, float boost, float falloff, float2 normal, float stretch)
{
float3 site = cultmath_lattice_site(cell, time, drift);
float border = cultmath_power_border(float3((cell + 0.5) * cellSize, 0.0), bodies, count).w;
return cultmath_lattice_distance(q, site.xy, cultmath_lattice_weight(site.z, border, boost, falloff), normal, stretch);
}
float4 cultmath_weighted_lattice_cells(float2 p, float time, float4 bodies[CULTMATH_MAX_SITES], int count, float cellSize, float drift,
float boost, float falloff, float smoothing, float2 stretchNormal, float stretch)
{
float scale = max(abs(stretchNormal.x), abs(stretchNormal.y));
float2 normal = float2(1.0, 0.0);
if (scale > 0.0)
{
normal = stretchNormal / scale;
normal = normal / length(normal);
}
float2 q = p / cellSize;
float2 origin = floor(q);
int cx0 = (int)origin.x;
int cz0 = (int)origin.y;
float f1 = 1.0e30;
float f2 = 1.0e30;
int reach = 0;
for (int k = 0; k <= 37; k++)
{
if (k > 1 && 0.5 * (k - 1) >= max(f2, f1 + 2.0 * smoothing))
break;
for (int dz = -k; dz <= k; dz++)
{
int step = dz == -k || dz == k || k == 0 ? 1 : 2 * k;
for (int dx = -k; dx <= k; dx += step)
{
float d = cultmath_lattice_cell_distance(q, float2(cx0 + dx, cz0 + dz), time, drift, bodies, count, cellSize, boost, falloff, normal, stretch);
if (d < f1) { f2 = f1; f1 = d; }
else if (d < f2) f2 = d;
}
}
reach = k;
}
float m = f1 + smoothing;
float best = 1.0e30;
float second = 1.0e30;
int winDx = 0;
int winDz = 0;
for (int dz = -reach; dz <= reach; dz++)
for (int dx = -reach; dx <= reach; dx++)
{
float d = cultmath_lattice_cell_distance(q, float2(cx0 + dx, cz0 + dz), time, drift, bodies, count, cellSize, boost, falloff, normal, stretch);
if (d < best) { second = best; best = d; winDx = dx; winDz = dz; }
else if (d < second) second = d;
m = cultmath_lattice_smooth_step(m, d, f1, smoothing);
}
int4 id = cultmath_pcg4d(int4(cx0 + winDx, cz0 + winDz, 0, 0));
return float4(best, second, m, (float)((uint)id.w >> 8) * (1.0 / 16777216.0));
}

View file

@ -0,0 +1,50 @@
// Probe reference: writes the lattice cases (76 words each) and C#'s weighted_lattice_cells bits (4 words each).
// usage: Ref <in.bin> <ref.bin>; prints the case count.
using CultMath;
using static CultMath.math;
const int Max = 16;
var cases = new List<(float2 p, float t, float4[] b, float cell, float drift, float boost, float falloff, float s, float2 n, float st)>();
float4[] Bodies(float t, int count)
{
var b = new float4[count];
for (var i = 0; i < count; i++)
{
var a = 0.001f * (i + 1) * t + i; var r = 300.0f + 220.0f * i;
b[i] = new float4(r * MathF.Cos(a), r * MathF.Sin(a), 0.0f, 40.0f + 40.0f * i);
}
return b;
}
// The ring-17 point of LatticeCellsTests.TheCapIsReachedAndMatchesTheFullBox, and its neighbours.
for (var j = 0; j < 8; j++)
cases.Add((new float2(1446.7345f + 3.0f * j, -680.7637f), 97.69269f, Bodies(97.69269f, 6), 260.0f, 0.7f, 4.0f, 1.0e6f, 1.0f, new float2(0.6f, 0.8f), 2.0f));
var looks = new[] { (1.6f, 1.0f, 0.35f), (1.6f, 2.0f, 0.35f), (4.0f, 2.0f, 1.0f), (0.0f, 1.0f, 0.05f) };
var normals = new[] { new float2(0.6f, 0.8f), new float2(3.0f, 4.0f), new float2(3.0e-30f, -4.0e-30f), new float2(1.0e30f, 2.0e30f), new float2(-1.0f, 1.0e-3f) };
var rng = new System.Random(20261017);
float U(float a, float b) => a + (b - a) * (float)rng.NextDouble();
for (var i = 0; i < 248; i++)
{
var (boost, stretch, s) = looks[i % 4];
var n = normals[(i / 4) % normals.Length];
var count = new[] { 6, 0, 1, 16, 6, 3 }[(i / 20) % 6];
var t = U(0.0f, 200.0f);
cases.Add((new float2(U(-3000, 3000), U(-3000, 3000)), t, Bodies(t, count), 260.0f, 0.7f, boost, 120.0f, s, n, stretch));
}
// Zero normal at stretch 1 is (1, 0).
cases.Add((new float2(10.0f, 20.0f), 1.0f, Bodies(1.0f, 6), 260.0f, 0.7f, 1.6f, 120.0f, 0.35f, new float2(0.0f, 0.0f), 1.0f));
using var input = new BinaryWriter(File.Create(args[0]));
using var reference = new BinaryWriter(File.Create(args[1]));
foreach (var c in cases)
{
input.Write(c.p.x); input.Write(c.p.y);
for (var k = 0; k < Max; k++)
{
var v = k < c.b.Length ? c.b[k] : new float4(0.0f, 0.0f, 0.0f, 0.0f);
input.Write(v.x); input.Write(v.y); input.Write(v.z); input.Write(v.w);
}
input.Write(c.b.Length);
foreach (var f in new[] { c.t, c.cell, c.drift, c.boost, c.falloff, c.s, c.n.x, c.n.y, c.st }) input.Write(f);
var r = weighted_lattice_cells(c.p, c.t, c.b, c.cell, c.drift, c.boost, c.falloff, c.s, c.n, c.st);
reference.Write(r.x); reference.Write(r.y); reference.Write(r.z); reference.Write(r.w);
}
Console.WriteLine(cases.Count);

View file

@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup><ProjectReference Include="../../../../packages/cultmath/src/CultMath/CultMath.csproj" /></ItemGroup>
</Project>