From ebe35e2ef711eee4851ae274b6fa45647ae3a9e6 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 18 Nov 2026 09:44:30 -0500 Subject: [PATCH] Match runtime pixel logarithms and powers of two across the normalized range --- crates/nodes/src/function/arithmetic.rs | 3 + .../nodes/src/function/binary_exponential.rs | 71 +++++++++++++++++++ crates/nodes/src/function/fixed_point.rs | 35 +++++++++ crates/nodes/src/function/mod.rs | 1 + crates/nodes/src/function/tests.rs | 24 +++++++ crates/nodes/src/function/trigonometry.rs | 38 +++------- docs/parity-fixes.md | 23 ++++++ docs/sbs-root-nodes.md | 2 +- 8 files changed, 168 insertions(+), 29 deletions(-) create mode 100644 crates/nodes/src/function/binary_exponential.rs diff --git a/crates/nodes/src/function/arithmetic.rs b/crates/nodes/src/function/arithmetic.rs index c80a4a4..d493cc2 100644 --- a/crates/nodes/src/function/arithmetic.rs +++ b/crates/nodes/src/function/arithmetic.rs @@ -91,9 +91,12 @@ pub(crate) fn evaluate(instruction: &super::instruction::Instruction, args: &[Va "ceil" => left.ceil(), "sqrt" => left.sqrt(), "exp" => left.exp(), + "log" if pixel_math => super::binary_exponential::log2(left) * std::f32::consts::LN_2, "log" => left.ln(), + "log2" if pixel_math => super::binary_exponential::log2(left), "log2" => left.log2(), "pow" => left.powf(right), + "pow2" if pixel_math => super::binary_exponential::exp2(left), "pow2" => left.exp2(), "sin" => angle_component(left, false), "cos" => angle_component(left, true), diff --git a/crates/nodes/src/function/binary_exponential.rs b/crates/nodes/src/function/binary_exponential.rs new file mode 100644 index 0000000..9daa8c8 --- /dev/null +++ b/crates/nodes/src/function/binary_exponential.rs @@ -0,0 +1,71 @@ +//! Logarithm and exponential for runtime pixel expressions. + +use super::fixed_point::{Quadratic, square_fraction, truncate_float}; +use std::{f64::consts::LN_2, sync::LazyLock}; + +const WIDTH: f64 = 1.0 / 64.0; +const MANTISSA: u32 = 0x7f_ffff; + +// Scale each fitted coefficient to integer units of 2^-38 for evaluation. +static LOGARITHMS: LazyLock<[Quadratic; 64]> = LazyLock::new(|| { + std::array::from_fn(|index| { + let start = 1.0 + index as f64 * WIDTH; + let reciprocal = WIDTH / (start + 0.5 * WIDTH); + let derivatives = [reciprocal / LN_2, -reciprocal.powi(2) / LN_2, 2.0 * reciprocal.powi(3) / LN_2]; + let mut bin = Quadratic::fit(|t| (start + t * WIDTH).log2(), derivatives, [26, 21, 22]); + bin.constant = (bin.constant + 3) << 12; + bin.curvature *= 2; + bin + }) +}); + +static EXPONENTIALS: LazyLock<[Quadratic; 64]> = LazyLock::new(|| { + std::array::from_fn(|index| { + let start = index as f64 * WIDTH; + let mid = (start + 0.5 * WIDTH).exp2(); + let rate = WIDTH * LN_2; + let derivatives = [mid * rate, mid * rate.powi(2), mid * rate.powi(3)]; + let mut bin = Quadratic::fit(|t| (start + t * WIDTH).exp2(), derivatives, [25, 21, 23]); + bin.constant = (bin.constant + 2) << 13; + bin + }) +}); + +fn interpolate(bins: &[Quadratic; 64], bits: u32) -> i64 { + let bin = &bins[((bits & MANTISSA) >> 17) as usize]; + let fraction = bits & 0x1_ffff; + bin.constant + bin.slope * i64::from(fraction) + bin.curvature * i64::from(square_fraction(fraction >> 1)) +} + +pub(super) fn log2(value: f32) -> f32 { + if value.abs() < f32::MIN_POSITIVE { + return f32::NEG_INFINITY; + } + if value <= 0.0 || !value.is_finite() || value == 1.0 { + return value.log2(); + } + let bits = value.to_bits(); + let exponent = i64::from(bits >> 23) - 127; + let fixed = (exponent << 38) + interpolate(&LOGARITHMS, bits); + // A two-bit truncation precedes float normalization. Negative results round one such unit higher. + let rounded = (fixed + 837 + if fixed < 0 { 4 } else { 0 }) & !3; + truncate_float(rounded as f64 / 274_877_906_944.0) +} + +pub(super) fn exp2(value: f32) -> f32 { + if value < -126.0 { + return 0.0; + } + if value >= 128.0 || value.is_nan() { + return value.exp2(); + } + let mut fixed = (value * 8_388_608.0) as i32; + // Negative fractional arguments use the one's complement of the fractional magnitude. + if value < 0.0 && fixed as u32 & MANTISSA != 0 { + fixed -= 1; + } + let exponent = (fixed >> 23) + 126; + let polynomial = interpolate(&EXPONENTIALS, fixed as u32); + let significand = ((polynomial + 16_384 - 2_078) >> 15) as u32; + f32::from_bits(((exponent as u32) << 23) + significand) +} diff --git a/crates/nodes/src/function/fixed_point.rs b/crates/nodes/src/function/fixed_point.rs index 316cb95..eddaf53 100644 --- a/crates/nodes/src/function/fixed_point.rs +++ b/crates/nodes/src/function/fixed_point.rs @@ -1,3 +1,38 @@ +pub(super) struct Quadratic { + pub constant: i64, + pub slope: i64, + pub curvature: i64, +} + +impl Quadratic { + // Fit one interval in local coordinates t=0..1. The derivatives are taken at t=1/2. + pub fn fit(value: impl Fn(f64) -> f64, [first, second, third]: [f64; 3], [a, b, c]: [i32; 3]) -> Self { + let curvature_scale = 2_f64.powi(c); + let ratio = 1_i64 << (c - b); + // On [-1/2,1/2] the linear minimax approximation of the centered cubic is 3t/16. + let center_slope = curvature_scale * (first + third / 32.0); + let slope = ((center_slope - curvature_scale * second * 0.5) / ratio as f64).round() as i64; + let curvature = center_slope.round() as i64 - ratio * slope; + let constant_scale = 2_f64.powi(a); + let linear = 2_f64.powi(a - b) * slope as f64; + let square = 2_f64.powi(a - c) * curvature as f64; + let mut low = f64::INFINITY; + let mut high = f64::NEG_INFINITY; + for step in 0..=64 { + let t = f64::from(step) / 64.0; + let residual = constant_scale * value(t) - linear * t - square * t * t; + low = low.min(residual); + high = high.max(residual); + } + Self { constant: ((low + high) * 0.5).round() as i64, slope, curvature } + } +} + +pub(super) fn truncate_float(value: f64) -> f32 { + let nearest = value as f32; + if f64::from(nearest).abs() > value.abs() { f32::from_bits(nearest.to_bits().saturating_sub(1)) } else { nearest } +} + // Square a 16-bit fraction, retaining partial products in the top 15 fractional columns. // A pair of distinct bits contributes twice. A diagonal bit contributes once. pub(super) fn square_fraction(fraction: u32) -> u32 { diff --git a/crates/nodes/src/function/mod.rs b/crates/nodes/src/function/mod.rs index 5cad1f2..2cdbedf 100644 --- a/crates/nodes/src/function/mod.rs +++ b/crates/nodes/src/function/mod.rs @@ -9,6 +9,7 @@ const MAX_CALL_DEPTH: usize = 16; const DEFAULT_LOOP_LIMIT: i32 = 32; mod arithmetic; +mod binary_exponential; mod catalog; mod compile; mod evaluation_context; diff --git a/crates/nodes/src/function/tests.rs b/crates/nodes/src/function/tests.rs index 741d627..58b87b0 100644 --- a/crates/nodes/src/function/tests.rs +++ b/crates/nodes/src/function/tests.rs @@ -48,6 +48,30 @@ fn scoped_operation(scope: super::FunctionScope, op: &str, operands: &[Value], l compile(&graph, 0).unwrap().evaluate_pixel(&context, &mut EvaluationState::default()).unwrap() } +#[test] +fn runtime_pixel_logarithms_and_powers_of_two() { + for (op, input, expected) in [ + ("log2", 0.5, 0xbf7ffffe), + ("log2", 0.7, 0xbf03bb10), + ("log2", 1.0, 0), + ("log2", f32::MIN_POSITIVE, 0xc2fbffff), + ("log", 0.5, 0xbf317217), + ("pow2", -0.5, 0x3f3504f2), + ("pow2", 0.5, 0x3fb504f3), + ("pow2", 1.375, 0x4025fed7), + ("pow2", -126.0, 0x00800000), + ("pow2", -127.0, 0), + ("pow2", 128.0, 0x7f800000), + ] { + let Value::Float(value) = pixel_operation(op, &[Value::Float(input)], false) else { panic!("expected a scalar") }; + assert_eq!(value.to_bits(), expected, "{op}({input})"); + } + for scope in [super::FunctionScope::Node, super::FunctionScope::ValueProcessor, super::FunctionScope::FxMap] { + assert_eq!(scoped_operation(scope, "log2", &[Value::Float(0.5)], false), Value::Float(-1.0)); + } + assert_eq!(pixel_operation("log2", &[Value::Float(0.5)], true), Value::Float(-1.0)); +} + #[test] fn runtime_pixel_sine_and_cosine_reduce_the_phase_before_interpolation() { use std::f32::consts::{FRAC_PI_4, TAU}; diff --git a/crates/nodes/src/function/trigonometry.rs b/crates/nodes/src/function/trigonometry.rs index d048dbc..014cd0c 100644 --- a/crates/nodes/src/function/trigonometry.rs +++ b/crates/nodes/src/function/trigonometry.rs @@ -1,42 +1,25 @@ //! Runtime sine and cosine for pixel and uniform function scopes. -use super::fixed_point::square_fraction; +use super::fixed_point::{Quadratic, square_fraction, truncate_float}; use std::sync::LazyLock; const QUARTER: u32 = 1 << 23; -struct Polynomial { - constant: i64, - slope: i64, - curvature: i64, -} - // Derive each quadratic from the sine function over one 64th of the quadrant. -static QUARTER_WAVE: LazyLock<[Polynomial; 64]> = LazyLock::new(|| std::array::from_fn(quarter_polynomial)); +static QUARTER_WAVE: LazyLock<[Quadratic; 64]> = LazyLock::new(|| std::array::from_fn(quarter_polynomial)); -fn quarter_polynomial(index: usize) -> Polynomial { +fn quarter_polynomial(index: usize) -> Quadratic { let width = std::f64::consts::PI / 128.0; let (sine, cosine) = ((index as f64 + 0.5) * width).sin_cos(); - // The linear minimax approximation of the centered cubic on [-1/2, 1/2] is 3t/16. - let center_slope = 4_194_304.0 * (width * cosine - width.powi(3) * cosine / 32.0); - let slope = ((center_slope + 4_194_304.0 * width * width * sine * 0.5) / 4.0).round() as i64; - let curvature = center_slope.round() as i64 - 4 * slope; - let mut low = f64::INFINITY; - let mut high = f64::NEG_INFINITY; - for step in 0..=64 { - let t = f64::from(step) / 64.0; - let residual = 33_554_432.0 * ((index as f64 + t) * width).sin() - 32.0 * slope as f64 * t - 8.0 * curvature as f64 * t * t; - low = low.min(residual); - high = high.max(residual); - } - let midpoint = ((low + high) * 0.5).round() as i64; - let constant = match index { + let derivatives = [width * cosine, -width.powi(2) * sine, -width.powi(3) * cosine]; + let mut polynomial = Quadratic::fit(|t| ((index as f64 + t) * width).sin(), derivatives, [25, 20, 22]); + polynomial.constant = match index { 0 => 0, // These three measured intervals start one constant unit below the rounded midpoint. - 2 | 18 | 46 => midpoint - 1, - _ => midpoint, + 2 | 18 | 46 => polynomial.constant - 1, + _ => polynomial.constant, }; - Polynomial { constant, slope, curvature } + polynomial } // One turn spans 25 bits. Retaining the product word before the exponent shift @@ -72,8 +55,7 @@ fn pixel_component(angle: f32, cosine: bool) -> f32 { let fixed = (bin.constant << 12) + bin.slope * i64::from(fraction) + bin.curvature * i64::from(square_fraction(fraction >> 1)); // The quarter-wave magnitude truncates to the next representable float below the polynomial. let exact = fixed as f64 / 137_438_953_472.0; - let nearest = exact as f32; - let magnitude = if f64::from(nearest) > exact { f32::from_bits(nearest.to_bits().saturating_sub(1)) } else { nearest }; + let magnitude = truncate_float(exact); if (phase & (2 * QUARTER) != 0) ^ (!cosine && angle.is_sign_negative()) { -magnitude } else { magnitude } } diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index cf48084..0bf4fbb 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -224,6 +224,29 @@ For normalized distance at 16² and 64² use a grayscale byte field (17x+7y+3xy) The [wired bridge distance](#height-distance-texture-mapping-skew-and-weave) root was also retested. With count two, 32² and 64² now match 1,024/1,024 and 4,096/4,096. The 16² case matches 252/256 with maximum 5.96046448e−8. All three count-one cases remain exact. +### Runtime pixel logarithms and powers of two + +An original pixel function returns (log2(1+t), 2ᵗ, 2⁻ᵗ, log2((1+t)/2)). Across eight 1024² RGBA32F images all **8,388,608 pixels and 33,554,432 components** match bit for bit, maximum error zero. For image j=0..7, let t=(j×2²⁰+i)/2²³ with row-major index i, seed 251. Supply the four arguments as a linear RGBA32F input and sample at pixel centers with nearest filtering. This exhausts all float32 mantissas in [1,2) for the logarithm and all 23-bit fixed fractions in [0,1) for the exponential. + +| Additional per-pixel controls | Cases | Exact / compared | Maximum finite error | +|---|---:|---:|---:| +| Logarithm base two and power of two on the 256² fields below | 22 | 1,441,792/1,441,792 | 0 | +| Natural logarithm, log2(x)×float32(ln(2)), and 2^(log2(x)×y) on signed and exceptional pairs | 6 | 393,216/393,216 | 0 | +| Both signs of zero, subnormals, smallest normals and NaN payloads, three operations at 16² | 3 | 768/768 | 0 | +| Exposed scalar passed directly to the pixel function, three operations | 28 | 7,168/7,168 | 0 | + +For the 256² fields use the row-major 32-bit hash h from [the runtime trigonometry controls](#runtime-pixel-sine-cosine-and-atlas-rotation). At seed 239, set (x,y)=(1+t,t) with the 23-bit numerator of t equal to 128i, i, h mod 2²³, or 0x3a0000+i. For the signed field use x=4h/2³²−2 and y=12i/65535−6. The exceptional field cycles x through NaN, −∞, −2, −1, −0, +0, 2⁻¹⁴⁰, 2⁻¹²⁶, .25, .5, 1, 2, 2²⁰, +∞. Repeat each y for 17 pixels in the cycle NaN, −∞, −129, −126, −2, −1, −.5, −0, +0, .5, 1, 2, 3, 127, 128, +∞. Round inputs to float32 before sampling. + +At seed 193, the full-range field combines exponent bits i mod 255 and mantissa h mod 2²³ for x, and uses y=300h/2³²−150. The power-boundary field starts at float bit pattern ((i mod 254)+1)×2²³ for x and at float32((i mod 255)−127) for y, then offsets their bit patterns by (floor(i/254) mod 17)−8 and (floor(i/255) mod 17)−8 respectively. For the near-one field offset the bit pattern of 1 by i−32768 and set y=(i−32768)/2³¹. A fourth field uses x=.5+1.5h/2³² and y=2h/2³²−1. The last cycles x through (.5,.7,.625,.2,.8,1,1.125,2,0,−1,−.7) and repeats each successive y in (0,1,2,3,4,5,6,7,.5,1.375,−1) for 13 pixels. For the 16² exceptional controls, cycle float32 input bits through 00000001, 007fffff, 80000001, 807fffff, 00000000, 80000000, 00800000, 80800000, 7fc12345 and ffc12345 at seed 17. + +Both pixel operations evaluate a quadratic over one of 64 intervals. The coefficients come from the mathematical functions and the sampled rounding thresholds. The runtime logarithm of .5 has bits `bf7ffffe`, the literal result has bits `bf800000`. The pixel natural logarithm multiplies the base-two result by float32(ln(2)). Replaying the 30 existing sine and cosine comparisons after sharing the polynomial fitting routine gives 1,443,840/1,443,840 pixels, maximum zero. + +For the exposed scalar controls use .5, .625, .7, 1, 1.125, 1.25, 2, 4 and 1.375 for either logarithm. For the exponential use −2, −1, −.625, −.5, −.125, 0, .5, 1, 1.375 and 2. Cycle seeds 71, 137 and 313 at 16². In a separate Value Processor, the same arguments match 5/9 typed base-two logarithms, 5/9 natural logarithms and 9/10 powers of two. Maximum errors are 5.96046448e−8, 2.98023224e−8 and 2.38418579e−7 respectively. These uniform operations remain open. + +Literal-only pixel graphs at 16², seed 23, give 512/768 exact pixels for each logarithm on .5, .7 and 1. At .7 their maximum errors are 5.96046448e−8 for log2 and 2.98023224e−8 for ln. Literal powers of two match 768/768 at −.5, 1.375 and 2, maximum zero. + +The shared-lookup ridged root still matches 5,160/16,384 at changed roughness in F32, maximum 1.78813934e−7. Its one-octave .7 control still matches 1,847/4,096, maximum 2.38418579e−7. For positive normal x on the signed field, the reference's general power agrees with exp(y×ln(x)) on all 32,614 pixels. On .7 with exponent 1 it returns `3f333334`. Further work on general power and natural exponential is tracked with the [octave controls](#ridged-noise-octave-isolation). + ### Ridged noise octave isolation Use the position ramp and original 1024×16 lookup under [basic and ridged 3D Perlin](#basic-and-ridged-3d-perlin). Retain the 128² position input and cook 64² LUM32F at seed 42. Each cell gives exact pixels out of 4,096 and maximum absolute error. Roughness .5 with one or two active levels matches every pixel. Roughness .7 already differs with a single active level. diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index 4e1f464..2764e90 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -48,7 +48,7 @@ The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard | [3d_gradient.sbs/3d_linear_gradient](../assets/sbs/3d_gradient.sbs) | 1 | No | [Parity · 12 wired and 5 disconnected cases, four formats](parity-fixes.md#runtime-reciprocal-and-3d-gradient-contrast) | | [3d_perlin_noise.sbs/3D_perlin_noise](../assets/sbs/3d_perlin_noise.sbs) | 1 | No | [In progress · shared lookup exact across seven cases, stock lookup differs](parity-fixes.md#pixel-processor-products-and-sums) | | [3d_perlin_noise.sbs/3D_perlin_noise_fractal](../assets/sbs/3d_perlin_noise.sbs) | 1 | No | [Parity: 4 cases](parity-fixes.md#verified-cases) | -| [3d_perlin_noise.sbs/3D_ridged_noise_fractal](../assets/sbs/3d_perlin_noise.sbs) | 1 | No | [In progress · 13 octave controls isolate a one-level roughness difference](parity-fixes.md#ridged-noise-octave-isolation) | +| [3d_perlin_noise.sbs/3D_ridged_noise_fractal](../assets/sbs/3d_perlin_noise.sbs) | 1 | No | [In progress · one-octave roughness and general power differ](parity-fixes.md#runtime-pixel-logarithms-and-powers-of-two) | | [3d_planar_projection.sbs/3d_planar_projection](../assets/sbs/3d_planar_projection.sbs) | 3 | No | [Parity · 15 projection cases, 168,960 exact pixels](parity-fixes.md#uniform-angles-and-planar-projection) | | [3d_planar_projection.sbs/3d_planar_projection_color](../assets/sbs/3d_planar_projection.sbs) | 3 | No | [Parity · 15 projection cases, 168,960 exact pixels](parity-fixes.md#uniform-angles-and-planar-projection) | | [3d_simplex_noise.sbs/3d_simplex_noise](../assets/sbs/3d_simplex_noise.sbs) | 1 | No | [Parity: 4 cases](parity-fixes.md#verified-cases) |