Merge remote-tracking branch 'origin/main' into hands/variants-c2a-main

This commit is contained in:
Meta Vens 2026-10-14 19:38:48 +02:00
commit 0f6edfbfbb
72 changed files with 78062 additions and 892 deletions

View file

@ -33,9 +33,20 @@ shader semantics.
- `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.
It includes `shaders/CultMath.Phacelle.hlsl` (MPL-2.0) and
It includes `shaders/CultMath.Phacelle.hlsl` (MPL-2.0),
`shaders/CultMath.Cycles.hlsl` (Apache-2.0) and
`shaders/CultMath.Interval.hlsl` and `shaders/CultMath.Affine.hlsl` from the same
directory, so ship all four.
directory, so ship all five.
- Cycles node semantics (Apache-2.0): `cycles_*` functions that compute what
Blender's Cycles renderer computes for the Math node operations whose results
differ from a plain intrinsic (`cycles_divide`, `cycles_power`, `cycles_modulo`,
`cycles_wrap`, `cycles_pingpong`, `cycles_smooth_min`, ...), Map Range
(`cycles_map_range_linear`, `_stepped`, `_smoothstep`, `_smootherstep`), Clamp
(`cycles_clamp_minmax`, `cycles_clamp_range`), Mix (`cycles_mix_float`,
`cycles_mix_vector` and every colour blend mode as `cycles_mix_<mode>`), RGB to BW,
and `cycles_ramp_index`, where a Color Ramp reads its table. `cultmath_cycles_*` in
HLSL and GLSL. Operands are finite floats, and the tests hold every function to
the results of Blender 5.2.2's own CPU Cycles (`tools/cycles-oracle`).
- interval arithmetic for culling empty space: `iv_*` functions
over `float2(lo, hi)` (`iv_add`, `iv_mul`, `iv_exp`, `iv_smoothstep`, ...)
and `iv_snoise_ball`/`iv_fbm_ball`, which bound `snoise` and `fbm_grad` over a
@ -58,12 +69,24 @@ shader semantics.
- `shaders/CultMath.glsl` (MIT), the same `cultmath_*` library in GLSL ES 3.00
for WebGL2, generated from `CultMath.hlsl` (never edited by hand), and
`shaders/CultMath.Phacelle.glsl` (MPL-2.0), generated from
`CultMath.Phacelle.hlsl`, which holds `cultmath_phacelle` alone. GLSL has no
`CultMath.Phacelle.hlsl`, which holds `cultmath_phacelle` alone, and
`shaders/CultMath.Cycles.glsl` (Apache-2.0), generated from
`CultMath.Cycles.hlsl`, which holds the `cultmath_cycles_*` functions. GLSL has no
`#include`: a WebGL consumer concatenates `CultMath.glsl` after its own
`#version 300 es` line and `precision highp float; precision highp int;`
(the library declares no precision, and its hashes need 32-bit integers),
then `CultMath.Phacelle.glsl` only if it calls `cultmath_phacelle`, then its
then `CultMath.Phacelle.glsl` only if it calls `cultmath_phacelle` and
`CultMath.Cycles.glsl` only if it calls a `cultmath_cycles_` function, then its
own shader source.
- Span primitives (`math.Span.cs`, `cultmath_*` in HLSL and GLSL): `snoise_hessian`,
the analytic Hessian of `snoise(float3)` on the same lattice, hash and tie order as
`snoise_grad` (a symmetric `float3x3`; GLSL `mat3`), and `integral_clamp_linear(a,
b, lo, hi, t0, t1)`, the closed-form integral over `[t0, t1]` of `clamp(a + b t,
lo, hi)`. Three measured bounds describe `snoise`: `SNOISE_LIPSCHITZ` (gradient
length, `NoiseBoundTests.MeasureLipschitz`), `SNOISE_HESSIAN` (Hessian spectral
norm, `MeasureHessian`) and `SNOISE_THIRD` (third-derivative operator norm,
`MeasureThird`); each is 1.10 times a seeded maximum refined by ascent, and a
fast test pins it. They are empirical with a margin, not proofs.
- `Voronoi.SampleTones`, a C# batch surface that calls the Rust
`cultmath-core` native kernel when `cultmath_core` is available and falls back
to the managed parity path otherwise.

View file

@ -22,6 +22,35 @@ permutation and scale as `snoise(float3)`.
- Upstream: <https://github.com/ashima/webgl-noise>
- License: MIT.
## Cycles node semantics
`math.cycles_*` and `cultmath_cycles_*` port what Blender's Cycles renderer
computes for the Math, Map Range, Clamp, Mix and RGB to BW nodes and for a Color
Ramp lookup. Each function's comment names the Cycles file it follows, all from
`intern/cycles` at the Blender `v5.2.2` tag: `kernel/svm/math_util.h`,
`kernel/svm/map_range.h`, `kernel/svm/clamp.h`, `kernel/svm/mix.h`,
`kernel/svm/color_util.h`, `kernel/svm/ramp.h`, `kernel/svm/convert.h`,
`util/math_base.h`, `util/math_float3.h` and `util/color.h`. The code was
changed: Cycles C++ became C# and HLSL, one function per node operation, with
the nodes' socket defaults and clamp options left to the caller, and the modulo
is the quotient form every CultMath target shares rather than `fmodf`. Nothing
was read from Blender's GPL sources (`source/blender/gpu`, `source/blender/blenlib`).
- Copyright 2011-2022 Blender Foundation.
- Upstream: <https://projects.blender.org/blender/blender> (`intern/cycles`).
- License: Apache-2.0 (<https://www.apache.org/licenses/LICENSE-2.0>), which is
per-file here: it covers `src/CultMath/math.Cycles.cs`,
`shaders/CultMath.Cycles.hlsl` and the Unity copy of that include, and
`shaders/CultMath.Cycles.glsl`, which is generated from that include. Each
carries the Apache-2.0 header and this attribution. The rest of CultMath, the
generated GLSL library included, is MIT or MPL-2.0 as above, so the
`GameCult.Math` NuGet package and the `org.gamecult.cultmath` Unity package
both declare `MIT AND MPL-2.0 AND Apache-2.0` and ship this file.
- The test fixtures under `tests/CultMath.Tests/fixtures/cycles-oracle` are
results of running Blender 5.2.2 through `tools/cycles-oracle/oracle.py`
(GPL-3.0-or-later, a Blender Python script, shipped neither in the NuGet
package nor in the Unity package).
## Phacelle Noise
`math.phacelle` and `cultmath_phacelle` follow Rune Skovbo Johansen's Phacelle

View file

@ -764,12 +764,29 @@ radius is small and the axis carries the variation. `af_fbm` compounds octaves
as `iv_fbm_ball` does. The float32 evaluation allowance is derived in
`af_snoise`'s comment.
`SNOISE_HESSIAN = 56.050385` is 1.10 times the refined maximum of the spectral
`SNOISE_HESSIAN = 55.642143` is 1.10 times the refined maximum of the spectral
norm of the Hessian of `snoise(float3)`, measured by
`NoiseBoundTests.MeasureHessian` over 1e6 seeded points (central differences of
`snoise_grad`) and refined by ascent from the 1e4 largest: sampled 50.1366,
refined 50.9549, witness (-245.19885, -53.01323, -91.47363).
`NoiseBoundTests.MeasureHessian` over 1e6 seeded points (the analytic
`snoise_hessian`, below) and refined by ascent from the 1e4 largest: refined
maximum 50.5838. The central differences of `snoise_grad` that an earlier pin
used read 50.955 at h = 1e-3, their roundoff.
`HessianConstantPinsSampledCurvature` fails on a 1% move.
`snoise_hessian(float3)` (`math.Span.cs`) is the analytic Hessian of `snoise`: a
symmetric `float3x3` on the same lattice, hash and tie order as `snoise_grad`,
differentiating each corner's gradient `-8 m^3 s x + m^4 p` once more. Each
off-diagonal entry is computed once and placed twice, so the matrix equals its
transpose bit for bit, and a clamped corner (`m = 0`) contributes nothing. Built
from nine scalars, the matrix reads as columns in GLSL (`mat3`) and rows in HLSL,
which is the same matrix because it is symmetric. `SNOISE_THIRD = 536.9152`
(`math.Span.cs`) is the next order: 1.10 times the maximum, over 1e6 seeded points,
of the operator norm of the third-derivative tensor of `snoise` (central
differences of `snoise_hessian` at h = 1e-3, then an ascent over unit vectors),
refined from the 1e4 largest; measured 488.1047 on the tied kernel.
`MeasureThird` takes the measurement and `ThirdConstantPinsSampled` pins it.
`integral_clamp_linear(a, b, lo, hi, t0, t1)` is the closed-form integral over
`[t0, t1]` of `clamp(a + b t, lo, hi)`. All three have HLSL and GLSL lowerings and
`glsl-parity.json` fixture families (`snoise_hessian`, `integral_clamp_linear`; the
`af_snoise` and `af_fbm` families are regenerated for the re-pin).
`SNOISE2_LIPSCHITZ = 8.117002` is the same for the gradient of `snoise(float2)`
(`MeasureLipschitz2`: sampled 7.2575, refined 7.3791, witness (-67.12454,
-129.53296), `|snoise2|` at most 0.99964), and it backs `iv_snoise_ball(float2,
@ -779,7 +796,7 @@ curvature constant 20% low, so `SNOISE_HESSIAN` is defended by
(`af_snoise` at the point where the curvature is realised, along 4,000 directions: a
constant of 40 misses there). The margin over the function itself: a scan of the whole
289^3 hash period found a realised maximum of 50.58, and bounding each corner's gradient
independently over every hash configuration gives 52.22, so 56.05 sits 7% above the
independently over every hash configuration gives 52.22, so 55.64 sits 7% above the
configuration bound. A change to the kernels must re-run the measurements.
The slice. `af_frustum_ball(centreSlope, z0, z1, footprintPerDepth,
@ -834,6 +851,39 @@ interval, under the affine bound and under the oracle mask (one logarithmic
scale) and the transmittance. Its run: 4.23, 3.60 and 2.02 cells per ray on
average, 44 the most, mean transmittance 0.278.
## Expressions
`CultMath.Expr` holds a scalar SSA expression graph as a persisted value, a builder
for it, and a C# evaluator.
- **Graph (`ExprGraph`)**: a sealed immutable class. It has no name of its own; the
consumer record that holds it names it. Nodes are in topological order, an operand
names a lower node, and an edit builds a new graph. A persisted graph carries a
format version (1); one naming an unknown op, a newer format or a forward operand is
refused whole at decode. `ExprGraph.Create` is the one validator, run by the builder
and by decode.
- **Node**: its index in the topological order. The builder hash-conses identical
(op, operands, constant bits) nodes and drops nodes no output reaches, so one
expression always builds the same bytes; any rebuild may renumber nodes.
- **Port**: graph inputs vary per point, params are uniform per batch and carry a
default, outputs name a node. Names are `[A-Za-z_][A-Za-z0-9_]*`, unique per kind.
An op's operands are positional; a multi-result op (`cellular3`: nearest.xyzw,
edge.xyzw, id) is read only through `Pick`.
- **Op vocabulary**: one table (`ExprOps`), a stable string per op, append-only.
Vector arguments are decomposed operands: `snoise2`, `snoise3`, `cellular3`. An op
calls its CultMath function; a function's value change is a Breaking release note.
- **Evaluation**: `ExprEvaluator.Evaluate` runs the nodes in order through the table,
one IEEE single per op, so a result equals the direct composition of the same math
calls bit for bit. Params bind by name (`ExprBindings`): a missing name takes its
default and an unknown name is refused.
- **Stencils** are substitution at build time (`ExprBuilder.Substitute`, Fidget's
`remap_xyz`): N substitutions of the position inputs combined by ops give an ordinary
flat graph. There is no loop construct.
The MessagePack shape belongs to `GameCult.Caching.MessagePack` (`CultMathExprResolver`).
Interval, affine and gradient evaluation over the graph, bytecode, the HLSL
interpreter and pruning are not built.
## Rules
- Keep type names HLSL-shaped: `float2`, `float3`, `float4`, `float3x3`, and `math`.

View file

@ -86,7 +86,9 @@ $requiredTemplateFiles = @(
"Shaders\CultMath.Interval.hlsl",
"Shaders\CultMath.Interval.hlsl.meta",
"Shaders\CultMath.Affine.hlsl",
"Shaders\CultMath.Affine.hlsl.meta"
"Shaders\CultMath.Affine.hlsl.meta",
"Shaders\CultMath.Cycles.hlsl",
"Shaders\CultMath.Cycles.hlsl.meta"
)
foreach ($relativePath in $requiredTemplateFiles) {
if (-not (Test-Path -LiteralPath (Join-Path $templateRoot $relativePath) -PathType Leaf)) {

View file

@ -10,7 +10,11 @@
// An upper bound on the spectral norm of the Hessian of cultmath_snoise(float3); provenance in
// math.Affine.cs (SNOISE_HESSIAN).
static const float CULTMATH_SNOISE_HESSIAN = 56.050385;
static const float CULTMATH_SNOISE_HESSIAN = 55.642143;
// An upper bound on the operator norm of the third-derivative tensor of cultmath_snoise(float3), the
// next order after CULTMATH_SNOISE_HESSIAN; provenance in math.Span.cs (SNOISE_THIRD).
static const float CULTMATH_SNOISE_THIRD = 536.9152;
float3 cultmath_af_point(float value) { return float3(value, 0.0, 0.0); }
float3 cultmath_af_symbol(float x0, float a) { return float3(x0, a, 0.0); }

View file

@ -0,0 +1,363 @@
// Generated from shaders/CultMath.Cycles.hlsl by GlslLowering (packages/cultmath/tests/CultMath.Tests/GlslLowering.cs). Do not edit; regenerate with CULTMATH_WRITE_GLSL=1 dotnet test --filter GlslMirrorTests. Apache-2.0; requires CultMath.glsl before it.
#ifndef CULTMATH_CYCLES_GLSL
#define CULTMATH_CYCLES_GLSL
// SPDX-License-Identifier: Apache-2.0
//
// Cycles node semantics: what Blender's Cycles renderer computes for the Math, Map Range, Clamp, Mix and
// RGB to BW nodes and for a Color Ramp lookup, ported function by function from the Cycles kernel
// (intern/cycles of the Blender v5.2.2 tag; SPDX-FileCopyrightText: 2011-2022 Blender Foundation, Apache-2.0):
// kernel/svm/{math_util,map_range,clamp,mix,color_util,ramp,convert}.h, util/math_base.h, util/color.h and
// util/math_float3.h. Each function's comment names its Cycles source. Modified by GameCult: Cycles C++
// becomes HLSL, a function per node operation, and the node's socket defaults and clamp options are left to
// the caller. This file is Apache-2.0 (section 4: it was changed); CultMath.hlsl, which includes it after its
// own definitions, is MIT (see THIRD-PARTY-NOTICES.md). math.Cycles.cs mirrors it bit for bit.
//
// Operands are finite floats. NaN and infinite operands are outside the oracle's reach and the mirror's.
// FLT_EPSILON, the least epsilon a Compare node honours.
const float CULTMATH_CYCLES_FLT_EPSILON = 1.1920929e-07;
// The scene-linear luminance coefficients Cycles reads from Blender 5.2.2's default OCIO config
// (kernel/film linear_rgb_to_gray). The oracle fixture pins them with a case per primary.
const float CULTMATH_CYCLES_RGB_TO_Y_R = 0.212639093;
const float CULTMATH_CYCLES_RGB_TO_Y_G = 0.715169132;
const float CULTMATH_CYCLES_RGB_TO_Y_B = 0.0721927434;
// ---- Math node (kernel/svm/math_util.h svm_math; util/math_base.h) ----
// safe_divide
float cultmath_cycles_divide(float a, float b) { return b != 0.0 ? a / b : 0.0; }
// safe_powf with compatible_powf. A negative base takes an integral exponent's parity; a base below zero
// with a fractional exponent is 0.
float cultmath_cycles_power(float a, float b)
{
float whole = b >= 0.0 ? floor(b) : ceil(b);
if (a < 0.0 && b != whole)
return 0.0;
if (b == 0.0)
return 1.0;
if (a == 0.0)
return 0.0;
if (a < 0.0)
{
float magnitude = pow(-a, b);
// Odd exactly when the remainder is 1: an infinite exponent leaves NaN here and is even, as powf(a, +-inf) is never negative.
return b - 2.0 * floor(0.5 * b) == 1.0 ? -magnitude : magnitude;
}
return pow(a, b);
}
// safe_logf
float cultmath_cycles_logarithm(float a, float b)
{
if (a <= 0.0 || b <= 0.0)
return 0.0;
float denominator = log(b);
return denominator != 0.0 ? log(a) / denominator : 0.0;
}
// safe_sqrtf
float cultmath_cycles_sqrt(float a) { return sqrt(max(a, 0.0)); }
// inversesqrtf
float cultmath_cycles_inverse_sqrt(float a) { return a > 0.0 ? 1.0 / sqrt(a) : 0.0; }
// safe_modulo is fmodf, the remainder with the dividend's sign, exactly. GLSL has no fmod, and a - b trunc(a / b)
// is wrong where the quotient rounds up to an integer or the product rounds (3 mod 0.3 is 0.29999995, not 0).
// So this subtracts the largest power-of-two multiple of the divisor not above the remainder until the
// remainder is below the divisor: every step is an exact subtraction, as in fmod. The loops are bounded by the
// binades a float spans.
float cultmath_cycles_modulo(float a, float b)
{
float remainder = abs(a);
float divisor = abs(b);
for (int steps = 0; steps < 300 && remainder >= divisor && divisor > 0.0; steps++)
{
float multiple = divisor;
for (int doublings = 0; doublings < 300 && multiple * 2.0 <= remainder; doublings++)
multiple = multiple * 2.0;
remainder = remainder - multiple;
}
return b != 0.0 ? (a < 0.0 ? -remainder : remainder) : 0.0;
}
// safe_floored_modulo; a build that contracts it differs by a bound stated at cycles_floored_modulo in math.Cycles.cs and the README
float cultmath_cycles_floored_modulo(float a, float b) { return b != 0.0 ? a - floor(a / b) * b : 0.0; }
// wrapf (note the argument order: value, max, min); contraction bound as for floored_modulo
float cultmath_cycles_wrap(float value, float max_value, float min_value)
{
float range = max_value - min_value;
return range != 0.0 ? value - (range * floor((value - min_value) / range)) : min_value;
}
// floorf(safe_divide(a, b)) * b
float cultmath_cycles_snap(float a, float b) { return floor(cultmath_cycles_divide(a, b)) * b; }
// pingpongf
float cultmath_cycles_pingpong(float a, float b)
{
float scaled = (a - b) / (b * 2.0);
return b != 0.0 ? abs((scaled - floor(scaled)) * b * 2.0 - b) : 0.0;
}
// smoothminf
float cultmath_cycles_smooth_min(float a, float b, float k)
{
float h = max(k - abs(a - b), 0.0) / k;
return k != 0.0 ? min(a, b) - h * h * h * k * 0.16666667 : min(a, b);
}
// -smoothminf(-a, -b, k)
float cultmath_cycles_smooth_max(float a, float b, float k) { return -cultmath_cycles_smooth_min(-a, -b, k); }
// NODE_MATH_COMPARE
float cultmath_cycles_compare(float a, float b, float epsilon)
{
return (a == b || abs(a - b) <= max(epsilon, CULTMATH_CYCLES_FLT_EPSILON)) ? 1.0 : 0.0;
}
// NODE_MATH_ROUND
float cultmath_cycles_round(float a) { return floor(a + 0.5); }
// NODE_MATH_TRUNC
float cultmath_cycles_trunc(float a) { return a >= 0.0 ? floor(a) : ceil(a); }
// NODE_MATH_FRACTION
float cultmath_cycles_fract(float a) { return a - floor(a); }
// compatible_signf
float cultmath_cycles_sign(float a) { return a == 0.0 ? 0.0 : (a < 0.0 ? -1.0 : 1.0); }
// safe_asinf
float cultmath_cycles_arcsine(float a) { return asin(clamp(a, -1.0, 1.0)); }
// safe_acosf
float cultmath_cycles_arccosine(float a) { return acos(clamp(a, -1.0, 1.0)); }
// compatible_atan2 (a is y, b is x)
float cultmath_cycles_arctan2(float a, float b) { return (b == 0.0 && a == 0.0) ? 0.0 : atan(a, b); }
// ---- Map Range node (kernel/svm/map_range.h svm_node_map_range) ----
// A Map Range node's Clamp option is a Clamp node of type Range on its result (MapRangeNode::expand):
// compose cultmath_cycles_clamp_range over these.
float cultmath_cycles_map_range_linear(float value, float from_min, float from_max, float to_min, float to_max)
{
float factor = (value - from_min) / (from_max - from_min);
return from_max != from_min ? to_min + factor * (to_max - to_min) : 0.0;
}
float cultmath_cycles_map_range_stepped(float value, float from_min, float from_max, float to_min, float to_max, float steps)
{
float factor = (value - from_min) / (from_max - from_min);
factor = steps > 0.0 ? floor(factor * (steps + 1.0)) / steps : 0.0;
return from_max != from_min ? to_min + factor * (to_max - to_min) : 0.0;
}
// The value itself, not a normalized one, goes through smoothstep(from_min, from_max, .), flipped when
// from_min > from_max (util/math_base.h smoothstep).
float cultmath_cycles_map_range_smoothstep(float value, float from_min, float from_max, float to_min, float to_max)
{
float low = min(from_min, from_max);
float high = max(from_min, from_max);
float t = (value - low) / (high - low);
float eased = value < low ? 0.0 : (value >= high ? 1.0 : (3.0 - 2.0 * t) * (t * t));
float factor = from_min > from_max ? 1.0 - eased : eased;
return from_max != from_min ? to_min + factor * (to_max - to_min) : 0.0;
}
// smootherstep of map_range.h, flipped when from_min > from_max.
float cultmath_cycles_map_range_smootherstep(float value, float from_min, float from_max, float to_min, float to_max)
{
float low = min(from_min, from_max);
float high = max(from_min, from_max);
float x = clamp(cultmath_cycles_divide(value - low, high - low), 0.0, 1.0);
float eased = x * x * x * (x * (x * 6.0 - 15.0) + 10.0);
float factor = from_min > from_max ? 1.0 - eased : eased;
return from_max != from_min ? to_min + factor * (to_max - to_min) : 0.0;
}
// ---- Clamp node (kernel/svm/clamp.h svm_node_clamp) ----
// Type Min Max
float cultmath_cycles_clamp_minmax(float value, float min_value, float max_value) { return clamp(value, min_value, max_value); }
// Type Range: the bounds swap when min_value > max_value.
float cultmath_cycles_clamp_range(float value, float min_value, float max_value)
{
return min_value > max_value ? clamp(value, max_value, min_value) : clamp(value, min_value, max_value);
}
// ---- Mix node (kernel/svm/mix.h, color_util.h) ----
// Factor clamping (svm_node_mix_color's saturatef) and result clamping (saturate) are the caller's.
// svm_node_mix_float
float cultmath_cycles_mix_float(float t, float a, float b) { return a * (1.0 - t) + b * t; }
// svm_node_mix_vector
vec3 cultmath_cycles_mix_vector(float t, vec3 a, vec3 b) { return a * (vec3(1.0, 1.0, 1.0) - t) + b * t; }
vec3 cultmath_cycles_mix_blend(float t, vec3 col1, vec3 col2) { return col1 + t * (col2 - col1); }
vec3 cultmath_cycles_mix_add(float t, vec3 col1, vec3 col2) { return col1 + t * ((col1 + col2) - col1); }
vec3 cultmath_cycles_mix_mul(float t, vec3 col1, vec3 col2) { return col1 + t * (col1 * col2 - col1); }
vec3 cultmath_cycles_mix_screen(float t, vec3 col1, vec3 col2)
{
float tm = 1.0 - t;
vec3 one = vec3(1.0, 1.0, 1.0);
return one - (vec3(tm, tm, tm) + t * (one - col2)) * (one - col1);
}
vec3 cultmath_cycles_mix_overlay(float t, vec3 col1, vec3 col2)
{
float tm = 1.0 - t;
return vec3(
col1.x < 0.5 ? col1.x * (tm + 2.0 * t * col2.x) : 1.0 - (tm + 2.0 * t * (1.0 - col2.x)) * (1.0 - col1.x),
col1.y < 0.5 ? col1.y * (tm + 2.0 * t * col2.y) : 1.0 - (tm + 2.0 * t * (1.0 - col2.y)) * (1.0 - col1.y),
col1.z < 0.5 ? col1.z * (tm + 2.0 * t * col2.z) : 1.0 - (tm + 2.0 * t * (1.0 - col2.z)) * (1.0 - col1.z));
}
vec3 cultmath_cycles_mix_sub(float t, vec3 col1, vec3 col2) { return col1 + t * ((col1 - col2) - col1); }
vec3 cultmath_cycles_mix_div(float t, vec3 col1, vec3 col2)
{
float tm = 1.0 - t;
return vec3(
col2.x != 0.0 ? tm * col1.x + t * col1.x / col2.x : col1.x,
col2.y != 0.0 ? tm * col1.y + t * col1.y / col2.y : col1.y,
col2.z != 0.0 ? tm * col1.z + t * col1.z / col2.z : col1.z);
}
vec3 cultmath_cycles_mix_diff(float t, vec3 col1, vec3 col2) { return col1 + t * (abs(col1 - col2) - col1); }
vec3 cultmath_cycles_mix_exclusion(float t, vec3 col1, vec3 col2)
{
return max(col1 + t * ((col1 + col2 - 2.0 * col1 * col2) - col1), vec3(0.0, 0.0, 0.0));
}
vec3 cultmath_cycles_mix_dark(float t, vec3 col1, vec3 col2) { return col1 + t * (min(col1, col2) - col1); }
vec3 cultmath_cycles_mix_light(float t, vec3 col1, vec3 col2) { return col1 + t * (max(col1, col2) - col1); }
vec3 cultmath_cycles_mix_dodge(float t, vec3 col1, vec3 col2)
{
vec3 divisor = vec3(1.0, 1.0, 1.0) - t * col2;
return vec3(
col1.x != 0.0 ? (divisor.x <= 0.0 ? 1.0 : min(col1.x / divisor.x, 1.0)) : col1.x,
col1.y != 0.0 ? (divisor.y <= 0.0 ? 1.0 : min(col1.y / divisor.y, 1.0)) : col1.y,
col1.z != 0.0 ? (divisor.z <= 0.0 ? 1.0 : min(col1.z / divisor.z, 1.0)) : col1.z);
}
vec3 cultmath_cycles_mix_burn(float t, vec3 col1, vec3 col2)
{
float tm = 1.0 - t;
vec3 divisor = tm + t * col2;
vec3 burnt = vec3(1.0, 1.0, 1.0) - (vec3(1.0, 1.0, 1.0) - col1) / divisor;
return vec3(
divisor.x <= 0.0 ? 0.0 : clamp(burnt.x, 0.0, 1.0),
divisor.y <= 0.0 ? 0.0 : clamp(burnt.y, 0.0, 1.0),
divisor.z <= 0.0 ? 0.0 : clamp(burnt.z, 0.0, 1.0));
}
// rgb_to_hsv of util/color.h
vec3 cultmath_cycles_rgb_to_hsv(vec3 rgb)
{
float cmax = max(rgb.x, max(rgb.y, rgb.z));
float cmin = min(rgb.x, min(rgb.y, rgb.z));
float cdelta = cmax - cmin;
float s = cmax != 0.0 ? cdelta / cmax : 0.0;
vec3 c = (vec3(cmax, cmax, cmax) - rgb) / cdelta;
float h = rgb.x == cmax ? c.z - c.y : (rgb.y == cmax ? 2.0 + c.x - c.z : 4.0 + c.y - c.x);
h = h * 0.16666667; // Cycles' kernel is built with reciprocal math: h /= 6.0f computes h * (1 / 6.0f).
h = h < 0.0 ? h + 1.0 : h;
return vec3(s != 0.0 ? h : 0.0, s, cmax);
}
// hsv_to_rgb of util/color.h
vec3 cultmath_cycles_hsv_to_rgb(vec3 hsv)
{
float h = hsv.x == 1.0 ? 0.0 : hsv.x;
h = h * 6.0;
float i = floor(h);
float f = h - i;
float p = hsv.z * (1.0 - hsv.y);
float q = hsv.z * (1.0 - (hsv.y * f));
float t = hsv.z * (1.0 - (hsv.y * (1.0 - f)));
vec3 rgb = i == 0.0 ? vec3(hsv.z, t, p) :
(i == 1.0 ? vec3(q, hsv.z, p) :
(i == 2.0 ? vec3(p, hsv.z, t) :
(i == 3.0 ? vec3(p, q, hsv.z) :
(i == 4.0 ? vec3(t, p, hsv.z) : vec3(hsv.z, p, q)))));
return hsv.y != 0.0 ? rgb : vec3(hsv.z, hsv.z, hsv.z);
}
vec3 cultmath_cycles_mix_hue(float t, vec3 col1, vec3 col2)
{
vec3 hsv2 = cultmath_cycles_rgb_to_hsv(col2);
vec3 hsv = cultmath_cycles_rgb_to_hsv(col1);
vec3 shifted = cultmath_cycles_hsv_to_rgb(vec3(hsv2.x, hsv.y, hsv.z));
return hsv2.y != 0.0 ? col1 + t * (shifted - col1) : col1;
}
vec3 cultmath_cycles_mix_sat(float t, vec3 col1, vec3 col2)
{
float tm = 1.0 - t;
vec3 hsv = cultmath_cycles_rgb_to_hsv(col1);
vec3 hsv2 = cultmath_cycles_rgb_to_hsv(col2);
return hsv.y != 0.0 ? cultmath_cycles_hsv_to_rgb(vec3(hsv.x, tm * hsv.y + t * hsv2.y, hsv.z)) : col1;
}
vec3 cultmath_cycles_mix_val(float t, vec3 col1, vec3 col2)
{
float tm = 1.0 - t;
vec3 hsv = cultmath_cycles_rgb_to_hsv(col1);
vec3 hsv2 = cultmath_cycles_rgb_to_hsv(col2);
return cultmath_cycles_hsv_to_rgb(vec3(hsv.x, hsv.y, tm * hsv.z + t * hsv2.z));
}
vec3 cultmath_cycles_mix_color(float t, vec3 col1, vec3 col2)
{
vec3 hsv2 = cultmath_cycles_rgb_to_hsv(col2);
vec3 hsv = cultmath_cycles_rgb_to_hsv(col1);
vec3 shifted = cultmath_cycles_hsv_to_rgb(vec3(hsv2.x, hsv2.y, hsv.z));
return hsv2.y != 0.0 ? col1 + t * (shifted - col1) : col1;
}
vec3 cultmath_cycles_mix_soft(float t, vec3 col1, vec3 col2)
{
float tm = 1.0 - t;
vec3 one = vec3(1.0, 1.0, 1.0);
vec3 scr = one - (one - col2) * (one - col1);
return tm * col1 + t * ((one - col1) * col2 * col1 + col1 * scr);
}
vec3 cultmath_cycles_mix_linear(float t, vec3 col1, vec3 col2)
{
return col1 + t * (2.0 * col2 + vec3(-1.0, -1.0, -1.0));
}
// ---- RGB to BW node (kernel/svm/convert.h NODE_CONVERT_CF) ----
float cultmath_cycles_rgb_to_bw(vec3 color)
{
return color.x * CULTMATH_CYCLES_RGB_TO_Y_R + color.y * CULTMATH_CYCLES_RGB_TO_Y_G + color.z * CULTMATH_CYCLES_RGB_TO_Y_B;
}
// ---- Color Ramp lookup (kernel/svm/ramp.h rgb_ramp_lookup, without extrapolation) ----
// Where a ramp of `size` table entries is read at t: (index, weight), the lower entry and the weight of the
// next one. The colour is table[index] when weight is 0 and (1 - weight) table[index] + weight table[index + 1]
// otherwise. The ramp table itself is the caller's; Blender's holds 257 entries, the ramp sampled at i / 256.
vec2 cultmath_cycles_ramp_index(float t, int size)
{
float f = (t > 0.0 ? (t < 1.0 ? t : 1.0) : 0.0) * float(size - 1);
int index = clamp(int(f), 0, size - 1);
float lower = float(index);
return vec2(lower, f - lower);
}
#endif

View file

@ -0,0 +1,363 @@
#ifndef CULTMATH_CYCLES_HLSL
#define CULTMATH_CYCLES_HLSL
// SPDX-License-Identifier: Apache-2.0
//
// Cycles node semantics: what Blender's Cycles renderer computes for the Math, Map Range, Clamp, Mix and
// RGB to BW nodes and for a Color Ramp lookup, ported function by function from the Cycles kernel
// (intern/cycles of the Blender v5.2.2 tag; SPDX-FileCopyrightText: 2011-2022 Blender Foundation, Apache-2.0):
// kernel/svm/{math_util,map_range,clamp,mix,color_util,ramp,convert}.h, util/math_base.h, util/color.h and
// util/math_float3.h. Each function's comment names its Cycles source. Modified by GameCult: Cycles C++
// becomes HLSL, a function per node operation, and the node's socket defaults and clamp options are left to
// the caller. This file is Apache-2.0 (section 4: it was changed); CultMath.hlsl, which includes it after its
// own definitions, is MIT (see THIRD-PARTY-NOTICES.md). math.Cycles.cs mirrors it bit for bit.
//
// Operands are finite floats. NaN and infinite operands are outside the oracle's reach and the mirror's.
// FLT_EPSILON, the least epsilon a Compare node honours.
static const float CULTMATH_CYCLES_FLT_EPSILON = 1.1920929e-07;
// The scene-linear luminance coefficients Cycles reads from Blender 5.2.2's default OCIO config
// (kernel/film linear_rgb_to_gray). The oracle fixture pins them with a case per primary.
static const float CULTMATH_CYCLES_RGB_TO_Y_R = 0.212639093;
static const float CULTMATH_CYCLES_RGB_TO_Y_G = 0.715169132;
static const float CULTMATH_CYCLES_RGB_TO_Y_B = 0.0721927434;
// ---- Math node (kernel/svm/math_util.h svm_math; util/math_base.h) ----
// safe_divide
float cultmath_cycles_divide(float a, float b) { return b != 0.0 ? a / b : 0.0; }
// safe_powf with compatible_powf. A negative base takes an integral exponent's parity; a base below zero
// with a fractional exponent is 0.
float cultmath_cycles_power(float a, float b)
{
float whole = b >= 0.0 ? floor(b) : ceil(b);
if (a < 0.0 && b != whole)
return 0.0;
if (b == 0.0)
return 1.0;
if (a == 0.0)
return 0.0;
if (a < 0.0)
{
float magnitude = pow(-a, b);
// Odd exactly when the remainder is 1: an infinite exponent leaves NaN here and is even, as powf(a, +-inf) is never negative.
return b - 2.0 * floor(0.5 * b) == 1.0 ? -magnitude : magnitude;
}
return pow(a, b);
}
// safe_logf
float cultmath_cycles_logarithm(float a, float b)
{
if (a <= 0.0 || b <= 0.0)
return 0.0;
float denominator = log(b);
return denominator != 0.0 ? log(a) / denominator : 0.0;
}
// safe_sqrtf
float cultmath_cycles_sqrt(float a) { return sqrt(max(a, 0.0)); }
// inversesqrtf
float cultmath_cycles_inverse_sqrt(float a) { return a > 0.0 ? 1.0 / sqrt(a) : 0.0; }
// safe_modulo is fmodf, the remainder with the dividend's sign, exactly. GLSL has no fmod, and a - b trunc(a / b)
// is wrong where the quotient rounds up to an integer or the product rounds (3 mod 0.3 is 0.29999995, not 0).
// So this subtracts the largest power-of-two multiple of the divisor not above the remainder until the
// remainder is below the divisor: every step is an exact subtraction, as in fmod. The loops are bounded by the
// binades a float spans.
float cultmath_cycles_modulo(float a, float b)
{
float remainder = abs(a);
float divisor = abs(b);
for (int steps = 0; steps < 300 && remainder >= divisor && divisor > 0.0; steps++)
{
float multiple = divisor;
for (int doublings = 0; doublings < 300 && multiple * 2.0 <= remainder; doublings++)
multiple = multiple * 2.0;
remainder = remainder - multiple;
}
return b != 0.0 ? (a < 0.0 ? -remainder : remainder) : 0.0;
}
// safe_floored_modulo; a build that contracts it differs by a bound stated at cycles_floored_modulo in math.Cycles.cs and the README
float cultmath_cycles_floored_modulo(float a, float b) { return b != 0.0 ? a - floor(a / b) * b : 0.0; }
// wrapf (note the argument order: value, max, min); contraction bound as for floored_modulo
float cultmath_cycles_wrap(float value, float max_value, float min_value)
{
float range = max_value - min_value;
return range != 0.0 ? value - (range * floor((value - min_value) / range)) : min_value;
}
// floorf(safe_divide(a, b)) * b
float cultmath_cycles_snap(float a, float b) { return floor(cultmath_cycles_divide(a, b)) * b; }
// pingpongf
float cultmath_cycles_pingpong(float a, float b)
{
float scaled = (a - b) / (b * 2.0);
return b != 0.0 ? abs((scaled - floor(scaled)) * b * 2.0 - b) : 0.0;
}
// smoothminf
float cultmath_cycles_smooth_min(float a, float b, float k)
{
float h = max(k - abs(a - b), 0.0) / k;
return k != 0.0 ? min(a, b) - h * h * h * k * 0.16666667 : min(a, b);
}
// -smoothminf(-a, -b, k)
float cultmath_cycles_smooth_max(float a, float b, float k) { return -cultmath_cycles_smooth_min(-a, -b, k); }
// NODE_MATH_COMPARE
float cultmath_cycles_compare(float a, float b, float epsilon)
{
return (a == b || abs(a - b) <= max(epsilon, CULTMATH_CYCLES_FLT_EPSILON)) ? 1.0 : 0.0;
}
// NODE_MATH_ROUND
float cultmath_cycles_round(float a) { return floor(a + 0.5); }
// NODE_MATH_TRUNC
float cultmath_cycles_trunc(float a) { return a >= 0.0 ? floor(a) : ceil(a); }
// NODE_MATH_FRACTION
float cultmath_cycles_fract(float a) { return a - floor(a); }
// compatible_signf
float cultmath_cycles_sign(float a) { return a == 0.0 ? 0.0 : (a < 0.0 ? -1.0 : 1.0); }
// safe_asinf
float cultmath_cycles_arcsine(float a) { return asin(clamp(a, -1.0, 1.0)); }
// safe_acosf
float cultmath_cycles_arccosine(float a) { return acos(clamp(a, -1.0, 1.0)); }
// compatible_atan2 (a is y, b is x)
float cultmath_cycles_arctan2(float a, float b) { return (b == 0.0 && a == 0.0) ? 0.0 : atan2(a, b); }
// ---- Map Range node (kernel/svm/map_range.h svm_node_map_range) ----
// A Map Range node's Clamp option is a Clamp node of type Range on its result (MapRangeNode::expand):
// compose cultmath_cycles_clamp_range over these.
float cultmath_cycles_map_range_linear(float value, float from_min, float from_max, float to_min, float to_max)
{
float factor = (value - from_min) / (from_max - from_min);
return from_max != from_min ? to_min + factor * (to_max - to_min) : 0.0;
}
float cultmath_cycles_map_range_stepped(float value, float from_min, float from_max, float to_min, float to_max, float steps)
{
float factor = (value - from_min) / (from_max - from_min);
factor = steps > 0.0 ? floor(factor * (steps + 1.0)) / steps : 0.0;
return from_max != from_min ? to_min + factor * (to_max - to_min) : 0.0;
}
// The value itself, not a normalized one, goes through smoothstep(from_min, from_max, .), flipped when
// from_min > from_max (util/math_base.h smoothstep).
float cultmath_cycles_map_range_smoothstep(float value, float from_min, float from_max, float to_min, float to_max)
{
float low = min(from_min, from_max);
float high = max(from_min, from_max);
float t = (value - low) / (high - low);
float eased = value < low ? 0.0 : (value >= high ? 1.0 : (3.0 - 2.0 * t) * (t * t));
float factor = from_min > from_max ? 1.0 - eased : eased;
return from_max != from_min ? to_min + factor * (to_max - to_min) : 0.0;
}
// smootherstep of map_range.h, flipped when from_min > from_max.
float cultmath_cycles_map_range_smootherstep(float value, float from_min, float from_max, float to_min, float to_max)
{
float low = min(from_min, from_max);
float high = max(from_min, from_max);
float x = clamp(cultmath_cycles_divide(value - low, high - low), 0.0, 1.0);
float eased = x * x * x * (x * (x * 6.0 - 15.0) + 10.0);
float factor = from_min > from_max ? 1.0 - eased : eased;
return from_max != from_min ? to_min + factor * (to_max - to_min) : 0.0;
}
// ---- Clamp node (kernel/svm/clamp.h svm_node_clamp) ----
// Type Min Max
float cultmath_cycles_clamp_minmax(float value, float min_value, float max_value) { return clamp(value, min_value, max_value); }
// Type Range: the bounds swap when min_value > max_value.
float cultmath_cycles_clamp_range(float value, float min_value, float max_value)
{
return min_value > max_value ? clamp(value, max_value, min_value) : clamp(value, min_value, max_value);
}
// ---- Mix node (kernel/svm/mix.h, color_util.h) ----
// Factor clamping (svm_node_mix_color's saturatef) and result clamping (saturate) are the caller's.
// svm_node_mix_float
float cultmath_cycles_mix_float(float t, float a, float b) { return a * (1.0 - t) + b * t; }
// svm_node_mix_vector
float3 cultmath_cycles_mix_vector(float t, float3 a, float3 b) { return a * (float3(1.0, 1.0, 1.0) - t) + b * t; }
float3 cultmath_cycles_mix_blend(float t, float3 col1, float3 col2) { return col1 + t * (col2 - col1); }
float3 cultmath_cycles_mix_add(float t, float3 col1, float3 col2) { return col1 + t * ((col1 + col2) - col1); }
float3 cultmath_cycles_mix_mul(float t, float3 col1, float3 col2) { return col1 + t * (col1 * col2 - col1); }
float3 cultmath_cycles_mix_screen(float t, float3 col1, float3 col2)
{
float tm = 1.0 - t;
float3 one = float3(1.0, 1.0, 1.0);
return one - (float3(tm, tm, tm) + t * (one - col2)) * (one - col1);
}
float3 cultmath_cycles_mix_overlay(float t, float3 col1, float3 col2)
{
float tm = 1.0 - t;
return float3(
col1.x < 0.5 ? col1.x * (tm + 2.0 * t * col2.x) : 1.0 - (tm + 2.0 * t * (1.0 - col2.x)) * (1.0 - col1.x),
col1.y < 0.5 ? col1.y * (tm + 2.0 * t * col2.y) : 1.0 - (tm + 2.0 * t * (1.0 - col2.y)) * (1.0 - col1.y),
col1.z < 0.5 ? col1.z * (tm + 2.0 * t * col2.z) : 1.0 - (tm + 2.0 * t * (1.0 - col2.z)) * (1.0 - col1.z));
}
float3 cultmath_cycles_mix_sub(float t, float3 col1, float3 col2) { return col1 + t * ((col1 - col2) - col1); }
float3 cultmath_cycles_mix_div(float t, float3 col1, float3 col2)
{
float tm = 1.0 - t;
return float3(
col2.x != 0.0 ? tm * col1.x + t * col1.x / col2.x : col1.x,
col2.y != 0.0 ? tm * col1.y + t * col1.y / col2.y : col1.y,
col2.z != 0.0 ? tm * col1.z + t * col1.z / col2.z : col1.z);
}
float3 cultmath_cycles_mix_diff(float t, float3 col1, float3 col2) { return col1 + t * (abs(col1 - col2) - col1); }
float3 cultmath_cycles_mix_exclusion(float t, float3 col1, float3 col2)
{
return max(col1 + t * ((col1 + col2 - 2.0 * col1 * col2) - col1), float3(0.0, 0.0, 0.0));
}
float3 cultmath_cycles_mix_dark(float t, float3 col1, float3 col2) { return col1 + t * (min(col1, col2) - col1); }
float3 cultmath_cycles_mix_light(float t, float3 col1, float3 col2) { return col1 + t * (max(col1, col2) - col1); }
float3 cultmath_cycles_mix_dodge(float t, float3 col1, float3 col2)
{
float3 divisor = float3(1.0, 1.0, 1.0) - t * col2;
return float3(
col1.x != 0.0 ? (divisor.x <= 0.0 ? 1.0 : min(col1.x / divisor.x, 1.0)) : col1.x,
col1.y != 0.0 ? (divisor.y <= 0.0 ? 1.0 : min(col1.y / divisor.y, 1.0)) : col1.y,
col1.z != 0.0 ? (divisor.z <= 0.0 ? 1.0 : min(col1.z / divisor.z, 1.0)) : col1.z);
}
float3 cultmath_cycles_mix_burn(float t, float3 col1, float3 col2)
{
float tm = 1.0 - t;
float3 divisor = tm + t * col2;
float3 burnt = float3(1.0, 1.0, 1.0) - (float3(1.0, 1.0, 1.0) - col1) / divisor;
return float3(
divisor.x <= 0.0 ? 0.0 : clamp(burnt.x, 0.0, 1.0),
divisor.y <= 0.0 ? 0.0 : clamp(burnt.y, 0.0, 1.0),
divisor.z <= 0.0 ? 0.0 : clamp(burnt.z, 0.0, 1.0));
}
// rgb_to_hsv of util/color.h
float3 cultmath_cycles_rgb_to_hsv(float3 rgb)
{
float cmax = max(rgb.x, max(rgb.y, rgb.z));
float cmin = min(rgb.x, min(rgb.y, rgb.z));
float cdelta = cmax - cmin;
float s = cmax != 0.0 ? cdelta / cmax : 0.0;
float3 c = (float3(cmax, cmax, cmax) - rgb) / cdelta;
float h = rgb.x == cmax ? c.z - c.y : (rgb.y == cmax ? 2.0 + c.x - c.z : 4.0 + c.y - c.x);
h = h * 0.16666667; // Cycles' kernel is built with reciprocal math: h /= 6.0f computes h * (1 / 6.0f).
h = h < 0.0 ? h + 1.0 : h;
return float3(s != 0.0 ? h : 0.0, s, cmax);
}
// hsv_to_rgb of util/color.h
float3 cultmath_cycles_hsv_to_rgb(float3 hsv)
{
float h = hsv.x == 1.0 ? 0.0 : hsv.x;
h = h * 6.0;
float i = floor(h);
float f = h - i;
float p = hsv.z * (1.0 - hsv.y);
float q = hsv.z * (1.0 - (hsv.y * f));
float t = hsv.z * (1.0 - (hsv.y * (1.0 - f)));
float3 rgb = i == 0.0 ? float3(hsv.z, t, p) :
(i == 1.0 ? float3(q, hsv.z, p) :
(i == 2.0 ? float3(p, hsv.z, t) :
(i == 3.0 ? float3(p, q, hsv.z) :
(i == 4.0 ? float3(t, p, hsv.z) : float3(hsv.z, p, q)))));
return hsv.y != 0.0 ? rgb : float3(hsv.z, hsv.z, hsv.z);
}
float3 cultmath_cycles_mix_hue(float t, float3 col1, float3 col2)
{
float3 hsv2 = cultmath_cycles_rgb_to_hsv(col2);
float3 hsv = cultmath_cycles_rgb_to_hsv(col1);
float3 shifted = cultmath_cycles_hsv_to_rgb(float3(hsv2.x, hsv.y, hsv.z));
return hsv2.y != 0.0 ? col1 + t * (shifted - col1) : col1;
}
float3 cultmath_cycles_mix_sat(float t, float3 col1, float3 col2)
{
float tm = 1.0 - t;
float3 hsv = cultmath_cycles_rgb_to_hsv(col1);
float3 hsv2 = cultmath_cycles_rgb_to_hsv(col2);
return hsv.y != 0.0 ? cultmath_cycles_hsv_to_rgb(float3(hsv.x, tm * hsv.y + t * hsv2.y, hsv.z)) : col1;
}
float3 cultmath_cycles_mix_val(float t, float3 col1, float3 col2)
{
float tm = 1.0 - t;
float3 hsv = cultmath_cycles_rgb_to_hsv(col1);
float3 hsv2 = cultmath_cycles_rgb_to_hsv(col2);
return cultmath_cycles_hsv_to_rgb(float3(hsv.x, hsv.y, tm * hsv.z + t * hsv2.z));
}
float3 cultmath_cycles_mix_color(float t, float3 col1, float3 col2)
{
float3 hsv2 = cultmath_cycles_rgb_to_hsv(col2);
float3 hsv = cultmath_cycles_rgb_to_hsv(col1);
float3 shifted = cultmath_cycles_hsv_to_rgb(float3(hsv2.x, hsv2.y, hsv.z));
return hsv2.y != 0.0 ? col1 + t * (shifted - col1) : col1;
}
float3 cultmath_cycles_mix_soft(float t, float3 col1, float3 col2)
{
float tm = 1.0 - t;
float3 one = float3(1.0, 1.0, 1.0);
float3 scr = one - (one - col2) * (one - col1);
return tm * col1 + t * ((one - col1) * col2 * col1 + col1 * scr);
}
float3 cultmath_cycles_mix_linear(float t, float3 col1, float3 col2)
{
return col1 + t * (2.0 * col2 + float3(-1.0, -1.0, -1.0));
}
// ---- RGB to BW node (kernel/svm/convert.h NODE_CONVERT_CF) ----
float cultmath_cycles_rgb_to_bw(float3 color)
{
return color.x * CULTMATH_CYCLES_RGB_TO_Y_R + color.y * CULTMATH_CYCLES_RGB_TO_Y_G + color.z * CULTMATH_CYCLES_RGB_TO_Y_B;
}
// ---- Color Ramp lookup (kernel/svm/ramp.h rgb_ramp_lookup, without extrapolation) ----
// Where a ramp of `size` table entries is read at t: (index, weight), the lower entry and the weight of the
// next one. The colour is table[index] when weight is 0 and (1 - weight) table[index] + weight table[index + 1]
// otherwise. The ramp table itself is the caller's; Blender's holds 257 entries, the ramp sampled at i / 256.
float2 cultmath_cycles_ramp_index(float t, int size)
{
float f = (t > 0.0 ? (t < 1.0 ? t : 1.0) : 0.0) * (float)(size - 1);
int index = clamp((int)f, 0, size - 1);
float lower = (float)index;
return float2(lower, f - lower);
}
#endif

View file

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: e7f15f6042b54d728ada5e82dee741b4
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,4 +1,4 @@
// Generated from shaders/CultMath.hlsl and CultMath.Interval.hlsl and CultMath.Affine.hlsl by GlslLowering (packages/cultmath/tests/CultMath.Tests/GlslLowering.cs). Do not edit; regenerate with CULTMATH_WRITE_GLSL=1 dotnet test --filter GlslMirrorTests. MIT. cultmath_phacelle is in CultMath.Phacelle.glsl, to be concatenated after this file by consumers that call it.
// Generated from shaders/CultMath.hlsl and CultMath.Interval.hlsl and CultMath.Affine.hlsl by GlslLowering (packages/cultmath/tests/CultMath.Tests/GlslLowering.cs). Do not edit; regenerate with CULTMATH_WRITE_GLSL=1 dotnet test --filter GlslMirrorTests. MIT. cultmath_phacelle is in CultMath.Phacelle.glsl, to be concatenated after this file by consumers that call it. cultmath_cycles_divide, cultmath_cycles_power, cultmath_cycles_logarithm, cultmath_cycles_sqrt, cultmath_cycles_inverse_sqrt, cultmath_cycles_modulo, cultmath_cycles_floored_modulo, cultmath_cycles_wrap, cultmath_cycles_snap, cultmath_cycles_pingpong, cultmath_cycles_smooth_min, cultmath_cycles_smooth_max, cultmath_cycles_compare, cultmath_cycles_round, cultmath_cycles_trunc, cultmath_cycles_fract, cultmath_cycles_sign, cultmath_cycles_arcsine, cultmath_cycles_arccosine, cultmath_cycles_arctan2, cultmath_cycles_map_range_linear, cultmath_cycles_map_range_stepped, cultmath_cycles_map_range_smoothstep, cultmath_cycles_map_range_smootherstep, cultmath_cycles_clamp_minmax, cultmath_cycles_clamp_range, cultmath_cycles_mix_float, cultmath_cycles_mix_vector, cultmath_cycles_mix_blend, cultmath_cycles_mix_add, cultmath_cycles_mix_mul, cultmath_cycles_mix_screen, cultmath_cycles_mix_overlay, cultmath_cycles_mix_sub, cultmath_cycles_mix_div, cultmath_cycles_mix_diff, cultmath_cycles_mix_exclusion, cultmath_cycles_mix_dark, cultmath_cycles_mix_light, cultmath_cycles_mix_dodge, cultmath_cycles_mix_burn, cultmath_cycles_rgb_to_hsv, cultmath_cycles_hsv_to_rgb, cultmath_cycles_mix_hue, cultmath_cycles_mix_sat, cultmath_cycles_mix_val, cultmath_cycles_mix_color, cultmath_cycles_mix_soft, cultmath_cycles_mix_linear, cultmath_cycles_rgb_to_bw, cultmath_cycles_ramp_index is in CultMath.Cycles.glsl, to be concatenated after this file by consumers that call it.
#ifndef CULTMATH_GLSL
#define CULTMATH_GLSL
// CultMath HLSL mirror.
@ -228,6 +228,97 @@ vec4 cultmath_snoise_grad(vec3 value)
return vec4(grad, value2);
}
// Analytic Hessian of cultmath_snoise(vec3); see the C# math.snoise_hessian comment for the
// derivation. Every local up through p0..p3 and x0..x3 is cultmath_snoise_grad's own. The matrix is
// built from nine scalars, which read as rows in HLSL and as columns in GLSL; it is symmetric, so the
// two agree.
mat3 cultmath_snoise_hessian(vec3 value)
{
vec2 c = vec2(1.0 / 6.0, 1.0 / 3.0);
vec3 i = floor(value + dot(value, c.yyy));
vec3 x0 = value - i + dot(i, c.xxx);
vec3 g = vec3(step(x0.y, x0.x), step(x0.z, x0.y), 1.0 - step(x0.z, x0.x));
vec3 l = 1.0 - g;
vec3 i1 = min(g.xyz, l.zxy);
vec3 i2 = max(g.xyz, l.zxy);
vec3 x1 = x0 - i1 + c.xxx;
vec3 x2 = x0 - i2 + c.yyy;
vec3 x3 = x0 - 0.5;
i = cultmath_snoise_mod289(i);
vec4 p = cultmath_snoise_permute(cultmath_snoise_permute(cultmath_snoise_permute(
i.z + vec4(0.0, i1.z, i2.z, 1.0)) + i.y + vec4(0.0, i1.y, i2.y, 1.0)) + i.x + vec4(0.0, i1.x, i2.x, 1.0));
const float n_ = 0.142857142857;
vec3 ns = vec3(2.0 * n_, 0.5 * n_ - 1.0, n_);
vec4 j = p - 49.0 * floor(p * ns.z * ns.z);
vec4 x_ = floor(j * ns.z);
vec4 y_ = floor(j - 7.0 * x_);
vec4 x = x_ * ns.x + ns.yyyy;
vec4 y = y_ * ns.x + ns.yyyy;
vec4 h = 1.0 - abs(x) - abs(y);
vec4 b0 = vec4(x.xy, y.xy);
vec4 b1 = vec4(x.zw, y.zw);
vec4 s0 = floor(b0) * 2.0 + 1.0;
vec4 s1 = floor(b1) * 2.0 + 1.0;
vec4 sh = -step(h, vec4(0.0, 0.0, 0.0, 0.0));
vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;
vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;
vec3 p0 = vec3(a0.xy, h.x);
vec3 p1 = vec3(a0.zw, h.y);
vec3 p2 = vec3(a1.xy, h.z);
vec3 p3 = vec3(a1.zw, h.w);
vec4 norm = 1.79284291400159 - 0.85373472095314 * vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3));
p0 *= norm.x;
p1 *= norm.y;
p2 *= norm.z;
p3 *= norm.w;
vec4 m0 = max(0.5 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);
vec4 m2 = m0 * m0;
vec4 m3 = m2 * m0;
vec4 px = vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3));
vec4 wide = 48.0 * m2 * px;
vec4 narrow = 8.0 * m3;
vec4 cxx = vec4(x0.x, x1.x, x2.x, x3.x);
vec4 cxy = vec4(x0.y, x1.y, x2.y, x3.y);
vec4 cxz = vec4(x0.z, x1.z, x2.z, x3.z);
vec4 cpx = vec4(p0.x, p1.x, p2.x, p3.x);
vec4 cpy = vec4(p0.y, p1.y, p2.y, p3.y);
vec4 cpz = vec4(p0.z, p1.z, p2.z, p3.z);
float hxx = 105.0 * (dot(wide * cxx, cxx) - dot(narrow, 2.0 * cpx * cxx + px));
float hyy = 105.0 * (dot(wide * cxy, cxy) - dot(narrow, 2.0 * cpy * cxy + px));
float hzz = 105.0 * (dot(wide * cxz, cxz) - dot(narrow, 2.0 * cpz * cxz + px));
float hxy = 105.0 * (dot(wide * cxx, cxy) - dot(narrow, cpx * cxy + cpy * cxx));
float hxz = 105.0 * (dot(wide * cxx, cxz) - dot(narrow, cpx * cxz + cpz * cxx));
float hyz = 105.0 * (dot(wide * cxy, cxz) - dot(narrow, cpy * cxz + cpz * cxy));
return mat3(hxx, hxy, hxz, hxy, hyy, hyz, hxz, hyz, hzz);
}
// The integral over [t0, t1] of clamp(a + b t, lo, hi); see the C# math.integral_clamp_linear comment.
float cultmath_integral_clamp_linear(float a, float b, float lo, float hi, float t0, float t1)
{
if (b == 0.0)
return clamp(a, lo, hi) * (t1 - t0);
lo = min(lo, hi);
float direction = t1 < t0 ? -1.0 : 1.0;
float start = min(t0, t1);
float stop = max(t0, t1);
float atLo = (lo - a) / b;
float atHi = (hi - a) / b;
float enter = clamp(min(atLo, atHi), start, stop);
float leave = clamp(max(atLo, atHi), start, stop);
float before = b > 0.0 ? lo : hi;
float after = b > 0.0 ? hi : lo;
float total = before * (enter - start) + (a + b * (0.5 * (enter + leave))) * (leave - enter) + after * (stop - leave);
return direction * total;
}
// Octave sum of cultmath_snoise_grad (invariant 8); see the C# math.fbm_grad comment for the
// per-octave frequency/amplitude derivation and why octaves is clamped.
vec4 cultmath_fbm_grad(vec3 p, int octaves, float lacunarity, float gain)
@ -653,7 +744,11 @@ vec4 cultmath_iv_frustum_ball(vec2 centreSlope, float z0, float z1, float footpr
// An upper bound on the spectral norm of the Hessian of cultmath_snoise(vec3); provenance in
// math.Affine.cs (SNOISE_HESSIAN).
const float CULTMATH_SNOISE_HESSIAN = 56.050385;
const float CULTMATH_SNOISE_HESSIAN = 55.642143;
// An upper bound on the operator norm of the third-derivative tensor of cultmath_snoise(vec3), the
// next order after CULTMATH_SNOISE_HESSIAN; provenance in math.Span.cs (SNOISE_THIRD).
const float CULTMATH_SNOISE_THIRD = 536.9152;
vec3 cultmath_af_point(float value) { return vec3(value, 0.0, 0.0); }
vec3 cultmath_af_symbol(float x0, float a) { return vec3(x0, a, 0.0); }

View file

@ -228,6 +228,97 @@ float4 cultmath_snoise_grad(float3 value)
return float4(grad, value2);
}
// Analytic Hessian of cultmath_snoise(float3); see the C# math.snoise_hessian comment for the
// derivation. Every local up through p0..p3 and x0..x3 is cultmath_snoise_grad's own. The matrix is
// built from nine scalars, which read as rows in HLSL and as columns in GLSL; it is symmetric, so the
// two agree.
float3x3 cultmath_snoise_hessian(float3 value)
{
float2 c = float2(1.0 / 6.0, 1.0 / 3.0);
float3 i = floor(value + dot(value, c.yyy));
float3 x0 = value - i + dot(i, c.xxx);
float3 g = float3(step(x0.y, x0.x), step(x0.z, x0.y), 1.0 - step(x0.z, x0.x));
float3 l = 1.0 - g;
float3 i1 = min(g.xyz, l.zxy);
float3 i2 = max(g.xyz, l.zxy);
float3 x1 = x0 - i1 + c.xxx;
float3 x2 = x0 - i2 + c.yyy;
float3 x3 = x0 - 0.5;
i = cultmath_snoise_mod289(i);
float4 p = cultmath_snoise_permute(cultmath_snoise_permute(cultmath_snoise_permute(
i.z + float4(0.0, i1.z, i2.z, 1.0)) + i.y + float4(0.0, i1.y, i2.y, 1.0)) + i.x + float4(0.0, i1.x, i2.x, 1.0));
const float n_ = 0.142857142857;
float3 ns = float3(2.0 * n_, 0.5 * n_ - 1.0, n_);
float4 j = p - 49.0 * floor(p * ns.z * ns.z);
float4 x_ = floor(j * ns.z);
float4 y_ = floor(j - 7.0 * x_);
float4 x = x_ * ns.x + ns.yyyy;
float4 y = y_ * ns.x + ns.yyyy;
float4 h = 1.0 - abs(x) - abs(y);
float4 b0 = float4(x.xy, y.xy);
float4 b1 = float4(x.zw, y.zw);
float4 s0 = floor(b0) * 2.0 + 1.0;
float4 s1 = floor(b1) * 2.0 + 1.0;
float4 sh = -step(h, float4(0.0, 0.0, 0.0, 0.0));
float4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;
float4 a1 = b1.xzyw + s1.xzyw * sh.zzww;
float3 p0 = float3(a0.xy, h.x);
float3 p1 = float3(a0.zw, h.y);
float3 p2 = float3(a1.xy, h.z);
float3 p3 = float3(a1.zw, h.w);
float4 norm = 1.79284291400159 - 0.85373472095314 * float4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3));
p0 *= norm.x;
p1 *= norm.y;
p2 *= norm.z;
p3 *= norm.w;
float4 m0 = max(0.5 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);
float4 m2 = m0 * m0;
float4 m3 = m2 * m0;
float4 px = float4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3));
float4 wide = 48.0 * m2 * px;
float4 narrow = 8.0 * m3;
float4 cxx = float4(x0.x, x1.x, x2.x, x3.x);
float4 cxy = float4(x0.y, x1.y, x2.y, x3.y);
float4 cxz = float4(x0.z, x1.z, x2.z, x3.z);
float4 cpx = float4(p0.x, p1.x, p2.x, p3.x);
float4 cpy = float4(p0.y, p1.y, p2.y, p3.y);
float4 cpz = float4(p0.z, p1.z, p2.z, p3.z);
float hxx = 105.0 * (dot(wide * cxx, cxx) - dot(narrow, 2.0 * cpx * cxx + px));
float hyy = 105.0 * (dot(wide * cxy, cxy) - dot(narrow, 2.0 * cpy * cxy + px));
float hzz = 105.0 * (dot(wide * cxz, cxz) - dot(narrow, 2.0 * cpz * cxz + px));
float hxy = 105.0 * (dot(wide * cxx, cxy) - dot(narrow, cpx * cxy + cpy * cxx));
float hxz = 105.0 * (dot(wide * cxx, cxz) - dot(narrow, cpx * cxz + cpz * cxx));
float hyz = 105.0 * (dot(wide * cxy, cxz) - dot(narrow, cpy * cxz + cpz * cxy));
return float3x3(hxx, hxy, hxz, hxy, hyy, hyz, hxz, hyz, hzz);
}
// The integral over [t0, t1] of clamp(a + b t, lo, hi); see the C# math.integral_clamp_linear comment.
float cultmath_integral_clamp_linear(float a, float b, float lo, float hi, float t0, float t1)
{
if (b == 0.0)
return clamp(a, lo, hi) * (t1 - t0);
lo = min(lo, hi);
float direction = t1 < t0 ? -1.0 : 1.0;
float start = min(t0, t1);
float stop = max(t0, t1);
float atLo = (lo - a) / b;
float atHi = (hi - a) / b;
float enter = clamp(min(atLo, atHi), start, stop);
float leave = clamp(max(atLo, atHi), start, stop);
float before = b > 0.0 ? lo : hi;
float after = b > 0.0 ? hi : lo;
float total = before * (enter - start) + (a + b * (0.5 * (enter + leave))) * (leave - enter) + after * (stop - leave);
return direction * total;
}
// Octave sum of cultmath_snoise_grad (invariant 8); see the C# math.fbm_grad comment for the
// per-octave frequency/amplitude derivation and why octaves is clamped.
float4 cultmath_fbm_grad(float3 p, int octaves, float lacunarity, float gain)
@ -509,6 +600,7 @@ CultCellular cultmath_cellular(float3 p)
#include "CultMath.Phacelle.hlsl"
#include "CultMath.Interval.hlsl"
#include "CultMath.Cycles.hlsl"
#include "CultMath.Affine.hlsl"
float cultmath_value_noise(float2 position)

View file

@ -8,8 +8,8 @@
<RootNamespace>CultMath</RootNamespace>
<AssemblyName>CultMath</AssemblyName>
<PackageId>GameCult.Math</PackageId>
<!-- MIT overall; math.Phacelle.cs and CultPhasor.cs (and the two Phacelle HLSL files) are MPL-2.0. -->
<PackageLicenseExpression>MIT AND MPL-2.0</PackageLicenseExpression>
<!-- MIT overall; math.Phacelle.cs and CultPhasor.cs (and the two Phacelle HLSL files) are MPL-2.0; math.Cycles.cs and CultMath.Cycles.hlsl are Apache-2.0. -->
<PackageLicenseExpression>MIT AND MPL-2.0 AND Apache-2.0</PackageLicenseExpression>
<Version>0.4.1</Version>
<Description>Clean-room C# math shaped for HLSL-style renderer code.</Description>
<Authors>GameCult</Authors>
@ -26,6 +26,7 @@
<None Include="..\..\shaders\CultMath.Phacelle.hlsl" Pack="true" PackagePath="contentFiles\any\any\shaders\CultMath.Phacelle.hlsl" CopyToOutputDirectory="PreserveNewest" />
<None Include="..\..\shaders\CultMath.Interval.hlsl" Pack="true" PackagePath="contentFiles\any\any\shaders\CultMath.Interval.hlsl" CopyToOutputDirectory="PreserveNewest" />
<None Include="..\..\shaders\CultMath.Affine.hlsl" Pack="true" PackagePath="contentFiles\any\any\shaders\CultMath.Affine.hlsl" CopyToOutputDirectory="PreserveNewest" />
<None Include="..\..\shaders\CultMath.Cycles.hlsl" Pack="true" PackagePath="contentFiles\any\any\shaders\CultMath.Cycles.hlsl" CopyToOutputDirectory="PreserveNewest" />
<None Include="..\..\THIRD-PARTY-NOTICES.md" Pack="true" PackagePath="\" />
</ItemGroup>

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a99b96b837a3454781b426cec6bfe837
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,39 @@
namespace CultMath.Expr;
/// <summary>
/// The param values of one graph for an evaluation batch: every param at its default unless overridden by name.
/// </summary>
public sealed class ExprBindings
{
private ExprBindings(ExprGraph graph, float[] values)
{
Graph = graph;
Values = values;
}
public ExprGraph Graph { get; }
/// <summary>One value per param, in the graph's param order.</summary>
internal float[] Values { get; }
/// <summary>
/// Binds <paramref name="graph"/>'s params: a name in <paramref name="overrides"/> replaces the param's default
/// and every other param keeps it. A name the graph has no param for is refused.
/// </summary>
public static ExprBindings Bind(ExprGraph graph, IReadOnlyDictionary<string, float>? overrides = null)
{
var values = new float[graph.ParamNames.Count];
for (var i = 0; i < values.Length; i++) values[i] = BitConverter.Int32BitsToSingle(graph.ParamDefaultBits[i]);
if (overrides is not null)
{
foreach (var pair in overrides)
{
var index = graph.ParamIndex(pair.Key);
if (index < 0) throw new ExprGraphException("unknown-param");
values[index] = pair.Value;
}
}
return new ExprBindings(graph, values);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c9dea1bb6c854e8f80a5e0f05902fd17

View file

@ -0,0 +1,184 @@
namespace CultMath.Expr;
/// <summary>A node of an <see cref="ExprBuilder"/> under construction. Only the builder that made it accepts it.</summary>
public sealed class ExprValue
{
internal ExprValue(ExprBuilder owner, int index, int resultCount)
{
Owner = owner;
Index = index;
ResultCount = resultCount;
}
internal ExprBuilder Owner { get; }
internal int Index { get; }
/// <summary>More than one for a multi-result op, whose results are read only through <see cref="ExprBuilder.Pick"/>.</summary>
public int ResultCount { get; }
}
/// <summary>
/// Builds an <see cref="ExprGraph"/>. Identical (op, operands, constant bits) nodes are one node, and
/// <see cref="Build"/> drops nodes no output reaches and renumbers densely, so the same call sequence builds
/// byte-identical graphs. Every call runs the validator's rules and refuses at the call.
/// </summary>
public sealed class ExprBuilder
{
private readonly List<ExprNode> nodes = new();
private readonly List<ExprValue> handles = new();
private readonly Dictionary<string, int> interned = new();
private readonly List<string> inputNames = new();
private readonly List<string> paramNames = new();
private readonly List<int> paramDefaultBits = new();
private readonly List<string> outputNames = new();
private readonly List<int> outputNodes = new();
/// <summary>The graph input of this name, declared on first use.</summary>
public ExprValue Input(string name)
{
var port = inputNames.IndexOf(name);
if (port < 0)
{
ExprGraph.CheckPortName(name);
port = inputNames.Count;
inputNames.Add(name);
}
return Intern(ExprNode.Input(port));
}
/// <summary>The graph param of this name, declared on first use. Declaring it again with other default bits is refused.</summary>
public ExprValue Param(string name, float defaultValue) => ParamBits(name, BitConverter.SingleToInt32Bits(defaultValue));
/// <summary>A constant; its bits (a signed zero, a NaN payload, a subnormal) are kept.</summary>
public ExprValue Const(float value) => ConstBits(BitConverter.SingleToInt32Bits(value));
public ExprValue Call(string op, params ExprValue[] operands)
{
var indices = new int[operands.Length];
for (var i = 0; i < operands.Length; i++) indices[i] = Own(operands[i]);
return Intern(ExprNode.Call(op, indices));
}
/// <summary>Result <paramref name="k"/> of a multi-result node.</summary>
public ExprValue Pick(ExprValue node, int k) => Intern(ExprNode.Pick(Own(node), k));
/// <summary>Names a single-result node as an output.</summary>
public void Output(string name, ExprValue value)
{
ExprGraph.CheckPortName(name);
if (outputNames.Contains(name)) throw new ExprGraphException("duplicate-port-name");
var node = Own(value);
ExprGraph.CheckOutput(node, nodes);
outputNames.Add(name);
outputNodes.Add(node);
}
/// <summary>The graph of the outputs declared so far: only nodes an output reaches, renumbered densely in build order.</summary>
public ExprGraph Build()
{
var live = new bool[nodes.Count];
foreach (var node in outputNodes) live[node] = true;
for (var i = nodes.Count - 1; i >= 0; i--)
if (live[i])
foreach (var operand in nodes[i].Operands) live[operand] = true;
var renumbered = new int[nodes.Count];
var kept = new List<ExprNode>();
for (var i = 0; i < nodes.Count; i++)
{
if (!live[i]) continue;
renumbered[i] = kept.Count;
kept.Add(nodes[i].WithOperands(nodes[i].Operands.Select(operand => renumbered[operand]).ToArray()));
}
return ExprGraph.Create(
ExprGraph.FormatVersion, inputNames, paramNames, paramDefaultBits, outputNames, outputNodes.Select(node => renumbered[node]).ToList(), kept);
}
/// <summary>
/// Rebuilds <paramref name="graph"/> inside this builder with the named inputs replaced by the given values
/// (Fidget's remap_xyz) and returns each output's value by name. An input not named is this builder's input
/// of that name; every param is this builder's param of that name. A stencil is N substitutions combined by
/// ops: an ordinary flat graph, with no loop construct.
/// </summary>
public IReadOnlyDictionary<string, ExprValue> Substitute(ExprGraph graph, IReadOnlyDictionary<string, ExprValue> replacements)
{
foreach (var pair in replacements)
{
if (!graph.InputNames.Contains(pair.Key)) throw new ExprGraphException("unknown-input");
Own(pair.Value);
if (pair.Value.ResultCount != 1) throw new ExprGraphException("bare-multi-result");
}
var mapped = new ExprValue[graph.Nodes.Count];
for (var i = 0; i < mapped.Length; i++)
{
var node = graph.Nodes[i];
switch (node.Kind)
{
case ExprNodeKind.Input:
var input = graph.InputNames[node.Payload];
mapped[i] = replacements.TryGetValue(input, out var replacement) ? replacement : Input(input);
break;
case ExprNodeKind.Param:
mapped[i] = ParamBits(graph.ParamNames[node.Payload], graph.ParamDefaultBits[node.Payload]);
break;
case ExprNodeKind.Const:
mapped[i] = ConstBits(node.Payload);
break;
case ExprNodeKind.Pick:
mapped[i] = Pick(mapped[node.Operands[0]], node.Payload);
break;
default:
mapped[i] = Call(node.WireName, node.Operands.Select(operand => mapped[operand]).ToArray());
break;
}
}
var outputs = new Dictionary<string, ExprValue>();
for (var o = 0; o < graph.OutputNames.Count; o++) outputs[graph.OutputNames[o]] = mapped[graph.OutputNodes[o]];
return outputs;
}
private ExprValue ParamBits(string name, int bits)
{
var port = paramNames.IndexOf(name);
if (port < 0)
{
ExprGraph.CheckPortName(name);
port = paramNames.Count;
paramNames.Add(name);
paramDefaultBits.Add(bits);
}
else if (paramDefaultBits[port] != bits)
{
throw new ExprGraphException("port-conflict");
}
return Intern(ExprNode.Param(port));
}
private ExprValue ConstBits(int bits) => Intern(ExprNode.Const(bits));
private int Own(ExprValue value)
{
if (value.Owner != this) throw new ExprGraphException("foreign-operand", nodes.Count);
return value.Index;
}
private ExprValue Intern(ExprNode node)
{
ExprGraph.CheckNode(nodes.Count, node, nodes, inputNames.Count, paramNames.Count);
if (!interned.TryGetValue(node.Key, out var index))
{
index = nodes.Count;
nodes.Add(node);
handles.Add(new ExprValue(this, index, node.ResultCount));
interned[node.Key] = index;
}
return handles[index];
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7326eeabc2d04a43b3d0a1fe6e45b018

View file

@ -0,0 +1,57 @@
namespace CultMath.Expr;
/// <summary>
/// Evaluates an <see cref="ExprGraph"/> per point: nodes in order through <see cref="ExprOps"/>, IEEE single per op,
/// so a result equals the direct composition of the same math calls bit for bit. Allocates once per call, never per point.
/// </summary>
public static class ExprEvaluator
{
/// <summary>
/// Columns are contiguous: input <c>i</c> of point <c>p</c> is <c>inputs[i * n + p]</c>, and output <c>o</c> is
/// <c>outputs[o * n + p]</c>, where n = <c>outputs.Length / graph.OutputNames.Count</c>.
/// </summary>
public static void Evaluate(ExprGraph graph, ExprBindings bindings, ReadOnlySpan<float> inputs, Span<float> outputs)
{
if (bindings.Graph != graph) throw new ExprGraphException("foreign-bindings");
var outputCount = graph.OutputNames.Count;
if (outputCount == 0) return;
if (outputs.Length % outputCount != 0) throw new ExprGraphException("column-shape");
var points = outputs.Length / outputCount;
if (inputs.Length != points * graph.InputNames.Count) throw new ExprGraphException("column-shape");
var nodes = graph.NodeArray;
var outputNodes = graph.OutputNodeArray;
var start = graph.SlotStart;
var slots = new float[graph.SlotCount];
Span<float> operands = stackalloc float[ExprOps.MaxArity];
for (var point = 0; point < points; point++)
{
for (var i = 0; i < nodes.Length; i++)
{
var node = nodes[i];
switch (node.Kind)
{
case ExprNodeKind.Input:
slots[start[i]] = inputs[node.Payload * points + point];
break;
case ExprNodeKind.Param:
slots[start[i]] = bindings.Values[node.Payload];
break;
case ExprNodeKind.Const:
slots[start[i]] = BitConverter.Int32BitsToSingle(node.Payload);
break;
case ExprNodeKind.Pick:
slots[start[i]] = slots[start[node.OperandArray[0]] + node.Payload];
break;
default:
var op = node.Op!;
for (var k = 0; k < op.Arity; k++) operands[k] = slots[start[node.OperandArray[k]]];
op.Evaluate(operands.Slice(0, op.Arity), new Span<float>(slots, start[i], op.ResultCount));
break;
}
}
for (var o = 0; o < outputCount; o++) outputs[o * points + point] = slots[start[outputNodes[o]]];
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 38108254b5b4430b8f87094e6905dc59

View file

@ -0,0 +1,180 @@
namespace CultMath.Expr;
/// <summary>
/// An immutable scalar SSA expression graph: nodes in topological order (an operand names a lower node), named
/// inputs that vary per point, named params that are uniform per batch and carry a default, and named outputs.
/// A graph is a value; an edit builds a new one. <see cref="Create"/> is the one validator: the builder runs
/// it on <see cref="ExprBuilder.Build"/> and a decoder runs it on persisted bytes, so no partial graph is ever returned.
/// </summary>
public sealed class ExprGraph
{
/// <summary>The persisted format version this build reads and writes.</summary>
public const int FormatVersion = 1;
private readonly string[] inputNames;
private readonly string[] paramNames;
private readonly int[] paramDefaultBits;
private readonly string[] outputNames;
private readonly int[] outputNodes;
private readonly ExprNode[] nodes;
private ExprGraph(string[] inputNames, string[] paramNames, int[] paramDefaultBits, string[] outputNames, int[] outputNodes, ExprNode[] nodes)
{
this.inputNames = inputNames;
this.paramNames = paramNames;
this.paramDefaultBits = paramDefaultBits;
this.outputNames = outputNames;
this.outputNodes = outputNodes;
this.nodes = nodes;
InputNames = Array.AsReadOnly(inputNames);
ParamNames = Array.AsReadOnly(paramNames);
ParamDefaultBits = Array.AsReadOnly(paramDefaultBits);
OutputNames = Array.AsReadOnly(outputNames);
OutputNodes = Array.AsReadOnly(outputNodes);
Nodes = Array.AsReadOnly(nodes);
SlotStart = new int[nodes.Length];
var slots = 0;
for (var i = 0; i < nodes.Length; i++)
{
SlotStart[i] = slots;
slots += nodes[i].ResultCount;
}
SlotCount = slots;
}
public IReadOnlyList<string> InputNames { get; }
public IReadOnlyList<string> ParamNames { get; }
/// <summary>The default of each param as float bits, so a NaN payload or a signed zero survives.</summary>
public IReadOnlyList<int> ParamDefaultBits { get; }
public IReadOnlyList<string> OutputNames { get; }
/// <summary>The node each output reads.</summary>
public IReadOnlyList<int> OutputNodes { get; }
public IReadOnlyList<ExprNode> Nodes { get; }
/// <summary>The evaluator's view of the nodes: the private array, never handed out.</summary>
internal ExprNode[] NodeArray => nodes;
/// <summary>The evaluator's view of the output nodes: the private array, never handed out.</summary>
internal int[] OutputNodeArray => outputNodes;
/// <summary>Where each node's results start in an evaluator's value array.</summary>
internal int[] SlotStart { get; }
internal int SlotCount { get; }
/// <summary>The index of the param of this name, or -1.</summary>
internal int ParamIndex(string name) => Array.IndexOf(paramNames, name);
/// <summary>
/// Validates and returns a graph, or throws <see cref="ExprGraphException"/> naming the rule and the node.
/// The rules: format version, port counts, port names (syntax, unique per kind), and per node its kind's
/// operand count, a known op and its arity, operands below the node and never a bare multi-result node,
/// pick range, port index and payload; and per output a node in range that is not a bare multi-result node.
/// </summary>
public static ExprGraph Create(
int version,
IReadOnlyList<string> inputNames,
IReadOnlyList<string> paramNames,
IReadOnlyList<int> paramDefaultBits,
IReadOnlyList<string> outputNames,
IReadOnlyList<int> outputNodes,
IReadOnlyList<ExprNode> nodes)
{
if (version != FormatVersion) throw new ExprGraphException("version");
if (paramNames.Count != paramDefaultBits.Count || outputNames.Count != outputNodes.Count) throw new ExprGraphException("port-count");
CheckPortNames(inputNames);
CheckPortNames(paramNames);
CheckPortNames(outputNames);
var before = new List<ExprNode>(nodes.Count);
for (var i = 0; i < nodes.Count; i++)
{
CheckNode(i, nodes[i], before, inputNames.Count, paramNames.Count);
before.Add(nodes[i]);
}
foreach (var node in outputNodes) CheckOutput(node, before);
return new ExprGraph(
inputNames.ToArray(), paramNames.ToArray(), paramDefaultBits.ToArray(), outputNames.ToArray(), outputNodes.ToArray(), nodes.ToArray());
}
/// <summary>A port name is <c>[A-Za-z_][A-Za-z0-9_]*</c>.</summary>
internal static void CheckPortName(string name)
{
if (name.Length == 0 || !IsHead(name[0])) throw new ExprGraphException("port-name");
for (var i = 1; i < name.Length; i++)
if (!IsHead(name[i]) && !(name[i] >= '0' && name[i] <= '9')) throw new ExprGraphException("port-name");
}
private static bool IsHead(char c) => c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
private static void CheckPortNames(IReadOnlyList<string> names)
{
var seen = new HashSet<string>();
foreach (var name in names)
{
CheckPortName(name);
if (!seen.Add(name)) throw new ExprGraphException("duplicate-port-name");
}
}
/// <summary>The rules for one node given the nodes before it. The builder runs this per call, the validator per node.</summary>
internal static void CheckNode(int index, ExprNode node, IReadOnlyList<ExprNode> before, int inputCount, int paramCount)
{
var operands = node.Operands;
switch (node.Kind)
{
case ExprNodeKind.Input:
CheckLeaf(index, node, inputCount);
break;
case ExprNodeKind.Param:
CheckLeaf(index, node, paramCount);
break;
case ExprNodeKind.Const:
if (operands.Count != 0) throw new ExprGraphException("arity", index);
break;
case ExprNodeKind.Pick:
if (operands.Count != 1) throw new ExprGraphException("arity", index);
CheckOperandOrder(index, operands[0]);
var results = before[operands[0]].ResultCount;
if (results <= 1 || node.Payload < 0 || node.Payload >= results) throw new ExprGraphException("pick-range", index);
break;
default:
if (node.Op is null) throw new ExprGraphException("unknown-op", index);
if (operands.Count != node.Op.Arity) throw new ExprGraphException("arity", index);
if (node.Payload != 0) throw new ExprGraphException("payload", index);
foreach (var operand in operands)
{
CheckOperandOrder(index, operand);
if (before[operand].ResultCount != 1) throw new ExprGraphException("bare-multi-result", index);
}
break;
}
}
private static void CheckLeaf(int index, ExprNode node, int portCount)
{
if (node.Operands.Count != 0) throw new ExprGraphException("arity", index);
if (node.Payload < 0 || node.Payload >= portCount) throw new ExprGraphException("port-index", index);
}
private static void CheckOperandOrder(int index, int operand)
{
if (operand < 0 || operand >= index) throw new ExprGraphException("operand-order", index);
}
/// <summary>An output reads a node in range that is single-result.</summary>
internal static void CheckOutput(int node, IReadOnlyList<ExprNode> nodes)
{
if (node < 0 || node >= nodes.Count) throw new ExprGraphException("output-node");
if (nodes[node].ResultCount != 1) throw new ExprGraphException("bare-multi-result", node);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 04d707ad2a4e4e0299407ce1d86afea3

View file

@ -0,0 +1,22 @@
namespace CultMath.Expr;
/// <summary>
/// The one refusal of the expression graph: a build call, a decoded encoding, a binding or an evaluation
/// that breaks a rule. <see cref="Rule"/> names the rule and <see cref="NodeIndex"/> the node it broke at
/// (-1 when no node is involved). The message names the rule and never echoes a value it was given.
/// </summary>
public sealed class ExprGraphException : Exception
{
public ExprGraphException(string rule, int nodeIndex = -1)
: base(nodeIndex < 0 ? rule : rule + " at node " + nodeIndex)
{
Rule = rule;
NodeIndex = nodeIndex;
}
/// <summary>The rule broken, a short stable name such as <c>unknown-op</c> or <c>operand-order</c>.</summary>
public string Rule { get; }
/// <summary>The index of the node the rule broke at, or -1.</summary>
public int NodeIndex { get; }
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 88e355a7be3f44ada7f1d9464c60428e

View file

@ -0,0 +1,83 @@
namespace CultMath.Expr;
/// <summary>What a node is: a graph input, a graph param, a constant, a pick of one result of a multi-result node, or a call of an op.</summary>
public enum ExprNodeKind
{
Input,
Param,
Const,
Pick,
Call,
}
/// <summary>
/// One node of an <see cref="ExprGraph"/>: a kind, the operand node indices (always lower than its own),
/// and one integer payload: the port index of an input or param, the float bits of a constant, the result
/// index of a pick, and zero for a call. Immutable.
/// </summary>
public sealed class ExprNode
{
private const string InputName = "input";
private const string ParamName = "param";
private const string ConstName = "const";
private const string PickName = "pick";
private static readonly int[] NoOperands = Array.Empty<int>();
private readonly int[] operandArray;
private ExprNode(ExprNodeKind kind, string wireName, int[] operands, int payload, ExprOp? op)
{
Kind = kind;
WireName = wireName;
operandArray = operands;
Operands = Array.AsReadOnly(operands);
Payload = payload;
Op = op;
ResultCount = op?.ResultCount ?? 1;
}
public ExprNodeKind Kind { get; }
/// <summary>The persisted name: an op name for a call, otherwise <c>input</c>, <c>param</c>, <c>const</c> or <c>pick</c>.</summary>
public string WireName { get; }
public IReadOnlyList<int> Operands { get; }
/// <summary>The evaluator's view of the operands: the private array, never handed out.</summary>
internal int[] OperandArray => operandArray;
public int Payload { get; }
/// <summary>How many floats the node produces: the op's result count for a call, otherwise one.</summary>
public int ResultCount { get; }
/// <summary>The op of a known call; null for every other node and for a call naming an unknown op.</summary>
internal ExprOp? Op { get; }
public static ExprNode Input(int port) => new(ExprNodeKind.Input, InputName, NoOperands, port, null);
public static ExprNode Param(int port) => new(ExprNodeKind.Param, ParamName, NoOperands, port, null);
public static ExprNode Const(int bits) => new(ExprNodeKind.Const, ConstName, NoOperands, bits, null);
public static ExprNode Pick(int node, int result) => new(ExprNodeKind.Pick, PickName, new[] { node }, result, null);
public static ExprNode Call(string op, IReadOnlyList<int> operands) =>
new(ExprNodeKind.Call, op, operands.ToArray(), 0, ExprOps.Find(op));
/// <summary>The node a persisted <paramref name="wireName"/> names. A name that is none of the four kinds is a call, which the validator checks against the op table.</summary>
public static ExprNode FromWire(string wireName, IReadOnlyList<int> operands, int payload) => wireName switch
{
InputName => new ExprNode(ExprNodeKind.Input, wireName, operands.ToArray(), payload, null),
ParamName => new ExprNode(ExprNodeKind.Param, wireName, operands.ToArray(), payload, null),
ConstName => new ExprNode(ExprNodeKind.Const, wireName, operands.ToArray(), payload, null),
PickName => new ExprNode(ExprNodeKind.Pick, wireName, operands.ToArray(), payload, null),
_ => new ExprNode(ExprNodeKind.Call, wireName, operands.ToArray(), payload, ExprOps.Find(wireName)),
};
internal ExprNode WithOperands(int[] operands) => new(Kind, WireName, operands, Payload, Op);
/// <summary>Equal keys are the same expression: the builder's hash-consing identity.</summary>
internal string Key => WireName + "|" + string.Join(",", operandArray) + "|" + Payload;
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: fc3cb4abaa27482aa98a76cd876b8805

View file

@ -0,0 +1,86 @@
using static CultMath.math;
namespace CultMath.Expr;
/// <summary>One entry of the op table: a stable name, its arity, its result count and its C# implementation.</summary>
public sealed class ExprOp
{
/// <summary>Writes <paramref name="results"/> (<see cref="ResultCount"/> floats) from <paramref name="operands"/>
/// (<see cref="Arity"/> floats).</summary>
public delegate void Function(ReadOnlySpan<float> operands, Span<float> results);
private readonly Function function;
internal ExprOp(string name, int arity, int resultCount, Function function)
{
Name = name;
Arity = arity;
ResultCount = resultCount;
this.function = function;
}
/// <summary>The persisted name. Append-only: a released name keeps its meaning.</summary>
public string Name { get; }
public int Arity { get; }
/// <summary>One for a scalar op; more for an op read only through <see cref="ExprBuilder.Pick"/>.</summary>
public int ResultCount { get; }
public void Evaluate(ReadOnlySpan<float> operands, Span<float> results) => function(operands, results);
}
/// <summary>
/// The one op table of the expression graph: each op names a CultMath function and calls it, wrapping no type
/// and copying no body. The C# evaluator reads it, and so does any later lowering.
/// </summary>
public static class ExprOps
{
/// <summary>The largest arity in the table.</summary>
internal const int MaxArity = 4;
private static ExprOp Op(string name, int arity, ExprOp.Function function) => new(name, arity, 1, function);
private static readonly ExprOp[] Table =
{
Op("add", 2, (a, r) => r[0] = a[0] + a[1]),
Op("sub", 2, (a, r) => r[0] = a[0] - a[1]),
Op("mul", 2, (a, r) => r[0] = a[0] * a[1]),
Op("div", 2, (a, r) => r[0] = a[0] / a[1]),
Op("neg", 1, (a, r) => r[0] = -a[0]),
Op("min", 2, (a, r) => r[0] = min(a[0], a[1])),
Op("max", 2, (a, r) => r[0] = max(a[0], a[1])),
Op("abs", 1, (a, r) => r[0] = abs(a[0])),
Op("floor", 1, (a, r) => r[0] = floor(a[0])),
Op("frac", 1, (a, r) => r[0] = frac(a[0])),
Op("sqrt", 1, (a, r) => r[0] = sqrt(a[0])),
Op("exp", 1, (a, r) => r[0] = exp(a[0])),
Op("log", 1, (a, r) => r[0] = log(a[0])),
Op("pow", 2, (a, r) => r[0] = pow(a[0], a[1])),
Op("sin", 1, (a, r) => r[0] = sin(a[0])),
Op("cos", 1, (a, r) => r[0] = cos(a[0])),
Op("clamp", 3, (a, r) => r[0] = clamp(a[0], a[1], a[2])),
Op("saturate", 1, (a, r) => r[0] = saturate(a[0])),
Op("lerp", 3, (a, r) => r[0] = lerp(a[0], a[1], a[2])),
Op("step", 2, (a, r) => r[0] = step(a[0], a[1])),
Op("smoothstep", 3, (a, r) => r[0] = smoothstep(a[0], a[1], a[2])),
Op("select", 4, (a, r) => r[0] = select(a[0] > a[1], a[2], a[3])),
Op("snoise2", 2, (a, r) => r[0] = snoise(new float2(a[0], a[1]))),
Op("snoise3", 3, (a, r) => r[0] = snoise(new float3(a[0], a[1], a[2]))),
new ExprOp("cellular3", 3, 9, (a, r) =>
{
var c = cellular(new float3(a[0], a[1], a[2]));
r[0] = c.nearest.x; r[1] = c.nearest.y; r[2] = c.nearest.z; r[3] = c.nearest.w;
r[4] = c.edge.x; r[5] = c.edge.y; r[6] = c.edge.z; r[7] = c.edge.w;
r[8] = c.id;
}),
};
private static readonly Dictionary<string, ExprOp> ByName = Table.ToDictionary(op => op.Name);
/// <summary>Every op, in declaration order.</summary>
public static IReadOnlyList<ExprOp> All => Table;
/// <summary>The op with this persisted name, or null.</summary>
public static ExprOp? Find(string name) => ByName.TryGetValue(name, out var op) ? op : null;
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f2cb6ebc7a4f43d59009e613a1b75888

View file

@ -21,9 +21,10 @@ public static partial class math
// plain function of float values, so it mirrors into the HLSL common subset.
// An upper bound on the spectral norm of the Hessian of snoise(float3). Provenance:
// NoiseBoundTests.MeasureHessian (slow, explicit) takes the largest Hessian norm (central
// differences of snoise_grad, largest absolute eigenvalue) over 1e6 seeded points, refines the 1e4
// largest by ascent, and multiplies the refined maximum by 1.10;
// NoiseBoundTests.MeasureHessian (slow, explicit) takes the largest Hessian norm (snoise_hessian,
// largest absolute eigenvalue) over 1e6 seeded points, refines the 1e4 largest by ascent, and
// multiplies the refined maximum by 1.10 (50.5838 measured, 55.642143 pinned; the central
// differences of snoise_grad it replaced read 50.955 here, their roundoff at h = 1e-3);
// NoiseBoundTests.HessianConstantPinsSampledCurvature pins this value against a fast re-measure and
// the ascent from MeasureHessian's witness. Empirical with a margin, not a proof. Random balls
// cannot see a constant 20% low, so the defence is those two curvature tests plus
@ -31,8 +32,8 @@ public static partial class math
// curvature is realised if the constant is under it. The margin over the function: a scan of the
// whole 289^3 hash period found a realised maximum of 50.58, and bounding each corner's gradient
// independently over every hash configuration gives 52.22 (Soul pass s1). A change to the snoise
// kernel must re-run MeasureHessian and re-pin it.
public const float SNOISE_HESSIAN = 56.050385f;
// kernel must re-run MeasureHessian and re-pin it. SNOISE_THIRD (math.Span.cs) is the next-order pin.
public const float SNOISE_HESSIAN = 55.642143f;
/// <summary>The point form (x, 0, 0): the value x at every eps. Exact.</summary>
public static float3 af_point(float value) => new(value, 0.0f, 0.0f);

View file

@ -0,0 +1,397 @@
// SPDX-License-Identifier: Apache-2.0
//
// Cycles node semantics: what Blender's Cycles renderer computes for the Math, Map Range, Clamp, Mix and
// RGB to BW nodes and for a Color Ramp lookup, ported function by function from the Cycles kernel
// (intern/cycles of the Blender v5.2.2 tag; SPDX-FileCopyrightText: 2011-2022 Blender Foundation, Apache-2.0):
// kernel/svm/{math_util,map_range,clamp,mix,color_util,ramp,convert}.h, util/math_base.h, util/color.h and
// util/math_float3.h. Each function's comment names its Cycles source. Modified by GameCult: Cycles C++
// becomes C#, a function per node operation, and the node's socket defaults and clamp options are left to
// the caller. This file is Apache-2.0 (section 4: it was changed); the rest of CultMath is MIT, except the
// MPL-2.0 Phacelle files (see THIRD-PARTY-NOTICES.md). shaders/CultMath.Cycles.hlsl mirrors it bit for bit.
//
// Operands are finite floats. NaN and infinite operands are outside the oracle's reach and the mirror's.
// CyclesOracleTests holds every function to the results of Blender 5.2.2's own CPU Cycles.
namespace CultMath;
public static partial class math
{
// FLT_EPSILON, the least epsilon a Compare node honours.
private const float CYCLES_FLT_EPSILON = 1.1920929e-07f;
/// <summary>The scene-linear red luminance coefficient Cycles' RGB to BW node reads from Blender 5.2.2's default OCIO config.</summary>
public const float CYCLES_RGB_TO_Y_R = 0.212639093f;
/// <summary>The scene-linear green luminance coefficient Cycles' RGB to BW node reads from Blender 5.2.2's default OCIO config.</summary>
public const float CYCLES_RGB_TO_Y_G = 0.715169132f;
/// <summary>The scene-linear blue luminance coefficient Cycles' RGB to BW node reads from Blender 5.2.2's default OCIO config.</summary>
public const float CYCLES_RGB_TO_Y_B = 0.0721927434f;
// ---- Math node (kernel/svm/math_util.h svm_math; util/math_base.h) ----
/// <summary>Math node Divide (safe_divide): a / b, or 0 when b is 0.</summary>
public static float cycles_divide(float a, float b) => b != 0.0f ? a / b : 0.0f;
/// <summary>
/// Math node Power (safe_powf with compatible_powf): 0 for a negative base with a fractional exponent,
/// 1 for exponent 0, 0 for base 0. A negative base takes an integral exponent's parity.
/// </summary>
public static float cycles_power(float a, float b)
{
var whole = b >= 0.0f ? floor(b) : ceil(b);
if (a < 0.0f && b != whole)
return 0.0f;
if (b == 0.0f)
return 1.0f;
if (a == 0.0f)
return 0.0f;
if (a < 0.0f)
{
var magnitude = pow(-a, b);
// Odd exactly when the remainder is 1: an infinite exponent leaves NaN here and is even, as powf(a, +-inf) is never negative.
return b - 2.0f * floor(0.5f * b) == 1.0f ? -magnitude : magnitude;
}
return pow(a, b);
}
/// <summary>Math node Logarithm (safe_logf): log(a) / log(b), or 0 when a or b is not positive or log(b) is 0.</summary>
public static float cycles_logarithm(float a, float b)
{
if (a <= 0.0f || b <= 0.0f)
return 0.0f;
var denominator = log(b);
return denominator != 0.0f ? log(a) / denominator : 0.0f;
}
/// <summary>Math node Square Root (safe_sqrtf): the square root of max(a, 0).</summary>
public static float cycles_sqrt(float a) => sqrt(max(a, 0.0f));
/// <summary>Math node Inverse Square Root (inversesqrtf): 1 / sqrt(a), or 0 when a is not positive.</summary>
public static float cycles_inverse_sqrt(float a) => a > 0.0f ? 1.0f / sqrt(a) : 0.0f;
/// <summary>
/// Math node Truncated Modulo (safe_modulo), the remainder with the dividend's sign, exactly as fmodf computes
/// it, or 0 when b is 0. GLSL has no fmod, and a - b trunc(a / b) is wrong where the quotient rounds up to an
/// integer or the product rounds (3 mod 0.3 is 0.29999995, not 0). So this subtracts the largest power-of-two
/// multiple of the divisor not above the remainder until the remainder is below the divisor: every step is an
/// exact subtraction, as in fmod. The loops are bounded by the binades a float spans.
/// </summary>
public static float cycles_modulo(float a, float b)
{
var remainder = abs(a);
var divisor = abs(b);
for (var steps = 0; steps < 300 && remainder >= divisor && divisor > 0.0f; steps++)
{
var multiple = divisor;
for (var doublings = 0; doublings < 300 && multiple * 2.0f <= remainder; doublings++)
multiple = multiple * 2.0f;
remainder = remainder - multiple;
}
return b != 0.0f ? (a < 0.0f ? -remainder : remainder) : 0.0f;
}
/// <summary>Math node Floored Modulo (safe_floored_modulo): a - floor(a / b) b, or 0 when b is 0, with one IEEE single
/// rounding per operation (the reference of ruling cycles-kernel-reference-ruled). A build that contracts
/// a - floor(a / b) b into one fused operation differs by at most 2^-23 (|a / b| + 1) |b| (measured 0.91 of 2^-24 (|a| + |b|)
/// on Blender 5.2.2's AVX2 kernel); a fast-math build may also move floor(a / b) by one near an integer quotient,
/// so the result differs by a whole |b|. See tools/cycles-oracle/README.md.</summary>
public static float cycles_floored_modulo(float a, float b) => b != 0.0f ? a - floor(a / b) * b : 0.0f;
/// <summary>Math node Wrap (wrapf; note the argument order): value wrapped into [min_value, max_value), or min_value for an empty range,
/// with one IEEE single rounding per operation. A build that contracts value - range floor(...) into one fused operation differs by at
/// most 2^-23 (|value| + |min_value| + |range|) (measured 0.77 of 2^-24 on the AVX2 kernel); a fast-math build may also move floor by one,
/// a whole |range|. See tools/cycles-oracle/README.md.</summary>
public static float cycles_wrap(float value, float max_value, float min_value)
{
var range = max_value - min_value;
return range != 0.0f ? value - (range * floor((value - min_value) / range)) : min_value;
}
/// <summary>Math node Snap: floor(safe_divide(a, b)) b.</summary>
public static float cycles_snap(float a, float b) => floor(cycles_divide(a, b)) * b;
/// <summary>Math node Ping-Pong (pingpongf): a triangle wave of a with period 2 b, or 0 when b is 0.</summary>
public static float cycles_pingpong(float a, float b)
{
var scaled = (a - b) / (b * 2.0f);
return b != 0.0f ? abs((scaled - floor(scaled)) * b * 2.0f - b) : 0.0f;
}
/// <summary>Math node Smooth Minimum (smoothminf): the polynomial smooth minimum of width k, or min(a, b) when k is 0.</summary>
public static float cycles_smooth_min(float a, float b, float k)
{
var h = max(k - abs(a - b), 0.0f) / k;
return k != 0.0f ? min(a, b) - h * h * h * k * 0.16666667f : min(a, b);
}
/// <summary>Math node Smooth Maximum: -smoothminf(-a, -b, k).</summary>
public static float cycles_smooth_max(float a, float b, float k) => -cycles_smooth_min(-a, -b, k);
/// <summary>Math node Compare: 1 when a equals b or they differ by at most max(epsilon, FLT_EPSILON), else 0.</summary>
public static float cycles_compare(float a, float b, float epsilon) =>
(a == b || abs(a - b) <= max(epsilon, CYCLES_FLT_EPSILON)) ? 1.0f : 0.0f;
/// <summary>Math node Round: floor(a + 0.5).</summary>
public static float cycles_round(float a) => floor(a + 0.5f);
/// <summary>Math node Truncate: floor for a >= 0, ceil otherwise.</summary>
public static float cycles_trunc(float a) => a >= 0.0f ? floor(a) : ceil(a);
/// <summary>Math node Fraction: a - floor(a).</summary>
public static float cycles_fract(float a) => a - floor(a);
/// <summary>Math node Sign (compatible_signf): 0 for 0, -1 below, 1 above.</summary>
public static float cycles_sign(float a) => a == 0.0f ? 0.0f : (a < 0.0f ? -1.0f : 1.0f);
/// <summary>Math node Arcsine (safe_asinf, util/math_base.h): asin of a clamped to [-1, 1].</summary>
public static float cycles_arcsine(float a) => asin(clamp(a, -1.0f, 1.0f));
/// <summary>Math node Arccosine (safe_acosf, util/math_base.h): acos of a clamped to [-1, 1].</summary>
public static float cycles_arccosine(float a) => acos(clamp(a, -1.0f, 1.0f));
/// <summary>Math node Arctan2 (compatible_atan2, util/math_base.h; a is y, b is x): 0 at the origin, else atan2(a, b).</summary>
public static float cycles_arctan2(float a, float b) => (b == 0.0f && a == 0.0f) ? 0.0f : atan2(a, b);
// ---- Map Range node (kernel/svm/map_range.h svm_node_map_range) ----
// A Map Range node's Clamp option is a Clamp node of type Range on its result (MapRangeNode::expand):
// compose cycles_clamp_range over these.
/// <summary>Map Range, Linear: to_min + (value - from_min) / (from_max - from_min) (to_max - to_min), or 0 when from_max equals from_min.</summary>
public static float cycles_map_range_linear(float value, float from_min, float from_max, float to_min, float to_max)
{
var factor = (value - from_min) / (from_max - from_min);
return from_max != from_min ? to_min + factor * (to_max - to_min) : 0.0f;
}
/// <summary>Map Range, Stepped: the linear factor quantized to `steps` steps (0 when steps is not positive), or 0 when from_max equals from_min.</summary>
public static float cycles_map_range_stepped(float value, float from_min, float from_max, float to_min, float to_max, float steps)
{
var factor = (value - from_min) / (from_max - from_min);
factor = steps > 0.0f ? floor(factor * (steps + 1.0f)) / steps : 0.0f;
return from_max != from_min ? to_min + factor * (to_max - to_min) : 0.0f;
}
/// <summary>
/// Map Range, Smooth Step: the value goes through smoothstep(from_min, from_max, .), flipped when from_min
/// is above from_max (util/math_base.h smoothstep), or 0 when from_max equals from_min.
/// </summary>
public static float cycles_map_range_smoothstep(float value, float from_min, float from_max, float to_min, float to_max)
{
var low = min(from_min, from_max);
var high = max(from_min, from_max);
var t = (value - low) / (high - low);
var eased = value < low ? 0.0f : (value >= high ? 1.0f : (3.0f - 2.0f * t) * (t * t));
var factor = from_min > from_max ? 1.0f - eased : eased;
return from_max != from_min ? to_min + factor * (to_max - to_min) : 0.0f;
}
/// <summary>Map Range, Smoother Step (map_range.h smootherstep), flipped when from_min is above from_max, or 0 when from_max equals from_min.</summary>
public static float cycles_map_range_smootherstep(float value, float from_min, float from_max, float to_min, float to_max)
{
var low = min(from_min, from_max);
var high = max(from_min, from_max);
var x = clamp(cycles_divide(value - low, high - low), 0.0f, 1.0f);
var eased = x * x * x * (x * (x * 6.0f - 15.0f) + 10.0f);
var factor = from_min > from_max ? 1.0f - eased : eased;
return from_max != from_min ? to_min + factor * (to_max - to_min) : 0.0f;
}
// ---- Clamp node (kernel/svm/clamp.h svm_node_clamp) ----
/// <summary>Clamp node, Min Max: clamp(value, min_value, max_value).</summary>
public static float cycles_clamp_minmax(float value, float min_value, float max_value) => clamp(value, min_value, max_value);
/// <summary>Clamp node, Range: as Min Max, with the bounds swapped when min_value is above max_value.</summary>
public static float cycles_clamp_range(float value, float min_value, float max_value) =>
min_value > max_value ? clamp(value, max_value, min_value) : clamp(value, min_value, max_value);
// ---- Mix node (kernel/svm/mix.h, color_util.h) ----
// Factor clamping (svm_node_mix_color's saturatef) and result clamping (saturate) are the caller's.
/// <summary>Mix node, Float (svm_node_mix_float): a (1 - t) + b t.</summary>
public static float cycles_mix_float(float t, float a, float b) => a * (1.0f - t) + b * t;
/// <summary>Mix node, Vector, uniform factor (svm_node_mix_vector): a (1 - t) + b t per component.</summary>
public static float3 cycles_mix_vector(float t, float3 a, float3 b) => a * (new float3(1.0f, 1.0f, 1.0f) - t) + b * t;
/// <summary>Mix node, Mix blend mode (svm_mix_blend).</summary>
public static float3 cycles_mix_blend(float t, float3 col1, float3 col2) => col1 + t * (col2 - col1);
/// <summary>Mix node, Add blend mode (svm_mix_add).</summary>
public static float3 cycles_mix_add(float t, float3 col1, float3 col2) => col1 + t * ((col1 + col2) - col1);
/// <summary>Mix node, Multiply blend mode (svm_mix_mul).</summary>
public static float3 cycles_mix_mul(float t, float3 col1, float3 col2) => col1 + t * (col1 * col2 - col1);
/// <summary>Mix node, Screen blend mode (svm_mix_screen).</summary>
public static float3 cycles_mix_screen(float t, float3 col1, float3 col2)
{
var tm = 1.0f - t;
var one = new float3(1.0f, 1.0f, 1.0f);
return one - (new float3(tm, tm, tm) + t * (one - col2)) * (one - col1);
}
/// <summary>Mix node, Overlay blend mode (svm_mix_overlay).</summary>
public static float3 cycles_mix_overlay(float t, float3 col1, float3 col2)
{
var tm = 1.0f - t;
return new float3(
col1.x < 0.5f ? col1.x * (tm + 2.0f * t * col2.x) : 1.0f - (tm + 2.0f * t * (1.0f - col2.x)) * (1.0f - col1.x),
col1.y < 0.5f ? col1.y * (tm + 2.0f * t * col2.y) : 1.0f - (tm + 2.0f * t * (1.0f - col2.y)) * (1.0f - col1.y),
col1.z < 0.5f ? col1.z * (tm + 2.0f * t * col2.z) : 1.0f - (tm + 2.0f * t * (1.0f - col2.z)) * (1.0f - col1.z));
}
/// <summary>Mix node, Subtract blend mode (svm_mix_sub).</summary>
public static float3 cycles_mix_sub(float t, float3 col1, float3 col2) => col1 + t * ((col1 - col2) - col1);
/// <summary>Mix node, Divide blend mode (svm_mix_div): a channel whose col2 is 0 keeps col1.</summary>
public static float3 cycles_mix_div(float t, float3 col1, float3 col2)
{
var tm = 1.0f - t;
return new float3(
col2.x != 0.0f ? tm * col1.x + t * col1.x / col2.x : col1.x,
col2.y != 0.0f ? tm * col1.y + t * col1.y / col2.y : col1.y,
col2.z != 0.0f ? tm * col1.z + t * col1.z / col2.z : col1.z);
}
/// <summary>Mix node, Difference blend mode (svm_mix_diff).</summary>
public static float3 cycles_mix_diff(float t, float3 col1, float3 col2) => col1 + t * (abs(col1 - col2) - col1);
/// <summary>Mix node, Exclusion blend mode (svm_mix_exclusion).</summary>
public static float3 cycles_mix_exclusion(float t, float3 col1, float3 col2) =>
max(col1 + t * ((col1 + col2 - 2.0f * col1 * col2) - col1), new float3(0.0f, 0.0f, 0.0f));
/// <summary>Mix node, Darken blend mode (svm_mix_dark).</summary>
public static float3 cycles_mix_dark(float t, float3 col1, float3 col2) => col1 + t * (min(col1, col2) - col1);
/// <summary>Mix node, Lighten blend mode (svm_mix_light).</summary>
public static float3 cycles_mix_light(float t, float3 col1, float3 col2) => col1 + t * (max(col1, col2) - col1);
/// <summary>Mix node, Dodge blend mode (svm_mix_dodge).</summary>
public static float3 cycles_mix_dodge(float t, float3 col1, float3 col2)
{
var divisor = new float3(1.0f, 1.0f, 1.0f) - t * col2;
return new float3(
col1.x != 0.0f ? (divisor.x <= 0.0f ? 1.0f : min(col1.x / divisor.x, 1.0f)) : col1.x,
col1.y != 0.0f ? (divisor.y <= 0.0f ? 1.0f : min(col1.y / divisor.y, 1.0f)) : col1.y,
col1.z != 0.0f ? (divisor.z <= 0.0f ? 1.0f : min(col1.z / divisor.z, 1.0f)) : col1.z);
}
/// <summary>Mix node, Burn blend mode (svm_mix_burn).</summary>
public static float3 cycles_mix_burn(float t, float3 col1, float3 col2)
{
var tm = 1.0f - t;
var divisor = tm + t * col2;
var burnt = new float3(1.0f, 1.0f, 1.0f) - (new float3(1.0f, 1.0f, 1.0f) - col1) / divisor;
return new float3(
divisor.x <= 0.0f ? 0.0f : clamp(burnt.x, 0.0f, 1.0f),
divisor.y <= 0.0f ? 0.0f : clamp(burnt.y, 0.0f, 1.0f),
divisor.z <= 0.0f ? 0.0f : clamp(burnt.z, 0.0f, 1.0f));
}
/// <summary>RGB to HSV as Cycles computes it (util/color.h rgb_to_hsv): hue in [0, 1), saturation, value.</summary>
public static float3 cycles_rgb_to_hsv(float3 rgb)
{
var cmax = max(rgb.x, max(rgb.y, rgb.z));
var cmin = min(rgb.x, min(rgb.y, rgb.z));
var cdelta = cmax - cmin;
var s = cmax != 0.0f ? cdelta / cmax : 0.0f;
var c = (new float3(cmax, cmax, cmax) - rgb) / cdelta;
var h = rgb.x == cmax ? c.z - c.y : (rgb.y == cmax ? 2.0f + c.x - c.z : 4.0f + c.y - c.x);
h = h * 0.16666667f; // Cycles' kernel is built with reciprocal math: h /= 6.0f computes h * (1 / 6.0f).
h = h < 0.0f ? h + 1.0f : h;
return new float3(s != 0.0f ? h : 0.0f, s, cmax);
}
/// <summary>HSV to RGB as Cycles computes it (util/color.h hsv_to_rgb).</summary>
public static float3 cycles_hsv_to_rgb(float3 hsv)
{
var h = hsv.x == 1.0f ? 0.0f : hsv.x;
h = h * 6.0f;
var i = floor(h);
var f = h - i;
var p = hsv.z * (1.0f - hsv.y);
var q = hsv.z * (1.0f - (hsv.y * f));
var t = hsv.z * (1.0f - (hsv.y * (1.0f - f)));
var rgb = i == 0.0f ? new float3(hsv.z, t, p) :
(i == 1.0f ? new float3(q, hsv.z, p) :
(i == 2.0f ? new float3(p, hsv.z, t) :
(i == 3.0f ? new float3(p, q, hsv.z) :
(i == 4.0f ? new float3(t, p, hsv.z) : new float3(hsv.z, p, q)))));
return hsv.y != 0.0f ? rgb : new float3(hsv.z, hsv.z, hsv.z);
}
/// <summary>Mix node, Hue blend mode (svm_mix_hue).</summary>
public static float3 cycles_mix_hue(float t, float3 col1, float3 col2)
{
var hsv2 = cycles_rgb_to_hsv(col2);
var hsv = cycles_rgb_to_hsv(col1);
var shifted = cycles_hsv_to_rgb(new float3(hsv2.x, hsv.y, hsv.z));
return hsv2.y != 0.0f ? col1 + t * (shifted - col1) : col1;
}
/// <summary>Mix node, Saturation blend mode (svm_mix_sat).</summary>
public static float3 cycles_mix_sat(float t, float3 col1, float3 col2)
{
var tm = 1.0f - t;
var hsv = cycles_rgb_to_hsv(col1);
var hsv2 = cycles_rgb_to_hsv(col2);
return hsv.y != 0.0f ? cycles_hsv_to_rgb(new float3(hsv.x, tm * hsv.y + t * hsv2.y, hsv.z)) : col1;
}
/// <summary>Mix node, Value blend mode (svm_mix_val).</summary>
public static float3 cycles_mix_val(float t, float3 col1, float3 col2)
{
var tm = 1.0f - t;
var hsv = cycles_rgb_to_hsv(col1);
var hsv2 = cycles_rgb_to_hsv(col2);
return cycles_hsv_to_rgb(new float3(hsv.x, hsv.y, tm * hsv.z + t * hsv2.z));
}
/// <summary>Mix node, Color blend mode (svm_mix_color).</summary>
public static float3 cycles_mix_color(float t, float3 col1, float3 col2)
{
var hsv2 = cycles_rgb_to_hsv(col2);
var hsv = cycles_rgb_to_hsv(col1);
var shifted = cycles_hsv_to_rgb(new float3(hsv2.x, hsv2.y, hsv.z));
return hsv2.y != 0.0f ? col1 + t * (shifted - col1) : col1;
}
/// <summary>Mix node, Soft Light blend mode (svm_mix_soft).</summary>
public static float3 cycles_mix_soft(float t, float3 col1, float3 col2)
{
var tm = 1.0f - t;
var one = new float3(1.0f, 1.0f, 1.0f);
var scr = one - (one - col2) * (one - col1);
return tm * col1 + t * ((one - col1) * col2 * col1 + col1 * scr);
}
/// <summary>Mix node, Linear Light blend mode (svm_mix_linear).</summary>
public static float3 cycles_mix_linear(float t, float3 col1, float3 col2) =>
col1 + t * (2.0f * col2 + new float3(-1.0f, -1.0f, -1.0f));
// ---- RGB to BW node (kernel/svm/convert.h NODE_CONVERT_CF) ----
/// <summary>RGB to BW node: the scene-linear luminance of a colour.</summary>
public static float cycles_rgb_to_bw(float3 color) =>
color.x * CYCLES_RGB_TO_Y_R + color.y * CYCLES_RGB_TO_Y_G + color.z * CYCLES_RGB_TO_Y_B;
// ---- Color Ramp lookup (kernel/svm/ramp.h rgb_ramp_lookup, without extrapolation) ----
/// <summary>
/// Where a Color Ramp of `size` table entries is read at t: (index, weight), the lower entry and the
/// weight of the next one. The colour is table[index] when weight is 0 and
/// (1 - weight) table[index] + weight table[index + 1] otherwise. The ramp table itself is the caller's;
/// Blender's holds 257 entries, the ramp sampled at i / 256.
/// </summary>
public static float2 cycles_ramp_index(float t, int size)
{
var f = (t > 0.0f ? (t < 1.0f ? t : 1.0f) : 0.0f) * (float)(size - 1);
var index = clamp((int)f, 0, size - 1);
var lower = (float)index;
return new float2(lower, f - lower);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0484788fead24b7cb0b8b373bf7e1f9d

View file

@ -0,0 +1,123 @@
namespace CultMath;
public static partial class math
{
// An upper bound on the operator norm of the third-derivative tensor of snoise(float3):
// max over unit u of |D^3 snoise(p)[u, u, u]|, the next order after SNOISE_LIPSCHITZ (gradient)
// and SNOISE_HESSIAN (curvature). Provenance: NoiseBoundTests.MeasureThird (slow, explicit) takes
// the largest such norm over 1e6 seeded points of [-256, 256]^3 (central differences of
// snoise_hessian at h = 1e-3, then an ascent over unit vectors for the tensor's operator norm),
// refines the 1e4 largest by ascent over the point, and multiplies the maximum by 1.10; it prints
// the witness start. NoiseBoundTests.ThirdConstantPinsSampled pins the value against a fast
// re-measure and the ascent from that witness. Measured on the tied kernel (snoise_grad's order),
// not on any pre-tie splice. Measured 488.1047 (a dense sweep of 20,000 directions at the witness
// found 99.9998% of the tensor norm there). Empirical with a margin, not a proof. A change to the snoise kernel
// must re-run MeasureThird and re-pin it.
public const float SNOISE_THIRD = 536.9152f;
// Analytic Hessian of snoise(float3): the symmetric matrix of second partial derivatives, same
// lattice, hash and tie order as snoise_grad, whose kernel it differentiates once more. Every local
// up through p0..p3 and x0..x3 is snoise_grad's own derivation verbatim. Per corner, with
// m = max(0.5 - dot(x,x), 0) and s = dot(p,x), the corner's gradient is -8 m^3 s x + m^4 p, so
// d/dx_j of its i-th component is 48 m^2 s x_i x_j - 8 m^3 (p_j x_i + p_i x_j + s delta_ij) (the
// derivative of m^3 is -6 m^2 x_j, of s is p_j); summed over the four corners and scaled by the
// same 105. A clamped corner (m = 0) contributes nothing, and the m^2 and m^3 factors make the
// contribution vanish continuously as it clamps. Each off-diagonal entry is computed once and
// placed twice, so the matrix is its own transpose bit for bit. A float3x3 is built from its nine
// scalars, which the GLSL lowering reads as columns and HLSL as rows: the matrix is symmetric.
public static float3x3 snoise_hessian(float3 value)
{
const float cx = 1.0f / 6.0f;
const float cy = 1.0f / 3.0f;
var i = floor(value + dot(value, new float3(cy, cy, cy)));
var x0 = value - i + dot(i, new float3(cx, cx, cx));
var g = new float3(step(x0.y, x0.x), step(x0.z, x0.y), 1.0f - step(x0.z, x0.x));
var l = 1.0f - g;
var lzxy = new float3(l.z, l.x, l.y);
var i1 = min(g, lzxy);
var i2 = max(g, lzxy);
var x1 = x0 - i1 + cx;
var x2 = x0 - i2 + cy;
var x3 = x0 - 0.5f;
i = snoise_mod289(i);
var p = snoise_permute(snoise_permute(snoise_permute(
i.z + new float4(0.0f, i1.z, i2.z, 1.0f)) + i.y + new float4(0.0f, i1.y, i2.y, 1.0f)) + i.x + new float4(0.0f, i1.x, i2.x, 1.0f));
const float n = 0.142857142857f;
var ns = new float3(2.0f * n, 0.5f * n - 1.0f, n);
var j = p - 49.0f * floor(p * ns.z * ns.z);
var xs = floor(j * ns.z);
var ys = floor(j - 7.0f * xs);
var x = xs * ns.x + ns.y;
var y = ys * ns.x + ns.y;
var h = 1.0f - abs(x) - abs(y);
var b0 = new float4(x.x, x.y, y.x, y.y);
var b1 = new float4(x.z, x.w, y.z, y.w);
var s0 = floor(b0) * 2.0f + 1.0f;
var s1 = floor(b1) * 2.0f + 1.0f;
var sh = -step(h, 0.0f);
var a0 = new float4(b0.x, b0.z, b0.y, b0.w) + new float4(s0.x, s0.z, s0.y, s0.w) * new float4(sh.x, sh.x, sh.y, sh.y);
var a1 = new float4(b1.x, b1.z, b1.y, b1.w) + new float4(s1.x, s1.z, s1.y, s1.w) * new float4(sh.z, sh.z, sh.w, sh.w);
var p0 = new float3(a0.x, a0.y, h.x);
var p1 = new float3(a0.z, a0.w, h.y);
var p2 = new float3(a1.x, a1.y, h.z);
var p3 = new float3(a1.z, a1.w, h.w);
var norm = 1.79284291400159f - 0.85373472095314f * new float4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3));
p0 *= norm.x;
p1 *= norm.y;
p2 *= norm.z;
p3 *= norm.w;
var m0 = max(0.5f - new float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0f);
var m2 = m0 * m0;
var m3 = m2 * m0;
var px = new float4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3));
var wide = 48.0f * m2 * px;
var narrow = 8.0f * m3;
// One component of every corner's x and p per register.
var cxx = new float4(x0.x, x1.x, x2.x, x3.x);
var cxy = new float4(x0.y, x1.y, x2.y, x3.y);
var cxz = new float4(x0.z, x1.z, x2.z, x3.z);
var cpx = new float4(p0.x, p1.x, p2.x, p3.x);
var cpy = new float4(p0.y, p1.y, p2.y, p3.y);
var cpz = new float4(p0.z, p1.z, p2.z, p3.z);
var hxx = 105.0f * (dot(wide * cxx, cxx) - dot(narrow, 2.0f * cpx * cxx + px));
var hyy = 105.0f * (dot(wide * cxy, cxy) - dot(narrow, 2.0f * cpy * cxy + px));
var hzz = 105.0f * (dot(wide * cxz, cxz) - dot(narrow, 2.0f * cpz * cxz + px));
var hxy = 105.0f * (dot(wide * cxx, cxy) - dot(narrow, cpx * cxy + cpy * cxx));
var hxz = 105.0f * (dot(wide * cxx, cxz) - dot(narrow, cpx * cxz + cpz * cxx));
var hyz = 105.0f * (dot(wide * cxy, cxz) - dot(narrow, cpy * cxz + cpz * cxy));
return new float3x3(hxx, hxy, hxz, hxy, hyy, hyz, hxz, hyz, hzz);
}
// The integral over [t0, t1] of clamp(a + b t, lo, hi) dt, in closed form. The line meets lo at
// (lo - a) / b and hi at (hi - a) / b; the span is cut at those two crossings into the stretch held
// at the bound the line starts beyond, the stretch on the ramp (a trapezoid: its length times the
// line's value at the stretch's midpoint), and the stretch held at the far bound. b = 0 is the
// constant clamp(a, lo, hi); t1 < t0 is the negative of the integral over [t1, t0]; lo above hi
// clamps to hi everywhere, as clamp does. A crossing that overflows (b tiny) lies past the span and
// cuts nothing.
public static float integral_clamp_linear(float a, float b, float lo, float hi, float t0, float t1)
{
if (b == 0.0f)
return clamp(a, lo, hi) * (t1 - t0);
lo = min(lo, hi);
var direction = t1 < t0 ? -1.0f : 1.0f;
var start = min(t0, t1);
var stop = max(t0, t1);
var atLo = (lo - a) / b;
var atHi = (hi - a) / b;
var enter = clamp(min(atLo, atHi), start, stop);
var leave = clamp(max(atLo, atHi), start, stop);
var before = b > 0.0f ? lo : hi;
var after = b > 0.0f ? hi : lo;
var total = before * (enter - start) + (a + b * (0.5f * (enter + leave))) * (leave - enter) + after * (stop - leave);
return direction * total;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1466848dfbfc420ab4f3f67090944a67

View file

@ -0,0 +1,460 @@
using System.Reflection;
using System.Text.Json.Nodes;
using Xunit;
namespace CultMath.Tests;
/// <summary>
/// math.cycles_* and the shader mirror's cultmath_cycles_* (shaders/CultMath.Cycles.hlsl, compiled as C#) against
/// the results of Blender 5.2.2's own Cycles on the CPU, the reference of ruling
/// cultmath-tapes:ruling:cycles-kernel-reference-ruled: Cycles' formulas with one IEEE single rounding per
/// operation. The fixtures under fixtures/cycles-oracle are written by
/// tools/cycles-oracle/oracle.py (never by hand): each case is the operands and the node's baked results as
/// float32 bit patterns. Every function is compared at every case within the tolerance named in
/// <see cref="Tolerances"/>; a function not named there is held to 0 ulp. Signed zeros are not distinguished (-0
/// equals 0), and NaN equals NaN. The fixtures come from Cycles' SSE4.2 CPU kernel, which does not fuse
/// multiply-adds as C# does not (oracle.py checks this before it bakes); other builds are other tolerance classes
/// (tools/cycles-oracle/README.md). Cycles' film writes 0 for an infinite or
/// NaN result, so a case whose result here is not finite and whose fixture result is 0 holds nothing to compare.
/// </summary>
public sealed class CyclesOracleTests
{
// The ulp distance a function is allowed from the reference. Empty: the fixtures are the SSE4.2 kernel's results
// and every function equals them, power and logarithm included (glibc's powf and logf, 0 ulp from MathF on Linux).
// An entry needs a measured case on the reference named in it (a failing case's bits and ulp); other builds'
// tolerances belong to the class table in tools/cycles-oracle/README.md, not here.
private static readonly Dictionary<string, (int Ulp, string Measured)> Tolerances = new();
private const string CSharp = "C#";
private const string Mirror = "HLSL mirror";
private static readonly Lazy<(object Shader, Type Type)> ShaderMirror = new(() =>
{
var (assembly, errors) = HlslSourceCompatibilityTests.CompileShaderMirror();
Assert.True(assembly is not null, string.Join(Environment.NewLine, errors));
var type = assembly!.GetType("CultMathHlsl.HlslShader")!;
return (Activator.CreateInstance(type)!, type);
});
/// <summary>One implementation of the Cycles functions: CultMath's C# or the HLSL text compiled as C#.</summary>
private static object Call(string target, string function, params object[] arguments)
{
if (target == CSharp)
return Method(function).Invoke(null, arguments)!;
var (shader, type) = ShaderMirror.Value;
var method = type.GetMethod("cultmath_" + function, BindingFlags.Instance | BindingFlags.NonPublic)
?? throw new InvalidOperationException("no mirror function cultmath_" + function);
return method.Invoke(shader, arguments)!;
}
public static IEnumerable<object[]> Families() =>
from family in new[] { "math", "map-range", "clamp", "mix", "rgb-to-bw" }
from target in new[] { CSharp, Mirror }
select new object[] { family, target };
public static IEnumerable<object[]> Targets() => new[] { CSharp, Mirror }.Select(target => new object[] { target });
private static string FixturePath(string family) =>
Path.Combine(HlslSourceCompatibilityTests.FindCultMathRoot(), "tests", "CultMath.Tests", "fixtures", "cycles-oracle", family + ".json");
private static JsonObject Load(string family) => JsonNode.Parse(File.ReadAllText(FixturePath(family)))!.AsObject();
private static float Float(string token) => BitConverter.Int32BitsToSingle((int)Convert.ToUInt32(token, 16));
// A float32 bit pattern as an integer whose order and differences are the floats' order and ulps.
private static int Ordered(float value)
{
var bits = BitConverter.SingleToInt32Bits(value);
return bits < 0 ? int.MinValue - bits : bits;
}
private static long Distance(float want, float have) =>
want == have || (float.IsNaN(want) && float.IsNaN(have)) ? 0 : float.IsNaN(want) || float.IsNaN(have) ? long.MaxValue : Math.Abs((long)Ordered(want) - Ordered(have));
// The method takes floats and float3s only; each float3 is three consecutive tokens.
private static object[] Arguments(MethodInfo method, string[] tokens)
{
var values = new List<object>();
var next = 0;
foreach (var parameter in method.GetParameters())
{
if (parameter.ParameterType == typeof(float))
values.Add(Float(tokens[next++]));
else if (parameter.ParameterType == typeof(float3))
{
values.Add(new float3(Float(tokens[next]), Float(tokens[next + 1]), Float(tokens[next + 2])));
next += 3;
}
else
throw new InvalidOperationException($"{method.Name}: parameter type {parameter.ParameterType.Name} is not a fixture operand");
}
// The operands a function does not take (Map Range's Steps, for the three kinds that ignore it) are left unread.
Assert.True(next <= tokens.Length, $"{method.Name}: {next} operands wanted, {tokens.Length} in the case");
return values.ToArray();
}
private static float[] Flatten(object result) => result switch
{
float f => new[] { f },
float2 v => new[] { v.x, v.y },
float3 v => new[] { v.x, v.y, v.z },
_ => throw new InvalidOperationException(result.GetType().Name),
};
private static MethodInfo Method(string name) =>
typeof(math).GetMethod(name, BindingFlags.Public | BindingFlags.Static) ?? throw new InvalidOperationException("no CultMath function " + name);
[Theory]
[MemberData(nameof(Families))]
public void FamilyMatchesBlender(string family, string target)
{
var fixture = Load(family);
Assert.Equal("5.2.2 LTS", (string?)fixture["blender"]);
Assert.Equal("d13f752e3b9c", (string?)fixture["build_hash"]);
var functions = fixture["functions"]!.AsArray();
Assert.NotEmpty(functions);
var failures = new List<string>();
foreach (var entry in functions)
{
var name = (string)entry!["function"]!;
var method = Method(name);
var clamped = (string?)entry["then"] is not null;
var allowed = Tolerances.TryGetValue(name, out var tolerance) ? tolerance.Ulp : 0;
var worst = 0L;
string? worstCase = null;
var cases = entry["cases"]!.AsArray();
Assert.True(cases.Count >= 1000, $"{name}: only {cases.Count} fixture cases");
foreach (var line in cases)
{
var sides = ((string)line!).Split(" -> ");
var operands = sides[0].Split(' ');
var have = Flatten(Call(target, name, Arguments(method, operands)));
if (clamped)
{
// A Map Range node's Clamp option is a Clamp node of type Range on its result.
have = Flatten(Call(target, "cycles_clamp_range", have[0], Float(operands[3]), Float(operands[4])));
}
var want = sides[1].Split(' ').Select(Float).ToArray();
Assert.Equal(want.Length, have.Length);
for (var k = 0; k < want.Length; k++)
{
if (!float.IsFinite(have[k]) && want[k] == 0.0f)
continue;
var distance = Distance(want[k], have[k]);
if (distance > worst)
{
worst = distance;
worstCase = $"{line} ({target} {BitConverter.SingleToInt32Bits(have[k]):x8})";
}
}
}
if (worst > allowed)
failures.Add($"{target} {name}{(clamped ? " with Clamp" : string.Empty)}: {worst} ulp from Blender, allowed {allowed}; worst case {worstCase}");
}
Assert.True(failures.Count == 0, string.Join(Environment.NewLine, failures));
}
private static JsonNode RampEntry(string interpolation) =>
Load("ramp")["functions"]!.AsArray().Single(e => e!["node"]!.ToString() == "ShaderNodeValToRGB " + interpolation)!;
[Theory]
[MemberData(nameof(Targets))]
public void RampIndexNamesTheEntryBlenderReads(string target)
{
var entry = RampEntry("CONSTANT");
var size = (int)entry["table_entries"]!;
var stops = entry["stops"]!.AsArray().Select(stop => (Position: Float((string)stop![0]!), Value: Float((string)stop[1]!))).ToArray();
// A constant ramp's table: the value of the last stop at or before the entry's position.
var table = Enumerable.Range(0, size).Select(i =>
{
var position = (double)i / (size - 1);
var stop = stops.LastOrDefault(s => s.Position <= position);
return stop == default ? stops[0].Value : stop.Value;
}).ToArray();
var cases = entry["cases"]!.AsArray().Select(line => ((string)line!).Split(" -> ")).ToArray();
Assert.True(table.Distinct().Count() > 30, "the constant ramp's table should name 32 entries apart");
foreach (var line in cases)
{
var lookup = Flatten(Call(target, "cycles_ramp_index", Float(line[0]), size));
var index = (int)lookup[0];
Assert.InRange(index, 0, size - 1);
Assert.True(Distance(Float(line[1]), table[index]) == 0, $"ramp t {line[0]}: index {index} reads {table[index]}, Blender {Float(line[1])}");
}
// Every stop's value appears in the results at its own boundary, so the cases do cross the entries.
Assert.True(cases.Select(line => line[1]).Distinct().Count() >= 32, "the cases never cross the stops");
}
[Theory]
[MemberData(nameof(Targets))]
public void RampWeightBlendsTheEntryWithTheNextOne(string target)
{
// A linear ramp from 0 to 1: entry i holds i / (size - 1) to within the float rounding of Blender's table, and
// a lookup at (index, weight) reads (index + weight) / (size - 1). A weight that is off by a fraction of a
// percent, or an index that is off by one, moves the result by more than the bound.
var entry = RampEntry("LINEAR");
var size = (int)entry["table_entries"]!;
var worst = 0.0;
var fractional = 0;
foreach (var line in entry["cases"]!.AsArray().Select(line => ((string)line!).Split(" -> ")))
{
var lookup = Flatten(Call(target, "cycles_ramp_index", Float(line[0]), size));
Assert.InRange(lookup[1], 0.0f, 1.0f);
fractional += lookup[1] > 0.0f ? 1 : 0;
var expected = (lookup[0] + lookup[1]) / (size - 1);
worst = Math.Max(worst, Math.Abs(expected - Float(line[1])));
}
Assert.True(fractional > 500, "the cases hold too few interpolated lookups");
Assert.True(worst <= Math.ScaleB(1.0, -22), $"a lookup is {worst} from (index + weight) / (size - 1), more than 2^-22");
}
[Theory]
[MemberData(nameof(Targets))]
public void ResultsTheFilmCannotShowFollowTheCyclesSource(string target)
{
// Cycles' film writes 0 for an infinite or NaN result, so the fixtures cannot tell the guards that return 0
// from the division that would return an infinity. These are the guards in svm_math (util/math_base.h):
// safe_logf, safe_divide and inversesqrtf return 0 where the plain operation is not finite.
float One(string function, params float[] arguments) => (float)Call(target, function, arguments.Cast<object>().ToArray());
Assert.Equal(0.0f, One("cycles_logarithm", 0.0f, 2.0f));
Assert.Equal(0.0f, One("cycles_logarithm", -1.0f, 2.0f));
Assert.Equal(0.0f, One("cycles_logarithm", 2.0f, 0.0f));
Assert.Equal(0.0f, One("cycles_logarithm", 2.0f, -1.0f));
Assert.Equal(0.0f, One("cycles_divide", 1.0f, 0.0f));
Assert.Equal(0.0f, One("cycles_inverse_sqrt", 0.0f));
Assert.Equal(0.0f, One("cycles_modulo", 1.0f, 0.0f));
Assert.Equal(0.0f, One("cycles_floored_modulo", 1.0f, 0.0f));
}
private static float OperandOrInfinity(string token) => token == "inf" ? float.PositiveInfinity : token == "-inf" ? float.NegativeInfinity : Float(token);
[Theory]
[MemberData(nameof(Targets))]
public void InfiniteOperandsFollowBlender(string target)
{
// infinite.json: operands that are infinite, made inside Blender's kernel (the film writes 0 for an infinity), and
// results read back through comparisons with 0 as "inf", "-inf" or "nan" where the film showed 0.
var functions = Load("infinite")["functions"]!.AsArray();
Assert.Equal(new[] { "cycles_power", "cycles_modulo", "cycles_map_range_smoothstep" }, functions.Select(f => (string)f!["function"]!).ToArray());
var cases = 0;
foreach (var entry in functions)
{
var name = (string)entry!["function"]!;
foreach (var line in entry["cases"]!.AsArray())
{
var sides = ((string)line!).Split(" -> ");
var operands = sides[0].Split(' ').Select(OperandOrInfinity).Cast<object>().ToArray();
var have = (float)Call(target, name, operands);
var ok = sides[1] switch
{
"nan" => float.IsNaN(have),
"inf" => float.IsPositiveInfinity(have),
"-inf" => float.IsNegativeInfinity(have),
var token => Distance(Float(token), have) == 0,
};
Assert.True(ok, $"{target} {name} {sides[0]}: Blender {sides[1]}, here {have}");
cases++;
}
}
Assert.True(cases >= 45, $"{cases} infinite-operand cases");
}
[Theory]
[MemberData(nameof(Targets))]
public void InfiniteOperandsFollowTheCyclesSource(string target)
{
// Blender 5.2.2 (infinite.json rows named beside each pin). powf(a, +-inf) is never negative, so an infinite
// exponent is even; modulo and smoothstep of an infinity are NaN where inf - inf or inf / inf forms.
float One(string function, params float[] arguments) => (float)Call(target, function, arguments.Cast<object>().ToArray());
const float inf = float.PositiveInfinity;
Assert.Equal(0x3f800000, BitConverter.SingleToInt32Bits(One("cycles_power", -1.0f, inf)));
Assert.Equal(0x3f800000, BitConverter.SingleToInt32Bits(One("cycles_power", -1.0f, -inf)));
Assert.Equal(inf, One("cycles_power", -2.0f, inf));
Assert.Equal(inf, One("cycles_power", -0.5f, -inf));
Assert.Equal(0, BitConverter.SingleToInt32Bits(One("cycles_power", -2.0f, -inf)));
Assert.Equal(-8.0f, One("cycles_power", -2.0f, 3.0f));
Assert.Equal(0x3f800000, BitConverter.SingleToInt32Bits(One("cycles_power", -1.0f, 2.0f)));
Assert.True(float.IsNaN(One("cycles_modulo", inf, 1.0f)));
Assert.True(float.IsNaN(One("cycles_modulo", -inf, 3.0f)));
Assert.True(float.IsNaN(One("cycles_modulo", inf, 0.1f)));
Assert.True(float.IsNaN(One("cycles_map_range_smoothstep", -inf, -inf, 1.0f, 2.0f, 3.0f)));
Assert.True(float.IsNaN(One("cycles_map_range_smoothstep", -inf, 1.0f, -inf, 2.0f, 3.0f)));
Assert.Equal(2.0f, One("cycles_map_range_smoothstep", -inf, 1.0f, 5.0f, 2.0f, 3.0f));
}
[Theory]
[MemberData(nameof(Targets))]
public void InverseTrigonometryFollowsTheCyclesGuards(string target)
{
// util/math_base.h: safe_asinf and safe_acosf clamp to [-1, 1] before asinf and acosf; compatible_atan2 returns 0
// at the origin (x == 0 && y == 0) and is atan2f everywhere else, so its guard is only the origin.
float One(string function, params float[] arguments) => (float)Call(target, function, arguments.Cast<object>().ToArray());
Assert.Equal(MathF.Asin(1.0f), One("cycles_arcsine", 2.0f));
Assert.Equal(MathF.Asin(-1.0f), One("cycles_arcsine", -1.5f));
Assert.Equal(MathF.Asin(1.0f), One("cycles_arcsine", 1.0000001f));
Assert.Equal(0.0f, One("cycles_arccosine", 2.0f));
Assert.Equal(MathF.Acos(-1.0f), One("cycles_arccosine", -2.0f));
Assert.Equal(0.0f, One("cycles_arctan2", 0.0f, 0.0f));
Assert.Equal(0.0f, One("cycles_arctan2", 0.0f, -0.0f));
Assert.Equal(0.0f, One("cycles_arctan2", -0.0f, -0.0f));
Assert.Equal(MathF.Atan2(-0.0f, -1.0f), One("cycles_arctan2", -0.0f, -1.0f));
Assert.Equal(MathF.Atan2(0.0f, -1.0f), One("cycles_arctan2", 0.0f, -1.0f));
Assert.Equal(MathF.Atan2(1.0f, 0.0f), One("cycles_arctan2", 1.0f, 0.0f));
Assert.Equal(MathF.Atan2(-1.0f, 0.0f), One("cycles_arctan2", -1.0f, 0.0f));
// The guard is the origin alone: a guard on either zero would zero these (the plain atan2 values are pi and pi/2).
Assert.NotEqual(0.0f, One("cycles_arctan2", 0.0f, -1.0f));
Assert.NotEqual(0.0f, One("cycles_arctan2", 1.0f, 0.0f));
foreach (var value in new[] { One("cycles_arcsine", 2.0f), One("cycles_arccosine", -2.0f), One("cycles_arctan2", 0.0f, -0.0f), One("cycles_arctan2", 1.0f, 0.0f) })
Assert.True(float.IsFinite(value));
}
[Theory]
[MemberData(nameof(Targets))]
public void MapRangeSmoothStepDecidesTheTopEdgeBeforeDividing(string target)
{
// util/math_base.h smoothstep returns 1 for x >= edge1 before it forms t. With an overflowing range
// (high - low = infinity) the division would be infinity / infinity, NaN.
float Smooth(params float[] arguments) => (float)Call(target, "cycles_map_range_smoothstep", arguments.Cast<object>().ToArray());
Assert.Equal(1.0f, Smooth(3.0e38f, -3.0e38f, 3.0e38f, 0.0f, 1.0f));
Assert.Equal(0.0f, Smooth(3.0e38f, 3.0e38f, -3.0e38f, 0.0f, 1.0f));
Assert.Equal(0.0f, Smooth(-3.0e38f, -3.0e38f, 3.0e38f, 0.0f, 1.0f));
}
[Fact]
public void FlooredModuloAndWrapUnderContractionStayWithinTheBound()
{
// Ruling cycles-kernel-reference-ruled: a build that contracts a - floor(a / b) b into one fused operation differs
// from the reference by at most 2^-23 (|a| + |b|), and the wrap model by 2^-23 (|value| + |min| + |range|). The fused
// model is MathF.FusedMultiplyAdd, test-only; no cycles_* function uses it.
var bound = Math.ScaleB(1.0, -23);
var worstModulo = 0.0;
var worstWrap = 0.0;
var seenPair = false;
foreach (var entry in Load("math")["functions"]!.AsArray())
{
var name = (string)entry!["function"]!;
if (name != "cycles_floored_modulo" && name != "cycles_wrap")
continue;
foreach (var line in entry["cases"]!.AsArray())
{
var o = ((string)line!).Split(" -> ")[0].Split(' ').Select(Float).ToArray();
if (name == "cycles_floored_modulo")
{
float a = o[0], b = o[1];
if (b == 0.0f)
continue;
var fused = MathF.FusedMultiplyAdd(-MathF.Floor(a / b), b, a);
var scale = Math.Abs((double)a) + Math.Abs((double)b);
var difference = Math.Abs((double)fused - math.cycles_floored_modulo(a, b));
Assert.True(difference <= bound * scale, $"floored modulo ({line}): fused {fused} is {difference / scale} of |a| + |b| from the reference");
worstModulo = Math.Max(worstModulo, difference / scale);
if (a == 10000.0f && b == 0.1f)
{
seenPair = true;
Assert.Equal(-1.4901161e-4f, fused);
Assert.Equal(0.0f, math.cycles_floored_modulo(a, b));
}
}
else
{
float value = o[0], max = o[1], min = o[2];
var range = max - min;
if (range == 0.0f)
continue;
var fused = MathF.FusedMultiplyAdd(-range, MathF.Floor((value - min) / range), value);
var scale = Math.Abs((double)value) + Math.Abs((double)min) + Math.Abs((double)range);
var difference = Math.Abs((double)fused - math.cycles_wrap(value, max, min));
Assert.True(difference <= bound * scale, $"wrap ({line}): fused {fused} is {difference / scale} of |value| + |min| + |range| from the reference");
worstWrap = Math.Max(worstWrap, difference / scale);
}
}
}
Assert.True(seenPair, "the fixture holds no (10000, 0.1) floored modulo case");
// The cases reach the contraction regime: a bound of 2^-25 would fail.
Assert.True(worstModulo > Math.ScaleB(1.0, -25), $"the worst floored modulo contraction is only {worstModulo} of |a| + |b|");
Assert.True(worstWrap > Math.ScaleB(1.0, -25), $"the worst wrap contraction is only {worstWrap} of |value| + |min| + |range|");
}
// The values oracle.py draws the specials of a function from (SPECIAL, plus the arcsine and arccosine edge rows); a row with any other operand holds a random draw.
private static readonly HashSet<float> Alphabet = new[]
{
0.0, 1.0, -1.0, 0.5, -0.5, 2.0, -2.0, 3.0, -2.75, 0.1, -0.1, 7.5, -7.5, 1.0e-7, -1.0e-7, 100.0, -100.0, 1.0e4, 0.3, 0.7, 1.5, 1.0000001, -1.0000001,
}.Select(v => (float)v).ToHashSet();
[Fact]
public void OperandStreamsDifferPerFunction()
{
// oracle.py seeds every function, every blend mode's second colours and every ramp from its own name, so no two
// share a stream of draws. At e48f9488 the seed was the name's first four bytes, and 'cycles_' shared them all.
var functions = Load("math")["functions"]!.AsArray()
.Select(e => (Name: (string)e!["function"]!, Rows: e["cases"]!.AsArray().Select(l => ((string)l!).Split(" -> ")[0]).ToArray()))
.ToArray();
Assert.True(functions.Length >= 17, "the math fixture lost functions");
foreach (var f in functions)
{
var draws = f.Rows.Where(row => row.Split(' ').Any(token => !Alphabet.Contains(Float(token)))).ToHashSet();
Assert.True(draws.Count >= 8, $"{f.Name} holds only {draws.Count} random-draw rows");
foreach (var g in functions.Where(g => string.CompareOrdinal(f.Name, g.Name) < 0 && g.Rows[0].Split(' ').Length == f.Rows[0].Split(' ').Length))
{
var shared = g.Rows.Count(row => draws.Contains(row));
Assert.True(shared == 0, $"{f.Name} and {g.Name} share {shared} random-draw rows");
}
}
var modes = Load("mix")["functions"]!.AsArray()
.Where(e => ((string)e!["function"]!).StartsWith("cycles_mix_") && ((string)e["cases"]![0]!).Split(" -> ")[0].Split(' ').Length == 7)
.Select(e => (Name: (string)e!["function"]!, Rows: e["cases"]!.AsArray().Select(l => ((string)l!).Split(" -> ")[0].Split(' ')).ToArray()))
.ToArray();
Assert.True(modes.Length >= 15, "the mix fixture lost blend modes");
static string Multiset(IEnumerable<string[]> rows, int first) => string.Join("|", rows.Select(r => string.Join(" ", r.Skip(first).Take(3))).OrderBy(x => x, StringComparer.Ordinal));
foreach (var mode in modes)
Assert.True(Multiset(mode.Rows, 1) != Multiset(mode.Rows, 4), $"{mode.Name}: the second colours are the first colours");
foreach (var f in modes)
foreach (var g in modes.Where(g => string.CompareOrdinal(f.Name, g.Name) < 0))
Assert.True(Multiset(f.Rows, 4) != Multiset(g.Rows, 4), $"{f.Name} and {g.Name} draw the same second colours");
var ramps = Load("ramp")["functions"]!.AsArray()
.Select(e => e!["cases"]!.AsArray().Select(l => ((string)l!).Split(" -> ")[0]).ToArray()).ToArray();
Assert.Equal(2, ramps.Length);
var tail = ramps[0].TakeLast(100).ToHashSet();
Assert.True(!ramps[1].TakeLast(100).Any(tail.Contains), "the ramps' random t tails overlap");
}
[Theory]
[MemberData(nameof(Targets))]
public void HueSaturationAndValueOfThePrimariesFollowCycles(string target)
{
// util/color.h rgb_to_hsv: hue 0 for red, 1/3 for green, 2/3 for blue, saturation 1, value 1; a grey has
// hue 0 and saturation 0. Red's hue is exactly 0 and not 1, which hsv_to_rgb would read the same.
float[] Hsv(float r, float g, float b) => Flatten(Call(target, "cycles_rgb_to_hsv", new float3(r, g, b)));
Assert.Equal(new[] { 0.0f, 1.0f, 1.0f }, Hsv(1.0f, 0.0f, 0.0f));
Assert.Equal(new[] { 0.0f, 0.0f, 0.5f }, Hsv(0.5f, 0.5f, 0.5f));
Assert.Equal(1.0f / 3.0f, Hsv(0.0f, 1.0f, 0.0f)[0], 6);
Assert.Equal(2.0f / 3.0f, Hsv(0.0f, 0.0f, 1.0f)[0], 6);
var back = Flatten(Call(target, "cycles_hsv_to_rgb", new float3(0.0f, 1.0f, 1.0f)));
Assert.Equal(new[] { 1.0f, 0.0f, 0.0f }, back);
}
[Fact]
public void RgbToBwCoefficientsAreTheOnesBlenderReads()
{
var entry = Load("rgb-to-bw")["functions"]!.AsArray().Single()!["cases"]!.AsArray().Select(line => ((string)line!).Split(" -> ")).ToArray();
float Primary(int channel) => Float(entry.First(c =>
{
var operands = c[0].Split(' ').Select(Float).ToArray();
return Enumerable.Range(0, 3).All(k => operands[k] == (k == channel ? 1.0f : 0.0f));
})[1]);
Assert.Equal(math.CYCLES_RGB_TO_Y_R, Primary(0));
Assert.Equal(math.CYCLES_RGB_TO_Y_G, Primary(1));
Assert.Equal(math.CYCLES_RGB_TO_Y_B, Primary(2));
}
}

View file

@ -0,0 +1,611 @@
using CultMath.Expr;
using Xunit;
using static CultMath.math;
namespace CultMath.Tests;
/// <summary>
/// CultMath.Expr: the evaluator equals the direct composition of the same math calls bit for bit (every op and a
/// corpus imitating Aetheria's trophic compositions), the builder is canonical and refuses at the call, substitution
/// builds stencils, constants and param defaults keep their bits, bindings resolve by name, the validator's rules
/// refuse each one by name, and no refusal echoes a value it was given.
///
/// Hand mutations these must kill: an op's implementation or operand order swapped in the table (the per-op
/// comparison); hash-consing disabled or the dead-node pass removed (BuildIsCanonical); Substitute leaving an input
/// unmapped (SubstituteEqualsOffsetEvaluation); a validator rule deleted (ValidatorRefusesEachRuleByName and the
/// builder refusals); a constant routed through float arithmetic (ConstantsKeepTheirBits).
/// </summary>
public sealed class ExprTests
{
private const int Points = 4096;
private const string Canary = "CANARY";
private static readonly float[] Edge =
{
0f, -0f, 1f, -1f, 0.5f, 3f, 1e-30f, float.Epsilon, -float.Epsilon, 1.17549435e-38f / 2f,
float.NaN, float.PositiveInfinity, float.NegativeInfinity, float.MaxValue, -float.MaxValue, 1e30f, -1e30f,
};
private static bool Same(float a, float b) =>
(float.IsNaN(a) && float.IsNaN(b)) || BitConverter.SingleToInt32Bits(a) == BitConverter.SingleToInt32Bits(b);
private static float[] Column(System.Random rng, int points, float lo, float hi, double edgeShare)
{
var column = new float[points];
for (var i = 0; i < points; i++)
column[i] = rng.NextDouble() < edgeShare ? Edge[rng.Next(Edge.Length)] : lo + (hi - lo) * rng.NextSingle();
return column;
}
private static float[] Pack(params float[][] columns) => columns.SelectMany(column => column).ToArray();
private static float[] Run(ExprGraph graph, ExprBindings bindings, params float[][] columns)
{
var points = columns[0].Length;
var outputs = new float[points * graph.OutputNames.Count];
ExprEvaluator.Evaluate(graph, bindings, Pack(columns), outputs);
return outputs;
}
private static void AssertSame(float[] expected, float[] actual, int offset, string what)
{
for (var i = 0; i < expected.Length; i++)
Assert.True(Same(expected[i], actual[offset + i]), $"{what} point {i}: expected bits {BitConverter.SingleToInt32Bits(expected[i]):X8}, got {BitConverter.SingleToInt32Bits(actual[offset + i]):X8}");
}
// The reference side is written by hand, beside the table and not from it.
private static readonly Dictionary<string, Func<float[], float[]>> Reference = new()
{
["add"] = a => new[] { a[0] + a[1] },
["sub"] = a => new[] { a[0] - a[1] },
["mul"] = a => new[] { a[0] * a[1] },
["div"] = a => new[] { a[0] / a[1] },
["neg"] = a => new[] { -a[0] },
["min"] = a => new[] { min(a[0], a[1]) },
["max"] = a => new[] { max(a[0], a[1]) },
["abs"] = a => new[] { abs(a[0]) },
["floor"] = a => new[] { floor(a[0]) },
["frac"] = a => new[] { frac(a[0]) },
["sqrt"] = a => new[] { sqrt(a[0]) },
["exp"] = a => new[] { exp(a[0]) },
["log"] = a => new[] { log(a[0]) },
["pow"] = a => new[] { pow(a[0], a[1]) },
["sin"] = a => new[] { sin(a[0]) },
["cos"] = a => new[] { cos(a[0]) },
["clamp"] = a => new[] { clamp(a[0], a[1], a[2]) },
["saturate"] = a => new[] { saturate(a[0]) },
["lerp"] = a => new[] { lerp(a[0], a[1], a[2]) },
["step"] = a => new[] { step(a[0], a[1]) },
["smoothstep"] = a => new[] { smoothstep(a[0], a[1], a[2]) },
["select"] = a => new[] { a[0] > a[1] ? a[2] : a[3] },
["snoise2"] = a => new[] { snoise(new float2(a[0], a[1])) },
["snoise3"] = a => new[] { snoise(new float3(a[0], a[1], a[2])) },
["cellular3"] = a =>
{
var c = cellular(new float3(a[0], a[1], a[2]));
return new[] { c.nearest.x, c.nearest.y, c.nearest.z, c.nearest.w, c.edge.x, c.edge.y, c.edge.z, c.edge.w, c.id };
},
};
[Fact]
public void OpTableIsTheStableVocabulary()
{
var expected = new (string Name, int Arity, int Results)[]
{
("add", 2, 1), ("sub", 2, 1), ("mul", 2, 1), ("div", 2, 1), ("neg", 1, 1), ("min", 2, 1), ("max", 2, 1),
("abs", 1, 1), ("floor", 1, 1), ("frac", 1, 1), ("sqrt", 1, 1), ("exp", 1, 1), ("log", 1, 1), ("pow", 2, 1),
("sin", 1, 1), ("cos", 1, 1), ("clamp", 3, 1), ("saturate", 1, 1), ("lerp", 3, 1), ("step", 2, 1),
("smoothstep", 3, 1), ("select", 4, 1), ("snoise2", 2, 1), ("snoise3", 3, 1), ("cellular3", 3, 9),
};
Assert.Equal(expected, ExprOps.All.Select(op => (op.Name, op.Arity, op.ResultCount)).ToArray());
Assert.Equal(ExprOps.All.Count, Reference.Count);
Assert.Equal(expected.Select(op => op.Name).OrderBy(name => name), Reference.Keys.OrderBy(name => name));
Assert.Null(ExprOps.Find("input"));
Assert.Null(ExprOps.Find("nope"));
Assert.Same(ExprOps.All[3], ExprOps.Find("div"));
}
[Fact]
public void EvaluatorEqualsDirectComposition()
{
var rng = new System.Random(20261014);
foreach (var op in ExprOps.All)
{
var builder = new ExprBuilder();
var inputs = Enumerable.Range(0, op.Arity).Select(i => builder.Input("i" + i)).ToArray();
var call = builder.Call(op.Name, inputs);
if (op.ResultCount == 1) builder.Output("r", call);
else for (var k = 0; k < op.ResultCount; k++) builder.Output("r" + k, builder.Pick(call, k));
var graph = builder.Build();
var columns = Enumerable.Range(0, op.Arity).Select(_ => Column(rng, Points, -8f, 8f, 0.25)).ToArray();
var outputs = Run(graph, ExprBindings.Bind(graph), columns);
for (var k = 0; k < op.ResultCount; k++)
{
var expected = new float[Points];
for (var p = 0; p < Points; p++)
expected[p] = Reference[op.Name](columns.Select(column => column[p]).ToArray())[k];
AssertSame(expected, outputs, k * Points, op.Name + " result " + k);
}
}
}
[Fact]
public void EvaluatorEqualsDirectCompositionOnTheCorpus()
{
var rng = new System.Random(77);
var x = Column(rng, Points, -2f, 3f, 0.2);
var z = Column(rng, Points, -500f, 500f, 0.1);
// smooth: smoothstep(0.2, 0.8, v)
var b = new ExprBuilder();
b.Output("o", b.Call("smoothstep", b.Const(0.2f), b.Const(0.8f), b.Input("v")));
var smooth = b.Build();
AssertSame(x.Select(v => smoothstep(0.2f, 0.8f, v)).ToArray(), Run(smooth, ExprBindings.Bind(smooth), x), 0, "smooth");
// holling: p * (1 + k) / (p + k), k a param
b = new ExprBuilder();
var p = b.Input("p");
var k = b.Param("k", 0.25f);
b.Output("o", b.Call("div", b.Call("mul", p, b.Call("add", b.Const(1f), k)), b.Call("add", p, k)));
var holling = b.Build();
AssertSame(x.Select(v => v * (1f + 0.25f) / (v + 0.25f)).ToArray(), Run(holling, ExprBindings.Bind(holling), x), 0, "holling");
var overrides = new Dictionary<string, float> { ["k"] = 0.4f };
AssertSame(x.Select(v => v * (1f + 0.4f) / (v + 0.4f)).ToArray(), Run(holling, ExprBindings.Bind(holling, overrides), x), 0, "holling k=0.4");
// envelope: b^0.75
b = new ExprBuilder();
b.Output("o", b.Call("pow", b.Input("b"), b.Const(0.75f)));
var envelope = b.Build();
AssertSame(x.Select(v => pow(v, 0.75f)).ToArray(), Run(envelope, ExprBindings.Bind(envelope), x), 0, "envelope");
// an 8-tap ring stencil of snoise2, with the centre, summed in order
var (ring, offsets) = RingStencil(48f);
var expected = new float[Points];
for (var i = 0; i < Points; i++)
{
var sum = snoise(new float2(x[i] * 0.013f, z[i] * 0.017f));
for (var t = 0; t < 8; t++) sum += snoise(new float2((x[i] + offsets[t].x) * 0.013f, (z[i] + offsets[t].y) * 0.017f));
expected[i] = sum / 9f;
}
AssertSame(expected, Run(ring, ExprBindings.Bind(ring), x, z), 0, "ring stencil");
// a cellular3 Pick chain: (edge.w - nearest.w) * id
b = new ExprBuilder();
var cell = b.Call("cellular3", b.Input("x"), b.Input("y"), b.Input("z"));
b.Output("o", b.Call("mul", b.Call("sub", b.Pick(cell, 7), b.Pick(cell, 3)), b.Pick(cell, 8)));
var chain = b.Build();
var y = Column(rng, Points, -6f, 6f, 0.05);
var cx = Column(rng, Points, -6f, 6f, 0.05);
var cz = Column(rng, Points, -6f, 6f, 0.05);
AssertSame(
Enumerable.Range(0, Points).Select(i =>
{
var c = cellular(new float3(cx[i], y[i], cz[i]));
return (c.edge.w - c.nearest.w) * c.id;
}).ToArray(),
Run(chain, ExprBindings.Bind(chain), cx, y, cz), 0, "cellular chain");
}
private static ExprGraph Field()
{
var b = new ExprBuilder();
b.Output("f", b.Call("snoise2", b.Call("mul", b.Input("x"), b.Const(0.013f)), b.Call("mul", b.Input("z"), b.Const(0.017f))));
return b.Build();
}
private static (ExprGraph Graph, (float x, float y)[] Offsets) RingStencil(float radius)
{
var field = Field();
var offsets = Enumerable.Range(0, 8)
.Select(t => (MathF.Cos(2f * MathF.PI * t / 8f) * radius, MathF.Sin(2f * MathF.PI * t / 8f) * radius))
.ToArray();
var b = new ExprBuilder();
var x = b.Input("x");
var z = b.Input("z");
var sum = b.Substitute(field, new Dictionary<string, ExprValue> { ["x"] = x, ["z"] = z })["f"];
foreach (var (ox, oz) in offsets)
{
var tap = b.Substitute(field, new Dictionary<string, ExprValue>
{
["x"] = b.Call("add", x, b.Const(ox)),
["z"] = b.Call("add", z, b.Const(oz)),
})["f"];
sum = b.Call("add", sum, tap);
}
b.Output("o", b.Call("div", sum, b.Const(9f)));
return (b.Build(), offsets);
}
[Fact]
public void SubstituteEqualsOffsetEvaluation()
{
var rng = new System.Random(5);
var x = Column(rng, Points, -500f, 500f, 0.05);
var z = Column(rng, Points, -500f, 500f, 0.05);
var field = Field();
var (stencil, offsets) = RingStencil(48f);
var centre = Run(field, ExprBindings.Bind(field), x, z);
var sum = (float[])centre.Clone();
for (var t = 0; t < 8; t++)
{
var tap = Run(field, ExprBindings.Bind(field), x.Select(v => v + offsets[t].x).ToArray(), z.Select(v => v + offsets[t].y).ToArray());
for (var i = 0; i < Points; i++) sum[i] += tap[i];
}
var expected = sum.Select(s => s / 9f).ToArray();
AssertSame(expected, Run(stencil, ExprBindings.Bind(stencil), x, z), 0, "substituted stencil");
// The wrong input substituted (z only) is a different graph and differs.
var b = new ExprBuilder();
b.Input("x");
var wz = b.Input("z");
var wrong = b.Substitute(field, new Dictionary<string, ExprValue> { ["z"] = b.Call("add", wz, b.Const(offsets[1].y)) })["f"];
b.Output("o", wrong);
var wrongGraph = b.Build();
var wrongOut = Run(wrongGraph, ExprBindings.Bind(wrongGraph), x, z);
var offsetOut = Run(field, ExprBindings.Bind(field), x, z.Select(v => v + offsets[1].y).ToArray());
AssertSame(offsetOut, wrongOut, 0, "z-only substitution equals z-only offset");
var xOffset = Run(field, ExprBindings.Bind(field), x.Select(v => v + offsets[1].x).ToArray(), z.Select(v => v + offsets[1].y).ToArray());
Assert.Contains(Enumerable.Range(0, Points), i => !Same(xOffset[i], wrongOut[i]));
// Substitute declares the graph's ports it does not replace, and refuses a name the graph lacks.
Assert.Equal(new[] { "x", "z" }, wrongGraph.InputNames);
var half = new ExprBuilder();
half.Output("f", half.Substitute(field, new Dictionary<string, ExprValue> { ["z"] = half.Const(1f) })["f"]);
Assert.Equal(new[] { "x" }, half.Build().InputNames);
var c = new ExprBuilder();
var ex = Assert.Throws<ExprGraphException>(() => c.Substitute(field, new Dictionary<string, ExprValue> { [Canary] = c.Const(1f) }));
Assert.Equal("unknown-input", ex.Rule);
Assert.DoesNotContain(Canary, ex.Message);
var d = new ExprBuilder();
var foreign = Assert.Throws<ExprGraphException>(() => d.Substitute(field, new Dictionary<string, ExprValue> { ["x"] = c.Const(1f) }));
Assert.Equal("foreign-operand", foreign.Rule);
var cell = d.Call("cellular3", d.Const(0f), d.Const(0f), d.Const(0f));
Assert.Equal("bare-multi-result", Assert.Throws<ExprGraphException>(() => d.Substitute(field, new Dictionary<string, ExprValue> { ["x"] = cell })).Rule);
// The checks are the call's own: a graph that is only its input still refuses a foreign or multi-result replacement.
var identity = new ExprBuilder();
identity.Output("o", identity.Input("x"));
var passThrough = identity.Build();
var e = new ExprBuilder();
Assert.Equal("foreign-operand", Refusal(() => e.Substitute(passThrough, new Dictionary<string, ExprValue> { ["x"] = c.Const(1f) })).Rule);
Assert.Equal("bare-multi-result", Refusal(() => e.Substitute(passThrough, new Dictionary<string, ExprValue> { ["x"] = e.Call("cellular3", e.Const(0f), e.Const(0f), e.Const(0f)) })).Rule);
Assert.Same(c.Const(1f), c.Substitute(passThrough, new Dictionary<string, ExprValue> { ["x"] = c.Const(1f) })["o"]);
}
[Fact]
public void SubstituteCarriesParamsConstantsAndPicks()
{
// o = p * k + cellular(p, p, k).edge.w - 0.5, with k a param of default 0.25.
var g = new ExprBuilder();
var gp = g.Input("p");
var gk = g.Param("k", 0.25f);
var cell = g.Call("cellular3", gp, gp, gk);
g.Output("o", g.Call("sub", g.Call("add", g.Call("mul", gp, gk), g.Pick(cell, 7)), g.Const(0.5f)));
var graph = g.Build();
var b = new ExprBuilder();
var shifted = b.Call("add", b.Input("x"), b.Const(1.5f));
b.Output("o", b.Substitute(graph, new Dictionary<string, ExprValue> { ["p"] = shifted })["o"]);
var rebuilt = b.Build();
Assert.Equal(new[] { "x" }, rebuilt.InputNames);
Assert.Equal(graph.ParamNames, rebuilt.ParamNames);
Assert.Equal(graph.ParamDefaultBits, rebuilt.ParamDefaultBits);
var x = Column(new System.Random(3), 512, -5f, 5f, 0.1);
foreach (var k in new[] { 0.25f, 0.9f })
{
var expected = x.Select(v =>
{
var p = v + 1.5f;
return p * k + cellular(new float3(p, p, k)).edge.w - 0.5f;
}).ToArray();
var bindings = ExprBindings.Bind(rebuilt, new Dictionary<string, float> { ["k"] = k });
AssertSame(expected, Run(rebuilt, bindings, x), 0, "substituted graph, k=" + k);
}
// A param met again with other default bits is a conflict, not a silent pick.
var c = new ExprBuilder();
c.Param("k", 0.5f);
Assert.Equal("port-conflict", Refusal(() => c.Substitute(graph, new Dictionary<string, ExprValue>())).Rule);
}
private static string Signature(ExprGraph g) =>
string.Join(";", g.InputNames) + "|" + string.Join(";", g.ParamNames.Zip(g.ParamDefaultBits, (n, v) => n + "=" + v)) + "|" +
string.Join(";", g.OutputNames.Zip(g.OutputNodes, (n, v) => n + "=" + v)) + "|" +
string.Join(";", g.Nodes.Select(n => n.WireName + "(" + string.Join(",", n.Operands) + ")" + n.Payload));
private static ExprGraph Sample(bool withDeadNode)
{
var b = new ExprBuilder();
var x = b.Input("x");
var y = b.Input("y");
b.Param("unused", 2f);
var once = b.Call("mul", x, y);
var twice = b.Call("mul", x, y);
if (withDeadNode) b.Call("sin", b.Call("neg", y));
b.Output("o", b.Call("add", once, twice));
return b.Build();
}
[Fact]
public void BuildIsCanonical()
{
var graph = Sample(false);
Assert.Equal(Signature(graph), Signature(Sample(false)));
Assert.Single(graph.Nodes, n => n.WireName == "mul");
Assert.Equal(new[] { "input", "input", "mul", "add" }, graph.Nodes.Select(n => n.WireName));
Assert.Equal(new[] { 2, 2 }, graph.Nodes[3].Operands);
var withDead = Sample(true);
Assert.Equal(Signature(graph), Signature(withDead));
Assert.DoesNotContain(withDead.Nodes, n => n.WireName == "sin" || n.WireName == "neg");
// The ports are the graph's contract: an unused param stays, and constants are told apart by bits.
Assert.Equal(new[] { "unused" }, graph.ParamNames);
var b = new ExprBuilder();
var sameZero = b.Call("add", b.Const(0f), b.Const(0f));
var minusZero = b.Const(-0f);
b.Output("a", sameZero);
b.Output("b", minusZero);
var zeros = b.Build();
Assert.Equal(new[] { 0, int.MinValue }, zeros.Nodes.Where(n => n.Kind == ExprNodeKind.Const).Select(n => n.Payload));
Assert.Equal(3, zeros.Nodes.Count);
}
[Fact]
public void ConstantsKeepTheirBits()
{
var nanBits = 0x7FC12345;
var constants = new[] { -0f, BitConverter.Int32BitsToSingle(nanBits), BitConverter.Int32BitsToSingle(1) };
var b = new ExprBuilder();
for (var i = 0; i < constants.Length; i++) b.Output("c" + i, b.Const(constants[i]));
b.Output("p", b.Param("p", BitConverter.Int32BitsToSingle(nanBits)));
var graph = b.Build();
Assert.Equal(new[] { unchecked((int)0x80000000), nanBits, 1 }, graph.Nodes.Where(n => n.Kind == ExprNodeKind.Const).Select(n => n.Payload));
Assert.Equal(new[] { nanBits }, graph.ParamDefaultBits);
var outputs = new float[graph.OutputNames.Count];
ExprEvaluator.Evaluate(graph, ExprBindings.Bind(graph), ReadOnlySpan<float>.Empty, outputs);
Assert.Equal(new[] { unchecked((int)0x80000000), nanBits, 1, nanBits }, outputs.Select(BitConverter.SingleToInt32Bits));
}
[Fact]
public void BindingsResolveByName()
{
var b = new ExprBuilder();
b.Output("o", b.Call("sub", b.Param("a", 1.5f), b.Param("b", 4f)));
var graph = b.Build();
float Eval(ExprBindings bindings)
{
var o = new float[1];
ExprEvaluator.Evaluate(graph, bindings, ReadOnlySpan<float>.Empty, o);
return o[0];
}
Assert.Equal(1.5f - 4f, Eval(ExprBindings.Bind(graph)));
Assert.Equal(1.5f - 4f, Eval(ExprBindings.Bind(graph, new Dictionary<string, float>())));
Assert.Equal(10f - 4f, Eval(ExprBindings.Bind(graph, new Dictionary<string, float> { ["a"] = 10f })));
Assert.Equal(1.5f - 7f, Eval(ExprBindings.Bind(graph, new Dictionary<string, float> { ["b"] = 7f })));
var ex = Assert.Throws<ExprGraphException>(() => ExprBindings.Bind(graph, new Dictionary<string, float> { [Canary] = 1f }));
Assert.Equal("unknown-param", ex.Rule);
Assert.DoesNotContain(Canary, ex.Message);
var other = new ExprBuilder();
other.Output("o", other.Const(1f));
var foreign = other.Build();
Assert.Equal("foreign-bindings", Assert.Throws<ExprGraphException>(() =>
ExprEvaluator.Evaluate(graph, ExprBindings.Bind(foreign), ReadOnlySpan<float>.Empty, new float[1])).Rule);
}
[Fact]
public void EvaluateRefusesWrongColumnShapes()
{
var b = new ExprBuilder();
b.Output("o", b.Input("x"));
b.Output("p", b.Call("neg", b.Input("x")));
var graph = b.Build();
var bindings = ExprBindings.Bind(graph);
Assert.Equal("column-shape", Assert.Throws<ExprGraphException>(() => ExprEvaluator.Evaluate(graph, bindings, new float[2], new float[5])).Rule);
Assert.Equal("column-shape", Assert.Throws<ExprGraphException>(() => ExprEvaluator.Evaluate(graph, bindings, new float[3], new float[4])).Rule);
var short_ = new float[4];
Assert.Equal("column-shape", Assert.Throws<ExprGraphException>(() => ExprEvaluator.Evaluate(graph, bindings, new float[1], short_)).Rule);
Assert.Equal("column-shape", Assert.Throws<ExprGraphException>(() => ExprEvaluator.Evaluate(graph, bindings, ReadOnlySpan<float>.Empty, short_)).Rule);
Assert.Equal(new float[4], short_);
var outputs = new float[6];
ExprEvaluator.Evaluate(graph, bindings, new[] { 1f, 2f, 3f }, outputs);
var none = new ExprBuilder().Build();
ExprEvaluator.Evaluate(none, ExprBindings.Bind(none), ReadOnlySpan<float>.Empty, Span<float>.Empty);
Assert.Equal(new[] { 1f, 2f, 3f, -1f, -2f, -3f }, outputs);
}
[Fact]
public void AValidatedGraphCannotBeChangedThroughItsLists()
{
var b = new ExprBuilder();
var x = b.Input("x");
var k = b.Param("k", 2f);
b.Output("o", b.Call("mul", x, k));
var graph = b.Build();
var input = new[] { 1f, 2f, 3f };
var before = new float[3];
ExprEvaluator.Evaluate(graph, ExprBindings.Bind(graph), input, before);
var operands = graph.Nodes[2].Operands;
Assert.False(graph.InputNames is string[] || graph.ParamNames is string[] || graph.OutputNames is string[]);
Assert.False(graph.ParamDefaultBits is int[] || graph.OutputNodes is int[] || operands is int[] || graph.Nodes is ExprNode[]);
Assert.Throws<NotSupportedException>(() => ((IList<int>)operands)[0] = 7);
Assert.Throws<NotSupportedException>(() => ((IList<int>)graph.OutputNodes)[0] = 99);
Assert.Throws<NotSupportedException>(() => ((IList<int>)graph.ParamDefaultBits)[0] = 0);
Assert.Throws<NotSupportedException>(() => ((IList<string>)graph.InputNames)[0] = "bad name");
Assert.Throws<NotSupportedException>(() => ((IList<string>)graph.ParamNames)[0] = "bad name");
Assert.Throws<NotSupportedException>(() => ((IList<string>)graph.OutputNames)[0] = "bad name");
Assert.Throws<NotSupportedException>(() => ((IList<ExprNode>)graph.Nodes)[0] = graph.Nodes[1]);
var after = new float[3];
ExprEvaluator.Evaluate(graph, ExprBindings.Bind(graph), input, after);
Assert.Equal(before, after);
Assert.Equal(new[] { 2f, 4f, 6f }, after);
}
[Fact]
public void CreateCopiesWhatItIsGiven()
{
var inputs = new[] { "x" };
var outputs = new[] { "o" };
var outputNodes = new[] { 0 };
var nodes = new[] { ExprNode.Input(0) };
var graph = ExprGraph.Create(ExprGraph.FormatVersion, inputs, Array.Empty<string>(), Array.Empty<int>(), outputs, outputNodes, nodes);
inputs[0] = "bad name";
outputs[0] = "bad name";
outputNodes[0] = 99;
nodes[0] = ExprNode.Const(0);
Assert.Equal(new[] { "x" }, graph.InputNames);
Assert.Equal(new[] { "o" }, graph.OutputNames);
Assert.Equal(new[] { 0 }, graph.OutputNodes);
Assert.Equal(ExprNodeKind.Input, graph.Nodes[0].Kind);
var operands = new[] { 0 };
var call = ExprNode.Call("neg", operands);
operands[0] = 5;
Assert.Equal(new[] { 0 }, call.Operands);
}
private static ExprGraphException Refusal(Action action) => Assert.Throws<ExprGraphException>(action);
[Fact]
public void TheBuilderRefusesAtTheCall()
{
var b = new ExprBuilder();
var x = b.Input("x");
var cell = b.Call("cellular3", x, x, x);
var unknown = Refusal(() => b.Call(Canary + "op", x));
Assert.Equal("unknown-op", unknown.Rule);
Assert.Equal(2, unknown.NodeIndex);
Assert.DoesNotContain(Canary, unknown.Message);
Assert.Equal("arity", Refusal(() => b.Call("add", x)).Rule);
Assert.Equal("arity", Refusal(() => b.Call("neg", x, x)).Rule);
Assert.Equal("pick-range", Refusal(() => b.Pick(x, 0)).Rule);
Assert.Equal("pick-range", Refusal(() => b.Pick(cell, 9)).Rule);
Assert.Equal("pick-range", Refusal(() => b.Pick(cell, -1)).Rule);
Assert.Equal("bare-multi-result", Refusal(() => b.Call("neg", cell)).Rule);
Assert.Equal("bare-multi-result", Refusal(() => b.Output("o", cell)).Rule);
Assert.Equal("foreign-operand", Refusal(() => b.Call("neg", new ExprBuilder().Const(1f))).Rule);
Assert.Equal("port-name", Refusal(() => b.Input(Canary + "-bad")).Rule);
Assert.Equal("port-name", Refusal(() => b.Input("1x")).Rule);
Assert.Equal("port-name", Refusal(() => b.Input("")).Rule);
Assert.Equal("port-name", Refusal(() => b.Param("a b", 1f)).Rule);
Assert.Equal("port-name", Refusal(() => b.Output("a.b", x)).Rule);
Assert.Equal(b.Pick(cell, 8).ResultCount, 1);
Assert.Equal(9, cell.ResultCount);
b.Output("o", x);
Assert.Equal("duplicate-port-name", Refusal(() => b.Output("o", x)).Rule);
Assert.Same(x, b.Input("x"));
b.Param("p", 1f);
Assert.Equal("port-conflict", Refusal(() => b.Param("p", 2f)).Rule);
Assert.Same(b.Param("p", 1f), b.Param("p", 1f));
Assert.NotNull(b.Input("p"));
Assert.Equal(new[] { "x", "p" }, b.Build().InputNames);
}
private static ExprNode[] N(params ExprNode[] nodes) => nodes;
private static ExprGraph Make(
ExprNode[] nodes,
int version = 1,
string[]? inputs = null,
string[]? paramNames = null,
int[]? paramBits = null,
string[]? outputNames = null,
int[]? outputNodes = null) =>
ExprGraph.Create(
version,
inputs ?? new[] { "x" },
paramNames ?? Array.Empty<string>(),
paramBits ?? Array.Empty<int>(),
outputNames ?? new[] { "o" },
outputNodes ?? new[] { 0 },
nodes);
[Fact]
public void ValidatorRefusesEachRuleByName()
{
void Rule(string rule, Action act, int node = -1)
{
var ex = Assert.Throws<ExprGraphException>(act);
Assert.Equal(rule, ex.Rule);
Assert.Equal(node, ex.NodeIndex);
}
var x = ExprNode.Input(0);
Assert.Equal(1, Make(nodes: N(x)).Nodes.Count);
Rule("version", () => Make(version: 2, nodes: N(x)));
Rule("version", () => Make(version: 0, nodes: N(x)));
Rule("port-count", () => Make(paramNames: new[] { "a" }, nodes: N(x)));
Rule("port-count", () => Make(outputNames: new[] { "a", "b" }, nodes: N(x)));
Rule("port-name", () => Make(inputs: new[] { "9" }, nodes: N(x)));
Rule("duplicate-port-name", () => Make(inputs: new[] { "x", "x" }, nodes: N(x)));
Rule("duplicate-port-name", () => Make(paramNames: new[] { "a", "a" }, paramBits: new[] { 0, 0 }, nodes: N(x)));
Rule("duplicate-port-name", () => Make(outputNames: new[] { "a", "a" }, outputNodes: new[] { 0, 0 }, nodes: N(x)));
Assert.Equal(1, Make(inputs: new[] { "x" }, paramNames: new[] { "x" }, paramBits: new[] { 0 }, nodes: N(x)).Nodes.Count);
Rule("port-index", () => Make(nodes: N(ExprNode.Input(1))), 0);
Rule("port-index", () => Make(nodes: N(ExprNode.Input(-1))), 0);
Rule("port-index", () => Make(nodes: N(x, ExprNode.Param(0))), 1);
Rule("arity", () => Make(nodes: N(ExprNode.FromWire("input", new[] { 0 }, 0))), 0);
Rule("arity", () => Make(nodes: N(ExprNode.FromWire("const", new[] { 0 }, 0))), 0);
Rule("arity", () => Make(nodes: N(x, ExprNode.FromWire("pick", new int[0], 0))), 1);
Rule("payload", () => Make(nodes: N(x, ExprNode.FromWire("neg", new[] { 0 }, 7))), 1);
Rule("output-node", () => Make(outputNodes: new[] { 1 }, nodes: N(x)));
Rule("output-node", () => Make(outputNodes: new[] { -1 }, nodes: N(x)));
Rule("bare-multi-result", () => Make(outputNodes: new[] { 1 }, nodes: N(x, ExprNode.Call("cellular3", new[] { 0, 0, 0 }))), 1);
Rule("pick-range", () => Make(outputNodes: new[] { 1 }, nodes: N(x, ExprNode.Pick(0, 0))), 1);
Rule("operand-order", () => Make(nodes: N(x, ExprNode.Pick(5, 0))), 1);
Rule("operand-order", () => Make(nodes: N(x, ExprNode.Call("neg", new[] { -1 }))), 1);
Rule("operand-order", () => Make(nodes: N(x, ExprNode.Call("neg", new[] { 1 }))), 1);
}
[Fact]
public void PortNamesAcceptTheirWholeAlphabetAndNothingBeside()
{
foreach (var name in new[] { "a", "z", "A", "Z", "_", "_9", "a0", "Z9", "x_Y_z_0" })
Assert.Equal(new[] { name }, Make(nodes: N(ExprNode.Input(0)), inputs: new[] { name }).InputNames);
foreach (var name in new[] { "", "9", "@", "[", "`", "{", "/", ":", "a b", "a-b", "é" })
Assert.Equal("port-name", Refusal(() => Make(nodes: N(ExprNode.Input(0)), inputs: new[] { name })).Rule);
foreach (var name in new[] { "a@", "a[", "a`", "a{", "a/", "a:" })
Assert.Equal("port-name", Refusal(() => Make(nodes: N(ExprNode.Input(0)), inputs: new[] { name })).Rule);
}
[Fact]
public void RefusalsNameTheirRuleAndNodeAndNothingElse()
{
var b = new ExprBuilder();
var x = b.Input("x");
Assert.Equal("unknown-op at node 1", Refusal(() => b.Call("nope", x)).Message);
Assert.Equal("port-name", Refusal(() => b.Input("1")).Message);
Assert.Equal("version", Refusal(() => Make(nodes: N(ExprNode.Input(0)), version: 3)).Message);
Assert.Equal(-1, Refusal(() => b.Input("1")).NodeIndex);
Assert.Equal(1, Refusal(() => b.Call("nope", x)).NodeIndex);
Assert.Equal(0, new ExprGraphException("r", 0).NodeIndex);
Assert.Equal("r at node 0", new ExprGraphException("r", 0).Message);
}
[Fact]
public void FromWireNamesTheFourLeafKindsAndCalls()
{
foreach (var kind in new[] { "input", "param", "const", "pick" })
Assert.Equal(kind, ExprNode.FromWire(kind, Array.Empty<int>(), 0).WireName);
Assert.Equal(ExprNodeKind.Call, ExprNode.FromWire("add", new[] { 0, 0 }, 0).Kind);
Assert.Equal(ExprNodeKind.Call, ExprNode.FromWire("nope", Array.Empty<int>(), 0).Kind);
Assert.Equal(new[] { ExprNodeKind.Input, ExprNodeKind.Param, ExprNodeKind.Const, ExprNodeKind.Pick },
new[] { "input", "param", "const", "pick" }.Select(name => ExprNode.FromWire(name, Array.Empty<int>(), 0).Kind));
}
}

View file

@ -21,6 +21,8 @@ internal static class GlslLowering
{
// Phacelle is a port of MPL-2.0 code, and MPL-2.0 covers the files that carry it.
["CultMath.Phacelle.hlsl"] = ("CultMath.Phacelle.glsl", "MPL-2.0"),
// The Cycles node semantics are a port of Apache-2.0 code, and the licence travels with the file.
["CultMath.Cycles.hlsl"] = ("CultMath.Cycles.glsl", "Apache-2.0"),
};
private const string Regenerate =
@ -72,7 +74,9 @@ internal static class GlslLowering
source = Regex.Replace(source, @"(?m)^[ \t]*#(ifndef|define|endif)\b.*$", string.Empty);
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.
// 3. Type names: floatN, intN, uintN and boolN become vecN, ivecN, uvecN and bvecN, and float3x3
// becomes mat3 (the one matrix type the library returns: a float3x3 is built from nine scalars,
// which HLSL reads as rows and GLSL as columns, so only symmetric matrices are exported).
source = LowerTypeNames(source);
// 4. File-scope `static const` becomes `const`.
@ -84,13 +88,15 @@ internal static class GlslLowering
source = LowerCasts(source);
// 6. Intrinsic renames: lerp -> mix, frac -> fract, rsqrt -> inversesqrt, asuint ->
// floatBitsToUint, asfloat -> uintBitsToFloat, and saturate(x) -> clamp(x, 0.0, 1.0).
// floatBitsToUint, asfloat -> uintBitsToFloat, atan2 -> atan (GLSL's two-argument arctangent),
// and saturate(x) -> clamp(x, 0.0, 1.0).
// Identifier boundaries keep cultmath_lerp and the rest of the cultmath_ names intact.
source = Regex.Replace(source, @"\blerp\(", "mix(");
source = Regex.Replace(source, @"\bfrac\(", "fract(");
source = Regex.Replace(source, @"\brsqrt\(", "inversesqrt(");
source = Regex.Replace(source, @"\basuint\(", "floatBitsToUint(");
source = Regex.Replace(source, @"\basfloat\(", "uintBitsToFloat(");
source = Regex.Replace(source, @"\batan2\(", "atan(");
source = LowerSaturate(source);
// 7. Float literals pass through: HLSL's unsuffixed 0.5 and 1.0e30 are GLSL literals already.
@ -106,7 +112,8 @@ internal static class GlslLowering
source = Regex.Replace(source, @"\bfloat([234])\b", "vec$1");
source = Regex.Replace(source, @"\bint([234])\b", "ivec$1");
source = Regex.Replace(source, @"\buint([234])\b", "uvec$1");
return Regex.Replace(source, @"\bbool([234])\b", "bvec$1");
source = Regex.Replace(source, @"\bbool([234])\b", "bvec$1");
return Regex.Replace(source, @"\bfloat3x3\b", "mat3");
}
private static readonly Regex Cast = new(@"\((float|int|uint)\)");

View file

@ -47,7 +47,7 @@ public sealed class GlslMirrorTests
// Identifier boundaries: cultmath_lerp is a CultMath function, lerp( is HLSL.
private static readonly Regex HlslOnly = new(
@"\b(float|u?int|bool)[234]\b|\blerp\(|\bfrac\(|\bsaturate\(|\brsqrt\(|\basuint\(|\basfloat\(|static const|\((float|int|uint)\)|Texture2D|SamplerState|#include|precision (high|medium|low)p");
@"\b(float|u?int|bool)[234]\b|\bfloat3x3\b|\blerp\(|\bfrac\(|\bsaturate\(|\brsqrt\(|\basuint\(|\basfloat\(|\batan2\(|static const|\((float|int|uint)\)|Texture2D|SamplerState|#include|precision (high|medium|low)p");
[Fact]
public void NoHlslOnlyTokensSurvive()
@ -86,6 +86,12 @@ public sealed class GlslMirrorTests
Assert.DoesNotContain(token, library);
Assert.Contains(token, phacelle);
}
// The Apache-2.0 code is in its own file too, and the MPL-2.0 file holds none of it.
var cycles = lowered.Single(output => output.File == "CultMath.Cycles.glsl").Text;
Assert.DoesNotContain("cultmath_cycles_divide(", library);
Assert.DoesNotContain("cultmath_cycles_divide(", phacelle);
Assert.Contains("float cultmath_cycles_divide(", cycles);
}
// The two-file contract a consumer relies on when it concatenates CultMath.Phacelle.glsl after
@ -106,6 +112,12 @@ public sealed class GlslMirrorTests
Assert.Contains("cultmath_phacelle is in CultMath.Phacelle.glsl", library);
Assert.Contains(" MPL-2.0;", phacelle);
Assert.DoesNotContain("MIT", phacelle);
var cycles = lowered.Single(output => output.File == "CultMath.Cycles.glsl").Text.Split('\n')[0];
Assert.Contains("cultmath_cycles_ramp_index is in CultMath.Cycles.glsl", library);
Assert.Contains(" Apache-2.0;", cycles);
Assert.DoesNotContain("MIT", cycles);
Assert.DoesNotContain("MPL", cycles);
}
[Fact]
@ -503,6 +515,12 @@ public sealed class GlslMirrorTests
"Tightness: R0 + d <= GPU radius <= R0 + d + 2^-19 (R0 + |c0|_1 + spread). " +
"Report the least slack of each side; only the bounds fail the check.";
// The Cycles node families' operands: values past [0, 1] on both sides, so the clamps, the extrapolating
// factors and the divisions by a small number all show.
private static float CyclesValue(System.Random r) => Uniform(r, -20.0f, 20.0f);
private static float CyclesFactor(System.Random r) => Uniform(r, -0.5f, 1.5f);
private static float3 CyclesColor(System.Random r) => new(Uniform(r, -0.25f, 1.25f), Uniform(r, -0.25f, 1.25f), Uniform(r, -0.25f, 1.25f));
// A Phacelle stripe wave vector: each component in [-6, 6], about one stripe per cell.
private static float3 Side(System.Random r) => new(Uniform(r, -6.0f, 6.0f), Uniform(r, -6.0f, 6.0f), Uniform(r, -6.0f, 6.0f));
@ -511,7 +529,7 @@ public sealed class GlslMirrorTests
// float families are ulp-bounded, with the bound measured on the device by the consumer, and
// iv_frustum_ball also carries an enclosure check. phacelle is in CultMath.Phacelle.glsl, so its
// evaluator concatenates that file after CultMath.glsl; the site, which does not vendor it, skips it.
private static readonly Family[] Families =
private static readonly Family[] Families = new Family[]
{
new("float cultmath_snoise(vec3)", "ulp-bounded", r => new object[] { Point3(r) }),
new("float cultmath_snoise(vec2)", "ulp-bounded", r => new object[] { new float2(Uniform(r, -50.0f, 50.0f), Uniform(r, -50.0f, 50.0f)) }),
@ -575,7 +593,52 @@ public sealed class GlslMirrorTests
new("vec2 cultmath_iv_snoise_ball(vec2, float)", "ulp-bounded", r => new object[] { new float2(Uniform(r, -50.0f, 50.0f), Uniform(r, -50.0f, 50.0f)), Uniform(r, 0.001f, 2.0f) }),
new("vec3 cultmath_af_snoise(vec3, vec3, float)", "ulp-bounded, reach 1e-6 to 1e-3", SmallReachSlice, SnoiseSmallForm, Verify: cases => AssertSnoiseForm(cases, allowanceDecides: true)),
new("vec3 cultmath_af_fbm(vec3, vec3, float, int, float, float)", "ulp-bounded, reach 1e-6 to 1e-3", r => SmallReachSlice(r).Concat(new object[] { 4, 2.0f, 0.5f }).ToArray(), FbmSmallForm, Verify: cases => AssertFbmForm(cases, allowanceDecides: true)),
};
new("float cultmath_cycles_divide(float, float)", "ulp-bounded", r => new object[] { CyclesValue(r), CyclesValue(r) }),
new("float cultmath_cycles_power(float, float)", "ulp-bounded, platform pow", r => new object[] { Uniform(r, -4.0f, 4.0f), r.Next(2) == 0 ? r.Next(-4, 5) : Uniform(r, -3.0f, 3.0f) }, Platform: Platform.Ulp),
new("float cultmath_cycles_logarithm(float, float)", "ulp-bounded, platform log", r => new object[] { Uniform(r, 0.01f, 20.0f), Uniform(r, 0.01f, 20.0f) }, Platform: Platform.Ulp),
new("float cultmath_cycles_sqrt(float)", "ulp-bounded", r => new object[] { CyclesValue(r) }),
new("float cultmath_cycles_inverse_sqrt(float)", "ulp-bounded", r => new object[] { CyclesValue(r) }),
new("float cultmath_cycles_modulo(float, float)", "ulp-bounded", r => new object[] { CyclesValue(r), CyclesValue(r) }),
new("float cultmath_cycles_floored_modulo(float, float)", "ulp-bounded", r => new object[] { CyclesValue(r), CyclesValue(r) }),
new("float cultmath_cycles_wrap(float, float, float)", "ulp-bounded", r => new object[] { CyclesValue(r), Uniform(r, -10.0f, 10.0f), Uniform(r, -10.0f, 10.0f) }),
new("float cultmath_cycles_snap(float, float)", "ulp-bounded", r => new object[] { CyclesValue(r), CyclesValue(r) }),
new("float cultmath_cycles_pingpong(float, float)", "ulp-bounded", r => new object[] { CyclesValue(r), CyclesValue(r) }),
new("float cultmath_cycles_smooth_min(float, float, float)", "ulp-bounded", r => new object[] { CyclesValue(r), CyclesValue(r), Uniform(r, -5.0f, 5.0f) }),
new("float cultmath_cycles_smooth_max(float, float, float)", "ulp-bounded", r => new object[] { CyclesValue(r), CyclesValue(r), Uniform(r, -5.0f, 5.0f) }),
new("float cultmath_cycles_compare(float, float, float)", "ulp-bounded", r => { var a = CyclesValue(r); return new object[] { a, a + Uniform(r, -1.0f, 1.0f) * 1.0e-3f, Uniform(r, 0.0f, 2.0e-3f) }; }),
new("float cultmath_cycles_round(float)", "ulp-bounded", r => new object[] { CyclesValue(r) }),
new("float cultmath_cycles_trunc(float)", "ulp-bounded", r => new object[] { CyclesValue(r) }),
new("float cultmath_cycles_fract(float)", "ulp-bounded", r => new object[] { CyclesValue(r) }),
new("float cultmath_cycles_sign(float)", "ulp-bounded", r => new object[] { r.Next(4) == 0 ? 0.0f : CyclesValue(r) }),
new("float cultmath_cycles_map_range_linear(float, float, float, float, float)", "ulp-bounded", r => new object[] { CyclesValue(r), CyclesValue(r), CyclesValue(r), CyclesValue(r), CyclesValue(r) }),
new("float cultmath_cycles_map_range_stepped(float, float, float, float, float, float)", "ulp-bounded", r => new object[] { CyclesValue(r), CyclesValue(r), CyclesValue(r), CyclesValue(r), CyclesValue(r), Uniform(r, -1.0f, 8.0f) }),
new("float cultmath_cycles_map_range_smoothstep(float, float, float, float, float)", "ulp-bounded", r => new object[] { CyclesValue(r), CyclesValue(r), CyclesValue(r), CyclesValue(r), CyclesValue(r) }),
new("float cultmath_cycles_map_range_smootherstep(float, float, float, float, float)", "ulp-bounded", r => new object[] { CyclesValue(r), CyclesValue(r), CyclesValue(r), CyclesValue(r), CyclesValue(r) }),
new("float cultmath_cycles_clamp_minmax(float, float, float)", "ulp-bounded", r => new object[] { CyclesValue(r), CyclesValue(r), CyclesValue(r) }),
new("float cultmath_cycles_clamp_range(float, float, float)", "ulp-bounded", r => new object[] { CyclesValue(r), CyclesValue(r), CyclesValue(r) }),
new("float cultmath_cycles_mix_float(float, float, float)", "ulp-bounded", r => new object[] { CyclesFactor(r), CyclesValue(r), CyclesValue(r) }),
new("vec3 cultmath_cycles_mix_vector(float, vec3, vec3)", "ulp-bounded", r => new object[] { CyclesFactor(r), CyclesColor(r), CyclesColor(r) }),
new("vec3 cultmath_cycles_rgb_to_hsv(vec3)", "ulp-bounded", r => new object[] { CyclesColor(r) }),
new("vec3 cultmath_cycles_hsv_to_rgb(vec3)", "ulp-bounded", r => new object[] { new float3(r.NextSingle(), r.NextSingle(), Uniform(r, 0.0f, 2.0f)) }),
new("float cultmath_cycles_rgb_to_bw(vec3)", "ulp-bounded", r => new object[] { CyclesColor(r) }),
new("vec2 cultmath_cycles_ramp_index(float, int)", "ulp-bounded", r => new object[] { Uniform(r, -0.25f, 1.25f), 257 }),
}.Concat(new[]
{
"blend", "add", "mul", "screen", "overlay", "sub", "div", "diff", "exclusion", "dark", "light", "dodge", "burn", "hue", "sat", "val", "color", "soft", "linear",
}.Select(mode => new Family($"vec3 cultmath_cycles_mix_{mode}(float, vec3, vec3)", "ulp-bounded", r => new object[] { CyclesFactor(r), CyclesColor(r), CyclesColor(r) }))).Concat(new[]
{
new Family("float cultmath_cycles_arcsine(float)", "ulp-bounded, platform asin", r => new object[] { Uniform(r, -1.5f, 1.5f) }, Platform: Platform.Ulp),
new Family("float cultmath_cycles_arccosine(float)", "ulp-bounded, platform acos", r => new object[] { Uniform(r, -1.5f, 1.5f) }, Platform: Platform.Ulp),
new Family("float cultmath_cycles_arctan2(float, float)", "ulp-bounded, platform atan", r => new object[] { Uniform(r, -20.0f, 20.0f), Uniform(r, -20.0f, 20.0f) }, Platform: Platform.Ulp),
new Family("mat3 cultmath_snoise_hessian(vec3)", "ulp-bounded", r => new object[] { Point3(r) }),
new Family("mat3 cultmath_snoise_hessian(vec3)", "ulp-bounded, on the simplex tie set", r => new object[] { TiePoint3(r) }),
new Family("float cultmath_integral_clamp_linear(float, float, float, float, float, float)", "ulp-bounded",
r =>
{
var lo = Uniform(r, -2.0f, 0.5f);
return new object[] { Uniform(r, -4.0f, 4.0f), r.Next(8) == 0 ? 0.0f : Uniform(r, -4.0f, 4.0f), lo, lo + Uniform(r, 0.0f, 3.0f), Uniform(r, -3.0f, 3.0f), Uniform(r, -3.0f, 3.0f) };
}),
}).ToArray();
// The fixture text, each case's arguments given by family and point index.
private static string GoldenFixture(Func<int, int, object[]> arguments)
@ -638,8 +701,12 @@ public sealed class GlslMirrorTests
_ => throw new InvalidOperationException(v.GetType().Name),
}));
// A float3x3 flattens row by row; the matrices the library exports are symmetric, so the order is
// 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 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)!));
// ---- A small unified diff for the failure message ----

View file

@ -67,6 +67,7 @@ public sealed class HlslMirrorTests
[InlineData("CultMath.Phacelle.hlsl")]
[InlineData("CultMath.Interval.hlsl")]
[InlineData("CultMath.Affine.hlsl")]
[InlineData("CultMath.Cycles.hlsl")]
public void UnityPackageShaderIsIdenticalToTheCanonicalShader(string name)
{
var root = GetCultMathRoot();

View file

@ -28,6 +28,8 @@ public sealed class HlslSourceCompatibilityTests
Assert.NotNull(ShaderFunction(shader, "cultmath_smin_grad", typeof(float4), typeof(float4), typeof(float)));
Assert.NotNull(ShaderFunction(shader, "cultmath_cellular", typeof(float3)));
Assert.NotNull(ShaderFunction(shader, "cultmath_snoise_grad", typeof(float3)));
Assert.NotNull(ShaderFunction(shader, "cultmath_snoise_hessian", typeof(float3)));
Assert.NotNull(ShaderFunction(shader, "cultmath_integral_clamp_linear", typeof(float), typeof(float), typeof(float), typeof(float), typeof(float), typeof(float)));
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)));
@ -137,7 +139,7 @@ public sealed class HlslSourceCompatibilityTests
}
Assert.True(mismatches.Count == 0, $"{mismatches.Count} mismatches:{Environment.NewLine}{string.Join(Environment.NewLine, mismatches.Take(12))}");
Assert.Equal(67, compared.Count);
Assert.Equal(120, compared.Count);
}
/// <summary>
@ -377,6 +379,9 @@ public sealed class HlslSourceCompatibilityTests
/// </summary>
private static Leaf[] Values(object value, string path = "") => Scalars.Contains(value.GetType())
? new[] { new Leaf(path, value.GetType(), value) }
: value is float3x3 matrix
? new[] { matrix._m00, matrix._m01, matrix._m02, matrix._m10, matrix._m11, matrix._m12, matrix._m20, matrix._m21, matrix._m22 }
.Select((entry, k) => new Leaf((path.Length == 0 ? "" : path + ".") + "_m" + k / 3 + k % 3, typeof(float), entry)).ToArray()
: value.GetType().GetFields().Where(f => !f.IsStatic)
.SelectMany(f => Values(f.GetValue(value)!, path.Length == 0 ? f.Name : path + "." + f.Name))
.ToArray();
@ -433,7 +438,7 @@ public sealed class HlslSourceCompatibilityTests
return "using CultMath;\nusing static CultMath.math;\nnamespace CultMathHlsl;\npublic class HlslShader\n{\n" + source + "\n}\n";
}
private static (Assembly? Assembly, IReadOnlyList<string> Errors) CompileShaderMirror()
internal static (Assembly? Assembly, IReadOnlyList<string> Errors) CompileShaderMirror()
{
var hlsl = ReadShaderSource(FindCultMathRoot());
var tree = CSharpSyntaxTree.ParseText(TransformHlslToCSharp(hlsl));

View file

@ -489,25 +489,13 @@ public sealed class NoiseBoundTests
// the quotient is not skewed by the rounding of p + h far from the origin.
private static double Step(float x, float h, out double back) { back = x - (double)(x - h); return (x + h) - (double)x; }
// The spectral norm (largest absolute eigenvalue) of the symmetrised Hessian of snoise(float3) at p,
// from central differences of snoise_grad at h = 1e-3.
// The spectral norm (largest absolute eigenvalue) of snoise's Hessian at p: the library's own
// snoise_hessian, symmetric bit for bit, then the closed-form eigenvalues of a symmetric 3x3.
private static double HessianNorm(float3 p)
{
const float h = 1.0e-3f;
var m = new double[3, 3];
for (var a = 0; a < 3; a++)
{
var e = new float3(a == 0 ? h : 0.0f, a == 1 ? h : 0.0f, a == 2 ? h : 0.0f);
var forward = Step(a == 0 ? p.x : a == 1 ? p.y : p.z, h, out var back);
var gp = snoise_grad(p + e);
var gm = snoise_grad(p - e);
m[0, a] = (gp.x - (double)gm.x) / (forward + back);
m[1, a] = (gp.y - (double)gm.y) / (forward + back);
m[2, a] = (gp.z - (double)gm.z) / (forward + back);
}
var (a00, a11, a22) = (m[0, 0], m[1, 1], m[2, 2]);
var (a01, a02, a12) = ((m[0, 1] + m[1, 0]) / 2, (m[0, 2] + m[2, 0]) / 2, (m[1, 2] + m[2, 1]) / 2);
var m = snoise_hessian(p);
var (a00, a11, a22) = ((double)m._m00, (double)m._m11, (double)m._m22);
var (a01, a02, a12) = ((double)m._m01, (double)m._m02, (double)m._m12);
var p1 = a01 * a01 + a02 * a02 + a12 * a12;
if (p1 == 0.0)
return Math.Max(Math.Abs(a00), Math.Max(Math.Abs(a11), Math.Abs(a22)));
@ -617,7 +605,7 @@ public sealed class NoiseBoundTests
}
// The start MeasureHessian printed as its witness.
private static readonly float3 HessianWitness = new(-245.19885f, -53.01323f, -91.47363f);
private static readonly float3 HessianWitness = new(-13.7920685f, -9.672134f, 61.563934f);
/// <summary>
/// Pins SNOISE_HESSIAN: no Hessian norm over 1e5 seeded points exceeds it, and the ascent from
@ -635,6 +623,181 @@ public sealed class NoiseBoundTests
Assert.True(Math.Abs(ratio - 1.0) <= 0.005, $"SNOISE_HESSIAN is {ratio:R} times 1.10 x the re-measured {refined:R}; re-run MeasureHessian and re-pin");
}
// ---- The third-derivative constant (math.Span.cs) ----
// The symmetric third-derivative tensor of snoise at p, entry (i * 3 + j) * 3 + k: central differences
// of snoise_hessian along each axis at h = 1e-3 over the exact float32 steps, symmetrised over the six
// index orders (the Hessian is symmetric, so only the derivative index can differ).
private static double[] ThirdTensor(float3 p)
{
const float h = 1.0e-3f;
var d = new double[27];
for (var k = 0; k < 3; k++)
{
var e = new float3(k == 0 ? h : 0.0f, k == 1 ? h : 0.0f, k == 2 ? h : 0.0f);
var forward = Step(k == 0 ? p.x : k == 1 ? p.y : p.z, h, out var back);
var plus = snoise_hessian(p + e);
var minus = snoise_hessian(p - e);
for (var i = 0; i < 3; i++)
for (var j = 0; j < 3; j++)
d[(i * 3 + j) * 3 + k] = (plus[i][j] - (double)minus[i][j]) / (forward + back);
}
var t = new double[27];
for (var i = 0; i < 3; i++)
for (var j = 0; j < 3; j++)
for (var k = 0; k < 3; k++)
t[(i * 3 + j) * 3 + k] = (d[(i * 3 + j) * 3 + k] + d[(i * 3 + k) * 3 + j] + d[(j * 3 + i) * 3 + k]
+ d[(j * 3 + k) * 3 + i] + d[(k * 3 + i) * 3 + j] + d[(k * 3 + j) * 3 + i]) / 6.0;
return t;
}
// T(u, u, u) for a symmetric 3-tensor.
private static double Cubic(double[] t, double[] u)
{
var sum = 0.0;
for (var i = 0; i < 3; i++)
for (var j = 0; j < 3; j++)
for (var k = 0; k < 3; k++)
sum += t[(i * 3 + j) * 3 + k] * u[i] * u[j] * u[k];
return sum;
}
// The 26 unit directions of the axes, the edge midpoints and the cube corners.
private static readonly double[][] TensorStarts = Enumerable.Range(0, 27).Select(c => new[] { c % 3 - 1.0, c / 3 % 3 - 1.0, c / 9 - 1.0 })
.Where(v => v[0] != 0.0 || v[1] != 0.0 || v[2] != 0.0)
.Select(v => { var length = Math.Sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); return new[] { v[0] / length, v[1] / length, v[2] / length }; }).ToArray();
// The operator norm of a symmetric 3-tensor, max over unit u of |T(u, u, u)| (for a symmetric tensor
// that is the injective norm). From the six of 26 starts (axes, edge midpoints, cube corners) with
// the largest |T(u, u, u)|, the shifted power ascent u <- normalise(T(u, u, .) +- alpha u), with alpha
// twice the largest absolute row sum, which makes the iteration monotone in the cubic form (Kolda and
// Mayo's SS-HOPM), the sign chosen as the start's. A local maximum, so a lower bound; MeasureThird
// checks it against a dense direction sweep at its witness.
private static double TensorNorm(double[] t)
{
var alpha = 0.0;
for (var i = 0; i < 3; i++)
{
var row = 0.0;
for (var jk = 0; jk < 9; jk++)
row += Math.Abs(t[i * 9 + jk]);
alpha = Math.Max(alpha, 2.0 * row);
}
var best = 0.0;
var g = new double[3];
foreach (var start in TensorStarts.OrderByDescending(v => Math.Abs(Cubic(t, v))).Take(6))
{
var u = (double[])start.Clone();
var sign = Cubic(t, u) < 0.0 ? -1.0 : 1.0;
for (var iteration = 0; iteration < 40; iteration++)
{
for (var i = 0; i < 3; i++)
{
var sum = 0.0;
for (var j = 0; j < 3; j++)
for (var k = 0; k < 3; k++)
sum += t[(i * 3 + j) * 3 + k] * u[j] * u[k];
g[i] = sign * sum + alpha * u[i];
}
var length = Math.Sqrt(g[0] * g[0] + g[1] * g[1] + g[2] * g[2]);
if (length == 0.0)
break;
var moved = 0.0;
for (var i = 0; i < 3; i++)
{
var next = g[i] / length;
moved += (next - u[i]) * (next - u[i]);
u[i] = next;
}
if (moved < 1.0e-20)
break;
}
best = Math.Max(best, Math.Abs(Cubic(t, u)));
}
return best;
}
// The operator norm of snoise's third-derivative tensor at p.
private static double ThirdNorm(float3 p) => TensorNorm(ThirdTensor(p));
[Fact]
public void TensorNormFindsKnownMaxima()
{
// T = e_x (x) e_x (x) e_x: the cubic form is u_x^3, norm 1.
var single = new double[27];
single[0] = 1.0;
Assert.InRange(TensorNorm(single), 1.0 - 1.0e-9, 1.0 + 1.0e-9);
// The six permutations of (0, 1, 2) at 1: the cubic form is 6 u_x u_y u_z, largest on the cube
// diagonal at 6 / (3 sqrt 3) = 2 / sqrt 3.
var permutations = new double[27];
foreach (var (i, j, k) in new[] { (0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0) })
permutations[(i * 3 + j) * 3 + k] = 1.0;
Assert.InRange(TensorNorm(permutations), 2.0 / Math.Sqrt(3.0) - 1.0e-9, 2.0 / Math.Sqrt(3.0) + 1.0e-9);
// A negative extremum counts by its absolute value.
var negative = new double[27];
negative[13] = -3.0;
Assert.InRange(TensorNorm(negative), 3.0 - 1.0e-9, 3.0 + 1.0e-9);
}
/// <summary>
/// The provenance of SNOISE_THIRD: the largest operator norm of snoise's third-derivative tensor
/// (ThirdNorm) over 1e6 seeded points of [-256, 256]^3, the 1e4 largest refined by ascent over the point,
/// times 1.10, on the tied kernel. Prints the start whose ascent reached the maximum, which
/// ThirdConstantPinsSampled climbs from again, and a sweep of 20,000 directions at the point the
/// ascent ends on (the tensor norm there against the largest cubic form the sweep finds, so the
/// tightness of the inner maximisation is on the record). Slow; run explicitly after any change to the
/// snoise kernel and re-pin the constant and the witness.
/// </summary>
[Fact(Explicit = true)]
[Trait("Category", "Slow")]
public void MeasureThird()
{
var (sampled, refined, witness) = MeasureMax(ThirdNorm, false, 0x4E57, 1_000_000, 10_000);
output.WriteLine($"IV-REPORT third: max |D3| sampled {sampled:R}, refined {refined:R}, x 1.10 = {(float)(refined * 1.10):R}, witness ({witness.x:R}, {witness.y:R}, {witness.z:R})");
var (best, at) = AscendPoint(ThirdNorm, witness);
var tensor = ThirdTensor(at);
var sweep = 0.0;
const int directions = 20_000;
for (var k = 0; k < directions; k++)
{
var z = 1.0 - 2.0 * (k + 0.5) / directions;
var r = Math.Sqrt(1.0 - z * z);
var phi = k * Math.PI * (3.0 - Math.Sqrt(5.0));
sweep = Math.Max(sweep, Math.Abs(Cubic(tensor, new[] { r * Math.Cos(phi), r * Math.Sin(phi), z })));
}
output.WriteLine($"IV-REPORT third witness ascent ends at ({at.x:R}, {at.y:R}, {at.z:R}): tensor norm {best:R}, dense sweep of {directions} directions {sweep:R} ({sweep / best:R} of it)");
Assert.True(sweep <= best * (1.0 + 1.0e-6), $"a direction sweep finds {sweep:R} over the ascent's {best:R}: the inner maximisation misses a maximum");
Assert.True(refined <= SNOISE_THIRD, $"measured {refined:R} exceeds SNOISE_THIRD {SNOISE_THIRD:R}");
}
// The start MeasureThird printed as its witness.
private static readonly float3 ThirdWitness = new(-168.3755f, -3.8205261f, -109.16948f);
/// <summary>
/// Pins SNOISE_THIRD: no third-derivative norm over 1e5 seeded points exceeds it, and the ascent from
/// MeasureThird's witness reaches a maximum that, times 1.10, is the constant to within half a
/// percent, so a constant moved by 1% fails here.
/// </summary>
[Fact]
public void ThirdConstantPinsSampled()
{
var (sampled, _, _) = MeasureMax(ThirdNorm, false, 0x4E58, 100_000, 0);
Assert.True(sampled <= SNOISE_THIRD, $"the third-derivative norm reaches {sampled:R}, above SNOISE_THIRD {SNOISE_THIRD:R}");
var refined = Ascend(ThirdNorm, ThirdWitness);
Assert.True(refined <= SNOISE_THIRD, $"the third-derivative norm reaches {refined:R}, above SNOISE_THIRD {SNOISE_THIRD:R}");
var ratio = SNOISE_THIRD / (1.10 * refined);
Assert.True(Math.Abs(ratio - 1.0) <= 0.005, $"SNOISE_THIRD is {ratio:R} times 1.10 x the re-measured {refined:R}; re-run MeasureThird and re-pin");
}
/// <summary>
/// SNOISE_HESSIAN where the curvature is realised. At the point the ascent from MeasureHessian's witness
/// reaches, the absolute second difference of snoise along 4,000 seeded directions u at step 0.05 has a

View file

@ -0,0 +1,341 @@
using CultMath;
using Xunit;
using static CultMath.math;
namespace CultMath.Tests;
/// <summary>
/// The span primitives (math.Span.cs): snoise_hessian against the finite differences of snoise_grad and of
/// snoise, with each tolerance measured by Richardson's two step sizes rather than assumed; its symmetry and
/// its continuity across the simplex diagonal; and integral_clamp_linear against adaptive quadrature in
/// double. SNOISE_THIRD is measured and pinned in NoiseBoundTests (MeasureThird, ThirdConstantPinsSampled).
///
/// Hand mutations these must kill: any term of the per-corner second derivative dropped or mis-signed
/// (48 m^2 s x_i x_j, 8 m^3 p_j x_i, 8 m^3 p_i x_j, 8 m^3 s delta_ij) fails
/// SnoiseHessianMatchesCentralDifferences; the 0.3.0 cyclic tie order fails
/// SnoiseHessianContinuousOnSimplexDiagonal; a crossing of integral_clamp_linear moved, a clamp piece
/// dropped or the reversed-span sign lost fails IntegralClampLinearMatchesQuadrature.
/// </summary>
public sealed class SpanPrimitiveTests
{
private readonly ITestOutputHelper output;
public SpanPrimitiveTests(ITestOutputHelper output) => this.output = output;
private const double Unit = 1.0 / 16777216.0;
// A point of [-50, 50]^3 on the 2^-10 lattice, so that p +- h is exact in float32 for h a power of two
// up to 2^-4 and the finite-difference quotients carry no step rounding.
private static float3 LatticePoint(System.Random random)
{
float Axis() => MathF.Round((random.NextSingle() * 100.0f - 50.0f) * 1024.0f) / 1024.0f;
return new float3(Axis(), Axis(), Axis());
}
// The simplex tie set of NoiseGradTests.SnoiseIsContinuousOnTheSimplexDiagonal: the line (t, t, t) and
// the lattice diagonals v + s (1, 1, 1), v = L - sum(L) / 6.
private static List<float3> TiePoints()
{
const int vertices = 160;
const int perVertex = 8;
var random = new System.Random(0x71E5);
var points = new List<float3>();
for (var k = 0; k < 400; k++)
{
var t = (float)(random.NextDouble() * 128.0 - 64.0);
points.Add(new float3(t, t, t));
}
points.Add(new float3(0.0f, 0.0f, 0.0f));
for (var k = 0; k < vertices; k++)
{
var lx = random.Next(-64, 65);
var ly = random.Next(-64, 65);
var lz = random.Next(-64, 65);
var shift = (lx + ly + lz) / 6.0f;
for (var j = 0; j < perVertex; j++)
{
var s = j == 0 ? 0.0f : random.NextSingle();
points.Add(new float3(lx - shift + s, ly - shift + s, lz - shift + s));
}
}
return points;
}
private static float3 Axis(int a, float h) => new(a == 0 ? h : 0.0f, a == 1 ? h : 0.0f, a == 2 ? h : 0.0f);
// Column a of the Hessian by the central difference of snoise_grad at step h, in double.
private static double[] GradientDifference(float3 p, int a, float h)
{
var plus = snoise_grad(p + Axis(a, h));
var minus = snoise_grad(p - Axis(a, h));
return new[] { (plus.x - (double)minus.x) / (2.0 * h), (plus.y - (double)minus.y) / (2.0 * h), (plus.z - (double)minus.z) / (2.0 * h) };
}
// Worst ratio of |H - D(h/2)| to its tolerance, the number of entries compared and the largest |H| met.
private (double Worst, int Compared, double LargestEntry, double LargestTolerance) CompareToGradientDifferences(IEnumerable<float3> points)
{
const float h = 1.0f / 256.0f;
double worst = 0.0, largest = 0.0, largestTolerance = 0.0;
var compared = 0;
foreach (var p in points)
{
var hessian = snoise_hessian(p);
var gradient = snoise_grad(p);
var scale = Math.Max(Math.Max(Math.Abs(gradient.x), Math.Abs(gradient.y)), Math.Max(Math.Abs(gradient.z), 1.0));
for (var a = 0; a < 3; a++)
{
var coarse = GradientDifference(p, a, h);
var fine = GradientDifference(p, a, h / 2.0f);
for (var i = 0; i < 3; i++)
{
// The truncation of the finer quotient is a third of the gap between the two, as the
// error is O(h^2); the roundoff is a few ulp of the gradient over the step. Both are
// measured per entry and tripled, so the tolerance follows the point's own roughness.
var tolerance = 3.0 * (Math.Abs(coarse[i] - fine[i]) + 64.0 * Unit * scale / (h / 2.0));
var error = Math.Abs(hessian[i][a] - fine[i]);
worst = Math.Max(worst, error / tolerance);
largest = Math.Max(largest, Math.Abs(hessian[i][a]));
largestTolerance = Math.Max(largestTolerance, tolerance);
Assert.True(error <= tolerance, $"snoise_hessian({p})[{i}][{a}] = {hessian[i][a]:R} differs from the central difference of snoise_grad {fine[i]:R} by {error:R}, over the measured tolerance {tolerance:R}");
compared++;
}
}
}
return (worst, compared, largest, largestTolerance);
}
[Fact]
public void SnoiseHessianMatchesCentralDifferences()
{
var random = new System.Random(0x5A11);
var points = Enumerable.Range(0, 10_000).Select(_ => LatticePoint(random)).ToList();
var (worst, compared, largest, largestTolerance) = CompareToGradientDifferences(points);
output.WriteLine($"snoise_hessian vs central differences of snoise_grad over {points.Count} seeded points: {compared} entries, worst error {worst:F3} of its Richardson tolerance, largest |H| {largest:R}, largest tolerance {largestTolerance:R}");
// The comparison has teeth: curvature of the size the constant claims is present, and the tolerance
// is far under it, so a dropped term of the second derivative cannot hide in it.
Assert.True(largest > 10.0, $"the sample never meets curvature above 10 (largest {largest:R})");
Assert.True(largestTolerance < 0.5, $"the tolerance reaches {largestTolerance:R}, too wide to see a dropped term");
var (tieWorst, tieCompared, tieLargest, tieTolerance) = CompareToGradientDifferences(TiePoints());
output.WriteLine($"snoise_hessian vs central differences of snoise_grad on the simplex tie set: {tieCompared} entries, worst error {tieWorst:F3} of its Richardson tolerance, largest |H| {tieLargest:R}, largest tolerance {tieTolerance:R}");
Assert.True(tieLargest > 1.0, $"the tie set never meets curvature above 1 (largest {tieLargest:R})");
}
// The second difference of snoise in double, h apart, for the entry (i, j): the three-point stencil
// for i = j, the four-point mixed stencil otherwise.
private static double SecondDifference(float3 p, int i, int j, float h)
{
if (i == j)
return (snoise(p + Axis(i, h)) - 2.0 * (double)snoise(p) + snoise(p - Axis(i, h))) / ((double)h * h);
var pp = snoise(p + Axis(i, h) + Axis(j, h));
var pm = snoise(p + Axis(i, h) - Axis(j, h));
var mp = snoise(p - Axis(i, h) + Axis(j, h));
var mm = snoise(p - Axis(i, h) - Axis(j, h));
return ((double)pp - pm - mp + mm) / (4.0 * h * h);
}
[Fact]
public void SnoiseHessianMatchesSecondDifferencesOfSnoise()
{
var random = new System.Random(0x5A12);
double worst = 0.0, largest = 0.0;
var compared = 0;
var outside = 0;
for (var k = 0; k < 4000; k++)
{
var p = LatticePoint(random);
var hessian = snoise_hessian(p);
for (var i = 0; i < 3; i++)
for (var j = i; j < 3; j++)
{
// Richardson on the O(h^2) second difference: (4 S(h/2) - S(h)) / 3 is O(h^4). Two such
// extrapolations, from (h, h/2) and from (h/2, h/4), differ by about fifteen times the
// error of the finer one, so the comparison is against the finer and its tolerance is
// four times that gap, plus the roundoff of snoise (a few ulp) over (h/4)^2. Near a
// kernel's edge (m = 0) snoise's fourth derivative jumps and the extrapolation loses its
// order: such an entry may exceed the tight tolerance, but never by more than the gap
// between the last two second differences (an error that shrinks at least linearly in h
// is at most that gap), and the tight tolerance must hold for all but a fraction.
const float h = 1.0f / 16.0f;
var s0 = SecondDifference(p, i, j, h);
var s1 = SecondDifference(p, i, j, h / 2.0f);
var s2 = SecondDifference(p, i, j, h / 4.0f);
var coarseExtrapolation = (4.0 * s1 - s0) / 3.0;
var extrapolated = (4.0 * s2 - s1) / 3.0;
var tolerance = 4.0 * Math.Abs(extrapolated - coarseExtrapolation) + 64.0 * Unit / ((h / 4.0) * (h / 4.0));
var loose = tolerance + 2.0 * Math.Abs(s1 - s2);
var error = Math.Abs(hessian[i][j] - extrapolated);
worst = Math.Max(worst, error / tolerance);
largest = Math.Max(largest, Math.Abs(hessian[i][j]));
compared++;
if (error > tolerance)
outside++;
Assert.True(error <= loose, $"snoise_hessian({p})[{i}][{j}] = {hessian[i][j]:R} differs from the extrapolated second difference of snoise {extrapolated:R} by {error:R}, over the measured tolerance {loose:R}");
}
}
output.WriteLine($"snoise_hessian vs Richardson second differences of snoise over 4000 seeded points: {compared} entries, {outside} over the tight tolerance, worst error {worst:F3} of it, largest |H| {largest:R}");
Assert.True(largest > 10.0, $"the sample never meets curvature above 10 (largest {largest:R})");
Assert.True(outside <= compared / 200, $"{outside} of {compared} entries are over the tight Richardson tolerance, more than 0.5%");
}
[Fact]
public void SnoiseHessianIsSymmetric()
{
var random = new System.Random(0x5A13);
var points = Enumerable.Range(0, 20_000).Select(_ => new float3(random.NextSingle() * 512.0f - 256.0f, random.NextSingle() * 512.0f - 256.0f, random.NextSingle() * 512.0f - 256.0f))
.Concat(TiePoints()).Append(new float3(0.0f, 0.0f, 0.0f)).ToList();
foreach (var p in points)
{
var h = snoise_hessian(p);
Assert.True(BitConverter.SingleToInt32Bits(h._m01) == BitConverter.SingleToInt32Bits(h._m10)
&& BitConverter.SingleToInt32Bits(h._m02) == BitConverter.SingleToInt32Bits(h._m20)
&& BitConverter.SingleToInt32Bits(h._m12) == BitConverter.SingleToInt32Bits(h._m21), $"snoise_hessian({p}) is not its own transpose: {h}");
}
}
[Fact]
public void SnoiseHessianContinuousOnSimplexDiagonal()
{
// Within 1 or 2 ulp of a tie point along each axis the Hessian moves by at most the third derivative
// bound times the distance: SNOISE_THIRD x 2 sqrt 3 x 1e-4 covers a 1e-4 ball, and the points are
// far closer than that. The 0.3.0 cyclic tie order is a jump of order one here.
var bound = SNOISE_THIRD * 2.0 * Math.Sqrt(3.0) * 1.0e-4;
var worst = 0.0;
foreach (var p in TiePoints())
{
var centre = snoise_hessian(p);
for (var axis = 0; axis < 3; axis++)
{
for (var direction = -1; direction <= 1; direction += 2)
{
var q = p;
for (var ulp = 1; ulp <= 2; ulp++)
{
var component = axis == 0 ? q.x : axis == 1 ? q.y : q.z;
component = direction < 0 ? MathF.BitDecrement(component) : MathF.BitIncrement(component);
q = axis == 0 ? new float3(component, q.y, q.z) : axis == 1 ? new float3(q.x, component, q.z) : new float3(q.x, q.y, component);
var moved = snoise_hessian(q);
for (var i = 0; i < 3; i++)
for (var j = 0; j < 3; j++)
{
var jump = Math.Abs(moved[i][j] - (double)centre[i][j]);
worst = Math.Max(worst, jump);
Assert.True(jump <= bound, $"snoise_hessian jumps {jump:R} in entry [{i}][{j}] within {ulp} ulp of {p}, over {bound:R}");
}
}
}
}
}
output.WriteLine($"largest Hessian jump within 2 ulp of the simplex tie set: {worst:R} against the bound {bound:R}");
}
// Adaptive Simpson of f over [a, b] in double, to an absolute tolerance, with a depth cap.
private static double Quadrature(Func<double, double> f, double a, double b, double tolerance)
{
double Simpson(double fa, double fm, double fb, double width) => width / 6.0 * (fa + 4.0 * fm + fb);
double Recurse(double x0, double x1, double f0, double fm, double f1, double whole, double eps, int depth)
{
var mid = 0.5 * (x0 + x1);
var lm = 0.5 * (x0 + mid);
var rm = 0.5 * (mid + x1);
var flm = f(lm);
var frm = f(rm);
var left = Simpson(f0, flm, fm, mid - x0);
var right = Simpson(fm, frm, f1, x1 - mid);
if (depth <= 0 || Math.Abs(left + right - whole) <= 15.0 * eps)
return left + right + (left + right - whole) / 15.0;
return Recurse(x0, mid, f0, flm, fm, left, eps / 2.0, depth - 1) + Recurse(mid, x1, fm, frm, f1, right, eps / 2.0, depth - 1);
}
if (a == b)
return 0.0;
var fa = f(a);
var fb = f(b);
var fmid = f(0.5 * (a + b));
return Recurse(a, b, fa, fmid, fb, Simpson(fa, fmid, fb, b - a), tolerance, 40);
}
private static double ClampedLine(double a, double b, double lo, double hi, double t) => Math.Min(Math.Max(a + b * t, lo), hi);
// The reference integral in double: the adaptive quadrature of the clamped line, sign for a reversed span.
private static double ReferenceIntegral(float a, float b, float lo, float hi, float t0, float t1)
{
double low = Math.Min(lo, hi);
var integral = t0 <= t1
? Quadrature(t => ClampedLine(a, b, low, hi, t), t0, t1, 1.0e-12)
: -Quadrature(t => ClampedLine(a, b, low, hi, t), t1, t0, 1.0e-12);
return integral;
}
[Fact]
public void IntegralClampLinearMatchesQuadrature()
{
var random = new System.Random(0x1A7E);
float Uniform(float lo, float hi) => lo + (hi - lo) * random.NextSingle();
double worstRatio = 0.0;
int zeroSlopes = 0, reversed = 0, both = 0, neither = 0, ramps = 0;
for (var k = 0; k < 100_000; k++)
{
var a = Uniform(-4.0f, 4.0f);
// One in eight slopes is zero, one in sixteen is tiny (a crossing far outside any span).
var b = (k % 8) switch { 0 => 0.0f, 1 => 1.0e-30f * (k % 16 == 1 ? 1.0f : -1.0f), _ => Uniform(-4.0f, 4.0f) };
var lo = Uniform(-2.0f, 0.5f);
var hi = lo + Uniform(0.0f, 3.0f);
var t0 = Uniform(-3.0f, 3.0f);
var t1 = Uniform(-3.0f, 3.0f);
var got = integral_clamp_linear(a, b, lo, hi, t0, t1);
var want = ReferenceIntegral(a, b, lo, hi, t0, t1);
var span = Math.Abs((double)t1 - t0);
var error = Math.Abs(got - want);
worstRatio = Math.Max(worstRatio, error / Math.Max(1.0e-5 * Math.Abs(want), 1.0e-6 * span));
Assert.True(error <= 1.0e-5 * Math.Abs(want) || error <= 1.0e-6 * span, $"integral_clamp_linear({a:R}, {b:R}, {lo:R}, {hi:R}, {t0:R}, {t1:R}) = {got:R}, quadrature {want:R}");
if (b == 0.0f)
zeroSlopes++;
if (t1 < t0)
reversed++;
if (b != 0.0f)
{
double atLo = (lo - (double)a) / b, atHi = (hi - (double)a) / b;
double from = Math.Min(t0, t1), to = Math.Max(t0, t1);
var crossesLo = atLo > from && atLo < to;
var crossesHi = atHi > from && atHi < to;
if (crossesLo && crossesHi)
both++;
else if (!crossesLo && !crossesHi)
neither++;
if (hi > lo && (crossesLo || crossesHi))
ramps++;
}
}
output.WriteLine($"integral_clamp_linear vs adaptive quadrature over 100000 cases: {zeroSlopes} flat, {reversed} reversed, {both} crossing both bounds, {neither} crossing neither, {ramps} on a ramp; worst error {worstRatio:F3} of its tolerance");
Assert.True(zeroSlopes > 10_000 && reversed > 40_000 && both > 2_000 && neither > 2_000, $"the sample meets a branch too rarely: {zeroSlopes} flat, {reversed} reversed, {both} both, {neither} neither");
}
[Fact]
public void IntegralClampLinearHasExactValuesOnTheBinaryFloats()
{
// The ramp t from 0 to 1 clamped to [0.25, 0.75] over [0, 1]: 0.25 x 0.25 below, 0.5 x 0.5 on the ramp, 0.75 x 0.25 above.
Assert.Equal(0.0625f + 0.25f + 0.1875f, integral_clamp_linear(0.0f, 1.0f, 0.25f, 0.75f, 0.0f, 1.0f));
// A reversed span is the negative of the span.
Assert.Equal(-0.5f, integral_clamp_linear(0.0f, 1.0f, 0.25f, 0.75f, 1.0f, 0.0f));
Assert.Equal(integral_clamp_linear(0.3f, -0.7f, -0.5f, 0.9f, -2.0f, 1.5f), -integral_clamp_linear(0.3f, -0.7f, -0.5f, 0.9f, 1.5f, -2.0f));
// b = 0 is the constant, clamped.
Assert.Equal(2.0f * 3.0f, integral_clamp_linear(5.0f, 0.0f, 0.0f, 2.0f, 1.0f, 4.0f));
Assert.Equal(-1.0f * 3.0f, integral_clamp_linear(-5.0f, 0.0f, -1.0f, 2.0f, 1.0f, 4.0f));
// An empty span, and a span that never leaves the ramp (the trapezoid: 3 x mean of 1 and 4).
Assert.Equal(0.0f, integral_clamp_linear(0.0f, 1.0f, -9.0f, 9.0f, 2.0f, 2.0f));
Assert.Equal(7.5f, integral_clamp_linear(0.0f, 1.0f, -9.0f, 9.0f, 1.0f, 4.0f));
// A falling line starts at the upper bound: 1 for t in [0, 1], the ramp 1 to 0 over [1, 2], 0 after.
Assert.Equal(1.0f + 0.5f, integral_clamp_linear(2.0f, -1.0f, 0.0f, 1.0f, 0.0f, 3.0f));
// lo above hi clamps to hi everywhere.
Assert.Equal(2.0f * 3.0f, integral_clamp_linear(0.0f, 1.0f, 5.0f, 2.0f, 0.0f, 3.0f));
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,75 @@
{
"oracle": "tools/cycles-oracle/oracle.py (Blender 5.2.2 LTS, build d13f752e3b9c, Cycles CPU, 1 sample, Emit bake, float Non-Color images)",
"blender": "5.2.2 LTS",
"build_hash": "d13f752e3b9c",
"platform": "Linux",
"encoding": "each case is 'operands -> results', every scalar a float32 bit pattern in hex, colours flattened as r g b",
"family": "infinite",
"functions": [
{
"function": "cycles_power",
"node": "ShaderNodeMath POWER",
"cases": [
"bf800000 inf -> 3f800000",
"bf800000 -inf -> 3f800000",
"c0000000 inf -> inf",
"c0000000 -inf -> 00000000",
"bf000000 inf -> 00000000",
"bf000000 -inf -> inf",
"80000000 inf -> 00000000",
"80000000 -inf -> 00000000",
"3f000000 inf -> 00000000",
"3f000000 -inf -> inf",
"40000000 inf -> inf",
"40000000 -inf -> 00000000",
"3f800000 inf -> 3f800000",
"00000000 inf -> 00000000",
"00000000 -inf -> 00000000",
"inf 40400000 -> inf",
"-inf 40400000 -> -inf",
"-inf 40000000 -> inf",
"inf bf800000 -> 00000000",
"-inf bf800000 -> 00000000",
"-inf inf -> inf",
"inf inf -> inf"
]
},
{
"function": "cycles_modulo",
"node": "ShaderNodeMath MODULO",
"cases": [
"inf 3f800000 -> nan",
"-inf 3f800000 -> nan",
"inf 40400000 -> nan",
"-inf 40400000 -> nan",
"inf 3dcccccd -> nan",
"-inf 3dcccccd -> nan",
"inf c0000000 -> nan",
"40a00000 inf -> 40a00000",
"c0a00000 inf -> c0a00000",
"40a00000 -inf -> 40a00000",
"inf inf -> nan",
"-inf inf -> nan",
"00000000 inf -> 00000000",
"inf 00000000 -> 00000000"
]
},
{
"function": "cycles_map_range_smoothstep",
"node": "ShaderNodeMapRange SMOOTHSTEP",
"cases": [
"-inf -inf 3f800000 40000000 40400000 -> nan",
"-inf 3f800000 -inf 40000000 40400000 -> nan",
"-inf 3f800000 40a00000 40000000 40400000 -> 40000000",
"-inf c0a00000 3f800000 40000000 40400000 -> 40000000",
"inf c0a00000 3f800000 40000000 40400000 -> 40400000",
"inf 3f800000 c0a00000 40000000 40400000 -> 40000000",
"inf inf 3f800000 40000000 40400000 -> 40000000",
"inf 3f800000 inf 40000000 40400000 -> 40400000",
"-inf inf 3f800000 40000000 40400000 -> 40400000",
"-inf 3f800000 inf 40000000 40400000 -> 40000000",
"3f800000 -inf inf 40000000 40400000 -> nan"
]
}
]
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -5,6 +5,9 @@ param(
# Also concatenate shaders\CultMath.Phacelle.glsl (MPL-2.0) after CultMath.glsl, as a consumer that
# calls cultmath_phacelle does. Without it the wrapper is the MIT library alone.
[switch]$Phacelle,
# Also concatenate shaders\CultMath.Cycles.glsl (Apache-2.0), as a consumer that calls a cultmath_cycles_
# function does.
[switch]$Cycles,
[string]$GlslangPath = ""
)
@ -23,6 +26,9 @@ $library = Get-Content -LiteralPath (Join-Path $repoRoot "shaders\CultMath.glsl"
if ($Phacelle) {
$library += Get-Content -LiteralPath (Join-Path $repoRoot "shaders\CultMath.Phacelle.glsl") -Raw
}
if ($Cycles) {
$library += Get-Content -LiteralPath (Join-Path $repoRoot "shaders\CultMath.Cycles.glsl") -Raw
}
$calls = foreach ($match in [regex]::Matches($library, '(?m)^\w+\s+(cultmath_\w+)\s*\(([^)]*)\)')) {
$arguments = foreach ($parameter in ($match.Groups[2].Value -split ',')) {
$type = ($parameter.Trim() -split '\s+')[0]

View file

@ -0,0 +1,70 @@
# Cycles oracle
`oracle.py` produces the fixtures that `CyclesOracleTests` holds `math.cycles_*` to: for each Cycles node
CultMath ports, the node's results as Blender's own Cycles computes them.
## Run
```
CYCLES_CPU_NO_AVX2=1 blender --background --factory-startup --python oracle.py -- <fixture directory> [<family> ...]
```
The fixture directory is `tests/CultMath.Tests/fixtures/cycles-oracle`. Families are `math`, `map-range`,
`clamp`, `mix`, `rgb-to-bw` and `ramp`; with none named, all are written. The tool is a Blender Python
script and runs only under Blender, never under a plain Python.
## The pin
It refuses to run under any Blender but **5.2.2 LTS, build hash `d13f752e3b9c`**, exits nonzero and names
the version and build it found beside the ones it needs. Blender 5.2.2 is
<https://download.blender.org/release/Blender5.2/> (`blender-5.2.2-linux-x64.tar.xz`). The platform is Linux x64: the fixtures reproduce
byte for byte only there, and the Steam/Windows build is another build (see below). The fixtures record the
version, the hash and the platform they were written on, as provenance.
## The reference and other builds
Ruling `cultmath-tapes:ruling:cycles-kernel-reference-ruled`: CultMath's Cycles converters mean Cycles' formulas
evaluated with IEEE single rounding per operation, and the Linux SSE4.2 oracle stays their bit-exact witness.
Every other Cycles build (AVX2 FMA-contracted, MSVC /fp:fast, GPU backends) and CultMath's own HLSL lowering are
held to a stated per-function tolerance class measured on that build; cancellation-prone functions (floored
modulo, wrap) get an error bound relative to |b| and a documented divergence note.
Cycles' AVX2 CPU kernel is compiled with fused multiply-add, so `a - floor(a / b) b` is one fused operation
there, and CultMath's C# (which fuses nothing) computes the unfused one. The fixtures pin the SSE4.2 kernel,
which has no FMA, by `CYCLES_CPU_NO_AVX2=1`; the tool bakes `10000 mod 0.1` before anything else and exits 4 if
the result is the fused one, so a run on the wrong kernel writes nothing. Other kernels are other builds:
measured under the table below, never written to these fixtures.
| build | how it was measured | fixture | per-function ulp or bound |
| --- | --- | --- | --- |
| Blender 5.2.2 Linux x64, SSE4.2 kernel (the reference) | `oracle.py` with `CYCLES_CPU_NO_AVX2=1`; `CyclesOracleTests` holds every function to the fixtures | `tests/CultMath.Tests/fixtures/cycles-oracle/*.json` | 0 ulp, every function |
| Blender 5.2.2 Linux x64, AVX2 kernel | the same oracle without the pin, 1024 rows per function, against the single-rounding model `fma(-floor(a / b), b, a)` (wrap: `fma(-range, floor((value - min) / range), value)`) | none committed | floored modulo: at most 2^-23 (\|a / b\| + 1) \|b\|, measured 0.91 of 2^-24 (\|a\| + \|b\|) on 151 rows; wrap: at most 2^-23 (\|value\| + \|min\| + \|range\|), measured 0.77 of 2^-24 on 30 rows; other functions unmeasured |
The divergence note: a build compiled with fast-math may also move `floor(a / b)` by one near an integer
quotient, so the result differs by a whole \|b\| (wrap: a whole range). Further rows come from follow-up
`cultmath-tapes:follow_up:cycles-tolerance-classes`; its per-build fixtures go under
`fixtures/cycles-oracle/<build>/` with their tolerances beside `Tolerances` in `CyclesOracleTests`.
## Method
Operands go into float, Non-Color input images (channel packed, read with Closest interpolation), three
operands per image. The node under test reads them. One Emit bake per output channel (Cycles on the CPU, 1
sample, margin 0, no denoising) writes the result to a float image; each pixel is one case. The tool first
checks that a bake returns an operand image bit for bit, and stops if it does not. The fixtures hold the
operands and the results as float32 bit patterns, so a test reads exactly what Cycles computed.
A Map Range node's Clamp option is baked as the node with Clamp on, which Cycles expands into a Clamp node
of type Range on the result. The ramp family bakes a Color Ramp whose table entries are each read at a `t`
whose product with 255 is the entry's index, so the first 256 cases are the ramp's own table.
## Fixtures
Written by this tool and never edited by hand. Rerunning it under the same Blender build on the same
platform rewrites them byte for byte; `CyclesOracleTests` holds every function to them at 0 ulp. Run the
oracle on Yggdrasil-class Linux, never on the workstation.
## Licence
`oracle.py` is GPL-3.0-or-later, as a script that runs inside Blender (`bpy`). It ships in no package: the
`GameCult.Math` NuGet package and the Unity package do not contain `tools/`. The fixtures are data it
produced. The Cycles functions they test are Apache-2.0 (`math.Cycles.cs`, `CultMath.Cycles.hlsl`).

View file

@ -0,0 +1,699 @@
# SPDX-License-Identifier: GPL-3.0-or-later
#
# The Cycles oracle for CultMath's Cycles node semantics (math.Cycles.cs, shaders/CultMath.Cycles.hlsl).
# A Blender Python script, so it is GPL-3.0-or-later; it is a test tool and ships in no package.
#
# blender --background --factory-startup --python oracle.py -- <fixture directory> [<family> ...]
#
# It refuses to run under any Blender but 5.2.2 LTS, build hash d13f752e3b9c. For each family it bakes
# the node under test with Cycles on the CPU and writes tests/CultMath.Tests/fixtures/cycles-oracle/<family>.json.
# Method: operands go into float, Non-Color input images read with Closest interpolation; one Emit bake per
# output channel (1 sample, margin 0, no denoising) writes the node's result to a float image whose pixels are
# the results, bit for bit. The fixtures are this tool's output and are never edited by hand. They witness the
# reference of ruling cultmath-tapes:ruling:cycles-kernel-reference-ruled (one IEEE single rounding per operation,
# the SSE4.2 kernel, CYCLES_CPU_NO_AVX2=1); other kernels are other builds and are never written here.
import hashlib
import json
import os
import sys
import bpy
import numpy as np
PINNED_VERSION = "5.2.2 LTS"
PINNED_HASH = "d13f752e3b9c"
SIDE = 32
CASES = SIDE * SIDE
def refuse_other_blender():
found = (bpy.app.version_string, bpy.app.build_hash.decode() if isinstance(bpy.app.build_hash, bytes) else bpy.app.build_hash)
if found != (PINNED_VERSION, PINNED_HASH):
sys.stderr.write(
"cycles-oracle: needs Blender %s build %s, found %s build %s\n" % (PINNED_VERSION, PINNED_HASH, found[0], found[1]))
sys.exit(2)
refuse_other_blender()
scene = bpy.context.scene
scene.render.engine = "CYCLES"
scene.cycles.device = "CPU"
scene.cycles.samples = 1
scene.cycles.use_denoising = False
bpy.ops.mesh.primitive_plane_add(size=2)
PLANE = bpy.context.active_object
def by_identifier(sockets, identifier):
"""A node's socket by identifier: several data types share one socket name."""
for socket in sockets:
if socket.identifier == identifier:
return socket
raise KeyError("no socket %s among %s" % (identifier, [s.identifier for s in sockets]))
def f32(values):
return np.asarray(values, dtype=np.float32)
def bits(value):
return "%08x" % int(np.asarray(value, dtype=np.float32).view(np.uint32))
def rng_for(name):
# One stream per name: a function, a blend mode's second colours (name + "2"), a ramp. Sharing a seed shares the draws.
return np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:8], "little"))
def new_image(name, rgba=None):
image = bpy.data.images.new(name, SIDE, SIDE, alpha=True, float_buffer=True)
image.colorspace_settings.name = "Non-Color"
image.alpha_mode = "CHANNEL_PACKED"
if rgba is not None:
image.pixels.foreach_set(rgba.reshape(-1))
image.pack()
return image
def pack_operands(columns):
"""Operand columns (CASES float32 each) to input images of three operands per image."""
images = []
for first in range(0, len(columns), 3):
rgba = np.zeros((SIDE * SIDE, 4), dtype=np.float32)
rgba[:, 3] = 1.0
for k, column in enumerate(columns[first:first + 3]):
rgba[:, k] = column
images.append(new_image("operands%d" % first, rgba.reshape(SIDE, SIDE, 4)))
return images
def operand_sockets(tree, images, count):
"""One float socket per operand, read from the input images with Closest interpolation."""
sockets = []
for image in images:
texture = tree.nodes.new("ShaderNodeTexImage")
texture.image = image
texture.interpolation = "Closest"
separate = tree.nodes.new("ShaderNodeSeparateColor")
tree.links.new(texture.outputs["Color"], separate.inputs[0])
sockets.append([separate.outputs[0], separate.outputs[1], separate.outputs[2]])
flat = [socket for triple in sockets for socket in triple]
return flat[:count]
def triple_socket(tree, images, first):
"""The colour made of operands first, first + 1, first + 2."""
combine = tree.nodes.new("ShaderNodeCombineColor")
sockets = operand_sockets(tree, images, first + 3)
for k in range(3):
tree.links.new(sockets[first + k], combine.inputs[k])
return combine.outputs[0]
def bake(label, images, build, channels):
"""Bakes build(tree, images) once per output channel; returns channels float32 arrays of CASES results."""
results = []
for channel in range(channels):
material = bpy.data.materials.new("%s.%d" % (label, channel))
material.use_nodes = True
tree = material.node_tree
tree.nodes.clear()
output = tree.nodes.new("ShaderNodeOutputMaterial")
emit = tree.nodes.new("ShaderNodeEmission")
tree.links.new(emit.outputs[0], output.inputs[0])
sockets = build(tree, images)
socket = sockets[channel]
if socket.type == "RGBA" or socket.type == "VECTOR":
separate = tree.nodes.new("ShaderNodeSeparateColor")
tree.links.new(socket, separate.inputs[0])
# Cycles stores a colour result channel by channel; the channel under test is red.
tree.links.new(separate.outputs[0], emit.inputs["Color"])
else:
tree.links.new(socket, emit.inputs["Color"])
target = new_image("%s.%d.out" % (label, channel))
target_node = tree.nodes.new("ShaderNodeTexImage")
target_node.image = target
tree.nodes.active = target_node
PLANE.data.materials.clear()
PLANE.data.materials.append(material)
bpy.context.view_layer.objects.active = PLANE
PLANE.select_set(True)
bpy.ops.object.bake(type="EMIT", margin=0)
pixels = np.empty(SIDE * SIDE * 4, dtype=np.float32)
target.pixels.foreach_get(pixels)
results.append(pixels.reshape(SIDE * SIDE, 4)[:, 0].copy())
return results
def vector_bake(label, images, build):
"""For a node whose result is a colour: one bake per RGB channel via Separate Color."""
results = []
for channel in range(3):
def pick(tree, imgs, channel=channel):
color = build(tree, imgs)
separate = tree.nodes.new("ShaderNodeSeparateColor")
tree.links.new(color, separate.inputs[0])
return [separate.outputs[channel]]
results.append(bake("%s.c%d" % (label, channel), images, pick, 1)[0])
return results
# ---- operand sets ----
SPECIAL = [0.0, 1.0, -1.0, 0.5, -0.5, 2.0, -2.0, 3.0, -2.75, 0.1, -0.1, 7.5, -7.5, 1.0e-7, -1.0e-7, 100.0, -100.0, 1.0e4, 0.3, 0.7]
POSITIVE = [0.0, 1.0, 0.5, 2.0, 3.0, 0.1, 10.0, 7.5, 1.0e-3, 100.0, 0.3, 0.7, 2.718281828]
FACTOR = [0.0, 0.5, 1.0, 1.5, -0.5, 0.25, 0.75, 2.0]
COLOR_SPECIAL = [0.0, 0.25, 0.5, 0.75, 1.0, 1.25, -0.25, 0.1, 0.9, 0.3333333, 0.6666667]
def sample_columns(name, count, specials, lows_highs, pair_specials=2):
"""CASES rows of `count` operands: the specials' product for the first operands, then uniform draws."""
rng = rng_for(name)
rows = []
import itertools
lists = [specials[k] if k < len(specials) else None for k in range(count)]
fixed = [lst for lst in lists if lst is not None]
if fixed:
for combo in itertools.product(*fixed):
row = list(combo) + [None] * (count - len(combo))
rows.append(row)
rows = rows[:CASES]
while len(rows) < CASES:
rows.append([None] * count)
columns = []
for k in range(count):
low, high = lows_highs[k]
column = np.empty(CASES, dtype=np.float32)
for r, row in enumerate(rows):
column[r] = row[k] if row[k] is not None else rng.uniform(low, high)
columns.append(column)
return columns
def random_color_rows(name, extra=0):
"""CASES colours: primaries, secondaries, greys, the specials' products, then random with tied channels."""
rng = rng_for(name)
rows = []
for r in COLOR_SPECIAL[:5]:
for g in COLOR_SPECIAL[:5]:
for b in COLOR_SPECIAL[:5]:
rows.append((r, g, b))
for v in COLOR_SPECIAL:
rows.append((v, v, v))
while len(rows) < CASES:
c = list(rng.uniform(-0.25, 1.25, 3))
tie = rng.integers(0, 6)
if tie == 0:
c[1] = c[0]
elif tie == 1:
c[2] = c[1]
elif tie == 2:
c[2] = c[0]
rows.append(tuple(c))
return rows[:CASES]
# ---- families ----
MATH = [
# (function, operation, operand count, operand specials, ranges)
("cycles_divide", "DIVIDE", 2, [SPECIAL, SPECIAL], [(-20, 20)] * 2),
("cycles_power", "POWER", 2, [SPECIAL, SPECIAL], [(-4, 4), (-4, 4)]),
("cycles_logarithm", "LOGARITHM", 2, [SPECIAL, SPECIAL], [(0.01, 20), (0.01, 20)]),
("cycles_sqrt", "SQRT", 1, [SPECIAL], [(-5, 20)]),
("cycles_inverse_sqrt", "INVERSE_SQRT", 1, [SPECIAL], [(-5, 20)]),
("cycles_modulo", "MODULO", 2, [SPECIAL, SPECIAL], [(-20, 20)] * 2),
("cycles_floored_modulo", "FLOORED_MODULO", 2, [SPECIAL, SPECIAL], [(-20, 20)] * 2),
("cycles_wrap", "WRAP", 3, [SPECIAL[:10], SPECIAL[:10], SPECIAL[:10]], [(-20, 20), (-10, 10), (-10, 10)]),
("cycles_snap", "SNAP", 2, [SPECIAL, SPECIAL], [(-20, 20)] * 2),
("cycles_pingpong", "PINGPONG", 2, [SPECIAL, SPECIAL], [(-20, 20)] * 2),
("cycles_smooth_min", "SMOOTH_MIN", 3, [SPECIAL[:10], SPECIAL[:10], SPECIAL[:10]], [(-20, 20), (-20, 20), (-3, 3)]),
("cycles_smooth_max", "SMOOTH_MAX", 3, [SPECIAL[:10], SPECIAL[:10], SPECIAL[:10]], [(-20, 20), (-20, 20), (-3, 3)]),
("cycles_compare", "COMPARE", 3, [SPECIAL[:10], SPECIAL[:10], [0.0, 0.5, 1.0, 1.0e-7]], [(-20, 20), (-20, 20), (0, 2)]),
("cycles_round", "ROUND", 1, [SPECIAL], [(-20, 20)]),
("cycles_trunc", "TRUNC", 1, [SPECIAL], [(-20, 20)]),
("cycles_fract", "FRACT", 1, [SPECIAL], [(-20, 20)]),
("cycles_sign", "SIGN", 1, [SPECIAL], [(-20, 20)]),
("cycles_arcsine", "ARCSINE", 1, [SPECIAL], [(-1.5, 1.5)]),
("cycles_arccosine", "ARCCOSINE", 1, [SPECIAL], [(-1.5, 1.5)]),
("cycles_arctan2", "ARCTAN2", 2, [SPECIAL, SPECIAL], [(-20, 20)] * 2),
]
# Operands that must be present as exact pairs whatever the random draws: the quirks the port names.
EXTRA_ROWS = {
"cycles_power": [(-2.0, 1.0e10), (-2.0, -1.0e10), (-2.0, 3.0), (-2.0, 2.0), (-2.0, -3.0), (-2.0, 2147483648.0), (-2.0, -2147483648.0),
(-8.0, 0.3333333), (2.0, 0.0), (0.0, 0.0), (0.0, 2.0), (-0.0, -3.0), (-1.5, 17.0), (-1.5, 16777217.0),
# A base of -1 keeps a finite result for any exponent, so the film shows the exponent past the int range.
(-1.0, 3.0e9), (-1.0, -3.0e9), (-1.0, 2147483648.0), (-1.0, 16777216.0), (-1.0, 16777215.0)],
"cycles_compare": [(0.0, 1.0e-7, 0.0), (1.0, 1.0000001, 0.0), (1.0, 1.0000002, 0.0), (0.0, 1.0e-7, 1.0e-8), (5.0, 5.0, 0.0), (0.0, 2.0e-7, 1.0e-7)],
# Burn with a divisor of exactly 0 (tm + t col2 = 0) and a colour above 1: the result is 1 for the channel Cycles reads
# as 0, and an infinity the film would hide for the others.
"cycles_mix_burn": [(2.0, 1.5, 0.5, 2.5, 0.5, 0.5, 0.5), (0.5, 1.5, 2.0, 3.0, -1.0, -1.0, -1.0)],
# safe_asinf / safe_acosf clamp to [-1, 1]; compatible_atan2 guards only the origin (y = a, x = b).
"cycles_arcsine": [(2.0,), (-2.0,), (1.0,), (-1.0,), (1.0000001,), (-1.0000001,), (1.5,)],
"cycles_arccosine": [(2.0,), (-2.0,), (1.0,), (-1.0,), (1.0000001,), (-1.0000001,), (1.5,)],
"cycles_arctan2": [(0.0, 0.0), (0.0, -0.0), (-0.0, -0.0), (-0.0, -1.0), (0.0, -1.0), (1.0, 0.0), (-1.0, 0.0), (1.0e-7, -1.0e-7)],
"cycles_modulo": [(0.3, 0.1), (-0.3, 0.1), (5.5, -2.0), (-5.5, -2.0), (1.0, 0.0), (1.0e7, 3.0), (7.0, 7.0), (-7.0, 7.0)],
}
MAP_RANGE = [
("cycles_map_range_linear", "LINEAR"),
("cycles_map_range_stepped", "STEPPED"),
("cycles_map_range_smoothstep", "SMOOTHSTEP"),
("cycles_map_range_smootherstep", "SMOOTHERSTEP"),
]
MIX_MODES = [
("cycles_mix_blend", "MIX"), ("cycles_mix_add", "ADD"), ("cycles_mix_mul", "MULTIPLY"), ("cycles_mix_screen", "SCREEN"),
("cycles_mix_overlay", "OVERLAY"), ("cycles_mix_sub", "SUBTRACT"), ("cycles_mix_div", "DIVIDE"), ("cycles_mix_diff", "DIFFERENCE"),
("cycles_mix_exclusion", "EXCLUSION"), ("cycles_mix_dark", "DARKEN"), ("cycles_mix_light", "LIGHTEN"), ("cycles_mix_dodge", "DODGE"),
("cycles_mix_burn", "BURN"), ("cycles_mix_hue", "HUE"), ("cycles_mix_sat", "SATURATION"), ("cycles_mix_val", "VALUE"),
("cycles_mix_color", "COLOR"), ("cycles_mix_soft", "SOFT_LIGHT"), ("cycles_mix_linear", "LINEAR_LIGHT"),
]
def with_extra(function, columns, count):
extra = EXTRA_ROWS.get(function, [])
for r, row in enumerate(extra):
for k in range(count):
columns[k][CASES - 1 - r] = row[k] if k < len(row) else 0.0
return columns
def encode_cases(columns, results):
cases = []
for r in range(CASES):
cases.append("%s -> %s" % (" ".join(bits(c[r]) for c in columns), " ".join(bits(x[r]) for x in results)))
return cases
def family_math():
functions = []
for function, operation, count, specials, ranges in MATH:
columns = with_extra(function, sample_columns(function, count, specials, ranges), count)
images = pack_operands(columns)
def build(tree, imgs, operation=operation, count=count):
node = tree.nodes.new("ShaderNodeMath")
node.operation = operation
sockets = operand_sockets(tree, imgs, count)
for k in range(count):
tree.links.new(sockets[k], node.inputs[k])
return [node.outputs[0]]
functions.append({"function": function, "node": "ShaderNodeMath " + operation, "cases": encode_cases(columns, bake(function, images, build, 1))})
return functions
def family_map_range():
functions = []
for function, kind in MAP_RANGE:
count = 6
specials = [SPECIAL[:10], SPECIAL[:5], SPECIAL[:5]]
columns = sample_columns(function, count, specials, [(-20, 20), (-10, 10), (-10, 10), (-20, 20), (-20, 20), (-1, 8)])
# Rows with From Min equal to From Max, and with From Min above From Max, whatever the draws.
for r in range(8):
columns[2][CASES - 1 - r] = columns[1][CASES - 1 - r]
for r in range(8, 16):
columns[1][CASES - 1 - r], columns[2][CASES - 1 - r] = max(columns[1][CASES - 1 - r], columns[2][CASES - 1 - r]), min(columns[1][CASES - 1 - r], columns[2][CASES - 1 - r])
for r in range(16, 24):
columns[5][CASES - 1 - r] = float(r - 18)
if kind == "SMOOTHSTEP":
# An overflowing range: from_max - from_min is infinite, and Cycles' smoothstep decides x >= edge1 before dividing.
for r, row in ((24, (3.0e38, -3.0e38, 3.0e38, 0.0, 1.0, 4.0)), (25, (3.0e38, 3.0e38, -3.0e38, 0.0, 1.0, 4.0))):
for k in range(6):
columns[k][CASES - 1 - r] = row[k]
images = pack_operands(columns)
def build(tree, imgs, kind=kind):
node = tree.nodes.new("ShaderNodeMapRange")
node.data_type = "FLOAT"
node.interpolation_type = kind
node.clamp = False
sockets = operand_sockets(tree, imgs, 6)
for k, identifier in enumerate(["Value", "From Min", "From Max", "To Min", "To Max", "Steps"]):
socket = by_identifier(node.inputs, identifier)
tree.links.new(sockets[k], socket)
return [node.outputs["Result"]]
functions.append({"function": function, "node": "ShaderNodeMapRange " + kind, "cases": encode_cases(columns, bake(function, images, build, 1))})
# The Clamp option, on the same operands: a Clamp node of type Range on the result.
def build_clamped(tree, imgs, kind=kind):
node = tree.nodes.new("ShaderNodeMapRange")
node.data_type = "FLOAT"
node.interpolation_type = kind
node.clamp = True
sockets = operand_sockets(tree, imgs, 6)
for k, identifier in enumerate(["Value", "From Min", "From Max", "To Min", "To Max", "Steps"]):
socket = by_identifier(node.inputs, identifier)
tree.links.new(sockets[k], socket)
return [node.outputs["Result"]]
functions.append({"function": function, "node": "ShaderNodeMapRange " + kind + " with Clamp",
"then": "cycles_clamp_range(result, to_min, to_max)",
"cases": encode_cases(columns, bake(function + ".clamped", images, build_clamped, 1))})
return functions
def family_clamp():
functions = []
for function, clamp_type in (("cycles_clamp_minmax", "MINMAX"), ("cycles_clamp_range", "RANGE")):
columns = sample_columns(function, 3, [SPECIAL[:10], SPECIAL[:10], SPECIAL[:10]], [(-20, 20)] * 3)
images = pack_operands(columns)
def build(tree, imgs, clamp_type=clamp_type):
node = tree.nodes.new("ShaderNodeClamp")
node.clamp_type = clamp_type
sockets = operand_sockets(tree, imgs, 3)
for k in range(3):
tree.links.new(sockets[k], node.inputs[k])
return [node.outputs[0]]
functions.append({"function": function, "node": "ShaderNodeClamp " + clamp_type, "cases": encode_cases(columns, bake(function, images, build, 1))})
return functions
def mix_columns(name, blend):
rng = rng_for(name)
colors = random_color_rows(name)
colors2 = random_color_rows(name + "2")
rng.shuffle(colors2)
factors = [FACTOR[r % len(FACTOR)] if r < 8 * 64 else float(rng.uniform(-0.5, 1.5)) for r in range(CASES)]
columns = [f32(factors)]
columns += [f32([c[k] for c in colors]) for k in range(3)]
columns += [f32([c[k] for c in colors2]) for k in range(3)]
return columns
def family_mix():
functions = []
rng = rng_for("mix-float")
# Mix, Float: a and b in the usual ranges, the factor as in the blend modes.
columns = [f32([FACTOR[r % len(FACTOR)] if r < 512 else rng.uniform(-0.5, 1.5) for r in range(CASES)]),
f32(rng.uniform(-20, 20, CASES)), f32(rng.uniform(-20, 20, CASES))]
images = pack_operands(columns)
def build_float(tree, imgs):
node = tree.nodes.new("ShaderNodeMix")
node.data_type = "FLOAT"
node.clamp_factor = False
node.clamp_result = False
sockets = operand_sockets(tree, imgs, 3)
for k, identifier in enumerate(["Factor_Float", "A_Float", "B_Float"]):
tree.links.new(sockets[k], by_identifier(node.inputs, identifier))
return [by_identifier(node.outputs, "Result_Float")]
functions.append({"function": "cycles_mix_float", "node": "ShaderNodeMix FLOAT", "cases": encode_cases(columns, bake("mix_float", images, build_float, 1))})
columns = mix_columns("mix-vector", "VECTOR")
images = pack_operands(columns)
def build_vector(tree, imgs):
node = tree.nodes.new("ShaderNodeMix")
node.data_type = "VECTOR"
node.factor_mode = "UNIFORM"
node.clamp_factor = False
sockets = operand_sockets(tree, imgs, 1)
tree.links.new(sockets[0], by_identifier(node.inputs, "Factor_Float"))
tree.links.new(triple_socket(tree, imgs, 1), by_identifier(node.inputs, "A_Vector"))
tree.links.new(triple_socket(tree, imgs, 4), by_identifier(node.inputs, "B_Vector"))
return by_identifier(node.outputs, "Result_Vector")
functions.append({"function": "cycles_mix_vector", "node": "ShaderNodeMix VECTOR UNIFORM", "cases": encode_cases(columns, vector_bake("mix_vector", images, build_vector))})
for function, blend in MIX_MODES:
columns = with_extra(function, mix_columns(function, blend), 7)
images = pack_operands(columns)
def build(tree, imgs, blend=blend):
node = tree.nodes.new("ShaderNodeMix")
node.data_type = "RGBA"
node.blend_type = blend
node.clamp_factor = False
node.clamp_result = False
sockets = operand_sockets(tree, imgs, 1)
tree.links.new(sockets[0], by_identifier(node.inputs, "Factor_Float"))
tree.links.new(triple_socket(tree, imgs, 1), by_identifier(node.inputs, "A_Color"))
tree.links.new(triple_socket(tree, imgs, 4), by_identifier(node.inputs, "B_Color"))
return by_identifier(node.outputs, "Result_Color")
functions.append({"function": function, "node": "ShaderNodeMix RGBA " + blend, "cases": encode_cases(columns, vector_bake(function, images, build))})
return functions
def family_rgb_to_bw():
rows = random_color_rows("rgb_to_bw")
columns = [f32([c[k] for c in rows]) for k in range(3)]
# One case per primary pins the scene-linear coefficients.
for k in range(3):
for j in range(3):
columns[j][CASES - 1 - k] = 1.0 if j == k else 0.0
images = pack_operands(columns)
def build(tree, imgs):
node = tree.nodes.new("ShaderNodeRGBToBW")
tree.links.new(triple_socket(tree, imgs, 0), node.inputs["Color"])
return [node.outputs["Val"]]
return [{"function": "cycles_rgb_to_bw", "node": "ShaderNodeRGBToBW", "cases": encode_cases(columns, bake("rgb_to_bw", images, build, 1))}]
# A Blender ramp is sampled at 256 intervals into a table of 257 entries (colorramp_to_array: size + 1 entries
# at i / size), and the kernel reads that table with table_size 257.
RAMP_SIZE = 257
# A constant ramp whose 32 stops sit half an entry past an entry boundary: its table is the stops' values, so
# a lookup's result names the entry it read.
CONSTANT_STOPS = [((8 * j + 3.5) / (RAMP_SIZE - 1), (j + 1) / 32.0) for j in range(32)]
def ramp_cases(rng, boundaries):
"""CASES values of t: the floats around each boundary t = i / 255, the specials, then uniform draws."""
values = []
for i in boundaries:
t = np.float32(i / (RAMP_SIZE - 1))
down = [t]
up = [t]
for _ in range(7):
down.append(np.nextafter(down[-1], np.float32(-1.0)))
up.append(np.nextafter(up[-1], np.float32(2.0)))
values += sorted(set(down + up))
values += [-0.5, -1.0e-7, 0.0, 1.0e-7, 1.0, 1.0000001, 1.5]
while len(values) < CASES:
values.append(float(rng.uniform(-0.25, 1.25)))
return f32(values[:CASES])
def ramp_entry(label, interpolation, stops, boundaries):
rng = rng_for("ramp-" + label)
column = ramp_cases(rng, boundaries)
images = pack_operands([column])
def build(tree, imgs):
node = tree.nodes.new("ShaderNodeValToRGB")
ramp = node.color_ramp
ramp.interpolation = interpolation
ramp.elements[0].position = stops[0][0]
ramp.elements[1].position = stops[-1][0]
for position, _ in stops[1:-1]:
ramp.elements.new(position)
for element, (_, red) in zip(ramp.elements, stops):
element.color = (red, 0.0, 0.0, 1.0)
tree.links.new(operand_sockets(tree, imgs, 1)[0], node.inputs["Fac"])
return [node.outputs["Color"]]
return {"function": "cycles_ramp_index", "node": "ShaderNodeValToRGB " + interpolation, "table_entries": RAMP_SIZE,
"stops": [[bits(position), bits(red)] for position, red in stops],
"cases": encode_cases([column], bake("ramp-" + label, images, build, 1))}
def family_ramp():
boundaries = [8 * j + 4 for j in range(32)]
return [
ramp_entry("constant", "CONSTANT", CONSTANT_STOPS, boundaries),
ramp_entry("linear", "LINEAR", [(0.0, 0.0), (1.0, 1.0)], list(range(1, RAMP_SIZE, 17))),
]
# ---- infinite operands ----
INF = float("inf")
# Rows of (function, node, operands) whose operands may be an infinity. The film writes 0 for an infinite operand and
# for an infinite or NaN result, so neither can travel through an image: the operand is made in-kernel (+-1 times
# exp(100), which overflows to +-inf) and the result is read back through three comparisons with 0.
INFINITE = [
("cycles_power", "POWER", [
(-1.0, INF), (-1.0, -INF), (-2.0, INF), (-2.0, -INF), (-0.5, INF), (-0.5, -INF), (-0.0, INF), (-0.0, -INF),
(0.5, INF), (0.5, -INF), (2.0, INF), (2.0, -INF), (1.0, INF), (0.0, INF), (0.0, -INF), (INF, 3.0), (-INF, 3.0),
(-INF, 2.0), (INF, -1.0), (-INF, -1.0), (-INF, INF), (INF, INF)]),
("cycles_modulo", "MODULO", [
(INF, 1.0), (-INF, 1.0), (INF, 3.0), (-INF, 3.0), (INF, 0.1), (-INF, 0.1), (INF, -2.0), (5.0, INF), (-5.0, INF),
(5.0, -INF), (INF, INF), (-INF, INF), (0.0, INF), (INF, 0.0)]),
]
# Map Range, Smooth Step: (value, from_min, from_max, to_min, to_max).
INFINITE_SMOOTHSTEP = [
(-INF, -INF, 1.0, 2.0, 3.0), (-INF, 1.0, -INF, 2.0, 3.0), (-INF, 1.0, 5.0, 2.0, 3.0), (-INF, -5.0, 1.0, 2.0, 3.0),
(INF, -5.0, 1.0, 2.0, 3.0), (INF, 1.0, -5.0, 2.0, 3.0), (INF, INF, 1.0, 2.0, 3.0), (INF, 1.0, INF, 2.0, 3.0),
(-INF, INF, 1.0, 2.0, 3.0), (-INF, 1.0, INF, 2.0, 3.0), (1.0, -INF, INF, 2.0, 3.0),
]
def result_token(value, greater, less, equal):
"""A result as the fixture writes it: float32 bits, or inf / -inf / nan where the film showed 0 and the comparisons say why."""
if bits(value) != "00000000" and bits(value) != "80000000":
return bits(value)
if equal:
return bits(value)
return "inf" if greater else ("-inf" if less else "nan")
def infinite_entry(function, node_label, build_node, rows):
count = len(rows[0])
value_columns = []
flag_columns = []
for k in range(count):
value_columns.append(f32([(0.0 if r >= len(rows) else (float(np.sign(rows[r][k])) if np.isinf(rows[r][k]) else rows[r][k])) for r in range(CASES)]))
flag_columns.append(f32([(0.0 if r >= len(rows) else (1.0 if np.isinf(rows[r][k]) else 0.0)) for r in range(CASES)]))
images = pack_operands(value_columns + flag_columns)
def build(tree, imgs):
sockets = operand_sockets(tree, imgs, 2 * count)
operands = []
for k in range(count):
hundred = tree.nodes.new("ShaderNodeMath")
hundred.operation = "MULTIPLY"
tree.links.new(sockets[count + k], hundred.inputs[0])
hundred.inputs[1].default_value = 100.0
overflow = tree.nodes.new("ShaderNodeMath")
overflow.operation = "EXPONENT"
tree.links.new(hundred.outputs[0], overflow.inputs[0])
made = tree.nodes.new("ShaderNodeMath")
made.operation = "MULTIPLY"
tree.links.new(sockets[k], made.inputs[0])
tree.links.new(overflow.outputs[0], made.inputs[1])
operands.append(made.outputs[0])
result = build_node(tree, operands)
probes = []
for operation in ("GREATER_THAN", "LESS_THAN", "COMPARE"):
probe = tree.nodes.new("ShaderNodeMath")
probe.operation = operation
tree.links.new(result, probe.inputs[0])
probe.inputs[1].default_value = 0.0
if operation == "COMPARE":
probe.inputs[2].default_value = 0.0
probes.append(probe.outputs[0])
return [result] + probes
value, greater, less, equal = bake(function + ".infinite", images, build, 4)
cases = []
for r, row in enumerate(rows):
operands = " ".join(("inf" if x == INF else "-inf" if x == -INF else bits(x)) for x in row)
cases.append("%s -> %s" % (operands, result_token(value[r], greater[r] > 0.5, less[r] > 0.5, equal[r] > 0.5)))
return {"function": function, "node": node_label, "cases": cases}
def family_infinite():
def math_node(operation):
def build(tree, operands):
node = tree.nodes.new("ShaderNodeMath")
node.operation = operation
for k, socket in enumerate(operands):
tree.links.new(socket, node.inputs[k])
return node.outputs[0]
return build
def smoothstep(tree, operands):
node = tree.nodes.new("ShaderNodeMapRange")
node.data_type = "FLOAT"
node.interpolation_type = "SMOOTHSTEP"
node.clamp = False
for identifier, socket in zip(["Value", "From Min", "From Max", "To Min", "To Max"], operands):
tree.links.new(socket, by_identifier(node.inputs, identifier))
return node.outputs["Result"]
functions = [infinite_entry(function, "ShaderNodeMath " + operation, math_node(operation), rows) for function, operation, rows in INFINITE]
functions.append(infinite_entry("cycles_map_range_smoothstep", "ShaderNodeMapRange SMOOTHSTEP", smoothstep, INFINITE_SMOOTHSTEP))
return functions
FAMILIES = {
"math": family_math,
"map-range": family_map_range,
"clamp": family_clamp,
"mix": family_mix,
"rgb-to-bw": family_rgb_to_bw,
"ramp": family_ramp,
"infinite": family_infinite,
}
def identity_check():
"""The bake must return an operand image bit for bit, or no fixture means anything."""
rng = np.random.default_rng(1)
column = f32(rng.uniform(-200, 200, CASES))
images = pack_operands([column])
def build(tree, imgs):
return [operand_sockets(tree, imgs, 1)[0]]
got = bake("identity", images, build, 1)[0]
if not np.array_equal(got.view(np.uint32), column.view(np.uint32)):
sys.stderr.write("cycles-oracle: the bake does not return its operands bit for bit\n")
sys.exit(3)
def kernel_check():
"""The fixtures witness the ruled reference: Cycles' formulas with one IEEE single rounding per operation.
Ruling cultmath-tapes:ruling:cycles-kernel-reference-ruled. Cycles' AVX2 CPU kernel is compiled with FMA, so
a - floor(a / b) b is one fused operation there and 10000 mod 0.1 is -1.5e-4; the SSE4.2 kernel has none, and
gives the unfused result 0 that CultMath's C# computes. Other kernels are other builds, measured under the
tolerance classes and never written here: run with CYCLES_CPU_NO_AVX2=1.
"""
a = f32([10000.0] * CASES)
b = f32([0.1] * CASES)
unfused = a - np.floor(a / b) * b
images = pack_operands([a, b])
def build(tree, imgs):
node = tree.nodes.new("ShaderNodeMath")
node.operation = "FLOORED_MODULO"
sockets = operand_sockets(tree, imgs, 2)
tree.links.new(sockets[0], node.inputs[0])
tree.links.new(sockets[1], node.inputs[1])
return [node.outputs[0]]
got = bake("kernel", images, build, 1)[0]
if not np.array_equal(got.view(np.uint32), unfused.astype(np.float32).view(np.uint32)):
sys.stderr.write("cycles-oracle: this Cycles CPU kernel fuses multiply-adds, which is not the reference of ruling cycles-kernel-reference-ruled; run with CYCLES_CPU_NO_AVX2=1\n")
sys.exit(4)
def main():
argv = sys.argv[sys.argv.index("--") + 1:]
out = argv[0]
wanted = argv[1:] or list(FAMILIES)
os.makedirs(out, exist_ok=True)
identity_check()
kernel_check()
header = {
"oracle": "tools/cycles-oracle/oracle.py (Blender %s, build %s, Cycles CPU, 1 sample, Emit bake, float Non-Color images)" % (PINNED_VERSION, PINNED_HASH),
"blender": PINNED_VERSION,
"build_hash": PINNED_HASH,
"platform": bpy.app.build_platform.decode() if isinstance(bpy.app.build_platform, bytes) else str(bpy.app.build_platform),
"encoding": "each case is 'operands -> results', every scalar a float32 bit pattern in hex, colours flattened as r g b",
}
for family in wanted:
document = dict(header)
document["family"] = family
document["functions"] = FAMILIES[family]()
text = json.dumps(document, indent=1) + "\n"
with open(os.path.join(out, family + ".json"), "w", newline="\n") as handle:
handle.write(text)
print("cycles-oracle: wrote", family, len(document["functions"]), "functions")
main()

View file

@ -7,9 +7,16 @@ files, which are licensed under the Mozilla Public License 2.0 (`MPL-2.0`):
- the Phacelle sources compiled into `Runtime/Plugins/CultMath.dll`
(`math.Phacelle.cs` and `CultPhasor.cs` in the GameCult/CultLib repository)
The package license expression is therefore `MIT AND MPL-2.0`, matching the
`GameCult.Math` NuGet package. MPL-2.0 is file-level: it applies to those files
and not to the rest of CultMath.
and for the Cycles node semantics files, which are licensed under the Apache
License 2.0 (`Apache-2.0`):
- `Shaders/CultMath.Cycles.hlsl`
- the Cycles sources compiled into `Runtime/Plugins/CultMath.dll`
(`math.Cycles.cs` in the GameCult/CultLib repository)
The package license expression is therefore `MIT AND MPL-2.0 AND Apache-2.0`,
matching the `GameCult.Math` NuGet package. MPL-2.0 and Apache-2.0 are file-level:
each applies to its files and not to the rest of CultMath.
The MPL-2.0 text is available from the Mozilla Foundation at
<https://www.mozilla.org/MPL/2.0/>. Source and modification history for the

View file

@ -10,7 +10,11 @@
// An upper bound on the spectral norm of the Hessian of cultmath_snoise(float3); provenance in
// math.Affine.cs (SNOISE_HESSIAN).
static const float CULTMATH_SNOISE_HESSIAN = 56.050385;
static const float CULTMATH_SNOISE_HESSIAN = 55.642143;
// An upper bound on the operator norm of the third-derivative tensor of cultmath_snoise(float3), the
// next order after CULTMATH_SNOISE_HESSIAN; provenance in math.Span.cs (SNOISE_THIRD).
static const float CULTMATH_SNOISE_THIRD = 536.9152;
float3 cultmath_af_point(float value) { return float3(value, 0.0, 0.0); }
float3 cultmath_af_symbol(float x0, float a) { return float3(x0, a, 0.0); }

View file

@ -0,0 +1,363 @@
#ifndef CULTMATH_CYCLES_HLSL
#define CULTMATH_CYCLES_HLSL
// SPDX-License-Identifier: Apache-2.0
//
// Cycles node semantics: what Blender's Cycles renderer computes for the Math, Map Range, Clamp, Mix and
// RGB to BW nodes and for a Color Ramp lookup, ported function by function from the Cycles kernel
// (intern/cycles of the Blender v5.2.2 tag; SPDX-FileCopyrightText: 2011-2022 Blender Foundation, Apache-2.0):
// kernel/svm/{math_util,map_range,clamp,mix,color_util,ramp,convert}.h, util/math_base.h, util/color.h and
// util/math_float3.h. Each function's comment names its Cycles source. Modified by GameCult: Cycles C++
// becomes HLSL, a function per node operation, and the node's socket defaults and clamp options are left to
// the caller. This file is Apache-2.0 (section 4: it was changed); CultMath.hlsl, which includes it after its
// own definitions, is MIT (see THIRD-PARTY-NOTICES.md). math.Cycles.cs mirrors it bit for bit.
//
// Operands are finite floats. NaN and infinite operands are outside the oracle's reach and the mirror's.
// FLT_EPSILON, the least epsilon a Compare node honours.
static const float CULTMATH_CYCLES_FLT_EPSILON = 1.1920929e-07;
// The scene-linear luminance coefficients Cycles reads from Blender 5.2.2's default OCIO config
// (kernel/film linear_rgb_to_gray). The oracle fixture pins them with a case per primary.
static const float CULTMATH_CYCLES_RGB_TO_Y_R = 0.212639093;
static const float CULTMATH_CYCLES_RGB_TO_Y_G = 0.715169132;
static const float CULTMATH_CYCLES_RGB_TO_Y_B = 0.0721927434;
// ---- Math node (kernel/svm/math_util.h svm_math; util/math_base.h) ----
// safe_divide
float cultmath_cycles_divide(float a, float b) { return b != 0.0 ? a / b : 0.0; }
// safe_powf with compatible_powf. A negative base takes an integral exponent's parity; a base below zero
// with a fractional exponent is 0.
float cultmath_cycles_power(float a, float b)
{
float whole = b >= 0.0 ? floor(b) : ceil(b);
if (a < 0.0 && b != whole)
return 0.0;
if (b == 0.0)
return 1.0;
if (a == 0.0)
return 0.0;
if (a < 0.0)
{
float magnitude = pow(-a, b);
// Odd exactly when the remainder is 1: an infinite exponent leaves NaN here and is even, as powf(a, +-inf) is never negative.
return b - 2.0 * floor(0.5 * b) == 1.0 ? -magnitude : magnitude;
}
return pow(a, b);
}
// safe_logf
float cultmath_cycles_logarithm(float a, float b)
{
if (a <= 0.0 || b <= 0.0)
return 0.0;
float denominator = log(b);
return denominator != 0.0 ? log(a) / denominator : 0.0;
}
// safe_sqrtf
float cultmath_cycles_sqrt(float a) { return sqrt(max(a, 0.0)); }
// inversesqrtf
float cultmath_cycles_inverse_sqrt(float a) { return a > 0.0 ? 1.0 / sqrt(a) : 0.0; }
// safe_modulo is fmodf, the remainder with the dividend's sign, exactly. GLSL has no fmod, and a - b trunc(a / b)
// is wrong where the quotient rounds up to an integer or the product rounds (3 mod 0.3 is 0.29999995, not 0).
// So this subtracts the largest power-of-two multiple of the divisor not above the remainder until the
// remainder is below the divisor: every step is an exact subtraction, as in fmod. The loops are bounded by the
// binades a float spans.
float cultmath_cycles_modulo(float a, float b)
{
float remainder = abs(a);
float divisor = abs(b);
for (int steps = 0; steps < 300 && remainder >= divisor && divisor > 0.0; steps++)
{
float multiple = divisor;
for (int doublings = 0; doublings < 300 && multiple * 2.0 <= remainder; doublings++)
multiple = multiple * 2.0;
remainder = remainder - multiple;
}
return b != 0.0 ? (a < 0.0 ? -remainder : remainder) : 0.0;
}
// safe_floored_modulo; a build that contracts it differs by a bound stated at cycles_floored_modulo in math.Cycles.cs and the README
float cultmath_cycles_floored_modulo(float a, float b) { return b != 0.0 ? a - floor(a / b) * b : 0.0; }
// wrapf (note the argument order: value, max, min); contraction bound as for floored_modulo
float cultmath_cycles_wrap(float value, float max_value, float min_value)
{
float range = max_value - min_value;
return range != 0.0 ? value - (range * floor((value - min_value) / range)) : min_value;
}
// floorf(safe_divide(a, b)) * b
float cultmath_cycles_snap(float a, float b) { return floor(cultmath_cycles_divide(a, b)) * b; }
// pingpongf
float cultmath_cycles_pingpong(float a, float b)
{
float scaled = (a - b) / (b * 2.0);
return b != 0.0 ? abs((scaled - floor(scaled)) * b * 2.0 - b) : 0.0;
}
// smoothminf
float cultmath_cycles_smooth_min(float a, float b, float k)
{
float h = max(k - abs(a - b), 0.0) / k;
return k != 0.0 ? min(a, b) - h * h * h * k * 0.16666667 : min(a, b);
}
// -smoothminf(-a, -b, k)
float cultmath_cycles_smooth_max(float a, float b, float k) { return -cultmath_cycles_smooth_min(-a, -b, k); }
// NODE_MATH_COMPARE
float cultmath_cycles_compare(float a, float b, float epsilon)
{
return (a == b || abs(a - b) <= max(epsilon, CULTMATH_CYCLES_FLT_EPSILON)) ? 1.0 : 0.0;
}
// NODE_MATH_ROUND
float cultmath_cycles_round(float a) { return floor(a + 0.5); }
// NODE_MATH_TRUNC
float cultmath_cycles_trunc(float a) { return a >= 0.0 ? floor(a) : ceil(a); }
// NODE_MATH_FRACTION
float cultmath_cycles_fract(float a) { return a - floor(a); }
// compatible_signf
float cultmath_cycles_sign(float a) { return a == 0.0 ? 0.0 : (a < 0.0 ? -1.0 : 1.0); }
// safe_asinf
float cultmath_cycles_arcsine(float a) { return asin(clamp(a, -1.0, 1.0)); }
// safe_acosf
float cultmath_cycles_arccosine(float a) { return acos(clamp(a, -1.0, 1.0)); }
// compatible_atan2 (a is y, b is x)
float cultmath_cycles_arctan2(float a, float b) { return (b == 0.0 && a == 0.0) ? 0.0 : atan2(a, b); }
// ---- Map Range node (kernel/svm/map_range.h svm_node_map_range) ----
// A Map Range node's Clamp option is a Clamp node of type Range on its result (MapRangeNode::expand):
// compose cultmath_cycles_clamp_range over these.
float cultmath_cycles_map_range_linear(float value, float from_min, float from_max, float to_min, float to_max)
{
float factor = (value - from_min) / (from_max - from_min);
return from_max != from_min ? to_min + factor * (to_max - to_min) : 0.0;
}
float cultmath_cycles_map_range_stepped(float value, float from_min, float from_max, float to_min, float to_max, float steps)
{
float factor = (value - from_min) / (from_max - from_min);
factor = steps > 0.0 ? floor(factor * (steps + 1.0)) / steps : 0.0;
return from_max != from_min ? to_min + factor * (to_max - to_min) : 0.0;
}
// The value itself, not a normalized one, goes through smoothstep(from_min, from_max, .), flipped when
// from_min > from_max (util/math_base.h smoothstep).
float cultmath_cycles_map_range_smoothstep(float value, float from_min, float from_max, float to_min, float to_max)
{
float low = min(from_min, from_max);
float high = max(from_min, from_max);
float t = (value - low) / (high - low);
float eased = value < low ? 0.0 : (value >= high ? 1.0 : (3.0 - 2.0 * t) * (t * t));
float factor = from_min > from_max ? 1.0 - eased : eased;
return from_max != from_min ? to_min + factor * (to_max - to_min) : 0.0;
}
// smootherstep of map_range.h, flipped when from_min > from_max.
float cultmath_cycles_map_range_smootherstep(float value, float from_min, float from_max, float to_min, float to_max)
{
float low = min(from_min, from_max);
float high = max(from_min, from_max);
float x = clamp(cultmath_cycles_divide(value - low, high - low), 0.0, 1.0);
float eased = x * x * x * (x * (x * 6.0 - 15.0) + 10.0);
float factor = from_min > from_max ? 1.0 - eased : eased;
return from_max != from_min ? to_min + factor * (to_max - to_min) : 0.0;
}
// ---- Clamp node (kernel/svm/clamp.h svm_node_clamp) ----
// Type Min Max
float cultmath_cycles_clamp_minmax(float value, float min_value, float max_value) { return clamp(value, min_value, max_value); }
// Type Range: the bounds swap when min_value > max_value.
float cultmath_cycles_clamp_range(float value, float min_value, float max_value)
{
return min_value > max_value ? clamp(value, max_value, min_value) : clamp(value, min_value, max_value);
}
// ---- Mix node (kernel/svm/mix.h, color_util.h) ----
// Factor clamping (svm_node_mix_color's saturatef) and result clamping (saturate) are the caller's.
// svm_node_mix_float
float cultmath_cycles_mix_float(float t, float a, float b) { return a * (1.0 - t) + b * t; }
// svm_node_mix_vector
float3 cultmath_cycles_mix_vector(float t, float3 a, float3 b) { return a * (float3(1.0, 1.0, 1.0) - t) + b * t; }
float3 cultmath_cycles_mix_blend(float t, float3 col1, float3 col2) { return col1 + t * (col2 - col1); }
float3 cultmath_cycles_mix_add(float t, float3 col1, float3 col2) { return col1 + t * ((col1 + col2) - col1); }
float3 cultmath_cycles_mix_mul(float t, float3 col1, float3 col2) { return col1 + t * (col1 * col2 - col1); }
float3 cultmath_cycles_mix_screen(float t, float3 col1, float3 col2)
{
float tm = 1.0 - t;
float3 one = float3(1.0, 1.0, 1.0);
return one - (float3(tm, tm, tm) + t * (one - col2)) * (one - col1);
}
float3 cultmath_cycles_mix_overlay(float t, float3 col1, float3 col2)
{
float tm = 1.0 - t;
return float3(
col1.x < 0.5 ? col1.x * (tm + 2.0 * t * col2.x) : 1.0 - (tm + 2.0 * t * (1.0 - col2.x)) * (1.0 - col1.x),
col1.y < 0.5 ? col1.y * (tm + 2.0 * t * col2.y) : 1.0 - (tm + 2.0 * t * (1.0 - col2.y)) * (1.0 - col1.y),
col1.z < 0.5 ? col1.z * (tm + 2.0 * t * col2.z) : 1.0 - (tm + 2.0 * t * (1.0 - col2.z)) * (1.0 - col1.z));
}
float3 cultmath_cycles_mix_sub(float t, float3 col1, float3 col2) { return col1 + t * ((col1 - col2) - col1); }
float3 cultmath_cycles_mix_div(float t, float3 col1, float3 col2)
{
float tm = 1.0 - t;
return float3(
col2.x != 0.0 ? tm * col1.x + t * col1.x / col2.x : col1.x,
col2.y != 0.0 ? tm * col1.y + t * col1.y / col2.y : col1.y,
col2.z != 0.0 ? tm * col1.z + t * col1.z / col2.z : col1.z);
}
float3 cultmath_cycles_mix_diff(float t, float3 col1, float3 col2) { return col1 + t * (abs(col1 - col2) - col1); }
float3 cultmath_cycles_mix_exclusion(float t, float3 col1, float3 col2)
{
return max(col1 + t * ((col1 + col2 - 2.0 * col1 * col2) - col1), float3(0.0, 0.0, 0.0));
}
float3 cultmath_cycles_mix_dark(float t, float3 col1, float3 col2) { return col1 + t * (min(col1, col2) - col1); }
float3 cultmath_cycles_mix_light(float t, float3 col1, float3 col2) { return col1 + t * (max(col1, col2) - col1); }
float3 cultmath_cycles_mix_dodge(float t, float3 col1, float3 col2)
{
float3 divisor = float3(1.0, 1.0, 1.0) - t * col2;
return float3(
col1.x != 0.0 ? (divisor.x <= 0.0 ? 1.0 : min(col1.x / divisor.x, 1.0)) : col1.x,
col1.y != 0.0 ? (divisor.y <= 0.0 ? 1.0 : min(col1.y / divisor.y, 1.0)) : col1.y,
col1.z != 0.0 ? (divisor.z <= 0.0 ? 1.0 : min(col1.z / divisor.z, 1.0)) : col1.z);
}
float3 cultmath_cycles_mix_burn(float t, float3 col1, float3 col2)
{
float tm = 1.0 - t;
float3 divisor = tm + t * col2;
float3 burnt = float3(1.0, 1.0, 1.0) - (float3(1.0, 1.0, 1.0) - col1) / divisor;
return float3(
divisor.x <= 0.0 ? 0.0 : clamp(burnt.x, 0.0, 1.0),
divisor.y <= 0.0 ? 0.0 : clamp(burnt.y, 0.0, 1.0),
divisor.z <= 0.0 ? 0.0 : clamp(burnt.z, 0.0, 1.0));
}
// rgb_to_hsv of util/color.h
float3 cultmath_cycles_rgb_to_hsv(float3 rgb)
{
float cmax = max(rgb.x, max(rgb.y, rgb.z));
float cmin = min(rgb.x, min(rgb.y, rgb.z));
float cdelta = cmax - cmin;
float s = cmax != 0.0 ? cdelta / cmax : 0.0;
float3 c = (float3(cmax, cmax, cmax) - rgb) / cdelta;
float h = rgb.x == cmax ? c.z - c.y : (rgb.y == cmax ? 2.0 + c.x - c.z : 4.0 + c.y - c.x);
h = h * 0.16666667; // Cycles' kernel is built with reciprocal math: h /= 6.0f computes h * (1 / 6.0f).
h = h < 0.0 ? h + 1.0 : h;
return float3(s != 0.0 ? h : 0.0, s, cmax);
}
// hsv_to_rgb of util/color.h
float3 cultmath_cycles_hsv_to_rgb(float3 hsv)
{
float h = hsv.x == 1.0 ? 0.0 : hsv.x;
h = h * 6.0;
float i = floor(h);
float f = h - i;
float p = hsv.z * (1.0 - hsv.y);
float q = hsv.z * (1.0 - (hsv.y * f));
float t = hsv.z * (1.0 - (hsv.y * (1.0 - f)));
float3 rgb = i == 0.0 ? float3(hsv.z, t, p) :
(i == 1.0 ? float3(q, hsv.z, p) :
(i == 2.0 ? float3(p, hsv.z, t) :
(i == 3.0 ? float3(p, q, hsv.z) :
(i == 4.0 ? float3(t, p, hsv.z) : float3(hsv.z, p, q)))));
return hsv.y != 0.0 ? rgb : float3(hsv.z, hsv.z, hsv.z);
}
float3 cultmath_cycles_mix_hue(float t, float3 col1, float3 col2)
{
float3 hsv2 = cultmath_cycles_rgb_to_hsv(col2);
float3 hsv = cultmath_cycles_rgb_to_hsv(col1);
float3 shifted = cultmath_cycles_hsv_to_rgb(float3(hsv2.x, hsv.y, hsv.z));
return hsv2.y != 0.0 ? col1 + t * (shifted - col1) : col1;
}
float3 cultmath_cycles_mix_sat(float t, float3 col1, float3 col2)
{
float tm = 1.0 - t;
float3 hsv = cultmath_cycles_rgb_to_hsv(col1);
float3 hsv2 = cultmath_cycles_rgb_to_hsv(col2);
return hsv.y != 0.0 ? cultmath_cycles_hsv_to_rgb(float3(hsv.x, tm * hsv.y + t * hsv2.y, hsv.z)) : col1;
}
float3 cultmath_cycles_mix_val(float t, float3 col1, float3 col2)
{
float tm = 1.0 - t;
float3 hsv = cultmath_cycles_rgb_to_hsv(col1);
float3 hsv2 = cultmath_cycles_rgb_to_hsv(col2);
return cultmath_cycles_hsv_to_rgb(float3(hsv.x, hsv.y, tm * hsv.z + t * hsv2.z));
}
float3 cultmath_cycles_mix_color(float t, float3 col1, float3 col2)
{
float3 hsv2 = cultmath_cycles_rgb_to_hsv(col2);
float3 hsv = cultmath_cycles_rgb_to_hsv(col1);
float3 shifted = cultmath_cycles_hsv_to_rgb(float3(hsv2.x, hsv2.y, hsv.z));
return hsv2.y != 0.0 ? col1 + t * (shifted - col1) : col1;
}
float3 cultmath_cycles_mix_soft(float t, float3 col1, float3 col2)
{
float tm = 1.0 - t;
float3 one = float3(1.0, 1.0, 1.0);
float3 scr = one - (one - col2) * (one - col1);
return tm * col1 + t * ((one - col1) * col2 * col1 + col1 * scr);
}
float3 cultmath_cycles_mix_linear(float t, float3 col1, float3 col2)
{
return col1 + t * (2.0 * col2 + float3(-1.0, -1.0, -1.0));
}
// ---- RGB to BW node (kernel/svm/convert.h NODE_CONVERT_CF) ----
float cultmath_cycles_rgb_to_bw(float3 color)
{
return color.x * CULTMATH_CYCLES_RGB_TO_Y_R + color.y * CULTMATH_CYCLES_RGB_TO_Y_G + color.z * CULTMATH_CYCLES_RGB_TO_Y_B;
}
// ---- Color Ramp lookup (kernel/svm/ramp.h rgb_ramp_lookup, without extrapolation) ----
// Where a ramp of `size` table entries is read at t: (index, weight), the lower entry and the weight of the
// next one. The colour is table[index] when weight is 0 and (1 - weight) table[index] + weight table[index + 1]
// otherwise. The ramp table itself is the caller's; Blender's holds 257 entries, the ramp sampled at i / 256.
float2 cultmath_cycles_ramp_index(float t, int size)
{
float f = (t > 0.0 ? (t < 1.0 ? t : 1.0) : 0.0) * (float)(size - 1);
int index = clamp((int)f, 0, size - 1);
float lower = (float)index;
return float2(lower, f - lower);
}
#endif

View file

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 477bb38d537244b78e3eaec093530bcc
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -228,6 +228,97 @@ float4 cultmath_snoise_grad(float3 value)
return float4(grad, value2);
}
// Analytic Hessian of cultmath_snoise(float3); see the C# math.snoise_hessian comment for the
// derivation. Every local up through p0..p3 and x0..x3 is cultmath_snoise_grad's own. The matrix is
// built from nine scalars, which read as rows in HLSL and as columns in GLSL; it is symmetric, so the
// two agree.
float3x3 cultmath_snoise_hessian(float3 value)
{
float2 c = float2(1.0 / 6.0, 1.0 / 3.0);
float3 i = floor(value + dot(value, c.yyy));
float3 x0 = value - i + dot(i, c.xxx);
float3 g = float3(step(x0.y, x0.x), step(x0.z, x0.y), 1.0 - step(x0.z, x0.x));
float3 l = 1.0 - g;
float3 i1 = min(g.xyz, l.zxy);
float3 i2 = max(g.xyz, l.zxy);
float3 x1 = x0 - i1 + c.xxx;
float3 x2 = x0 - i2 + c.yyy;
float3 x3 = x0 - 0.5;
i = cultmath_snoise_mod289(i);
float4 p = cultmath_snoise_permute(cultmath_snoise_permute(cultmath_snoise_permute(
i.z + float4(0.0, i1.z, i2.z, 1.0)) + i.y + float4(0.0, i1.y, i2.y, 1.0)) + i.x + float4(0.0, i1.x, i2.x, 1.0));
const float n_ = 0.142857142857;
float3 ns = float3(2.0 * n_, 0.5 * n_ - 1.0, n_);
float4 j = p - 49.0 * floor(p * ns.z * ns.z);
float4 x_ = floor(j * ns.z);
float4 y_ = floor(j - 7.0 * x_);
float4 x = x_ * ns.x + ns.yyyy;
float4 y = y_ * ns.x + ns.yyyy;
float4 h = 1.0 - abs(x) - abs(y);
float4 b0 = float4(x.xy, y.xy);
float4 b1 = float4(x.zw, y.zw);
float4 s0 = floor(b0) * 2.0 + 1.0;
float4 s1 = floor(b1) * 2.0 + 1.0;
float4 sh = -step(h, float4(0.0, 0.0, 0.0, 0.0));
float4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;
float4 a1 = b1.xzyw + s1.xzyw * sh.zzww;
float3 p0 = float3(a0.xy, h.x);
float3 p1 = float3(a0.zw, h.y);
float3 p2 = float3(a1.xy, h.z);
float3 p3 = float3(a1.zw, h.w);
float4 norm = 1.79284291400159 - 0.85373472095314 * float4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3));
p0 *= norm.x;
p1 *= norm.y;
p2 *= norm.z;
p3 *= norm.w;
float4 m0 = max(0.5 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);
float4 m2 = m0 * m0;
float4 m3 = m2 * m0;
float4 px = float4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3));
float4 wide = 48.0 * m2 * px;
float4 narrow = 8.0 * m3;
float4 cxx = float4(x0.x, x1.x, x2.x, x3.x);
float4 cxy = float4(x0.y, x1.y, x2.y, x3.y);
float4 cxz = float4(x0.z, x1.z, x2.z, x3.z);
float4 cpx = float4(p0.x, p1.x, p2.x, p3.x);
float4 cpy = float4(p0.y, p1.y, p2.y, p3.y);
float4 cpz = float4(p0.z, p1.z, p2.z, p3.z);
float hxx = 105.0 * (dot(wide * cxx, cxx) - dot(narrow, 2.0 * cpx * cxx + px));
float hyy = 105.0 * (dot(wide * cxy, cxy) - dot(narrow, 2.0 * cpy * cxy + px));
float hzz = 105.0 * (dot(wide * cxz, cxz) - dot(narrow, 2.0 * cpz * cxz + px));
float hxy = 105.0 * (dot(wide * cxx, cxy) - dot(narrow, cpx * cxy + cpy * cxx));
float hxz = 105.0 * (dot(wide * cxx, cxz) - dot(narrow, cpx * cxz + cpz * cxx));
float hyz = 105.0 * (dot(wide * cxy, cxz) - dot(narrow, cpy * cxz + cpz * cxy));
return float3x3(hxx, hxy, hxz, hxy, hyy, hyz, hxz, hyz, hzz);
}
// The integral over [t0, t1] of clamp(a + b t, lo, hi); see the C# math.integral_clamp_linear comment.
float cultmath_integral_clamp_linear(float a, float b, float lo, float hi, float t0, float t1)
{
if (b == 0.0)
return clamp(a, lo, hi) * (t1 - t0);
lo = min(lo, hi);
float direction = t1 < t0 ? -1.0 : 1.0;
float start = min(t0, t1);
float stop = max(t0, t1);
float atLo = (lo - a) / b;
float atHi = (hi - a) / b;
float enter = clamp(min(atLo, atHi), start, stop);
float leave = clamp(max(atLo, atHi), start, stop);
float before = b > 0.0 ? lo : hi;
float after = b > 0.0 ? hi : lo;
float total = before * (enter - start) + (a + b * (0.5 * (enter + leave))) * (leave - enter) + after * (stop - leave);
return direction * total;
}
// Octave sum of cultmath_snoise_grad (invariant 8); see the C# math.fbm_grad comment for the
// per-octave frequency/amplitude derivation and why octaves is clamped.
float4 cultmath_fbm_grad(float3 p, int octaves, float lacunarity, float gain)
@ -509,6 +600,7 @@ CultCellular cultmath_cellular(float3 p)
#include "CultMath.Phacelle.hlsl"
#include "CultMath.Interval.hlsl"
#include "CultMath.Cycles.hlsl"
#include "CultMath.Affine.hlsl"
float cultmath_value_noise(float2 position)

View file

@ -22,6 +22,35 @@ permutation and scale as `snoise(float3)`.
- Upstream: <https://github.com/ashima/webgl-noise>
- License: MIT.
## Cycles node semantics
`math.cycles_*` and `cultmath_cycles_*` port what Blender's Cycles renderer
computes for the Math, Map Range, Clamp, Mix and RGB to BW nodes and for a Color
Ramp lookup. Each function's comment names the Cycles file it follows, all from
`intern/cycles` at the Blender `v5.2.2` tag: `kernel/svm/math_util.h`,
`kernel/svm/map_range.h`, `kernel/svm/clamp.h`, `kernel/svm/mix.h`,
`kernel/svm/color_util.h`, `kernel/svm/ramp.h`, `kernel/svm/convert.h`,
`util/math_base.h`, `util/math_float3.h` and `util/color.h`. The code was
changed: Cycles C++ became C# and HLSL, one function per node operation, with
the nodes' socket defaults and clamp options left to the caller, and the modulo
is the quotient form every CultMath target shares rather than `fmodf`. Nothing
was read from Blender's GPL sources (`source/blender/gpu`, `source/blender/blenlib`).
- Copyright 2011-2022 Blender Foundation.
- Upstream: <https://projects.blender.org/blender/blender> (`intern/cycles`).
- License: Apache-2.0 (<https://www.apache.org/licenses/LICENSE-2.0>), which is
per-file here: it covers `src/CultMath/math.Cycles.cs`,
`shaders/CultMath.Cycles.hlsl` and the Unity copy of that include, and
`shaders/CultMath.Cycles.glsl`, which is generated from that include. Each
carries the Apache-2.0 header and this attribution. The rest of CultMath, the
generated GLSL library included, is MIT or MPL-2.0 as above, so the
`GameCult.Math` NuGet package and the `org.gamecult.cultmath` Unity package
both declare `MIT AND MPL-2.0 AND Apache-2.0` and ship this file.
- The test fixtures under `tests/CultMath.Tests/fixtures/cycles-oracle` are
results of running Blender 5.2.2 through `tools/cycles-oracle/oracle.py`
(GPL-3.0-or-later, a Blender Python script, shipped neither in the NuGet
package nor in the Unity package).
## Phacelle Noise
`math.phacelle` and `cultmath_phacelle` follow Rune Skovbo Johansen's Phacelle

View file

@ -4,7 +4,7 @@
"version": "0.4.1",
"unity": "2021.3",
"description": "Precompiled CultMath numeric primitives and matching HLSL semantics for GameCult Unity runtimes.",
"license": "MIT AND MPL-2.0",
"license": "MIT AND MPL-2.0 AND Apache-2.0",
"author": {
"name": "GameCult"
},