diff --git a/crates/nodes/src/function/compile.rs b/crates/nodes/src/function/compile.rs index b7d576c4..d7a0392f 100644 --- a/crates/nodes/src/function/compile.rs +++ b/crates/nodes/src/function/compile.rs @@ -206,20 +206,7 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu let input_type = |index: usize| inputs.get(index).and_then(|index| instructions.get(*index)).map_or(256, |instruction| instruction.type_code); let inferred = super::inferred_type::inferred_type(&node.op, value.as_ref(), input_type); let type_code = call.as_ref().map_or_else(|| if node.type_code == 0 { inferred } else { node.type_code }, |call| call.program.output_type()); - let operation = |inputs, value, call| Instruction { - id, - definition, - inputs, - value, - type_code, - literal: false, - literal_divisor: false, - reciprocal_factor: None, - pixel_product_sum: None, - pixel_interval: None, - control_registers: Vec::new(), - call, - }; + let operation = |inputs, value, call| Instruction { call, ..Instruction::new(id, definition, inputs, value, type_code) }; let mut inputs = inputs; if definition.id == "rand" && type_code == 256 diff --git a/crates/nodes/src/function/instruction.rs b/crates/nodes/src/function/instruction.rs index 5765358b..ea3bc211 100644 --- a/crates/nodes/src/function/instruction.rs +++ b/crates/nodes/src/function/instruction.rs @@ -22,6 +22,23 @@ pub(crate) struct Instruction { } impl Instruction { + pub(super) fn new(id: u32, definition: &'static FunctionDefinition, inputs: Vec, value: Option, type_code: u32) -> Self { + Self { + id, + definition, + inputs, + value, + type_code, + literal: false, + literal_divisor: false, + reciprocal_factor: None, + pixel_product_sum: None, + pixel_interval: None, + control_registers: Vec::new(), + call: None, + } + } + pub(super) fn depends_only_on_operands(&self) -> bool { self.call.is_none() && !self.inputs.is_empty() && !matches!(self.definition.id, "rand" | "samplelum" | "samplecol" | "set" | "while") } diff --git a/crates/nodes/src/function/mod.rs b/crates/nodes/src/function/mod.rs index 28f2af2a..7d9225f1 100644 --- a/crates/nodes/src/function/mod.rs +++ b/crates/nodes/src/function/mod.rs @@ -29,6 +29,7 @@ mod node_interface; mod node_types; mod operation; mod output; +mod pattern_channel_operations; mod pixel_condition; mod processor; mod product_sum; diff --git a/crates/nodes/src/function/pattern_channel_operations.rs b/crates/nodes/src/function/pattern_channel_operations.rs new file mode 100644 index 00000000..213c1f98 --- /dev/null +++ b/crates/nodes/src/function/pattern_channel_operations.rs @@ -0,0 +1,62 @@ +use super::{catalog, instruction::Instruction, returned_product::float_width, vector::PatternComponent}; +use materialcraft_core::Value; + +/// A pattern swizzle evaluates a component-wise expression for just the requested channel. +/// Use ordinary scalar instructions so that shared operands, branches and random draws keep +/// the same evaluation order as a scalar expression authored directly. +pub(super) fn project( + op: &Instruction, + original: &[Instruction], + sources: &[[Option; 4]], + generated: &mut Vec, +) -> Option<[Option; 4]> { + let width = float_width(op.type_code); + if width < 2 { + return None; + } + let kind = |i: usize| original.get(i).map(|input| input.type_code); + let valid = match (op.definition.id, op.inputs.as_slice()) { + ("ifelse", &[c, a, b]) => kind(c) == Some(4) && kind(a) == Some(op.type_code) && kind(b) == Some(op.type_code), + ("mul", &[a, b]) => kind(a) == Some(op.type_code) && kind(b) == Some(op.type_code), + ("lerp", &[a, b, x]) => kind(a) == Some(op.type_code) && kind(b) == Some(op.type_code) && kind(x) == Some(256), + _ => false, + }; + if !valid { + return None; + } + + let mut channels = [None; 4]; + for (lane, channel) in channels.iter_mut().take(width).enumerate() { + let mut inputs = Vec::with_capacity(op.inputs.len()); + for &index in &op.inputs { + let source = original.get(index)?; + let input = if source.type_code != op.type_code { + index + } else { + match sources.get(index)?[lane] { + Some(PatternComponent::Scalar(register)) => register, + Some(PatternComponent::Zero) => { + let register = original.len() + generated.len(); + generated.push(Instruction::new(source.id, catalog::definition("const_float1")?, vec![], Some(Value::Float(0.0)), 256)); + register + } + None => { + let register = original.len() + generated.len(); + generated.push(Instruction::new(source.id, catalog::definition("swizzle1")?, vec![index], Some(Value::Int(lane as i32)), 256)); + register + } + } + }; + inputs.push(input); + } + *channel = Some(PatternComponent::Scalar(original.len() + generated.len())); + let mut instruction = Instruction::new(op.id, op.definition, inputs, None, 256); + instruction.literal = op.literal; + generated.push(instruction); + } + Some(channels) +} + +#[cfg(test)] +#[path = "pattern_channels.test.rs"] +mod tests; diff --git a/crates/nodes/src/function/pattern_channels.test.rs b/crates/nodes/src/function/pattern_channels.test.rs new file mode 100644 index 00000000..e32854ea --- /dev/null +++ b/crates/nodes/src/function/pattern_channels.test.rs @@ -0,0 +1,54 @@ +use crate::function::{EvaluationContext, EvaluationState, FunctionScope, compile}; +use materialcraft_core::{FunctionGraph, Value}; +use std::collections::BTreeMap; + +fn random_color(graph: &mut FunctionGraph, one: u32) -> u32 { + let channels = [(); 4].map(|()| graph.add("rand", &[one], None)); + let lower = graph.add("vector2", &channels[..2], None); + let upper = graph.add("vector2", &channels[2..], None); + graph.add("vector4", &[lower, upper], None) +} + +#[test] +fn selecting_a_computed_pattern_channel_preserves_the_next_random_draw() { + for operation in ["ifelse", "mul", "lerp"] { + for lane in [0, 3] { + let mut graph = FunctionGraph::default(); + let one = graph.add_constant(Value::Float(1.0)); + let zero = graph.add_constant(Value::Float(0.0)); + let left = random_color(&mut graph, one); + let right = random_color(&mut graph, one); + let condition = graph.add("get_bool", &[], Some(Value::Text("choice".into()))); + let selected = match operation { + "ifelse" => graph.add(operation, &[condition, left, right], None), + "lerp" => { + let factor = graph.add_constant(Value::Float(0.375)); + graph.add(operation, &[left, right, factor], None) + } + _ => graph.add(operation, &[left, right], None), + }; + let channel = graph.add("swizzle1", &[selected], Some(Value::Int(lane))); + let observed = graph.add("mul", &[channel, zero], None); + let next = graph.add("rand", &[one], None); + graph.output = Some(graph.add("add", &[observed, next], None)); + + for choice in [true, false] { + let variables = BTreeMap::from([("choice".into(), Value::Bool(choice))]); + let context = EvaluationContext { + scope: FunctionScope::FxMap, + position: [0.5; 2], + size: [16.0; 2], + images: &[], + image_formats: &[], + tile: true, + variables: &variables, + }; + for (seed, after_one, after_two) in [(0, 0x3f08_683c, 0x3f41_3194), (17, 0x3f4e_0964, 0x3ec2_8a10)] { + let graph = compile(&graph, seed).unwrap(); + let expected = f32::from_bits(if operation == "ifelse" { after_one } else { after_two }); + assert_eq!(graph.evaluate(&context, &mut EvaluationState::default()).unwrap(), Value::Float(expected), "{operation} channel {lane}"); + } + } + } + } +} diff --git a/crates/nodes/src/function/vector.rs b/crates/nodes/src/function/vector.rs index 9fba773f..cb85d8f7 100644 --- a/crates/nodes/src/function/vector.rs +++ b/crates/nodes/src/function/vector.rs @@ -24,7 +24,10 @@ pub(super) fn identify_pattern_components(program: &mut super::Program) { } let mut sources = Vec::with_capacity(instructions.len()); let mut projections = Vec::new(); + let mut generated = Vec::new(); + let mut ranges = Vec::with_capacity(instructions.len()); for (index, op) in instructions.iter().enumerate() { + let start = instructions.len() + generated.len(); let mut lanes = [None; 4]; if let Some(forwarded) = super::returned_product::forwarded(op, instructions, &sources, Some(PatternComponent::Zero)) { lanes = forwarded; @@ -33,6 +36,8 @@ pub(super) fn identify_pattern_components(program: &mut super::Program) { { program.pattern_components.insert(index, source); } + } else if let Some(projected) = super::pattern_channel_operations::project(op, instructions, &sources, &mut generated) { + lanes = projected; } else if let Some(call) = &op.call { if let Some(arguments) = &call.pattern_arguments { lanes = arguments.channels.map(|register| register.map(PatternComponent::Scalar)); @@ -45,12 +50,21 @@ pub(super) fn identify_pattern_components(program: &mut super::Program) { lanes[0] = Some(PatternComponent::Scalar(index)); } sources.push(lanes); + ranges.push(start..instructions.len() + generated.len()); } for (index, projection) in projections { if let Some(call) = program.instructions.get_mut(index).and_then(|op| op.call.as_mut()) { call.pattern_arguments = Some(projection); } } + if !generated.is_empty() { + for op in program.instructions.iter_mut().filter(|op| op.definition.id == "while") { + // Each repetition also invalidates the scalar channels derived from its condition or body. + let repeated: Vec<_> = op.control_registers.iter().filter_map(|&i| ranges.get(i)).flat_map(|r| r.clone()).collect(); + op.control_registers.extend(repeated); + } + program.instructions.extend(generated); + } } pub(crate) fn evaluate(op: &str, args: &[Value], setting: Option<&Value>) -> Result { diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index aa44ac57..6484f740 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -73,6 +73,34 @@ For a separate check at 256² and seed 372421, compile the same original wrapper Maximum U16 error is zero throughout the three-setting desktop column. The desktop original and reopen also agree in 139,264/139,264 pixels per root. At the previously disputed 256² seed, MaterialCraft and the live desktop agree in 65,536/65,536 pixels per root. The same six, two and four discrepancies recur between the two reference rendering paths on all four one-worker runs per root. The eight-worker runs give more than one output for the same settings. The inventory retains the existing cross-worker differences. [Earlier seed and worker measurements](#computed-graph-seeds-on-load-evaluation-and-save) +### Selected channels in pattern expressions + +In an original single-square pattern, connect four independent random scalars to a four-component vector. Make a second vector the same way. Choose between the vectors with a boolean, multiply them component by component, or interpolate between them with a scalar factor of .375. Swizzle the first or last component into opacity. To observe how many draws the expression consumes, multiply the swizzled result by zero and add a new random draw. Test both gate values and seeds 0 and 17 at 16² in F32. Across the direct, nested, arithmetic and next-draw controls, 112 renders match 28,672/28,672 pixels, maximum error 0. Supplying a four-component interpolation factor in a further 16 probes still gives 0/4,096 exact pixels, maximum F32 error .59443158. + +The pattern evaluator previously drew every channel before selecting one. It now evaluates the scalar operands of the requested channel, preserving the chosen branch and the order of shared random draws. The isolated grayscale Tile Generator luminance pair (1,0) on a 4 × 14 grid now matches 4,096/4,096 U16 pixels at each of seeds 0 and 17, maximum error 0. This holds for literal grid counts and for a column input, a row input plus ten and a jitter input, including after ordinary saves. + +For a connected-source check, generate a grayscale U8 ramp of .75u + .25v at quarter width and height. Connect it to the Source pin. In the first instance select the source image, set the gap to .06, scale to 1.12 and luminance variation and contrast to (.49,.95). In the second instance select the square and set the luminance pair to (1,0). Set the row offset to .25, pattern-specific pair to (0,0) and blend mode to 2 on both. Render each at 64² with seed 0, a 4 × 14 grid and zero row jitter, then at 64 × 32 with seed 17, a 5 × 7 grid and .375 jitter, and at 32 × 128 with seed 12071, a 3 × 5 grid and .125 jitter. Use neutral grayscale Levels inheriting input dimensions to select the actual terminal U8, U16, F16 and F32 storage. Reopen the ordinary MaterialCraft saves in the reference desktop. + +| Tile Generator comparison | Settings | Exact pixels | Maximum error | +|---|---:|---:|---:| +| Grayscale root, earlier whole-root matrix | 55 | 284,416/284,416 | 0 | +| Grayscale root, archived saves reopened in the desktop | 43 | 179,968/179,968 | 0 | +| Source and square matrix, original vs. desktop | 24 | 81,920/81,920 | 0 | +| Same matrix, saved vs. desktop | 24 | 81,920/81,920 | 0 | +| Desktop original vs. reopened save | 24 | 81,920/81,920 | 0 | +| Related Tile Generator in the separate catalog package | 221 | 757,504/757,504 | 0 | + +With both the graph-color display correction and the pattern fix, Bricks 01 gives the following Base Color results. For the raw rows a pixel matches when all three U8 channel values agree. The last row compares the actual displayed RGB pixels from the two 1:1 2D views. + +| Bricks 01 Base Color | Exact pixels | Maximum byte error | +|---|---:|---:| +| 64², defaults, seed 0 | 4,096/4,096 | 0 | +| 64², luminosity .65, seed 19 | 4,094/4,096 | 1 | +| 128², defaults, seed 0 | 13,283/16,384 | 43 | +| 256² 2D views, defaults, seed 0 | 55,976/65,536 | 53 | + +At 64² and defaults, eight of the nine raw material outputs match every pixel. Normal matches 4,084/4,096 with maximum U16 error 1. At 256², mean displayed RGB is (153.61,115.32,91.40) in MaterialCraft and (153.55,115.21,91.28) in the reference. The whole material still has measured differences at higher resolutions. [Earlier comparison with the display correction alone](#stored-graph-color-in-the-2d-view) + ### Stored graph color in the 2D view Display the Base Color output of Bricks 01 at 1:1 with the default sRGB interpretation. With seed 0 and a 64² parent, all 4,096 pixels captured from the reference viewport match its raw U8 RGB output, maximum error 0. The old MaterialCraft viewport applied a linear-light to sRGB conversion to those already encoded numbers. The same conversion brightened graph thumbnails and the color sampler. diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index 207232d1..90cd4c50 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -35,15 +35,15 @@ A graph may accept input pins and still be a root under the dependency criterion Statuses: **Not checked**, **In progress**, **Parity** (exact pixels or typed values for the linked measured cases), or **Too hard** (reason recorded). Function calls do not count as regular graph dependencies. -The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard**. The current inventory has **479 Parity**, **67 In progress** and **0 Too hard**. The November 17–23 comparisons include raw counts, output formats and remaining differences. [November 17 measurements](parity-fixes.md#2026-11-17-root-comparisons) · [November 18 measurements](parity-fixes.md#2026-11-18-root-comparisons) · [November 19 measurements](parity-fixes.md#2026-11-19-root-comparisons) · [November 20 measurements](parity-fixes.md#2026-11-20-root-comparisons) · [November 21 measurements](parity-fixes.md#2026-11-21-root-comparisons) · [November 22 measurements](parity-fixes.md#2026-11-22-root-comparisons) · [November 23 measurements](parity-fixes.md#2026-11-23-root-comparisons) +The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard**. The current inventory has **480 Parity**, **66 In progress** and **0 Too hard**. The November 17–23 comparisons include raw counts, output formats and remaining differences. [November 17 measurements](parity-fixes.md#2026-11-17-root-comparisons) · [November 18 measurements](parity-fixes.md#2026-11-18-root-comparisons) · [November 19 measurements](parity-fixes.md#2026-11-19-root-comparisons) · [November 20 measurements](parity-fixes.md#2026-11-20-root-comparisons) · [November 21 measurements](parity-fixes.md#2026-11-21-root-comparisons) · [November 22 measurements](parity-fixes.md#2026-11-22-root-comparisons) · [November 23 measurements](parity-fixes.md#2026-11-23-root-comparisons) Nested Curvature, Curvature Smooth and Normal Sobel each match 2,304/2,304 original and 2,304/2,304 reopened pixels. Panorama 3D Position now reopens in the reference desktop and matches 2,304/2,304 pixels across six renders of an ordinary SBS save. Panorama Shape, Shape 2 and Spot each match 2,304/2,304 original and 2,304/2,304 reopened pixels in the same six settings. [Fixed vector arguments and whole-root counts](parity-fixes.md#float-vector-arguments-in-nested-functions) [Save, reopen and desktop comparisons](parity-fixes.md#ordinary-sbs-saves-with-verified-library-dependencies) [Working precision, blur inputs and whole-root counts](parity-fixes.md#output-precision-in-nested-generators-and-blurs) Ordinary SBS saves preserve graph seed inheritance across 22 nested graphs. The original and reopened random fields each match 22,528/22,528 pixels. BNW Spots 1 and Clouds 1 and 2 each match 9,216/9,216 pixels across four output formats in the two nested settings. [Seed settings, whole graphs and renderer repeats](parity-fixes.md#graph-random-seed-inheritance-on-save-and-in-nested-graphs) -The Bricks 01 material provides a separate 2D display check. The corrected preview matches all 258 tested encoded RGB channels. The headless 2D PNG also matches every pixel of a 16² uniform-color control in both display modes. At 64², its base-color mean is (155,122,98) against (152,120,98) in the reference. The cooked material still differs. [Color swatches and material measurements](parity-fixes.md#stored-graph-color-in-the-2d-view) +The Bricks 01 material provides a separate 2D display check. The corrected preview matches all 258 tested encoded RGB channels. The headless 2D PNG also matches every pixel of a 16² uniform-color control in both display modes. With the shared pattern fix, default Base Color matches 4,096/4,096 raw pixels at 64² and 13,283/16,384 at 128², maximum byte errors 0 and 43. The actual 256² 2D views match 55,976/65,536 pixels, maximum 53. [Color swatches](parity-fixes.md#stored-graph-color-in-the-2d-view) · [Whole-material measurements](parity-fixes.md#selected-channels-in-pattern-expressions) -Tile Generator has reopened. The 4 × 14 grayscale grid matches at seeds 0 and 17 until luminance variation is enabled. The isolated setting matches 0/4,096 at each seed. [Bricks 01 tile and noise stages](parity-fixes.md#tile-luminance-variation-in-bricks-01) +The grayscale Tile Generator again has measured parity. Its 55 earlier settings match 284,416/284,416 pixels. Both luminance seeds and all 24 new procedural source, grid and format settings match, including ordinary saves. [Reproduction and zero-error counts](parity-fixes.md#selected-channels-in-pattern-expressions) BNW Spots 1, Clouds 1 and Clouds 2 each match 9,216/9,216 direct U16 pixels and a further 9,216/9,216 across four actual output formats. Reopened graphs have the same counts and maximum error 0. At the disputed 256² seed, all three now match 65,536/65,536 in the live desktop. The standalone renderer differs from that same desktop by six, two and four pixels. [Direct desktop and standalone comparisons](parity-fixes.md#live-desktop-and-standalone-rendering-of-three-noise-roots) [Nested sizes, seeds and output formats](parity-fixes.md#computed-caller-sizes-on-bnw-spots-1-and-clouds-1-and-2) @@ -683,7 +683,7 @@ Creased matches 10,947,840/10,947,840 pixels across 100 distinct settings throug | [templates.sbs/Templates/Standard_Materials/Extended_Material](../assets/sbs/templates.sbs) | 0 | Yes | [Parity: 3 cases](parity-fixes.md#verified-cases) | | [templates.sbs/Templates/Standard_Materials/Simple_Material](../assets/sbs/templates.sbs) | 0 | Yes | [Parity: 3 cases](parity-fixes.md#verified-cases) | | [threshold.sbs/threshold](../assets/sbs/threshold.sbs) | 1 | No | [Parity: 4 cases](parity-fixes.md#verified-cases) | -| [tile_generator.sbs/tile_generator](../assets/sbs/tile_generator.sbs) | 2 | Yes | [In progress · 284,416/284,416 across 55 earlier settings, new luminance cases differ](parity-fixes.md#reopened-starburst-symmetry-tile-and-waveform-graphs) · [Earlier measurements](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) · [Bricks 01 tile and noise stages](parity-fixes.md#tile-luminance-variation-in-bricks-01) | +| [tile_generator.sbs/tile_generator](../assets/sbs/tile_generator.sbs) | 2 | Yes | [Parity · 284,416/284,416 across 55 settings and 81,920/81,920 in the 24 new settings, including reopen](parity-fixes.md#selected-channels-in-pattern-expressions) · [Earlier measurements](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) · [Bricks 01 tile and noise stages](parity-fixes.md#tile-luminance-variation-in-bricks-01) | | [tile_generator_color.sbs/tile_generator_color](../assets/sbs/tile_generator_color.sbs) | 2 | Yes | [Parity · 284,416/284,416 pixels across 55 distinct settings](parity-fixes.md#reopened-starburst-symmetry-tile-and-waveform-graphs) · [Earlier measurements](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) | | [tile_random.sbs/tile_random](../assets/sbs/tile_random.sbs) | 2 | Yes | [In progress · 111,364/142,592 whole pixels, first differing stages measured](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) · [saved authored and disc branches each match 4,864/4,864](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) | | [tile_random.sbs/tile_random_color](../assets/sbs/tile_random.sbs) | 2 | Yes | [In progress · 111,228/142,592 whole pixels, first differing stages measured](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) · [saved authored and disc branches each match 4,864/4,864](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) |