From 1cc2da0163fa2f902f87ca48335fe47e5168fd43 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Mon, 23 Nov 2026 17:55:05 -0500 Subject: [PATCH] Evaluate shared conditional inputs in arm order --- .../{branch_random.rs => branch_inputs.rs} | 53 +++++++------ .../nodes/src/function/branch_inputs.test.rs | 79 +++++++++++++++++++ crates/nodes/src/function/compile.rs | 5 +- crates/nodes/src/function/mod.rs | 2 +- crates/nodes/src/function/program.rs | 14 ++-- docs/parity-fixes.md | 17 +++- docs/sbs-root-nodes.md | 2 +- 7 files changed, 138 insertions(+), 34 deletions(-) rename crates/nodes/src/function/{branch_random.rs => branch_inputs.rs} (63%) create mode 100644 crates/nodes/src/function/branch_inputs.test.rs diff --git a/crates/nodes/src/function/branch_random.rs b/crates/nodes/src/function/branch_inputs.rs similarity index 63% rename from crates/nodes/src/function/branch_random.rs rename to crates/nodes/src/function/branch_inputs.rs index c65165b6..bd6a88e9 100644 --- a/crates/nodes/src/function/branch_random.rs +++ b/crates/nodes/src/function/branch_inputs.rs @@ -2,25 +2,24 @@ use super::{Program, vector::PatternComponent}; use materialcraft_core::Value; use std::collections::{BTreeMap, BTreeSet}; -pub(super) struct PatternDraws { +pub(super) struct BranchInputs { shared: Vec, true_count: usize, } -impl PatternDraws { - // The true arm occurs first. A skipped arm still consumes any draw needed outside it. +impl BranchInputs { + // The true arm occurs first. A skipped arm still evaluates effects shared with another consumer. pub(super) fn skipped(&self, take_true: bool) -> &[usize] { let (through_true, through_false_only) = self.shared.split_at(self.true_count); if take_true { through_false_only } else { through_true } } } -/// Schedule draws shared by an image branch and another part of its expression. An arm's -/// private draws stay lazy. The condition itself always runs first. +/// Schedule shared writes and draws from a skipped arm. Private expressions stay lazy. pub(super) fn identify(program: &mut Program) { let instructions = &program.instructions; if !instructions.iter().any(|op| op.definition.id == "ifelse") - || !instructions.iter().any(|op| op.definition.id == "rand") + || !instructions.iter().any(|op| matches!(op.definition.id, "rand" | "set")) || instructions.iter().any(|op| op.definition.id == "while" || op.call.as_ref().is_some_and(|call| call.exports)) { return; @@ -34,36 +33,32 @@ pub(super) fn identify(program: &mut Program) { }) .collect(); // A range depending on an assignment or image sample must stay at its original read. - let mut simple = Vec::with_capacity(instructions.len()); - let mut pattern_range = Vec::with_capacity(instructions.len()); + let mut independent_range = Vec::with_capacity(instructions.len()); for op in instructions { - simple.push(op.type_code == 256 && (op.definition.id == "const_float1" || (op.definition.id == "rand" && op.inputs.iter().all(|&i| simple[i])))); let fixed_input = op.definition.id == "get_float1" && matches!(&op.value, Some(Value::Text(name)) if !written.contains(name.as_str())); - pattern_range.push(op.type_code == 256 && (op.literal || fixed_input || (op.definition.id == "rand" && op.inputs.iter().all(|&i| pattern_range[i])))); + independent_range + .push(op.type_code == 256 && (op.literal || fixed_input || (op.definition.id == "rand" && op.inputs.iter().all(|&i| independent_range[i])))); } - let pixel = if written.is_empty() { shared_draws(program, &simple, None) } else { BTreeMap::new() }; // A called graph can observe the caller's assignments without listing them among its inputs. if written.is_empty() || instructions.iter().all(|op| op.call.is_none()) { - program.pattern_draws = shared_draws(program, &pattern_range, Some(&program.pattern_components)); - } - for (index, draws) in pixel { - program.instructions[index].control_registers = draws.shared; + program.processor_branches = shared_inputs(program, &independent_range, None); + program.pattern_branches = shared_inputs(program, &independent_range, Some(&program.pattern_components)); } } -fn shared_draws(program: &Program, ranges: &[bool], components: Option<&BTreeMap>) -> BTreeMap { +fn shared_inputs(program: &Program, ranges: &[bool], components: Option<&BTreeMap>) -> BTreeMap { let instructions = &program.instructions; let mut paths = vec![0_u8; instructions.len()]; let mut stack = Vec::new(); - let mut draws = Vec::new(); + let mut effects = Vec::new(); let mut plans = BTreeMap::new(); for (branch, op) in instructions.iter().enumerate().filter(|(_, op)| op.definition.id == "ifelse") { let &[_, yes, no] = op.inputs.as_slice() else { continue }; paths.fill(0); - draws.clear(); - // The first visit through the true arm sets the order when both arms use multiple draws. + effects.clear(); + // Record the order of first use through each arm. for (root, path) in [(yes, 1), (no, 2), (program.output, 4)] { - if path == 4 && draws.is_empty() { + if path == 4 && effects.is_empty() { break; } stack.push(root); @@ -72,10 +67,16 @@ fn shared_draws(program: &Program, ranges: &[bool], components: Option<&BTreeMap continue; } let node = &instructions[index]; - if paths[index] == 0 && path != 4 && ranges[index] && node.definition.id == "rand" && !node.inputs.is_empty() { - draws.push(index); + let shared_write = op.control_registers.binary_search(&index).is_ok(); + let draw = node.definition.id == "rand" && ranges[index] && !node.inputs.is_empty(); + if paths[index] == 0 && path != 4 && (shared_write || draw) { + effects.push(index); } paths[index] |= path; + // Evaluating a shared expression performs any conditional writes within it in their own scope. + if shared_write { + continue; + } match components.and_then(|components| components.get(&index)) { Some(PatternComponent::Scalar(source)) => stack.push(*source), Some(PatternComponent::Zero) => {} @@ -91,11 +92,15 @@ fn shared_draws(program: &Program, ranges: &[bool], components: Option<&BTreeMap } } } - let shared: Vec<_> = draws.iter().copied().filter(|&i| paths[i].count_ones() > 1).collect(); + let shared: Vec<_> = effects.iter().copied().filter(|&i| paths[i].count_ones() > 1).collect(); if !shared.is_empty() { let true_count = shared.iter().take_while(|&&i| paths[i] & 1 != 0).count(); - plans.insert(branch, PatternDraws { shared, true_count }); + plans.insert(branch, BranchInputs { shared, true_count }); } } plans } + +#[cfg(test)] +#[path = "branch_inputs.test.rs"] +mod tests; diff --git a/crates/nodes/src/function/branch_inputs.test.rs b/crates/nodes/src/function/branch_inputs.test.rs new file mode 100644 index 00000000..3cffe28f --- /dev/null +++ b/crates/nodes/src/function/branch_inputs.test.rs @@ -0,0 +1,79 @@ +use crate::function::{EvaluationContext, EvaluationState, FunctionScope, compile}; +use materialcraft_core::{FunctionGraph, Value}; +use std::collections::BTreeMap; + +#[test] +fn shared_conditional_draws_follow_their_arm_and_keep_their_original_position() { + let mut graph = FunctionGraph::default(); + let choice = graph.add("get_bool", &[], Some(Value::Text("first".into()))); + let one = graph.add_constant(Value::Float(1.0)); + let quarter = graph.add_constant(Value::Float(0.25)); + let [a, b, c, next] = std::array::from_fn(|_| graph.add("rand", &[one], None)); + let left = graph.add("add", &[b, a], None); + let right = graph.add("add", &[c, a], None); + let either = graph.add("ifelse", &[choice, left, right], None); + let false_only = graph.add("ifelse", &[choice, b, a], None); + let sum = graph.add("add", &[next, a], None); + let weighted = graph.add("mul", &[sum, quarter], None); + let both_result = graph.add("add", &[either, weighted], None); + let right_result = graph.add("add", &[false_only, weighted], None); + let pair = graph.add("vector2", &[a, b], None); + let control = graph.add("vector3", &[pair, c], None); + + for scope in [FunctionScope::Node, FunctionScope::PixelProcessor, FunctionScope::ValueProcessor, FunctionScope::FxMap] { + for first in [true, false] { + let values = BTreeMap::from([("first".into(), Value::Bool(first))]); + let ctx = EvaluationContext { scope, size: [16.0; 2], position: [0.03125; 2], images: &[], image_formats: &[], tile: true, variables: &values }; + for seed in [3, 20] { + graph.output = Some(control); + let Value::Float3([r1, r2, r3]) = compile(&graph, seed).unwrap().evaluate(&ctx, &mut EvaluationState::default()).unwrap() else { + panic!("three draws") + }; + let expected_both = r1 + r2 + (r3 + if first { r2 } else { r1 }) * 0.25; + let expected_right = if first { r1 + (r3 + r2) * 0.25 } else { r1 + (r2 + r1) * 0.25 }; + for (output, expected) in [(both_result, expected_both), (right_result, expected_right)] { + graph.output = Some(output); + assert_eq!( + compile(&graph, seed).unwrap().evaluate(&ctx, &mut EvaluationState::default()).unwrap(), + Value::Float(expected), + "{scope:?}, {first}, {output}" + ); + } + } + } + } +} + +#[test] +fn an_assignment_shared_only_with_the_later_arm_keeps_the_earlier_arms_read() { + let mut graph = FunctionGraph::default(); + let name = Some(Value::Text("tone".into())); + let choice = graph.add("get_bool", &[], Some(Value::Text("first".into()))); + let start = graph.add_constant(Value::Float(0.125)); + let changed = graph.add_constant(Value::Float(0.625)); + let quarter = graph.add_constant(Value::Float(0.25)); + let init = graph.add("set", &[start], name.clone()); + let set = graph.add("set", &[changed], name.clone()); + let read = graph.add("get_float1", &[], name); + let left = graph.add("ifelse", &[choice, set, read], None); + let right = graph.add("ifelse", &[choice, read, set], None); + let weighted = graph.add("mul", &[set, quarter], None); + let left_sum = graph.add("add", &[left, weighted], None); + let right_sum = graph.add("add", &[right, weighted], None); + let left_result = graph.add("sequence", &[init, left_sum], None); + let right_result = graph.add("sequence", &[init, right_sum], None); + for scope in [FunctionScope::Node, FunctionScope::PixelProcessor, FunctionScope::ValueProcessor, FunctionScope::FxMap] { + for first in [false, true] { + let values = BTreeMap::from([("first".into(), Value::Bool(first))]); + let ctx = EvaluationContext { scope, size: [16.0; 2], position: [0.03125; 2], images: &[], image_formats: &[], tile: true, variables: &values }; + for (root, expected) in [(left_result, 0.78125), (right_result, if first { 0.28125 } else { 0.78125 })] { + graph.output = Some(root); + assert_eq!( + compile(&graph, 0).unwrap().evaluate(&ctx, &mut EvaluationState::default()).unwrap(), + Value::Float(expected), + "{scope:?}, {first}, {root}" + ); + } + } + } +} diff --git a/crates/nodes/src/function/compile.rs b/crates/nodes/src/function/compile.rs index b499b83c..b3227baf 100644 --- a/crates/nodes/src/function/compile.rs +++ b/crates/nodes/src/function/compile.rs @@ -240,7 +240,8 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu output, seed, sequence_prefixes, - pattern_draws: BTreeMap::new(), + processor_branches: BTreeMap::new(), + pattern_branches: BTreeMap::new(), pattern_components: BTreeMap::new(), loop_sums: BTreeMap::new(), }) @@ -304,7 +305,7 @@ fn plan_pixel_operations(program: &mut Program, pixel: Option<&super::Evaluation super::product_sum::identify(&mut program.instructions, readers.as_deref()); super::branch_assignments::identify(program); super::vector::identify_pattern_components(program); - super::branch_random::identify(program); + super::branch_inputs::identify(program); let exported = super::returned_product::identify(program, returned, root); program.loop_sums = program.instructions.iter().enumerate().filter_map(|(index, op)| super::loop_sum::LoopSum::identify(program, op).map(|sum| (index, sum))).collect(); diff --git a/crates/nodes/src/function/mod.rs b/crates/nodes/src/function/mod.rs index 087690d4..f2175a07 100644 --- a/crates/nodes/src/function/mod.rs +++ b/crates/nodes/src/function/mod.rs @@ -12,7 +12,7 @@ mod arithmetic; mod assigned_product; mod binary_exponential; mod branch_assignments; -mod branch_random; +mod branch_inputs; mod catalog; mod compile; mod evaluation_context; diff --git a/crates/nodes/src/function/program.rs b/crates/nodes/src/function/program.rs index 9483e2f7..20314d7b 100644 --- a/crates/nodes/src/function/program.rs +++ b/crates/nodes/src/function/program.rs @@ -9,7 +9,8 @@ pub struct Program { pub(crate) instructions: Vec, pub(crate) output: usize, pub(crate) seed: u32, - pub(super) pattern_draws: std::collections::BTreeMap, + pub(super) processor_branches: std::collections::BTreeMap, + pub(super) pattern_branches: std::collections::BTreeMap, pub(super) pattern_components: std::collections::BTreeMap, pub(super) sequence_prefixes: Vec, pub(super) loop_sums: std::collections::BTreeMap, @@ -371,10 +372,13 @@ impl Program { let condition = state.values.pop().ok_or("missing branch condition")?; let take_true = value_type::boolean(&condition)?; let selected = self.input(index, if take_true { 1 } else { 2 })?; - let (shared, after_selected) = match context.scope { - super::FunctionScope::PixelProcessor => (self.instruction(index)?.control_registers.as_slice(), false), - super::FunctionScope::FxMap => self.pattern_draws.get(&index).map_or((&[][..], false), |draws| (draws.skipped(take_true), take_true)), - _ => (&[][..], false), + let branches = if context.scope == super::FunctionScope::FxMap { &self.pattern_branches } else { &self.processor_branches }; + let (shared, after_selected) = if let Some(inputs) = branches.get(&index) { + (inputs.skipped(take_true), take_true) + } else if context.scope == super::FunctionScope::PixelProcessor { + (self.instruction(index)?.control_registers.as_slice(), false) + } else { + (&[][..], false) }; let selected = || if prefix { Prefix(selected) } else { Enter(selected) }; if !after_selected { diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index 05d4fea0..dfec6c14 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -99,6 +99,21 @@ Each rectangular capture matches 8,192/8,192 pixels, maximum 0. The seed-0 defau At seed 372421, some BNW Spots 1 captures match the entire MaterialCraft buffer at each affinity. Clouds 1 has one stable differing pixel among the six eight-processor captures. Clouds 2 has one at each affinity. The six samples at each affinity establish repeatability only for those captures. All three remain in progress. [Single-processor desktop and standalone results](#live-desktop-and-standalone-rendering-of-three-noise-roots) +### Conditional inputs shared across function branches + +Build fourteen original functions that select between two arms. Share a Random(1) between an arm and the result, or between both arms. Place a separate draw before the shared draw in each arm. For an assignment, initialize a float to .125, assign .625 in one arm and read it from the other. Add a quarter of the assigned result after the conditional. Swap the arms and include both possible conditions. Additional controls use a stored range, a graph input as the range and an assignment read by the condition. Run each at 16² for graph seeds 0 and 17 and both signs of the control. Repeat on ordinary saves reopened in the reference desktop. + +| Function context | Previous exact samples · maximum error | Corrected original exact samples | Corrected reopened exact samples | +|---|---:|---:|---:| +| FX-Map quadrant opacity, F32 pixels | 11,776/14,336 · 0.5 | 14,336/14,336 | 14,336/14,336 | +| Pixel Processor, F32 pixels | 11,776/14,336 · 1.094946325 | 14,336/14,336 | 14,336/14,336 | +| Uniform Color parameter, RGBA F32 pixels | 9,216/14,336 · 0.5 | 14,336/14,336 | 14,336/14,336 | +| Value Processor, typed floats | 36/56 · 0.5 | 56/56 | 56/56 | + +Maximum error is zero in both corrected columns and between original and reopened desktop results. A shared write in the later arm takes effect after the earlier arm reads its variable. Sharing a draw across the arms preserves a selected arm’s preceding draw. The function evaluator now uses that order for shared writes and eligible random draws. Private arm expressions still evaluate lazily. + +Ten earlier conditional graphs match 94,720/94,720 pixels across 70 renders. White Noise v2 matches 10,240/10,240 intermediate pixels across ten ports and 69,120/69,120 root pixels across 72 captures. The grayscale Tile Generator matches 284,416/284,416 across its 55 distinct settings. All maximum errors are zero. Discarded loops and random graph arguments have separate outstanding measurements. [Loop controls](#sequence-evaluation-and-scalar-random-values) + ### Sequence evaluation and scalar random values Build an original function around two distinct Random(1) nodes. In Sequence, use the first draw directly, multiply it by zero in the returned expression, assign it to a variable, or use it in both the discarded input and the returned expression. Include a write with a second unused draw beside it, a conditional write and both signs of its control. Render the eleven variants at 16², with control +1 and −1 and graph seeds 0 and 17. Repeat after an ordinary MaterialCraft save and desktop reopen. @@ -112,7 +127,7 @@ Build an original function around two distinct Random(1) nodes. In Sequence, use A discarded draw leaves the next random value available. A write, a draw used elsewhere or a draw multiplied by zero in the returned expression can still advance the stream. Scalar Value Processor starts its stream at the zero-coordinate pixel hash. A second test uses the first draw, a zero-weighted draw and a shared draw, with twelve caller seeds from 0 through 372421, a relative seed offset of +3 and two sizes (16² and 128 × 32). All 72/72 typed results match on the original and the reopened graphs, maximum 0. Each original desktop result above also matches the reopened desktop result. -Two further controls put a three-iteration loop on the discarded side of Sequence. Its body either discards Random(1) or assigns the draw. The reference returns the first draw after either loop. These cases still differ in MaterialCraft. Across both loops and four settings, FX-Map matches 0/2,048, maximum 0.386968136, Pixel Processor matches 0/2,048, maximum 0.961201191 and Value Processor matches 0/8, maximum 0.662862062. Seven further controls outside those two loops, including an empty loop, produce 7,168/7,168, maximum 0 in FX-Map, 7,168/7,168, maximum 0 in Pixel Processor and 24/28, maximum 0.45432511 in Value Processor. The four scalar differences occur when a false conditional arm shares a draw with another expression. Random expressions passed as graph arguments are also under separate investigation. +Two further controls put a three-iteration loop on the discarded side of Sequence. Its body either discards Random(1) or assigns the draw. The reference returns the first draw after either loop. These cases still differ in MaterialCraft. Across both loops and four settings, FX-Map matches 0/2,048, maximum 0.386968136, Pixel Processor matches 0/2,048, maximum 0.961201191 and Value Processor matches 0/8, maximum 0.662862062. Seven further controls outside those two loops, including an empty loop, produce 7,168/7,168, maximum 0 in FX-Map, 7,168/7,168, maximum 0 in Pixel Processor and 24/28, maximum 0.45432511 in Value Processor. Those four scalar differences occurred when a false conditional arm shared a draw with another expression. The later conditional comparison measures that case after the correction. [Conditional results](#conditional-inputs-shared-across-function-branches) Random expressions passed as graph arguments are also under separate investigation. ### Sampling properties on graph inputs and outputs diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index e6aa8d44..bdc4bbff 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -45,7 +45,7 @@ An image wired through a graph instance retains its per-pin pixel size, tiling a 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 and instance pixel-size fixes, default Base Color matches 4,096/4,096 raw pixels at 64² and 16,379/16,384 at 128², maximum byte errors 0 and 1. At 256² the raw outputs match 65,508/65,536, maximum 1. [Child output pixel size and whole-material measurements](parity-fixes.md#pixel-size-on-graph-instance-outputs) [Color swatches](parity-fixes.md#stored-graph-color-in-the-2d-view) · [Whole-material measurements](parity-fixes.md#selected-channels-in-pattern-expressions) -Original Sequence controls and their ordinary saves each match 11,264/11,264 pixels in each of three image contexts and 44/44 typed Value Processor results. A further 72/72 typed values match across seeds and dimensions. Discarded loops and shared draws in scalar conditionals have remaining differences. [Procedure, exact counts and maximum errors](parity-fixes.md#sequence-evaluation-and-scalar-random-values) +Original Sequence controls and their ordinary saves each match 11,264/11,264 pixels in each of three image contexts and 44/44 typed Value Processor results. A further 72/72 typed values match across seeds and dimensions. Fourteen conditional graphs now match 14,336/14,336 pixels in each image context and 56/56 typed floats, on originals and ordinary saves. Discarded loops still differ. [Shared conditional draws and writes](parity-fixes.md#conditional-inputs-shared-across-function-branches) [Procedure, exact counts and maximum errors](parity-fixes.md#sequence-evaluation-and-scalar-random-values) 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)