From 59bdbeeadbe5b2219aa865edf26427c79651eea8 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Mon, 23 Nov 2026 01:17:48 -0500 Subject: [PATCH] Preserve floating color precision in Switch Blend --- crates/nodes/src/atomic/blend.rs | 99 ++++++++++++++++++++++++- crates/nodes/src/atomic/input_resize.rs | 19 ++++- crates/nodes/src/ops.rs | 11 ++- docs/parity-fixes.md | 30 +++++++- docs/sbs-root-nodes.md | 2 +- 5 files changed, 152 insertions(+), 9 deletions(-) diff --git a/crates/nodes/src/atomic/blend.rs b/crates/nodes/src/atomic/blend.rs index 748b389b..835c7fac 100644 --- a/crates/nodes/src/atomic/blend.rs +++ b/crates/nodes/src/atomic/blend.rs @@ -1,9 +1,10 @@ use super::ATOMIC; -use super::input_resize::{InputResize, resized_input}; +use super::input_resize::{InputResize, converted_color, resized_input}; use crate::ops; use crate::ops::BLEND_MODES; use crate::{CookContext, CookResult, NodeDefinition, node}; use craft_texture::{Image, Kind}; +use materialcraft_core::OutputFormat; pub(super) fn definition() -> NodeDefinition { node("blend", "Blend", ATOMIC) @@ -37,11 +38,31 @@ pub fn blend_selected_input(context: &CookContext) -> Option { } } +fn selected_float_color(context: &CookContext, port: usize) -> Option { + let image = context.input(port)?; + let source = context.input_formats.get(port).copied().unwrap_or(if image.integer_sampling() { OutputFormat::U16 } else { OutputFormat::F32 }); + if image.is_gray() + || (image.width(), image.height()) != (context.w, context.h) + || !matches!(source, OutputFormat::F16 | OutputFormat::F32) + || !matches!(context.format, OutputFormat::F16 | OutputFormat::F32) + { + return None; + } + // An unmasked endpoint copies the selected texels. A precision change converts their zero signs before rounding to storage. + Some(if source == context.format { image.clone() } else { image.map(Kind::Color, |pixel| converted_color(pixel.map(crate::function::flush_subnormal))) }) +} + fn blend(context: &CookContext) -> CookResult { let (mode, opacity) = (context.i("mode"), context.f("opacity")); // Stored graphs can compute an opacity outside the slider range. Bound it before applying the mask. let opacity = if (0..=8).contains(&mode) { opacity.clamp(0.0, 1.0) } else { opacity }; - let copies_foreground = blend_selected_input(context) == Some(0); + let selected = blend_selected_input(context); + if mode == 7 + && let Some(image) = selected.and_then(|port| selected_float_color(context, port)) + { + return Ok(vec![image]); + } + let copies_foreground = selected == Some(0); let foreground = resized_input(context, 0, if copies_foreground { InputResize::Copy } else { InputResize::Filter }); let background = resized_input(context, 1, if opacity == 0.0 { InputResize::Copy } else { InputResize::Filter }); let kind = if [&foreground, &background].iter().any(|i| i.as_ref().is_some_and(|i| !i.is_gray())) { Kind::Color } else { Kind::Gray }; @@ -72,6 +93,80 @@ mod tests { use materialcraft_core::{OutputFormat, Value}; use std::collections::BTreeMap; + #[test] + fn switch_endpoints_copy_signed_zero_at_the_selected_color_precision() { + use OutputFormat::{F16, F32}; + let small = -2.0_f32.powi(-27); + let pixels = [[0.5, -0.0, -0.25, -0.0], [-0.0, -0.5, -0.25, 0.5], [small, 0.5, 0.25, -0.0]]; + let field = Image::generate(3, 1, Kind::Color, |x, _| pixels[x as usize]); + let other = Image::filled(3, 1, Kind::Color, [-0.5, -1.0, 1.0, 0.5]); + for (source, target) in [(F32, F32), (F16, F32), (F32, F16), (F16, F16)] { + let selected = crate::output_precision::apply(field.clone(), source); + for (slot, opacity) in [(0, 1.0), (1, 0.0)] { + let mut inputs = [Some(other.clone()), Some(other.clone()), None]; + inputs[slot] = Some(selected.clone()); + let mut formats = [F32; 3]; + formats[slot] = source; + let params = resolve_params(&definition(), &BTreeMap::from([("mode".into(), Value::Enum(7)), ("opacity".into(), Value::Float(opacity))])); + let vars = BTreeMap::new(); + let context = CookContext { + w: 3, + h: 1, + seed: 0, + tile: true, + input_formats: &formats, + format: target, + inputs: &inputs, + params: ¶ms, + resource: &|_| None, + vars: &vars, + }; + let result = crate::output_precision::apply(blend(&context).unwrap().remove(0), target); + let same = source == target; + let zero = if same { -0.0_f32 } else { 0.0 }; + let tiny = match (source, target) { + (F32, F32) => small, + (F16, F32) => 0.0, + _ => -0.0, + }; + for (i, expected) in [[0.5, zero, -0.25, zero], pixels[1], [tiny, 0.5, 0.25, zero]].into_iter().enumerate() { + assert_eq!( + result.get(i as i64, 0, false).map(f32::to_bits), + expected.map(f32::to_bits), + "{source:?} to {target:?}, input {slot}, pixel {i}" + ); + } + } + } + } + + #[test] + fn switch_converts_subnormal_inputs_at_the_color_operation() { + let background = [0x0000_0000, 0xbfd3_82af, 0xbf69_87c4, 0x3f80_0000].map(f32::from_bits); + for (opacity, target, bits, expected) in [ + (1.0, OutputFormat::F16, [0xb180_0000, 0x3f80_0000, 0x8000_0001, 0x3b03_86a1], [0x8000_0000, 0x3f80_0000, 0, 0x3b03_8000]), + (0.6137, OutputFormat::F32, [0x8000_0001, 0x3b03_86a1, 0xbf69_87c4, 0x8000_0000], [0, 0xbf23_1903, 0xbf69_87c4, 0x3ec5_c91e]), + ] { + let inputs = [Some(Image::filled(1, 1, Kind::Color, bits.map(f32::from_bits))), Some(Image::filled(1, 1, Kind::Color, background)), None]; + let params = resolve_params(&definition(), &BTreeMap::from([("mode".into(), Value::Enum(7)), ("opacity".into(), Value::Float(opacity))])); + let vars = BTreeMap::new(); + let context = CookContext { + w: 1, + h: 1, + seed: 0, + tile: true, + input_formats: &[OutputFormat::F32; 3], + format: target, + inputs: &inputs, + params: ¶ms, + resource: &|_| None, + vars: &vars, + }; + let result = crate::output_precision::apply(blend(&context).unwrap().remove(0), target); + assert_eq!(result.get(0, 0, false).map(f32::to_bits), expected, "opacity {opacity}, {target:?}"); + } + } + #[test] fn add_sub_limits_global_opacity_before_blending() { let mut inputs = [ diff --git a/crates/nodes/src/atomic/input_resize.rs b/crates/nodes/src/atomic/input_resize.rs index 1c63847b..9cae753b 100644 --- a/crates/nodes/src/atomic/input_resize.rs +++ b/crates/nodes/src/atomic/input_resize.rs @@ -25,6 +25,15 @@ pub(super) fn sampled_input(context: &CookContext, port: usize) -> (Image, Outpu resized_texture(context, port, InputResize::Sampled).unwrap_or_else(|| (Image::filled(context.w, context.h, Kind::Gray, [0.0; 4]), context.format)) } +fn clear_zero_signs(pixel: [f32; 4]) -> [f32; 4] { + pixel.map(|v| if v == 0.0 { 0.0 } else { v }) +} + +/// Color conversion preserves negative zero in every channel when all three RGB signs are negative. +pub(super) fn converted_color(pixel: [f32; 4]) -> [f32; 4] { + if pixel[..3].iter().any(|v| v.is_sign_positive()) { clear_zero_signs(pixel) } else { pixel } +} + fn prepare_pattern_background(image: Image, mode: InputResize, source: OutputFormat, enlarged: bool) -> Image { if mode != InputResize::PatternBackground { return image; @@ -41,9 +50,13 @@ fn prepare_pattern_background(image: Image, mode: InputResize, source: OutputFor } image.map(image.kind(), |pixel| { let pixel = if flush { pixel.map(crate::function::flush_subnormal) } else { pixel }; - // In an enlarged color background a negative zero survives only when all three RGB signs are negative. - let clear_zero_sign = gray || (enlarged_color && pixel[..3].iter().any(|v| v.is_sign_positive())); - if clear_zero_sign { pixel.map(|v| if v == 0.0 { 0.0 } else { v }) } else { pixel } + if gray { + clear_zero_signs(pixel) + } else if enlarged_color { + converted_color(pixel) + } else { + pixel + } }) } diff --git a/crates/nodes/src/ops.rs b/crates/nodes/src/ops.rs index 7cc62dab..85e0c596 100644 --- a/crates/nodes/src/ops.rs +++ b/crates/nodes/src/ops.rs @@ -366,7 +366,16 @@ pub fn blend_channel(mode: i32, b: f32, f: f32) -> f32 { pub fn blend_px(mode: i32, bg: [f32; 4], fg: [f32; 4], opacity: f32, color_blending: i32, blend_alpha: bool, clamp: bool) -> [f32; 4] { if mode == 7 { // Switch interpolates each channel directly, including alpha. - let mut out = std::array::from_fn(|k| bg[k].mul_add(1.0 - opacity, fg[k] * opacity)); + let mut out = if opacity > 0.0 && opacity < 1.0 { + // Fractional weights flush subnormals before multiplication, after the first product and after the final add. + use crate::function::flush_subnormal; + std::array::from_fn(|k| { + let foreground = flush_subnormal(flush_subnormal(fg[k]) * opacity); + flush_subnormal(flush_subnormal(bg[k]).mul_add(1.0 - opacity, foreground)) + }) + } else { + std::array::from_fn(|k| bg[k].mul_add(1.0 - opacity, fg[k] * opacity)) + }; if clamp { for c in &mut out[..3] { *c = c.clamp(0.0, 1.0); diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index 9087b4d8..e2e638e2 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -59,6 +59,32 @@ The first pass classifies all 546 roots: 166 Parity and 380 Too hard. These meas ## 2026-11-23 root comparisons +### Signed zero when Switch Blend selects a floating-point color input + +In the [first eighth specular pass](#environment-and-intermediate-precision-in-the-eighth-specular-passes), render the black-specular-and-roughness control at 128² with F32 storage on the first pixel processor. Expose all three pixel processors and the two downstream Switch Blend results in a disposable MaterialCraft save. Read all five outputs from one cook in each application. The first processor and the final reference output each reproduced all 16,384 original pixels. Before the correction the three processors each matched 16,384/16,384 between applications. Their formats are F32, F16 and F16. The first Switch matched 16,345/16,384 and the second 16,353/16,384. Maximum numerical error was zero at all five stages. At (1,22) the first Switch returned `80000000` on green in MaterialCraft and `00000000` in the reference. + +An unmasked Switch at opacity zero or one copies the selected input. A same-size floating-point RGBA copy at the same precision preserves every channel bit. When converting F16 to F32 or F32 to F16, an existing zero retains its sign only when all three source RGB signs are negative. This also governs an existing zero in alpha. Converting before rounding to F16 preserves the sign of a negative nonzero component that rounds to zero. Subnormal F32 channels become signed zero before this precision conversion. At fractional weights the foreground and background channels, the rounded foreground product and the resulting multiply-add each flush subnormals to signed zero. + +Feed two nearest-sampling pixel processors into an unmasked Switch. For component c of each F32 RGBA field select words from `00000000 80000000 b1800000 31800000 bf800000 3f800000 3e8b217c bfd382af 80000001 00000001 c0000000 3b0386a1 b8899021 38f061d5 bf6987c4 405ccaac`. Index foreground by (x + 3c + 5j) modulo 16 and background by (y + 7c + 3j) modulo 16. Use 32 × 16, 16 × 32 and 32² for j = 0, 1 and 2 and seed 397091 + 47j. Use F32 for both processors at opacities 0, 1, .25 and .6137. Repeat with an F16 foreground at 0, 1, .5 and .6137. Store the Switch in all four formats at the first size and in F32 at the other two. + +For independent sign tests, use 16², 32 × 16 and 16 × 32. For source s = 0 for foreground or 1 for background, take bit c of (x + 5y + 7j + 3s) modulo 16 as the sign. Select a magnitude from (0,.5,2⁻²⁷,0,2⁻²⁴,.375,2⁻²⁵,1.125) by (y + 3c + s + 5j) modulo 8. Select each source in turn at F16 and F32 storage, leaving the other input at F32. Use seed 399023 + 47j. Store all four formats at the first size and F16 and F32 at the others. The sixteen sign masks distinguish the three RGB signs from all four channel signs, the first two signs and unconditional zero clearing. + +For a separate field around the smallest normal F32 value, use 16 × 32, 32 × 16 and 32² at seeds 404127 + 19j. Use the same eight graphs as the first comparison. Select channel words from `00000000 80000000 00000001 80000001 0071f5ab 80493874 007fffff 807fffff 00800000 80800000 00800001 80800001 00bce209 81d50c43 3f8c3793 c0666bbb`. Use index (7x + y + 5c + 7j) modulo 16 for foreground or (3x + 5y + 3c + 7j + 1) modulo 16 for background. Store all four formats at the first size and both floating formats at the others. With equal F32 inputs, all three flush stages are needed to reproduce every floating-output pixel at .25 and .6137. + +| Comparison | Renders | U8 exact / total · max | U16 exact / total · max | F16 exact / total · max | F32 exact / total · max | +|---|---:|---:|---:|---:|---:| +| Eight endpoint graphs, before correction | 56 | 3,072/3,072 · 0 | 3,072/3,072 · 0 | 4,726/7,168 · 0 | 10,234/13,312 · 0 | +| Eight endpoint graphs, corrected | 56 | 3,072/3,072 · 0 | 3,072/3,072 · 0 | 7,168/7,168 · 0 | 13,312/13,312 · 0 | +| Four endpoint SBS saves, opened in both applications | 28 | 1,536/1,536 · 0 | 1,536/1,536 · 0 | 3,584/3,584 · 0 | 6,656/6,656 · 0 | +| Four partial-opacity controls, before correction | 24 | 2,048/2,048 · 0 | 2,048/2,048 · 0 | 1,960/2,048 · 0 | 7,456/8,192 · 1.40129846e-45 | +| Four partial-opacity controls, corrected | 24 | 2,048/2,048 · 0 | 2,048/2,048 · 0 | 2,048/2,048 · 0 | 8,192/8,192 · 0 | +| Independent small magnitudes, four endpoint graphs | 32 | 2,048/2,048 · 0 | 2,048/2,048 · 0 | 8,192/8,192 · 0 | 8,192/8,192 · 0 | +| Independent small magnitudes, four partial-opacity graphs | 32 | 2,048/2,048 · 0 | 2,048/2,048 · 0 | 8,192/8,192 · 0 | 8,192/8,192 · 0 | +| Two small-magnitude SBS saves reopened in both applications | 16 | 1,024/1,024 · 0 | 1,024/1,024 · 0 | 4,096/4,096 · 0 | 4,096/4,096 · 0 | +| Reopened .6137 same-precision control | 6 | 512/512 · 0 | 512/512 · 0 | 512/512 · 0 | 2,048/2,048 · 0 | + +The endpoint saves cover F32 background selection, F16 foreground selection, a foreground stored in F32 and a background stored in F16. Each saved reference buffer matched its original. Both input processors matched at every setting. The two additional saves cover foreground selection and weighting at .6137. On the original three F32 output sizes at each of the four partial opacities, the three-stage flush rule reproduces 8,192/8,192 pixels. Both the selected-input and subnormal regressions failed before their respective corrections and passed afterward. All 398 node release tests, formatting, strict workspace Clippy, dependency layers and WebAssembly checks passed. + ### Stored products in pixel expressions and irradiance ray steps A straight-line pixel expression can assign a vector product to a variable and add it to several positions. For each component consumed only by additions, the evaluator now rounds the multiply and add together. Returning the stored blue component alongside the sum preserves the rounded blue product in both places. A subsequent assignment takes effect at the next read. The change applies to the shared expression evaluator. @@ -4062,11 +4088,11 @@ Each root matches 5,487,872/5,487,872 original pixels. At the disputed root outp ### Environment and intermediate precision in the eighth specular passes -Repeat the two [128² F16 settings](#rectangular-inputs-and-remaining-half-float-pixels-in-the-eighth-specular-passes) at seed zero, using the changed shape for root 396 and defaults for root 408. Keep the same eight bound inputs and final output format. Set only the first connected pixel processor to F32 and compare its raw RGBA with its F16 output at the root. All eight intermediate input images on this path matched in the preceding capture. +Repeat the two [128² F16 settings](#rectangular-inputs-and-remaining-half-float-pixels-in-the-eighth-specular-passes) at seed zero, using the changed shape for root 396 and defaults for root 408. Keep the same eight bound inputs and final output format. Set only the first connected pixel processor to F32 and compare its raw RGBA with the graph output. Pass 396 returns F32, with every stored value exactly representable in F16 across these five controls. Pass 408 returns F16. All eight intermediate input images on this path matched in the preceding capture. For three controls replace one input with a generated opaque black 128² F32 texture. For the fourth replace the environment with an F32 texture containing red (x+.5)/128, green (y+.5)/128, blue ((17x+37y+5xy) mod 257)/256 and alpha one. All other inputs and parameters keep their values from the same original setting. Each count below requires all four channel bit patterns of a pixel to match. -| Root | Input change | First processor F32 exact / 16,384 | Maximum F32 error | Final F16 exact / 16,384 | Maximum F16 error | +| Root | Input change | First processor F32 exact / 16,384 | Maximum F32 error | Final pixels exact / 16,384 | Maximum output error | |---|---|---:|---:|---:|---:| | 396 | Original inputs | 14,265 | 2.384185791015625e-07 | 16,383 | 0.0001220703125 | | 396 | Black environment | 16,384 | 0 | 16,384 | 0 | diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index 344d58fa..4fefe047 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -533,7 +533,7 @@ Creased matches 10,947,840/10,947,840 pixels across 100 distinct settings throug | [pbr_render.sbs/position_to_normal](../assets/sbs/pbr_render.sbs) | 2 | Yes | [Parity · 30 renders, all 515,328 RGBA pixels exact](parity-fixes.md#position-to-normal-outputs-in-both-renderers) | | [pbr_render.sbs/raytrace_position](../assets/sbs/pbr_render.sbs) | 4 | Yes | [Parity · 26 renders, all 142,340 RGBA pixels exact](parity-fixes.md#small-graph-parents-and-raytrace-positions) | | [pbr_render.sbs/raytraced_irradiance_pass_8](../assets/sbs/pbr_render.sbs) | 10 | Yes | [In progress · 124,769/124,928 pixels and 26/26 wired or default pass indices](parity-fixes.md#irradiance-with-a-connected-pass-index) · [First processor, 4,094/4,096 F16 and 3,023/4,096 F32, called ray steps](parity-fixes.md#stored-products-in-pixel-expressions-and-irradiance-ray-steps) | -| [pbr_render.sbs/raytraced_specular_pass_8](../assets/sbs/pbr_render.sbs) | 9 | Yes | [In progress · 142,335/142,340 pixels, five F16 differences](parity-fixes.md#eighth-raytraced-specular-passes) · [rectangular fields and saved packages](parity-fixes.md#rectangular-inputs-and-remaining-half-float-pixels-in-the-eighth-specular-passes) · [Environment controls and F32 boundary values](parity-fixes.md#environment-and-intermediate-precision-in-the-eighth-specular-passes) · [Reciprocal rounding and 128² recheck](parity-fixes.md#reciprocal-division-through-pixel-function-calls) | +| [pbr_render.sbs/raytraced_specular_pass_8](../assets/sbs/pbr_render.sbs) | 9 | Yes | [In progress · 143,300/143,300 original matrix and rectangular pixels, 16,704/16,704 reopened, 31 zero signs isolated in an additional control](parity-fixes.md#signed-zero-when-switch-blend-selects-a-floating-point-color-input) · [Earlier F16 comparisons](parity-fixes.md#eighth-raytraced-specular-passes) · [rectangular fields and saved packages](parity-fixes.md#rectangular-inputs-and-remaining-half-float-pixels-in-the-eighth-specular-passes) · [Environment controls and F32 boundary values](parity-fixes.md#environment-and-intermediate-precision-in-the-eighth-specular-passes) · [Reciprocal rounding and 128² recheck](parity-fixes.md#reciprocal-division-through-pixel-function-calls) | | [pbr_render2.sbs/PBR_render_mapping_color](../assets/sbs/pbr_render2.sbs) | 2 | No | [Parity · 13 cases, 163,840 exact pixels](parity-fixes.md#height-distance-texture-mapping-skew-and-weave) | | [pbr_render2.sbs/PBR_render_mapping_grayscale](../assets/sbs/pbr_render2.sbs) | 2 | No | [Parity · 13 cases, 163,840 exact pixels](parity-fixes.md#height-distance-texture-mapping-skew-and-weave) | | [pbr_render2.sbs/chroma_shift](../assets/sbs/pbr_render2.sbs) | 1 | Yes | [Parity · 13 cases, 163,840 exact pixels](parity-fixes.md#height-distance-texture-mapping-skew-and-weave) |