CultMath shaders: cultmath_power_border, cultmath_lattice_cell_distance and cultmath_weighted_lattice_cells over a fixed-capacity site array
CULTMATH_MAX_SITES defaults to 128 under #ifndef. The consumer-written ring-loop and border-loop comment recipes are deleted. The C# mirror takes the array as T[]; the span twins live in SiteArrays; the GLSL lowering keeps the capacity macro; gen.py learns the array leaf; the smooth-step family gains its cap-point draw; CULTMATH_WRITE_GLSL refuses non-Linux. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
3cd6815575
commit
150ea0a060
11 changed files with 474 additions and 73 deletions
|
|
@ -38,8 +38,9 @@ shader semantics.
|
|||
drifting lattice whose cell weights come from the exact power border of the body span at each cell centre, with a stretched
|
||||
metric and an exact ring search over the stated range (`LatticeMaxBoost`, `LatticeMaxStretch`, `LatticeMaxSmoothing`). It composes the
|
||||
public steps `lattice_site`, `lattice_weight`, `lattice_distance` and `lattice_smooth_step`. The shaders carry the four steps as
|
||||
`cultmath_lattice_site`, `cultmath_lattice_weight`, `cultmath_lattice_distance` and `cultmath_lattice_smooth_step`; the ring and box loops
|
||||
are the shader caller's, written as the comment above them in `CultMath.hlsl` gives them, and the argument checks become its preconditions.
|
||||
`cultmath_lattice_site`, `cultmath_lattice_weight`, `cultmath_lattice_distance` and `cultmath_lattice_smooth_step`, and the whole function as `cultmath_weighted_lattice_cells(p, time, bodies,
|
||||
count, ...)` over a `float4 bodies[CULTMATH_MAX_SITES]` array (128 by default; define the macro before including to change it);
|
||||
`cultmath_power_border(p, sites, count)` is the matching border. The argument checks become the shader caller's preconditions.
|
||||
- `shaders/CultMath.hlsl`, a canonical HLSL mirror include for shader-side
|
||||
parity. HLSL already owns `float2`, `float3`, and `float4`; the include
|
||||
exposes `cultmath_*` functions for shared semantics HLSL does not provide.
|
||||
|
|
|
|||
|
|
@ -95,7 +95,8 @@ and HLSL's one-based `_11`..`_33` element names.
|
|||
Roslyn against CultMath. These transformations are the complete list; if a body
|
||||
needs anything else, the test fails:
|
||||
|
||||
1. Include guards (`#ifndef`/`#define`/`#endif`) are dropped.
|
||||
1. Include guards (`#ifndef`/`#define`/`#endif`) are dropped, except the capacity macro (`#ifndef CULTMATH_MAX_SITES`,
|
||||
`#define CULTMATH_MAX_SITES 128`, `#endif`), which becomes `const int CULTMATH_MAX_SITES = 128;`.
|
||||
2. Functions taking `Texture2D`/`SamplerState` are dropped; GPU resources have
|
||||
no CultMath analog.
|
||||
3. File-scope `static const` becomes `const`.
|
||||
|
|
@ -103,7 +104,8 @@ needs anything else, the test fails:
|
|||
5. Struct fields gain `public`. HLSL struct members have no access-modifier
|
||||
concept; a C# struct's fields default to `private`, which would hide them
|
||||
from the mirror test's reflection-based field comparison.
|
||||
6. The file body is wrapped in a class, since C# has no free functions; HLSL
|
||||
6. An array parameter `T name[CULTMATH_MAX_SITES]` becomes `T[] name`.
|
||||
7. The file body is wrapped in a class, since C# has no free functions; HLSL
|
||||
functions become private instance methods.
|
||||
|
||||
HLSL constructs that stay outside the target and must not appear in the mirror:
|
||||
|
|
@ -156,6 +158,10 @@ hand. Regenerate them, and the golden fixture
|
|||
$env:CULTMATH_WRITE_GLSL = "1"; dotnet test packages/cultmath/tests/CultMath.Tests --filter GlslMirrorTests
|
||||
```
|
||||
|
||||
Run it on Yggdrasil's `mcr.microsoft.com/dotnet/sdk:10.0` image (Ubuntu 24.04) only: that image owns the fixture's platform
|
||||
families and `device-bounds-lavapipe.txt`, and `CULTMATH_WRITE_GLSL=1` fails on any other OS. Re-record the bounds there in
|
||||
the same revision (`WRITE_BOUNDS=1`, `tools/device/run-lavapipe.sh`).
|
||||
|
||||
`GlslMirrorTests.CommittedGlslEqualsLowering` fails on any difference between
|
||||
either committed file and the lowering of the committed HLSL. These
|
||||
transformations, in order, are the complete list:
|
||||
|
|
@ -519,11 +525,12 @@ running `float4(unit normal toward the owner, distance)` and the radical plane o
|
|||
the distance built from the offset `owner - p` and the weight difference `(w1 - w2)(w1 + w2)` so it does not
|
||||
cancel for close sites seen from far; the cell boundary distance is the least over every site except the owner
|
||||
(the fold's nearest), and a site coincident with the owner has no plane. The step trusts the caller's owner: a
|
||||
query outside the owner's cell reports distance 0 with that plane's normal, not an error. `power_border(p, sites)` is that loop.
|
||||
query outside the owner's cell reports distance 0 with that plane's normal, not an error. `power_border(p, sites)` is that loop;
|
||||
the shader's `cultmath_power_border(p, sites, count)` is the same loop over a by-value array (see "Sites in a shader" below).
|
||||
Cell spans refuse a non-finite query, site position or weight, and more than 2^24 sites (indices are floats).
|
||||
`power_cells` and
|
||||
`multiplicative_cells` are that loop over a `ReadOnlySpan<float4>` and nothing else; a shader caller writes the
|
||||
same loop over its own buffer. Every site of an explicit span is visited, so no window and no weight-ratio range
|
||||
same loop over its own array. Every site of an explicit span is visited, so no window and no weight-ratio range
|
||||
apply. `CultSiteCells` holds the two score fields and the two site indices (floats, -1 for none).
|
||||
|
||||
`gabriel_margin(a, b, other)` is `(|other - (a + b) / 2| - r) / r` with `r = |a - b| / 2`: zero on the diameter
|
||||
|
|
@ -557,8 +564,21 @@ The accepted range is boost 0 to `LatticeMaxBoost` (4, a weight ratio of 10:1),
|
|||
and smoothing up to `LatticeMaxSmoothing` (1); outside it the function throws `ArgumentException`. `LatticeMaxRing`
|
||||
(37) is the proven greatest ring at the range edge. Measured over 24,000 points on orbiting bodies (six bodies,
|
||||
sigma ratio 6:1, the ruled look and the range edge), the greatest ring visited has median 3, 99th percentile 7 and
|
||||
maximum 8 (49, 225 and 289 cells); `RingsStayWellInsideTheCap` asserts these. The function is C# only; the shader
|
||||
twins are the next cut.
|
||||
maximum 8 (49, 225 and 289 cells); `RingsStayWellInsideTheCap` asserts these.
|
||||
|
||||
### Sites in a shader
|
||||
|
||||
A shader function cannot take a span, so `cultmath_power_border(p, sites, count)`, `cultmath_lattice_cell_distance(...)`
|
||||
and `cultmath_weighted_lattice_cells(p, time, bodies, count, ...)` take `float4 sites[CULTMATH_MAX_SITES]` by value and the
|
||||
count in use, with `count` in `[0, CULTMATH_MAX_SITES]`. `CULTMATH_MAX_SITES` is 128 unless the consumer defines it before
|
||||
including the library (`#ifndef`): 128 covers every Aetheria zone within GLSL ES 3.00's 224 guaranteed fragment uniform
|
||||
vectors, and loops run to `count`, so the capacity costs uniform space, not iterations. A `StructuredBuffer` caller copies
|
||||
into a local array first; the library takes no resource, accessor macro or uniform of its own. The preconditions the C#
|
||||
functions throw for are the caller's in a shader (finite arguments, `cellSize > 0`, the stated ranges, `p` within 2^23
|
||||
cells). The ring pass is bounded `k <= 37` and exits as C# does; the box pass recomputes each distance instead of caching
|
||||
75 x 75 of them, which gives the same values. The C# mirror compiles the array as `T[]`, and
|
||||
`HlslSourceCompatibilityTests.SiteArrayMirrorsMatchCSharp` compares the three functions through the span twins in
|
||||
`SiteArrays` (reflection cannot pass a `ReadOnlySpan`); `CULTMATH_MAX_SITES` is a shader-only capacity with no C# twin.
|
||||
|
||||
## Intervals
|
||||
|
||||
|
|
|
|||
|
|
@ -600,14 +600,12 @@ CultCellular cultmath_cellular(float3 p)
|
|||
return result;
|
||||
}
|
||||
|
||||
// Sites: a site is float4(position.xyz, weight). A span is a loop over a per-site step, because a shader
|
||||
// function cannot take a span in the mirror (design.md, "Sites"). The consumer's loop, over its own buffer:
|
||||
// Sites: a site is float4(position.xyz, weight). A shader function cannot take a span (design.md, "Sites"), so a span is a
|
||||
// fixed-capacity array and a count (cultmath_power_border, below), or a loop over a per-site step:
|
||||
// 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);
|
||||
// The exact power cell border is a second loop over the buffer, skipping the owner cells.nearestSite:
|
||||
// float4 border = float4(0.0, 0.0, 0.0, 1.0e30); int owner = (int)cells.nearestSite;
|
||||
// for (int k = 0; k < count; k++) if (k != owner) border = cultmath_power_border_step(p, sites[owner], sites[k], border);
|
||||
// The exact power cell border is cultmath_power_border, the second loop over the sites that skips the owner cells.nearestSite.
|
||||
// The step trusts the owner: a p outside the owner's cell reports distance 0 with that plane's normal, not an error.
|
||||
// Statement for statement with math.Sites.cs (power_score, multiplicative_score, site_cells_*, gabriel_margin).
|
||||
struct CultSiteCells
|
||||
|
|
@ -688,21 +686,8 @@ float cultmath_gabriel_margin(float3 a, float3 b, float3 other)
|
|||
return (cultmath_distance(other, (a + b) * 0.5) - r) / r;
|
||||
}
|
||||
|
||||
// Weighted lattice cells: the four per-cell steps of math.Lattice.cs, statement for statement. A shader function cannot take a
|
||||
// span (design.md, "Sites"), so weighted_lattice_cells is the consumer's loop over its own body buffer, in two passes:
|
||||
// float2 q = p / cellSize; int2 c0 = (int2)floor(q); float f1 = 1.0e30, f2 = 1.0e30; int reach = 0;
|
||||
// for (int k = 0; ; k++) { // ring pass: Chebyshev rings 0, 1, 2, ... around c0, exact exit
|
||||
// if (k > 1 && 0.5 * (k - 1) >= max(f2, f1 + 2.0 * smoothing)) break; // k never reaches 38 in the accepted range
|
||||
// for each cell on ring k: d = cultmath_lattice_distance(q, cultmath_lattice_site(cell, time, drift).xy, w, normal, stretch),
|
||||
// w = cultmath_lattice_weight(site.z, border, boost, falloff), border = the .w of cultmath_power_border_step
|
||||
// folded over the bodies (owner = the nearest body of the cell centre (cell + 0.5) * cellSize, z = 0);
|
||||
// if (d < f1) { f2 = f1; f1 = d; } else if (d < f2) f2 = d; store d for the box pass
|
||||
// reach = k; }
|
||||
// float m = f1 + smoothing; // box pass: every stored cell, rows dz = -reach..reach, then dx = -reach..reach
|
||||
// for each (dz, dx): m = cultmath_lattice_smooth_step(m, d, f1, smoothing); // strict < for the winning id (earlier cell wins ties)
|
||||
// The preconditions the C# function throws for are the caller's in a shader: finite arguments, cellSize > 0, boost in [0, 4],
|
||||
// falloff > 0, smoothing in (0, 1], stretch in [1, 2], p within 2^23 cells. The normal is normalised as C# does: divide by its
|
||||
// largest component, then by its length (a zero normal means (1, 0) and needs stretch == 1). The ring bound is 37.
|
||||
// Weighted lattice cells: the four per-cell steps of math.Lattice.cs, statement for statement; cultmath_weighted_lattice_cells,
|
||||
// after them, is the whole function.
|
||||
float3 cultmath_lattice_site(float2 cell, float time, float drift)
|
||||
{
|
||||
int3 h = cultmath_pcg3d(int3((int)cell.x, (int)cell.y, 0));
|
||||
|
|
@ -734,6 +719,90 @@ float cultmath_lattice_smooth_step(float m, float d, float f1, float smoothing)
|
|||
return min(next, f1 + smoothing);
|
||||
}
|
||||
|
||||
// Sites by value: a shader function cannot take a span, so these take float4 sites[CULTMATH_MAX_SITES] and the count in use, with
|
||||
// count in [0, CULTMATH_MAX_SITES]. A consumer defines CULTMATH_MAX_SITES before including this file to change the capacity; loops
|
||||
// run to count, so the capacity costs uniform space, not iterations. A StructuredBuffer caller copies into a local array first.
|
||||
// The preconditions the C# functions throw for are the caller's in a shader: finite arguments, cellSize > 0, boost in [0, 4],
|
||||
// falloff > 0, smoothing in (0, 1], stretch in [1, 2], p within 2^23 cells. A zero stretchNormal means (1, 0) and needs stretch == 1.
|
||||
// cultmath_weighted_lattice_cells is math.weighted_lattice_cells: the ring pass is bounded by k <= 37 and exits as C# does, and the
|
||||
// box pass recomputes each distance instead of caching it (a 75 x 75 private array is not a shader option), with the same values.
|
||||
#ifndef CULTMATH_MAX_SITES
|
||||
#define CULTMATH_MAX_SITES 128
|
||||
#endif
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
float2 cultmath_segment_closest(float2 point_value, float2 start, float2 end)
|
||||
{
|
||||
float2 segment = end - start;
|
||||
|
|
|
|||
|
|
@ -200,7 +200,7 @@ public static partial class math
|
|||
return new float4(best, second, m, cellular_unit(id.w));
|
||||
}
|
||||
|
||||
private static float lattice_cell_distance(
|
||||
internal static float lattice_cell_distance(
|
||||
float2 q, float2 cell, float time, float drift, ReadOnlySpan<float4> bodies, float cellSize, float boost, float falloff,
|
||||
float2 normal, float stretch)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -70,8 +70,9 @@ internal static class GlslLowering
|
|||
var source = hlsl.ReplaceLineEndings("\n");
|
||||
|
||||
// 2. Include guards are dropped, and so are the functions taking Texture2D/SamplerState, exactly
|
||||
// as the C# mirror drops them; the host shader samples its own textures.
|
||||
source = Regex.Replace(source, @"(?m)^[ \t]*#(ifndef|define|endif)\b.*$", string.Empty);
|
||||
// as the C# mirror drops them; the host shader samples its own textures. The capacity macro
|
||||
// (#ifndef CULTMATH_MAX_SITES ... #endif) stays: GLSL has the preprocessor, and a consumer overrides it.
|
||||
source = HlslSourceCompatibilityTests.DropGuards(source, (name, value) => $"#ifndef {name}\n#define {name} {value}\n#endif");
|
||||
source = Regex.Replace(source, @"(?ms)^\w+ \w+\([^)]*\b(Texture2D|SamplerState)\b[^)]*\)\s*\{.*?^\}[ \t]*$", string.Empty);
|
||||
|
||||
// 3. Type names: floatN, intN, uintN and boolN become vecN, ivecN, uvecN and bvecN, and float3x3
|
||||
|
|
|
|||
|
|
@ -22,7 +22,11 @@ public sealed partial class GlslMirrorTests
|
|||
|
||||
public GlslMirrorTests(ITestOutputHelper output) => this.output = output;
|
||||
|
||||
private static bool Write => Environment.GetEnvironmentVariable("CULTMATH_WRITE_GLSL") == "1";
|
||||
// The fixture is written by Yggdrasil's mcr.microsoft.com/dotnet/sdk:10.0 image (Ubuntu 24.04) only: its platform families record
|
||||
// that platform's libm, so a write from another OS would move them.
|
||||
private static bool Write => Environment.GetEnvironmentVariable("CULTMATH_WRITE_GLSL") == "1"
|
||||
? OperatingSystem.IsLinux() ? true : throw new InvalidOperationException("CULTMATH_WRITE_GLSL=1 writes glsl-parity.json, whose platform families belong to Yggdrasil's Ubuntu image (mcr.microsoft.com/dotnet/sdk:10.0): regenerate it there.")
|
||||
: false;
|
||||
|
||||
private static string Root => HlslSourceCompatibilityTests.FindCultMathRoot();
|
||||
|
||||
|
|
@ -497,6 +501,14 @@ static int4 clamp(int4 x, int4 a, int4 b) { if (a.x > b.x || a.y > b.y || a.z >
|
|||
return (int)scalars.Dequeue();
|
||||
if (type == typeof(uint))
|
||||
return scalars.Dequeue();
|
||||
if (type.IsArray)
|
||||
{
|
||||
var array = Array.CreateInstance(type.GetElementType()!, SiteArrays.Capacity);
|
||||
for (var i = 0; i < array.Length; i++)
|
||||
array.SetValue(FromScalars(type.GetElementType()!, scalars), i);
|
||||
return array;
|
||||
}
|
||||
|
||||
var value = Activator.CreateInstance(type)!;
|
||||
foreach (var field in type.GetFields().Where(f => !f.IsStatic))
|
||||
field.SetValue(value, FromScalars(field.FieldType, scalars));
|
||||
|
|
@ -872,14 +884,26 @@ static int4 clamp(int4 x, int4 a, int4 b) { if (a.x > b.x || a.y > b.y || a.z >
|
|||
}),
|
||||
// The smooth step: d exactly at f1 + 2 smoothing one in four (the equal branch), near it one in four, the
|
||||
// smoothing near 0 and at 1, m anywhere up to f1 + smoothing.
|
||||
// One draw in four is the cap point: m = f1 + smoothing exactly and d = f1 + smoothing (1 + U(0.3, 0.9)) with smoothing in
|
||||
// [0.5, 1], where next exceeds f1 + smoothing and the min clamps; a step that returns next reads another function there.
|
||||
new Family("float cultmath_lattice_smooth_step(float, float, float, float)", "ulp-bounded", r =>
|
||||
{
|
||||
if (r.Next(4) == 0)
|
||||
{
|
||||
var cappedSmoothing = Uniform(r, 0.5f, 1.0f);
|
||||
var cappedF1 = Uniform(r, 0.0f, 10.0f);
|
||||
return new object[] { cappedF1 + cappedSmoothing, cappedF1 + cappedSmoothing * (1.0f + Uniform(r, 0.3f, 0.9f)), cappedF1, cappedSmoothing };
|
||||
}
|
||||
|
||||
var smoothing = r.Next(5) switch { 0 => 1.0f, 1 => Uniform(r, 1.0e-3f, 1.0e-2f), _ => Uniform(r, 0.01f, 1.0f) };
|
||||
var f1 = Uniform(r, 0.0f, 10.0f);
|
||||
var edge = f1 + 2.0f * smoothing;
|
||||
var d = r.Next(4) switch { 0 => edge, 1 => edge * Uniform(r, 0.99f, 1.01f), _ => Uniform(r, f1, edge + 1.0f) };
|
||||
return new object[] { Uniform(r, f1, f1 + smoothing), d, f1, smoothing };
|
||||
}),
|
||||
// The site-array functions: a fixed-capacity array and a count, killed on the device (the lattice at rings up to 17).
|
||||
new Family($"vec4 cultmath_power_border(vec3, vec4[{SiteArrays.Capacity}], int)", "ulp-bounded", SiteArrays.PowerBorderArguments),
|
||||
new Family($"vec4 cultmath_weighted_lattice_cells(vec2, float, vec4[{SiteArrays.Capacity}], int, float, float, float, float, float, vec2, float)", "ulp-bounded", SiteArrays.LatticeArguments),
|
||||
}).ToArray();
|
||||
|
||||
// A point of magnitude m, m log-uniform in [lo, hi]: one component at +-m, the other two uniform in [-m, m],
|
||||
|
|
@ -988,6 +1012,7 @@ static int4 clamp(int4 x, int4 a, int4 b) { if (a.x > b.x || a.y > b.y || a.z >
|
|||
["vec4"] = typeof(float4), ["ivec3"] = typeof(int3), ["ivec4"] = typeof(int4),
|
||||
["SpanPath"] = typeof(SpanPath), ["SpanStage"] = typeof(SpanStage),
|
||||
["CultSiteCells"] = typeof(CultSiteCells),
|
||||
[$"vec4[{SiteArrays.Capacity}]"] = typeof(float4[]),
|
||||
};
|
||||
|
||||
// The C# math method a GLSL signature names: cultmath_ dropped, parameter types mapped.
|
||||
|
|
@ -996,6 +1021,7 @@ static int4 clamp(int4 x, int4 a, int4 b) { if (a.x > b.x || a.y > b.y || a.z >
|
|||
var match = Regex.Match(glsl, @"^\w+ cultmath_(\w+)\(([^)]*)\)$");
|
||||
var types = match.Groups[2].Value.Split(", ").Select(t => GlslTypes[t]).ToArray();
|
||||
return typeof(math).GetMethod(match.Groups[1].Value, BindingFlags.Public | BindingFlags.Static, null, types, null)
|
||||
?? typeof(SiteArrays).GetMethod(match.Groups[1].Value, BindingFlags.NonPublic | BindingFlags.Static, null, types, null)
|
||||
?? throw new InvalidOperationException("no C# math counterpart for " + glsl);
|
||||
}
|
||||
|
||||
|
|
@ -1011,6 +1037,8 @@ static int4 clamp(int4 x, int4 a, int4 b) { if (a.x > b.x || a.y > b.y || a.z >
|
|||
// the same read as GLSL's columns.
|
||||
private static IEnumerable<object> Scalars(object value) => value is float or int or uint
|
||||
? new[] { value }
|
||||
: value is Array array
|
||||
? array.Cast<object>().SelectMany(Scalars)
|
||||
: value is float3x3 matrix
|
||||
? new object[] { matrix._m00, matrix._m01, matrix._m02, matrix._m10, matrix._m11, matrix._m12, matrix._m20, matrix._m21, matrix._m22 }
|
||||
: value.GetType().GetFields().Where(f => !f.IsStatic).SelectMany(f => Scalars(f.GetValue(value)!));
|
||||
|
|
|
|||
|
|
@ -70,7 +70,7 @@ public sealed class HlslSourceCompatibilityTests
|
|||
shader.GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic, null, parameters, null);
|
||||
|
||||
// Shader constants with no C# twin of the same name (empty when every constant has one).
|
||||
private static readonly string[] ConstantsWithoutTwin = Array.Empty<string>();
|
||||
private static readonly string[] ConstantsWithoutTwin = { "CULTMATH_MAX_SITES" };
|
||||
|
||||
/// <summary>
|
||||
/// Every static const of the compiled HLSL mirror (a static literal CULTMATH_* field, whatever its access) is the
|
||||
|
|
@ -85,7 +85,7 @@ public sealed class HlslSourceCompatibilityTests
|
|||
Assert.True(assembly is not null, string.Join(Environment.NewLine, errors));
|
||||
var shader = assembly!.GetType("CultMathHlsl.HlslShader")!;
|
||||
var constants = shader.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
|
||||
.Where(f => f.IsLiteral && f.Name.StartsWith("CULTMATH_", StringComparison.Ordinal))
|
||||
.Where(f => f.IsLiteral && f.FieldType == typeof(float) && f.Name.StartsWith("CULTMATH_", StringComparison.Ordinal))
|
||||
.ToArray();
|
||||
Assert.True(constants.Length >= 10, $"only {constants.Length} shader constants were found by reflection");
|
||||
foreach (var constant in constants)
|
||||
|
|
@ -183,7 +183,7 @@ public sealed class HlslSourceCompatibilityTests
|
|||
|
||||
var mismatches = new List<string>();
|
||||
var compared = new HashSet<string>();
|
||||
foreach (var mirror in shaderType.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic).Where(m => m.Name.StartsWith("cultmath_")))
|
||||
foreach (var mirror in shaderType.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic).Where(m => m.Name.StartsWith("cultmath_") && !m.GetParameters().Any(p => p.ParameterType.IsArray)))
|
||||
{
|
||||
var types = mirror.GetParameters().Select(p => p.ParameterType).ToArray();
|
||||
var counterpart = Twin(shaderType, mirror.Name["cultmath_".Length..], types);
|
||||
|
|
@ -204,7 +204,65 @@ public sealed class HlslSourceCompatibilityTests
|
|||
}
|
||||
|
||||
Assert.True(mismatches.Count == 0, $"{mismatches.Count} mismatches:{Environment.NewLine}{string.Join(Environment.NewLine, mismatches.Take(12))}");
|
||||
Assert.Equal(140, compared.Count);
|
||||
// The three site-array functions are compared by SiteArrayMirrorsMatchCSharp, which draws their counts and arrays.
|
||||
Assert.Equal(137, compared.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The shader functions that take a site array and a count are bit-equal to C#'s span functions on the same
|
||||
/// arguments: at least 64 compared cases each, counts 0 to the capacity with filler after the count (a loop bound that
|
||||
/// ignores the count reads it), the lattice at rings up to 17. A case C# refuses is skipped and counted.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void SiteArrayMirrorsMatchCSharp()
|
||||
{
|
||||
var (assembly, errors) = CompileShaderMirror();
|
||||
Assert.True(assembly is not null, string.Join(Environment.NewLine, errors));
|
||||
var shaderType = assembly!.GetType("CultMathHlsl.HlslShader")!;
|
||||
var shader = Activator.CreateInstance(shaderType);
|
||||
Assert.Equal(17, SiteArrays.FarPoints[0].Ring);
|
||||
Assert.All(SiteArrays.FarPoints, far => Assert.InRange(far.Ring, 8, LatticeMaxRing));
|
||||
|
||||
var draws = new (string Name, Func<System.Random, object[]> Draw)[]
|
||||
{
|
||||
("power_border", SiteArrays.PowerBorderArguments),
|
||||
("lattice_cell_distance", SiteArrays.LatticeCellDistanceArguments),
|
||||
("weighted_lattice_cells", SiteArrays.LatticeArguments),
|
||||
};
|
||||
foreach (var (name, draw) in draws)
|
||||
{
|
||||
var mirror = shaderType.GetMethod("cultmath_" + name, BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
var twin = typeof(SiteArrays).GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic)!;
|
||||
Assert.Equal(twin.GetParameters().Select(p => p.ParameterType), mirror.GetParameters().Select(p => p.ParameterType));
|
||||
var random = new System.Random(0x517E);
|
||||
int compared = 0, refused = 0;
|
||||
for (var i = 0; i < 160; i++)
|
||||
{
|
||||
var args = draw(random);
|
||||
object expected;
|
||||
try { expected = twin.Invoke(null, args)!; }
|
||||
catch (TargetInvocationException e) when (e.InnerException is ArgumentException) { refused++; continue; }
|
||||
var actual = Values(mirror.Invoke(shader, args)!);
|
||||
Assert.True(BitwiseEqual(Values(expected), actual),
|
||||
$"{name} case {i}: C# {string.Join(" ", Values(expected).Select(v => v.Value))}, mirror {string.Join(" ", actual.Select(v => v.Value))}");
|
||||
compared++;
|
||||
}
|
||||
|
||||
Assert.True(compared >= 64, $"{name} compared only {compared} cases ({refused} refused)");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A consumer defines CULTMATH_MAX_SITES before including the library; the mirror compiles with the capacity changed.</summary>
|
||||
[Fact]
|
||||
public void TheSiteCapacityIsOverridable()
|
||||
{
|
||||
var (assembly, errors) = CompileShaderMirror(defines: new Dictionary<string, int> { ["CULTMATH_MAX_SITES"] = 4 });
|
||||
Assert.True(assembly is not null, string.Join(Environment.NewLine, errors));
|
||||
var shaderType = assembly!.GetType("CultMathHlsl.HlslShader")!;
|
||||
Assert.Equal(4, (int)shaderType.GetField("CULTMATH_MAX_SITES", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)!.GetRawConstantValue()!);
|
||||
var sites = new[] { new float4(0, 0, 0, 1), new float4(10, 0, 0, 1), new float4(0, 10, 0, 2), new float4(-10, 0, 0, 1) };
|
||||
var border = (float4)shaderType.GetMethod("cultmath_power_border", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(Activator.CreateInstance(shaderType), new object[] { new float3(1, 1, 0), sites, 4 })!;
|
||||
Assert.Equal(power_border(new float3(1, 1, 0), sites), border);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -682,14 +740,23 @@ public sealed class HlslSourceCompatibilityTests
|
|||
: string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The text without its include-guard lines. A capacity macro (<c>#ifndef X</c>, <c>#define X n</c>, <c>#endif</c>, a
|
||||
/// consumer-overridable default) is not a guard: <paramref name="capacity"/> gives the text it becomes, from its name and value.
|
||||
/// </summary>
|
||||
internal static string DropGuards(string source, Func<string, string, string> capacity) =>
|
||||
Regex.Replace(source, @"(?m)^#ifndef (CULTMATH_MAX_\w+)\r?\n#define \1 (\d+)\r?\n#endif[ \t]*$|^[ \t]*#(ifndef|define|endif)\b.*$",
|
||||
match => match.Groups[1].Success ? capacity(match.Groups[1].Value, match.Groups[2].Value) : string.Empty);
|
||||
|
||||
/// <summary>
|
||||
/// The documented HLSL-to-C# transformations, and nothing else. <paramref name="members"/> is C# source a
|
||||
/// test supplies, placed first in the class body: it is not a transformation of the HLSL.
|
||||
/// </summary>
|
||||
internal static string TransformHlslToCSharp(string hlsl, string members = "")
|
||||
internal static string TransformHlslToCSharp(string hlsl, string members = "", IReadOnlyDictionary<string, int>? defines = null)
|
||||
{
|
||||
// 1. Include guards (#ifndef/#define/#endif) are dropped; C# has no textual include.
|
||||
var source = Regex.Replace(hlsl, @"(?m)^\s*#(ifndef|define|endif)\b.*$", string.Empty);
|
||||
// 1. Include guards (#ifndef/#define/#endif) are dropped; C# has no textual include. A capacity macro
|
||||
// (#ifndef X, #define X n, #endif) becomes `const int X = n;`, or the value a test defines for X.
|
||||
var source = DropGuards(hlsl, (name, value) => $"const int {name} = {(defines is not null && defines.TryGetValue(name, out var defined) ? defined : value)};");
|
||||
|
||||
// 2. Functions taking Texture2D/SamplerState resources are dropped; GPU resources have
|
||||
// no CultMath analog.
|
||||
|
|
@ -708,14 +775,17 @@ public sealed class HlslSourceCompatibilityTests
|
|||
source = Regex.Replace(source, @"(?ms)(struct\s+\w+\s*\{)(.*?)(\};)", m =>
|
||||
m.Groups[1].Value + Regex.Replace(m.Groups[2].Value, @"(?m)^(\s*)(\w+\s+\w+;)", "$1public $2") + m.Groups[3].Value);
|
||||
|
||||
// 6. The file body is wrapped in a class; C# has no free functions.
|
||||
// 6. An array parameter `T name[N]` becomes `T[] name`; the mirror takes the array whole and the count beside it.
|
||||
source = Regex.Replace(source, @"\b(\w+) (\w+)\[CULTMATH_MAX_\w+\]", "$1[] $2");
|
||||
|
||||
// 7. The file body is wrapped in a class; C# has no free functions.
|
||||
return "using CultMath;\nusing static CultMath.math;\nnamespace CultMathHlsl;\npublic class HlslShader\n{\n" + members + source + "\n}\n";
|
||||
}
|
||||
|
||||
internal static (Assembly? Assembly, IReadOnlyList<string> Errors) CompileShaderMirror(string members = "")
|
||||
internal static (Assembly? Assembly, IReadOnlyList<string> Errors) CompileShaderMirror(string members = "", IReadOnlyDictionary<string, int>? defines = null)
|
||||
{
|
||||
var hlsl = ReadShaderSource(FindCultMathRoot());
|
||||
var tree = CSharpSyntaxTree.ParseText(TransformHlslToCSharp(hlsl, members));
|
||||
var tree = CSharpSyntaxTree.ParseText(TransformHlslToCSharp(hlsl, members, defines));
|
||||
var references = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!)
|
||||
.Split(Path.PathSeparator)
|
||||
.Append(typeof(math).Assembly.Location)
|
||||
|
|
|
|||
|
|
@ -9,19 +9,19 @@ namespace CultMath.Tests;
|
|||
/// </summary>
|
||||
public sealed class LatticeCellsTests
|
||||
{
|
||||
private const float Cell = 260.0f;
|
||||
private const float Falloff = 120.0f;
|
||||
private const float Drift = 0.7f;
|
||||
private static readonly float2 Normal = new(0.6f, 0.8f);
|
||||
internal const float Cell = 260.0f;
|
||||
internal const float Falloff = 120.0f;
|
||||
internal const float Drift = 0.7f;
|
||||
internal static readonly float2 Normal = new(0.6f, 0.8f);
|
||||
|
||||
private sealed record Look(float Boost, float Stretch, float Smoothing, float Falloff = LatticeCellsTests.Falloff);
|
||||
internal sealed record Look(float Boost, float Stretch, float Smoothing, float Falloff = LatticeCellsTests.Falloff);
|
||||
|
||||
private static readonly Look[] Looks =
|
||||
internal static readonly Look[] Looks =
|
||||
{
|
||||
new(1.6f, 1.0f, 0.35f), new(1.6f, 2.0f, 0.35f), new(LatticeMaxBoost, LatticeMaxStretch, LatticeMaxSmoothing), new(0.0f, 1.0f, 0.05f),
|
||||
};
|
||||
|
||||
private static float4[] Bodies(float t)
|
||||
internal static float4[] Bodies(float t)
|
||||
{
|
||||
var bodies = new float4[6];
|
||||
for (var i = 0; i < bodies.Length; i++)
|
||||
|
|
@ -74,7 +74,7 @@ public sealed class LatticeCellsTests
|
|||
private static float4 Call(float2 p, float time, float4[] bodies, Look look, float2? normal = null) =>
|
||||
weighted_lattice_cells(p, time, bodies, Cell, Drift, look.Boost, look.Falloff, look.Smoothing, normal ?? Normal, look.Stretch);
|
||||
|
||||
private static float2 RandomPoint(System.Random r) =>
|
||||
internal static float2 RandomPoint(System.Random r) =>
|
||||
new((r.NextSingle() * 2.0f - 1.0f) * 1500.0f, (r.NextSingle() * 2.0f - 1.0f) * 1500.0f);
|
||||
|
||||
[Fact]
|
||||
|
|
@ -97,9 +97,9 @@ public sealed class LatticeCellsTests
|
|||
}
|
||||
}
|
||||
|
||||
private delegate bool Stop(int k, float f1, float f2, Look look);
|
||||
internal delegate bool Stop(int k, float f1, float f2, Look look);
|
||||
|
||||
private static readonly (string name, Stop stop)[] Rules =
|
||||
internal static readonly (string name, Stop stop)[] Rules =
|
||||
{
|
||||
("correct", (k, f1, f2, l) => k > 1 && 0.5f * (k - 1) >= max(f2, f1 + 2.0f * l.Smoothing)),
|
||||
("cutoff F1 + k", (k, f1, f2, l) => k > 1 && 0.5f * (k - 1) >= max(f2, f1 + l.Smoothing)),
|
||||
|
|
@ -109,7 +109,7 @@ public sealed class LatticeCellsTests
|
|||
};
|
||||
|
||||
// The radius of the box a search with the given exit rule visits (rings 0 to k - 1 when it stops before ring k).
|
||||
private static int Radius(float2 p, float time, float4[] bodies, Look look, Stop stop,
|
||||
internal static int Radius(float2 p, float time, float4[] bodies, Look look, Stop stop,
|
||||
Dictionary<(int, int), float> weights)
|
||||
{
|
||||
var q = p / Cell;
|
||||
|
|
|
|||
129
packages/cultmath/tests/CultMath.Tests/SiteArrays.cs
Normal file
129
packages/cultmath/tests/CultMath.Tests/SiteArrays.cs
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
using CultMath;
|
||||
using static CultMath.math;
|
||||
|
||||
namespace CultMath.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The shader's site-array functions as C# twins. A shader function cannot take a span, so
|
||||
/// <c>cultmath_power_border</c>, <c>cultmath_lattice_cell_distance</c> and <c>cultmath_weighted_lattice_cells</c> take
|
||||
/// <c>float4 sites[CULTMATH_MAX_SITES]</c> and a count; reflection cannot pass a <see cref="ReadOnlySpan{T}"/>, so each
|
||||
/// twin takes the array and the count and calls the span function on <c>sites[..count]</c>. This table is the one
|
||||
/// place that maps them, read by the mirror test and by the GLSL fixture. The draws are the cases both run.
|
||||
/// </summary>
|
||||
internal static class SiteArrays
|
||||
{
|
||||
/// <summary>The shader's default CULTMATH_MAX_SITES; the device families spell their array with it.</summary>
|
||||
internal const int Capacity = 128;
|
||||
|
||||
internal static float4 power_border(float3 p, float4[] sites, int count) => math.power_border(p, sites.AsSpan(0, count));
|
||||
|
||||
internal static float lattice_cell_distance(
|
||||
float2 q, float2 cell, float time, float drift, float4[] bodies, int count, float cellSize, float boost, float falloff,
|
||||
float2 normal, float stretch) =>
|
||||
math.lattice_cell_distance(q, cell, time, drift, bodies.AsSpan(0, count), cellSize, boost, falloff, normal, stretch);
|
||||
|
||||
internal static float4 weighted_lattice_cells(
|
||||
float2 p, float time, float4[] bodies, int count, float cellSize, float drift, float boost, float falloff,
|
||||
float smoothing, float2 stretchNormal, float stretch) =>
|
||||
math.weighted_lattice_cells(p, time, bodies.AsSpan(0, count), cellSize, drift, boost, falloff, smoothing, stretchNormal, stretch);
|
||||
|
||||
// The array the shader receives: the sites, then filler a loop running past the count would read. The filler is
|
||||
// finite and large, so a loop bound that ignores the count changes the result.
|
||||
private static float4[] Padded(IReadOnlyList<float4> sites)
|
||||
{
|
||||
var array = new float4[Capacity];
|
||||
for (var i = 0; i < Capacity; i++)
|
||||
array[i] = i < sites.Count ? sites[i] : new float4(40.0f * (i + 1), -30.0f * (i + 1), 7.0f, 90.0f + i);
|
||||
return array;
|
||||
}
|
||||
|
||||
private static float Uniform(System.Random r, float lo, float hi) => lo + (hi - lo) * r.NextSingle();
|
||||
|
||||
// Counts 0, 1, 6, 16 and the capacity are drawn often; the rest of [0, Capacity] fills between.
|
||||
private static int Count(System.Random r) => r.Next(3) == 0 ? r.Next(Capacity + 1) : new[] { 0, 1, 6, 16, Capacity }[r.Next(5)];
|
||||
|
||||
// Bodies on slow orbits (float4(position.xy, 0, sigma)), spread over the plane the lattice cells cover.
|
||||
private static float4[] Orbit(System.Random r, int count, float time)
|
||||
{
|
||||
var bodies = new List<float4>();
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var angle = 0.001f * (i + 1) * time + i;
|
||||
var radius = 100.0f + 2400.0f * r.NextSingle();
|
||||
bodies.Add(new float4(radius * MathF.Cos(angle), radius * MathF.Sin(angle), 0.0f, Uniform(r, 20.0f, 300.0f)));
|
||||
}
|
||||
|
||||
return Padded(bodies);
|
||||
}
|
||||
|
||||
internal static object[] PowerBorderArguments(System.Random r)
|
||||
{
|
||||
var count = Count(r);
|
||||
var sites = new List<float4>();
|
||||
for (var i = 0; i < count; i++)
|
||||
sites.Add(new float4(Uniform(r, -1500.0f, 1500.0f), Uniform(r, -1500.0f, 1500.0f), Uniform(r, -200.0f, 200.0f), Uniform(r, 10.0f, 300.0f)));
|
||||
return new object[] { new float3(Uniform(r, -1500.0f, 1500.0f), Uniform(r, -1500.0f, 1500.0f), Uniform(r, -200.0f, 200.0f)), Padded(sites), count };
|
||||
}
|
||||
|
||||
internal static object[] LatticeCellDistanceArguments(System.Random r)
|
||||
{
|
||||
var angle = Uniform(r, 0.0f, 6.2831855f);
|
||||
var look = LatticeCellsTests.Looks[r.Next(LatticeCellsTests.Looks.Length)];
|
||||
var cell = new float2(r.Next(-300, 300), r.Next(-300, 300));
|
||||
var count = Count(r);
|
||||
return new object[]
|
||||
{
|
||||
new float2(Uniform(r, -1500.0f, 1500.0f), Uniform(r, -1500.0f, 1500.0f)) / LatticeCellsTests.Cell, cell, Uniform(r, 0.0f, 200.0f), LatticeCellsTests.Drift,
|
||||
Orbit(r, count, Uniform(r, 0.0f, 200.0f)), count, LatticeCellsTests.Cell, look.Boost, look.Falloff, new float2(MathF.Cos(angle), MathF.Sin(angle)), look.Stretch,
|
||||
};
|
||||
}
|
||||
|
||||
// The unit-less normals the function normalises itself: ordinary, 3-4-5, tiny, huge, and zero (stretch 1 only).
|
||||
private static readonly float2[] Normals = { LatticeCellsTests.Normal, new(3.0f, 4.0f), new(3.0e-30f, -4.0e-30f), new(1.0e30f, 2.0e30f), new(0.0f, 0.0f) };
|
||||
|
||||
/// <summary>
|
||||
/// Points whose ring search runs to ring 8 or past it under the widest look (boost, stretch and smoothing at their
|
||||
/// maxima, falloff so wide that every cell is boosted), found once by the radius the exit rule visits, and the
|
||||
/// ring-17 point of LatticeCellsTests.TheCapIsReachedAndMatchesTheFullBox first. Each is (p, time).
|
||||
/// </summary>
|
||||
internal static readonly IReadOnlyList<(float2 P, float Time, int Ring)> FarPoints = FindFarPoints();
|
||||
|
||||
internal static readonly LatticeCellsTests.Look WidestLook = new(LatticeMaxBoost, LatticeMaxStretch, LatticeMaxSmoothing, 1.0e6f);
|
||||
|
||||
private static List<(float2, float, int)> FindFarPoints()
|
||||
{
|
||||
var found = new List<(float2, float, int)>();
|
||||
var cap = (new float2(1446.7345f, -680.7637f), 97.69269f);
|
||||
found.Add((cap.Item1, cap.Item2, LatticeCellsTests.Radius(cap.Item1, cap.Item2, LatticeCellsTests.Bodies(cap.Item2), WidestLook, LatticeCellsTests.Rules[0].stop, new Dictionary<(int, int), float>())));
|
||||
var r = new System.Random(0x1A77);
|
||||
while (found.Count < 12)
|
||||
{
|
||||
var p = LatticeCellsTests.RandomPoint(r);
|
||||
var time = 13.0f * r.Next(20);
|
||||
var ring = LatticeCellsTests.Radius(p, time, LatticeCellsTests.Bodies(time), WidestLook, LatticeCellsTests.Rules[0].stop, new Dictionary<(int, int), float>());
|
||||
if (ring >= 8)
|
||||
found.Add((p, time, ring));
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
internal static object[] LatticeArguments(System.Random r)
|
||||
{
|
||||
if (r.Next(3) == 0)
|
||||
{
|
||||
var far = FarPoints[r.Next(FarPoints.Count)];
|
||||
return Lattice(far.P, far.Time, Padded(LatticeCellsTests.Bodies(far.Time)), 6, WidestLook, LatticeCellsTests.Normal);
|
||||
}
|
||||
|
||||
var time = 13.0f * r.Next(20);
|
||||
var normal = Normals[r.Next(Normals.Length)];
|
||||
var look = normal.x == 0.0f ? LatticeCellsTests.Looks[0] : LatticeCellsTests.Looks[r.Next(LatticeCellsTests.Looks.Length)];
|
||||
var count = Count(r);
|
||||
return Lattice(LatticeCellsTests.RandomPoint(r), time, Orbit(r, count, time), count, look, normal);
|
||||
}
|
||||
|
||||
private static object[] Lattice(float2 p, float time, float4[] bodies, int count, LatticeCellsTests.Look look, float2 normal) =>
|
||||
new object[] { p, time, bodies, count, LatticeCellsTests.Cell, LatticeCellsTests.Drift,
|
||||
look.Boost, look.Falloff, look.Smoothing, normal, look.Stretch };
|
||||
}
|
||||
|
|
@ -16,6 +16,7 @@ import sys
|
|||
HLSL_VEC = re.compile(r'(float|int|uint)([234])$')
|
||||
GLSL_VEC = re.compile(r'(i|u|)vec([234])$')
|
||||
KIND = {'float': 'f', 'int': 'i', 'uint': 'u'}
|
||||
ARRAY = re.compile(r'(\w+)\[(\d+)\]$') # an array leaf, vec4[128]: N elements of one leaf type, N x its words
|
||||
|
||||
|
||||
def structs(root):
|
||||
|
|
@ -79,6 +80,19 @@ def body(sig, n, win, wout, defs, glsl):
|
|||
ret, name, params = m.group(1), m.group(2), [p.strip() for p in m.group(3).split(',') if p.strip()]
|
||||
lines, offset, args = [], 0, []
|
||||
for j, p in enumerate(params):
|
||||
array = ARRAY.match(p)
|
||||
if array:
|
||||
elem, size = array.group(1), int(array.group(2))
|
||||
words = leaves(elem, defs)
|
||||
lines.append(' %s a%d[%d];' % (elem if glsl else hlsl_type(elem), j, size))
|
||||
lines.append(' for (uint e = 0u; e < %du; e++) {' % size)
|
||||
for k, leaf in enumerate(words):
|
||||
word = ('In.a[b + %du + e * %du]' if glsl else 'In[b + %du + e * %du]') % (offset + k, len(words))
|
||||
lines.append(' a%d[e]%s = %s;' % (j, access(leaf, glsl), read(leaf[1], glsl, word)))
|
||||
lines.append(' }')
|
||||
offset += size * len(words)
|
||||
args.append('a%d' % j)
|
||||
continue
|
||||
ptype = p if glsl else hlsl_type(p)
|
||||
lines.append(' %s a%d;' % (ptype, j))
|
||||
for leaf in leaves(p, defs):
|
||||
|
|
|
|||
|
|
@ -600,14 +600,12 @@ CultCellular cultmath_cellular(float3 p)
|
|||
return result;
|
||||
}
|
||||
|
||||
// Sites: a site is float4(position.xyz, weight). A span is a loop over a per-site step, because a shader
|
||||
// function cannot take a span in the mirror (design.md, "Sites"). The consumer's loop, over its own buffer:
|
||||
// Sites: a site is float4(position.xyz, weight). A shader function cannot take a span (design.md, "Sites"), so a span is a
|
||||
// fixed-capacity array and a count (cultmath_power_border, below), or a loop over a per-site step:
|
||||
// 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);
|
||||
// The exact power cell border is a second loop over the buffer, skipping the owner cells.nearestSite:
|
||||
// float4 border = float4(0.0, 0.0, 0.0, 1.0e30); int owner = (int)cells.nearestSite;
|
||||
// for (int k = 0; k < count; k++) if (k != owner) border = cultmath_power_border_step(p, sites[owner], sites[k], border);
|
||||
// The exact power cell border is cultmath_power_border, the second loop over the sites that skips the owner cells.nearestSite.
|
||||
// The step trusts the owner: a p outside the owner's cell reports distance 0 with that plane's normal, not an error.
|
||||
// Statement for statement with math.Sites.cs (power_score, multiplicative_score, site_cells_*, gabriel_margin).
|
||||
struct CultSiteCells
|
||||
|
|
@ -688,21 +686,8 @@ float cultmath_gabriel_margin(float3 a, float3 b, float3 other)
|
|||
return (cultmath_distance(other, (a + b) * 0.5) - r) / r;
|
||||
}
|
||||
|
||||
// Weighted lattice cells: the four per-cell steps of math.Lattice.cs, statement for statement. A shader function cannot take a
|
||||
// span (design.md, "Sites"), so weighted_lattice_cells is the consumer's loop over its own body buffer, in two passes:
|
||||
// float2 q = p / cellSize; int2 c0 = (int2)floor(q); float f1 = 1.0e30, f2 = 1.0e30; int reach = 0;
|
||||
// for (int k = 0; ; k++) { // ring pass: Chebyshev rings 0, 1, 2, ... around c0, exact exit
|
||||
// if (k > 1 && 0.5 * (k - 1) >= max(f2, f1 + 2.0 * smoothing)) break; // k never reaches 38 in the accepted range
|
||||
// for each cell on ring k: d = cultmath_lattice_distance(q, cultmath_lattice_site(cell, time, drift).xy, w, normal, stretch),
|
||||
// w = cultmath_lattice_weight(site.z, border, boost, falloff), border = the .w of cultmath_power_border_step
|
||||
// folded over the bodies (owner = the nearest body of the cell centre (cell + 0.5) * cellSize, z = 0);
|
||||
// if (d < f1) { f2 = f1; f1 = d; } else if (d < f2) f2 = d; store d for the box pass
|
||||
// reach = k; }
|
||||
// float m = f1 + smoothing; // box pass: every stored cell, rows dz = -reach..reach, then dx = -reach..reach
|
||||
// for each (dz, dx): m = cultmath_lattice_smooth_step(m, d, f1, smoothing); // strict < for the winning id (earlier cell wins ties)
|
||||
// The preconditions the C# function throws for are the caller's in a shader: finite arguments, cellSize > 0, boost in [0, 4],
|
||||
// falloff > 0, smoothing in (0, 1], stretch in [1, 2], p within 2^23 cells. The normal is normalised as C# does: divide by its
|
||||
// largest component, then by its length (a zero normal means (1, 0) and needs stretch == 1). The ring bound is 37.
|
||||
// Weighted lattice cells: the four per-cell steps of math.Lattice.cs, statement for statement; cultmath_weighted_lattice_cells,
|
||||
// after them, is the whole function.
|
||||
float3 cultmath_lattice_site(float2 cell, float time, float drift)
|
||||
{
|
||||
int3 h = cultmath_pcg3d(int3((int)cell.x, (int)cell.y, 0));
|
||||
|
|
@ -734,6 +719,90 @@ float cultmath_lattice_smooth_step(float m, float d, float f1, float smoothing)
|
|||
return min(next, f1 + smoothing);
|
||||
}
|
||||
|
||||
// Sites by value: a shader function cannot take a span, so these take float4 sites[CULTMATH_MAX_SITES] and the count in use, with
|
||||
// count in [0, CULTMATH_MAX_SITES]. A consumer defines CULTMATH_MAX_SITES before including this file to change the capacity; loops
|
||||
// run to count, so the capacity costs uniform space, not iterations. A StructuredBuffer caller copies into a local array first.
|
||||
// The preconditions the C# functions throw for are the caller's in a shader: finite arguments, cellSize > 0, boost in [0, 4],
|
||||
// falloff > 0, smoothing in (0, 1], stretch in [1, 2], p within 2^23 cells. A zero stretchNormal means (1, 0) and needs stretch == 1.
|
||||
// cultmath_weighted_lattice_cells is math.weighted_lattice_cells: the ring pass is bounded by k <= 37 and exits as C# does, and the
|
||||
// box pass recomputes each distance instead of caching it (a 75 x 75 private array is not a shader option), with the same values.
|
||||
#ifndef CULTMATH_MAX_SITES
|
||||
#define CULTMATH_MAX_SITES 128
|
||||
#endif
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
float2 cultmath_segment_closest(float2 point_value, float2 start, float2 end)
|
||||
{
|
||||
float2 segment = end - start;
|
||||
|
|
|
|||
Loading…
Reference in a new issue