From 4851705016ac1fa7a7d8de01c1957e360ba1a3b0 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 25 Nov 2026 11:36:50 -0500 Subject: [PATCH] Resolve writable quadrant floats from their drawing inputs --- crates/eval/src/node_execution.rs | 9 +- crates/eval/src/parameter.rs | 11 ++- crates/eval/src/resolved_base_parameters.rs | 27 +++++- crates/eval/tests/pattern_opacity.rs | 58 +++++++++++ crates/nodes/src/function/program.rs | 8 +- crates/nodes/src/pattern/evaluation.rs | 101 ++++++++++++++++---- crates/nodes/src/pattern/mod.rs | 2 +- crates/nodes/src/pattern/tests.rs | 33 ++++++- crates/nodes/src/pattern/variables.rs | 11 ++- docs/parity-fixes.md | 27 ++++++ docs/sbs-root-nodes.md | 6 +- 11 files changed, 257 insertions(+), 36 deletions(-) diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs index 179068bf..28f16eda 100644 --- a/crates/eval/src/node_execution.rs +++ b/crates/eval/src/node_execution.rs @@ -172,11 +172,12 @@ pub(crate) fn cook_node( } let seed = base.seed; - let ResolvedParameters { values: mut parameters, instance_literals, dynamic_blend_opacity } = + let ResolvedParameters { values: mut parameters, instance_literals, dynamic_blend_opacity, bound_pattern_property } = match resolve_parameters(package, node, definition, &mut variables, base, &fixed) { Ok(parameters) => parameters, Err(error) => return fail(error, 0), }; + let bound_pattern_property = bound_pattern_property || (node.def == "fx_map" && (base.bound_seed || base.bound_size)); if matches!(node.def.as_str(), "blur" | "emboss") { variables.to_mut().insert("$pixelsize".into(), Value::Float2(base.pixel_size)); } @@ -214,7 +215,7 @@ pub(crate) fn cook_node( let key = hash_of(&( &node.def, serde_json::to_string(¶meters).unwrap_or_default(), - dynamic_blend_opacity, + (dynamic_blend_opacity, bound_pattern_property), ( w, h, @@ -223,7 +224,7 @@ pub(crate) fn cook_node( node.disabled, base.size, base.size_underflow, - base.dynamic_size, + (base.dynamic_size, base.bound_size), base.format, base.tiling, base.pixel_ratio, @@ -324,7 +325,7 @@ pub(crate) fn cook_node( Ok(vec![output]) } else { let result = if node.def == "fx_map" { - materialcraft_nodes::pattern::cook_with_base_level_inputs(&context, &base_level_only) + materialcraft_nodes::pattern::cook_with_bound_properties(&context, &base_level_only, bound_pattern_property) } else if node.def == "text" && !context.text("fontdata").is_empty() && let Some(font) = package.resource(context.text("fontdata")) diff --git a/crates/eval/src/parameter.rs b/crates/eval/src/parameter.rs index ba7787bb..ecacdd85 100644 --- a/crates/eval/src/parameter.rs +++ b/crates/eval/src/parameter.rs @@ -8,6 +8,7 @@ pub(crate) struct ResolvedParameters { pub values: BTreeMap, pub instance_literals: Vec, pub dynamic_blend_opacity: bool, + pub bound_pattern_property: bool, } pub(crate) fn supports_literal_argument(value: &Value) -> bool { @@ -50,6 +51,8 @@ pub(crate) fn resolve_parameters( let mut dynamic = std::collections::BTreeSet::new(); let mut dynamic_blend_opacity = false; + let mut bound_pattern_property = false; + let pattern_property = |name: &str| node.def == "fx_map" && matches!(name, "opacity" | "roughness" | "background" | "render_region" | "tiling_region"); let mut uniform_color = None; for (parameter, exposed) in &node.bindings { if node.def == "uniform" && parameter == "color" { @@ -64,6 +67,9 @@ pub(crate) fn resolve_parameters( if node.def == "blend" && parameter == "opacity" { dynamic_blend_opacity = !literal_inputs.contains(exposed); } + if pattern_property(parameter) && !node.functions.contains_key(parameter) { + bound_pattern_property |= !literal_inputs.contains(exposed); + } parameters.insert(parameter.clone(), coerced); } } @@ -86,6 +92,9 @@ pub(crate) fn resolve_parameters( if node.def == "blend" && parameter == "opacity" { dynamic_blend_opacity = program.reads_graph_parameter(variables); } + if pattern_property(parameter) { + bound_pattern_property |= program.reads_graph_parameter(variables); + } crate::parameter_function::evaluate(&program, expected, variables.to_mut(), base.size, mode, Some(current)) }) .map_err(|error| format!("function of `{parameter}`: {error}"))?; @@ -131,7 +140,7 @@ pub(crate) fn resolve_parameters( } else { Vec::new() }; - Ok(ResolvedParameters { values: parameters, instance_literals: fixed, dynamic_blend_opacity }) + Ok(ResolvedParameters { values: parameters, instance_literals: fixed, dynamic_blend_opacity, bound_pattern_property }) } pub(crate) fn inspection_parameters(node: &Node, parameters: &mut BTreeMap) { diff --git a/crates/eval/src/resolved_base_parameters.rs b/crates/eval/src/resolved_base_parameters.rs index e82b1609..b41a35b1 100644 --- a/crates/eval/src/resolved_base_parameters.rs +++ b/crates/eval/src/resolved_base_parameters.rs @@ -9,6 +9,12 @@ pub struct ResolvedBaseParameters { /// This texture inherits or evaluates a size controlled by a runtime parameter. #[serde(skip)] pub dynamic_size: bool, + /// The resolved dimensions depend on a live graph input, including through size inheritance. + #[serde(skip)] + pub bound_size: bool, + /// This node's seed expression reads a live graph input. + #[serde(skip)] + pub bound_seed: bool, /// Negative requested exponents on axes whose allocated texture is one texel. #[serde(skip)] pub size_underflow: [i32; 2], @@ -32,6 +38,8 @@ impl ResolvedBaseParameters { Self { size, dynamic_size: graph.absolute_output_size.is_none() && parent.is_some_and(|base| base.dynamic_size), + bound_size: graph.output_size_setting().0 != materialcraft_core::SizeMode::Absolute && parent.is_some_and(|base| base.bound_size), + bound_seed: false, size_underflow, seed: resolve_seed(graph.seed_mode, graph.seed, parent.map_or(0, |base| base.seed)), format: match graph.format { @@ -50,12 +58,13 @@ impl ResolvedBaseParameters { function: &materialcraft_core::FunctionGraph, options: &crate::Options<'_>, variables: &BTreeMap, - ) -> Result<(Value, bool), String> { + ) -> Result<(Value, bool, bool), String> { let mut variables = variables.clone(); self.variables(&mut variables); compile_with_literal_inputs(function, self.seed, &options.literal_inputs) .and_then(|program| { let dynamic = !program.output_is_literal() && !program.depends_only_on_image_size(); + let bound = program.reads_graph_parameter(&variables); let (value, _) = crate::parameter_function::evaluate( &program, parameter.value_type(), @@ -64,7 +73,7 @@ impl ResolvedBaseParameters { crate::parameter_function::ParameterMode::for_base(parameter), None, )?; - Ok((value, dynamic)) + Ok((value, dynamic, bound)) }) .map_err(|error| format!("graph {}: {error}", parameter.label().to_ascii_lowercase())) } @@ -78,10 +87,11 @@ impl ResolvedBaseParameters { parent.unwrap_or_else(|| (graph.parent_size_px(), [0; 2])) }; let context = Self { size, size_underflow, ..*self }; - let (value, dynamic) = context.graph_function_value(BaseParameter::OutputSize, function, options, variables)?; + let (value, dynamic, bound) = context.graph_function_value(BaseParameter::OutputSize, function, options, variables)?; let Value::Int2(offset) = value else { return Err("graph output size requires an integer pair".into()) }; (self.size, self.size_underflow) = graph.resolved_output_size(parent, Some(offset)); self.dynamic_size |= dynamic; + self.bound_size |= bound; Ok(()) } @@ -90,7 +100,7 @@ impl ResolvedBaseParameters { let parent_seed = options.parent_base.map_or(0, |base| base.seed); // Graph seed functions see the allocated dimensions even when descendants retain a negative size exponent. let context = Self { seed: resolve_seed(graph.seed_mode, 0, parent_seed), size_underflow: [0; 2], ..*self }; - let (value, _) = context.graph_function_value(BaseParameter::RandomSeed, function, options, variables)?; + let (value, _, _) = context.graph_function_value(BaseParameter::RandomSeed, function, options, variables)?; let Value::Int(offset) = value else { return Err("graph random seed requires an integer".into()) }; self.seed = resolve_seed(graph.seed_mode, offset, parent_seed); Ok(()) @@ -107,6 +117,8 @@ impl ResolvedBaseParameters { size, size_underflow, dynamic_size: size_mode.resolve(false, input.map(|base| base.dynamic_size), parent.dynamic_size), + bound_size: size_mode.resolve(false, input.map(|base| base.bound_size), parent.bound_size), + bound_seed: false, seed: resolve_seed(base.seed_mode, base.seed, parent.seed), format: BaseParameter::Format.inheritance(base).resolve(base.format, input.map(|base| base.format), parent.format), tiling: base.tiling_mode.resolve(base.tiling, input.map(|base| base.tiling), parent.tiling), @@ -161,6 +173,8 @@ pub(crate) fn evaluate( }; let mut values = BTreeMap::new(); let mut computed_size = false; + let mut bound_size = false; + let mut bound_seed = false; let mut resolved = ResolvedBaseParameters::resolve(&evaluated, input, parent); // Size and seed establish the context used by the remaining parameter functions @@ -186,6 +200,9 @@ pub(crate) fn evaluate( .and_then(|program| { if parameter == BaseParameter::OutputSize { computed_size = !program.output_is_literal() && !program.depends_only_on_image_size(); + bound_size = program.reads_graph_parameter(variables); + } else if parameter == BaseParameter::RandomSeed { + bound_seed = program.reads_graph_parameter(variables); } crate::parameter_function::evaluate( &program, @@ -206,5 +223,7 @@ pub(crate) fn evaluate( } resolved.dynamic_size |= computed_size; + resolved.bound_size |= bound_size; + resolved.bound_seed = bound_seed; Ok((resolved, values)) } diff --git a/crates/eval/tests/pattern_opacity.rs b/crates/eval/tests/pattern_opacity.rs index 6c707421..a9a42891 100644 --- a/crates/eval/tests/pattern_opacity.rs +++ b/crates/eval/tests/pattern_opacity.rs @@ -2,6 +2,64 @@ use materialcraft_core::{FunctionGraph, Graph, OutputFormat, Package, PatternGra use materialcraft_eval::{Cache, Options, cook}; use std::sync::Mutex; +#[test] +fn bound_pattern_property_changes_the_first_local_read_at_equal_opacity() { + let mut graph = Graph::new("First quadrant read"); + graph.size = [4; 2]; + graph.format = OutputFormat::F32; + let stamp = graph.add_node("fx_map", [0.0; 2]); + let node = graph.node_mut(stamp).unwrap(); + node.params.insert("color_mode".into(), Value::Bool(false)); + node.params.insert("roughness".into(), Value::Float(0.0)); + let mut pattern = PatternGraph::with_root(PatternNodeKind::Quadrant); + let fields = &mut pattern.nodes[0].parameters; + fields.insert("patterntype".into(), Value::Int(2)); + let mut tint = FunctionGraph::input("local", ValueType::Float); + let read = tint.output.unwrap(); + let equal = tint.add("eq", &[read, read], None); + let yes = tint.add_constant(Value::Float(0.375)); + let no = tint.add_constant(Value::Float(0.625)); + let choose = tint.add("ifelse", &[equal, yes, no], None); + tint.output = Some(tint.add("set", &[choose], Some(Value::Text("local".into())))); + fields.insert("opacity".into(), Value::Function(Box::new(tint))); + node.params.insert("pattern".into(), Value::PatternGraph(Box::new(pattern))); + + let mut package = Package::new("Quadrant parameter origin"); + package.graphs.push(graph); + let mut options = Options::new(&|_| None); + options.overrides.insert("gain".into(), Value::Float(1.0)); + let cache = Mutex::new(Cache::default()); + for direct in [true, false] { + let node = package.graphs[0].node_mut(stamp).unwrap(); + if direct { + node.bindings.insert("opacity".into(), "gain".into()); + } else { + node.bindings.clear(); + node.functions.insert("opacity".into(), FunctionGraph::input("gain", ValueType::Float)); + } + for fixed in [true, false, true] { + options.literal_inputs = if fixed { vec!["gain".into()] } else { Vec::new() }; + let result = cook(&package, 0, &options, &cache); + assert_eq!(result.nodes[&stamp].error, None); + let expected = if fixed { 0.375 } else { 0.625 }; + assert_eq!(result.image(stamp, 0).unwrap().get_gray(8, 8, false), expected, "direct {direct}, fixed {fixed}"); + } + } + + let graph = &mut package.graphs[0]; + graph.node_mut(stamp).unwrap().functions.clear(); + graph.output_size_function = Some(FunctionGraph::input("offset", ValueType::Integer2)); + options.overrides.insert("offset".into(), Value::Int2([0; 2])); + for (mode, expected) in [(materialcraft_core::SizeMode::RelativeToParent, 0.625), (materialcraft_core::SizeMode::Absolute, 0.375)] { + let base = &mut package.graphs[0].node_mut(stamp).unwrap().base; + base.size_mode = mode; + base.size = if mode == materialcraft_core::SizeMode::Absolute { [4; 2] } else { [0; 2] }; + let result = cook(&package, 0, &options, &cache); + assert_eq!(result.nodes[&stamp].error, None); + assert_eq!(result.image(stamp, 0).unwrap().get_gray(0, 0, false), expected, "{mode:?}"); + } +} + #[test] fn gray_pattern_opacity_keeps_signed_and_undefined_contributions_until_blending() { let mut graph = Graph::new("Signed stamp opacity"); diff --git a/crates/nodes/src/function/program.rs b/crates/nodes/src/function/program.rs index fdc0f4d5..16ddb7f3 100644 --- a/crates/nodes/src/function/program.rs +++ b/crates/nodes/src/function/program.rs @@ -58,10 +58,12 @@ impl Program { /// Whether the property reads a bound graph parameter, even if its final value is constant. pub fn reads_graph_parameter(&self, variables: &std::collections::BTreeMap) -> bool { + self.reads_bound_input(|name| variables.contains_key(name)) + } + + pub(crate) fn reads_bound_input(&self, bound: impl Fn(&str) -> bool) -> bool { self.instructions.iter().any(|op| { - !op.literal - && op.definition.id.starts_with("get_") - && matches!(&op.value, Some(Value::Text(name)) if !name.starts_with('$') && variables.contains_key(name)) + !op.literal && op.definition.id.starts_with("get_") && matches!(&op.value, Some(Value::Text(name)) if !name.starts_with('$') && bound(name)) }) } diff --git a/crates/nodes/src/pattern/evaluation.rs b/crates/nodes/src/pattern/evaluation.rs index 6f1f3d8e..26cf7838 100644 --- a/crates/nodes/src/pattern/evaluation.rs +++ b/crates/nodes/src/pattern/evaluation.rs @@ -1,9 +1,9 @@ -use materialcraft_core::{PatternNode, PatternNodeKind, Value}; +use materialcraft_core::{PatternNode, PatternNodeKind, Value, ValueType}; use std::collections::{BTreeMap, BTreeSet}; use super::mixed_depth_runs::MixedDepthRuns; use super::{catalog, footprint::SampleGrid, pattern_stamp::PatternStamp, pattern_visit::PatternVisit, raster, variables::PatternVariables}; -use crate::function::{EvaluationContext, EvaluationState, compile_with_literal_inputs}; +use crate::function::{EvaluationContext, EvaluationState, Program, compile_with_literal_inputs}; use crate::random::FunctionRandom; use crate::{CookContext, CookResult}; @@ -23,7 +23,75 @@ enum QuadrantChildren { Other, } -fn has_uniform_quadrant_leaves(root: u32, depth: u32, nodes: &BTreeMap) -> bool { +type PatternNodes<'a> = BTreeMap; +type PropertyPrograms<'a> = BTreeMap<(u32, &'a str), (Program, BTreeMap)>; + +fn quadrant_mode(kind: PatternNodeKind, name: &str) -> bool { + kind == PatternNodeKind::Quadrant && matches!(name, "patterntype" | "blendingmode" | "imagefiltering" | "imagepremul" | "randominherited") +} + +fn image_pattern(pattern: i32) -> bool { + pattern == 1 || (256..256 + crate::MAX_IMAGE_INPUTS as i32).contains(&pattern) +} + +fn uses_property(kind: PatternNodeKind, name: &str, pattern: i32) -> bool { + match name { + "randomseed" | "randominherited" | "patterntype" | "branchoffset" => true, + "imageindex" | "imagefiltering" | "imagepremul" => image_pattern(pattern), + _ => kind != PatternNodeKind::Quadrant || pattern != 0, + } +} + +fn has_bound_draw(root: Option, nodes: &PatternNodes, programs: &PropertyPrograms, context: &CookContext, modes: &BTreeMap) -> bool { + // Both connected alternatives contribute, even when a switch or zero iteration skips one during traversal. + let mut pending: Vec<_> = root.into_iter().collect(); + let mut seen = BTreeSet::new(); + let mut state = EvaluationState::default(); + while let Some(id) = pending.pop() { + if !seen.insert(id) { + continue; + } + let Some(&(node, _, _)) = nodes.get(&id) else { continue }; + pending.extend(node.children.iter().flatten().copied()); + let Some(definition) = catalog::definition(node.kind) else { continue }; + let mut pattern = None; + for field in &definition.params { + if field.id == "randominherited" + || quadrant_mode(node.kind, field.id) + || !programs + .get(&(id, field.id)) + .is_some_and(|(program, locals)| program.reads_bound_input(|name| !locals.contains_key(name) && context.vars.contains_key(name))) + { + continue; + } + if uses_property(node.kind, field.id, 0) { + return true; + } + let shape = pattern.get_or_insert_with(|| { + if let Some((program, _)) = programs.get(&(id, "patterntype")) { + let evaluation = EvaluationContext { + image_formats: context.input_formats.get(1..).unwrap_or(&[]), + scope: crate::function::FunctionScope::FxMap, + position: [0.0; 2], + size: [context.w as f32, context.h as f32], + images: context.inputs.get(1..).unwrap_or(&[]), + tile: context.tile, + variables: modes, + }; + program.evaluate_with_random(&evaluation, &mut state, &mut FunctionRandom::image(context.seed)).ok().and_then(|v| v.as_i32()).unwrap_or(0) + } else { + node.parameters.get("patterntype").and_then(Value::as_i32).unwrap_or(0) + } + }); + if uses_property(node.kind, field.id, *shape) { + return true; + } + } + } + false +} + +fn has_uniform_quadrant_leaves(root: u32, depth: u32, nodes: &PatternNodes) -> bool { let mut level = BTreeSet::from([root]); for current in 0..=depth { let mut next = BTreeSet::new(); @@ -108,10 +176,15 @@ pub(crate) fn cook(context: &CookContext) -> CookResult { /// Cook a pattern with the supplied base-level-only flags in image port order. pub fn cook_with_base_level_inputs(context: &CookContext, base_level_only: &[bool]) -> CookResult { - cook_with_visit_limit(context, base_level_only, MAX_VISITS) + cook_with_bound_properties(context, base_level_only, false) } -pub(super) fn cook_with_visit_limit(context: &CookContext, base_level_only: &[bool], visit_limit: usize) -> CookResult { +/// A live input to a drawing property affects reads of a local preceding its first assignment. +pub fn cook_with_bound_properties(context: &CookContext, base_level_only: &[bool], bound_property: bool) -> CookResult { + cook_with_visit_limit(context, base_level_only, MAX_VISITS, bound_property) +} + +pub(super) fn cook_with_visit_limit(context: &CookContext, base_level_only: &[bool], visit_limit: usize, bound_property: bool) -> CookResult { let Some(Value::PatternGraph(graph)) = context.params.get("pattern") else { return Err("missing pattern graph".into()); }; @@ -164,9 +237,9 @@ pub(super) fn cook_with_visit_limit(context: &CookContext, base_level_only: &[bo let mut branch_starts = [None; 4]; let mut variables = PatternVariables::new(context.vars.graph_values()); - let separate_child_variables = opacity_depth == 6 - && functions.values().any(|(_, names)| !names.is_empty()) - && graph.root.is_some_and(|root| has_uniform_quadrant_leaves(root, opacity_depth, &nodes)); + let has_locals = functions.values().any(|(_, names)| !names.is_empty()); + variables.bound_draw = has_locals && (bound_property || has_bound_draw(graph.root, &nodes, &functions, context, &variables.modes)); + let separate_child_variables = opacity_depth == 6 && has_locals && graph.root.is_some_and(|root| has_uniform_quadrant_leaves(root, opacity_depth, &nodes)); let mut max_depth = 0; let mut state = EvaluationState::default(); let mut terminal_siblings: Option<(usize, bool)> = None; @@ -250,8 +323,7 @@ pub(super) fn cook_with_visit_limit(context: &CookContext, base_level_only: &[bo let mut evaluate = |id: &str, random: &mut FunctionRandom| -> Result, String> { let Some((program, names)) = functions.get(&(node.id, id)) else { return Ok(node.parameters.get(id).cloned()) }; - let mode = - node.kind == PatternNodeKind::Quadrant && matches!(id, "patterntype" | "blendingmode" | "imagefiltering" | "imagepremul" | "randominherited"); + let mode = quadrant_mode(node.kind, id); if !mode { variables.enter(names, visit.depth, &mut declared); } @@ -291,14 +363,9 @@ pub(super) fn cook_with_visit_limit(context: &CookContext, base_level_only: &[bo parameter_values.clear(); let mut random = FunctionRandom::image(visit.seed); let mut pattern = if node.kind == PatternNodeKind::Quadrant { evaluate("patterntype", &mut random)?.and_then(|v| v.as_i32()).unwrap_or(0) } else { 0 }; - let image_pattern = pattern == 1 || (256..256 + crate::MAX_IMAGE_INPUTS as i32).contains(&pattern); + let image_pattern = image_pattern(pattern); // An unused stamp property cannot publish a Set to a child. The branch offset still positions that child. - let active = |id: &str| match id { - "patterntype" | "randomseed" | "randominherited" => false, - "branchoffset" => true, - "imageindex" | "imagefiltering" | "imagepremul" => image_pattern, - _ => node.kind != PatternNodeKind::Quadrant || pattern != 0, - }; + let active = |id: &str| !matches!(id, "patterntype" | "randomseed" | "randominherited") && uses_property(node.kind, id, pattern); for parameter in definition.params.iter().filter(|p| active(p.id)) { let mut stream = FunctionRandom::pattern(visit.seed, parameter.id); let value = evaluate(parameter.id, stream.as_mut().unwrap_or(&mut random))?.unwrap_or_else(|| parameter.default.clone()); diff --git a/crates/nodes/src/pattern/mod.rs b/crates/nodes/src/pattern/mod.rs index 68c22edb..26fe259d 100644 --- a/crates/nodes/src/pattern/mod.rs +++ b/crates/nodes/src/pattern/mod.rs @@ -19,7 +19,7 @@ mod variables; pub use catalog::{definition, definitions}; pub(crate) use evaluation::cook; -pub use evaluation::cook_with_base_level_inputs; +pub use evaluation::{cook_with_base_level_inputs, cook_with_bound_properties}; #[cfg(test)] mod tests; diff --git a/crates/nodes/src/pattern/tests.rs b/crates/nodes/src/pattern/tests.rs index c525f3f1..7ed60163 100644 --- a/crates/nodes/src/pattern/tests.rs +++ b/crates/nodes/src/pattern/tests.rs @@ -1829,7 +1829,7 @@ fn render_with_visit_limit(graph: &PatternGraph, limit: usize) -> crate::CookRes resource: &|_| None, vars: &BTreeMap::new(), }; - super::evaluation::cook_with_visit_limit(&context, &[], limit) + super::evaluation::cook_with_visit_limit(&context, &[], limit, false) } #[test] @@ -1996,6 +1996,37 @@ fn set_then_return(name: &str, value: Value, result: Value) -> Value { Value::Function(Box::new(function)) } +#[test] +fn first_writable_float_depends_on_connected_draw_properties() { + let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); + let writer = graph.add(PatternNodeKind::Quadrant).unwrap(); + let switch = graph.add(PatternNodeKind::Switch).unwrap(); + let other = graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes[0].children = vec![Some(writer), Some(writer), Some(writer), Some(switch)]; + graph.nodes[2].children[0] = Some(writer); + square(&mut graph, 1); + + let mut field = FunctionGraph::input("local", materialcraft_core::ValueType::Float); + let current = field.output.unwrap(); + let defined = field.add("eq", &[current, current], None); + let yes = field.add_constant(Value::Float(0.375)); + let no = field.add_constant(Value::Float(0.625)); + let next = field.add("ifelse", &[defined, yes, no], None); + field.output = Some(field.add("set", &[next], Some(Value::Text("local".into())))); + graph.nodes[1].parameters.insert("opacity".into(), Value::Function(Box::new(field))); + let published = FunctionGraph::input("gain", materialcraft_core::ValueType::Float); + graph.nodes[3].parameters.insert("opacity".into(), Value::Function(Box::new(published))); + let bindings = BTreeMap::from([("gain".into(), Value::Float(0.8125))]); + for (connected, shape, first) in [(false, 2, 0.375), (true, 0, 0.375), (true, 2, 0.625)] { + graph.nodes[2].children[1] = connected.then_some(other); + graph.nodes[3].parameters.insert("patterntype".into(), Value::Int(shape)); + let image = cook_with_variables(graph.clone(), &bindings, 41301).unwrap().remove(0); + for (x, y, expected) in [(4, 4, first), (12, 4, 0.375), (4, 12, 0.375), (12, 12, 0.375)] { + assert_eq!(image.get_gray(x, y, false), expected, "connected {connected}, shape {shape}, pixel ({x}, {y})"); + } + } +} + #[test] fn quadrant_children_accumulate_in_their_own_depth() { let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); diff --git a/crates/nodes/src/pattern/variables.rs b/crates/nodes/src/pattern/variables.rs index 20ac281d..4a283a3a 100644 --- a/crates/nodes/src/pattern/variables.rs +++ b/crates/nodes/src/pattern/variables.rs @@ -33,6 +33,7 @@ pub(super) struct PatternVariables<'a> { published: &'a BTreeMap, pub(super) drawing: BTreeMap, pub(super) modes: BTreeMap, + pub(super) bound_draw: bool, locals: BTreeMap, scopes: Vec<(usize, Vec)>, } @@ -46,7 +47,7 @@ impl<'a> PatternVariables<'a> { for name in ["$depth", "$depthpow2", "$number"] { modes.insert(name.into(), Value::Float(0.0)); } - Self { modes, drawing, published, locals: BTreeMap::new(), scopes: Vec::new() } + Self { modes, drawing, published, bound_draw: false, locals: BTreeMap::new(), scopes: Vec::new() } } pub(super) fn enter(&mut self, names: &BTreeMap, depth: u32, declared: &mut Vec) { @@ -58,7 +59,13 @@ impl<'a> PatternVariables<'a> { // A child may read its parent's value. Declaring the name opens the // last value written at this quadrant depth, including across siblings. self.modes.remove(name); - let value = local.saved.remove(&depth).unwrap_or_else(|| kind.default_value()); + let value = local.saved.remove(&depth).unwrap_or_else(|| match (self.bound_draw, kind) { + // A draw driven by a graph input starts these components undefined until the first write. + (true, ValueType::Float) => Value::Float(f32::NAN), + (true, ValueType::Float2) => Value::Float2([f32::NAN; 2]), + (true, ValueType::Float3) => Value::Float3([f32::NAN; 3]), + _ => kind.default_value(), + }); let previous = self.drawing.insert(name.clone(), value); let outer = local.depth.replace(depth).zip(previous); declared.push(Declaration { name: name.clone(), outer }); diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index 52c2374a..24d20362 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -57,6 +57,33 @@ The first pass classifies all 546 roots: 166 Parity and 380 Too hard. These meas - **2026-11-13 - Unconnected output images:** Unconnected output bridges now produce transparent RGBA instead of grayscale. The importer separately retains each output's declared image type so saving an unconnected output preserves the graph interface. Both material templates match all 1,179,648 RGBA8 pixels across six recorded cases. All 2,560 direct grayscale/color declaration probe pixels also match, and both declared image types survive save/reload. +## 2026-11-25 root comparisons + +### First reads of writable quadrant floats + +The first read of a writable scalar, float2 or float3 at a quadrant depth can produce undefined components when a drawing property reads a live graph input. The next visit at that depth sees the previous assignment. To distinguish these cases, connect four child slots to one square. In the square’s luminosity function, assign .375 if the local equals itself and .625 otherwise. With a live parent branch offset the squares read .625, .375, .375, .375 in traversal order. Substituting a literal for the graph input gives four .375 squares in this comparison. [Pattern evaluator](../crates/nodes/src/pattern/evaluation.rs) · [Variable scope](../crates/nodes/src/pattern/variables.rs) + +Use the eleven [tint and blend configurations](#undefined-components-in-a-computed-quadrant-tint) with the writable assignment of the previous local plus .0625. Use the published default .8125 at 16² F32 with seed 40991 and 32 × 16 U16 with seed 41005. Change the published input to .3125 at 16² F16 with seed 40998 and 32 × 16 U8 with seed 41012. Count a pixel as exact when every stored channel has the same bits, including NaNs. + +| Storage | Previous exact pixels | Corrected exact pixels | Previous maximum finite error | Corrected maximum error | +|---|---:|---:|---:|---:| +| U8 | 1,536/5,632 | 5,632/5,632 | 96 codes | 0 | +| U16 | 1,536/5,632 | 5,632/5,632 | 24,576 codes | 0 | +| F16 | 768/2,816 | 2,816/2,816 | .25 | 0 | +| F32 | 768/2,816 | 2,816/2,816 | .25 | 0 | + +The previous F16 and F32 results each had 768 differing nonfinite channels. All stored floating-point channels now match. Independently save each original in MaterialCraft and reopen it in the reference desktop. The original and reopened reference outputs agree on all 16,896 pixels. The five [nested caller configurations](#writable-first-reads-through-graph-instances) now match all 3,840 original and all 3,840 reopened F32 pixels, maximum zero in both sets. Changing only the origin of an opacity value of one also changes the first square when reusing the cook cache. [Cache regression](../crates/eval/tests/pattern_opacity.rs) + +For the component-width control, store the local plus a zero vector and start luminosity at .125. For each component unequal to itself, add 1/32, 2/32, 4/32 or 8/32 according to its position. Compare fixed opacity one with opacity one plus zero times a published input. The scalar, float2 and float3 cases match all 4,608 F32 pixels, maximum zero. The live float4 case still matches 0/768, maximum .21875. The fourth component can retain a finite value across reference cooks. The two integer controls match 0/1,536 with maximum .75. These initial values remain open. + +Connect a second square to a switch and drive its luminosity from a published input. The first square reads .625 even with the switch fixed to the other branch. Disconnecting the second square or setting its shape to zero gives .375. A published branch offset or seed still affects a shapeless quadrant. A published image index affects an image stamp with no texture connected. Image filtering and seed inheritance each leave the first square at .375. A graph-size function that returns (0,0) from a published scalar affects both relative size modes. With an absolute 16² size on the pattern node the first square reads .375. The six graph size and seed inheritance controls match 4,352/4,352 F32 pixels. [Connected-branch regression](../crates/nodes/src/pattern/tests.rs) + +Across ten scalar first-read expressions with fixed and live parents, 14,976/15,360 F32 pixels match, up from 14,016. The 384 remaining differences occur on the fixed-parent 32 × 16 captures, maximum .25. Thirty other binding and assignment variants improve from 12,288/23,040 to 19,200/23,040, maximum 1.5. A separate reference control with a live upstream Uniform color and literal properties on the pattern node also changes the first square. Disconnecting the Uniform or replacing its color with the same literal restores the four .375 readings. Propagation from the upstream image remains open. + +Seven original and four reopened settings of each Noise BNW Spots 1 version retain their previous MaterialCraft buffers bit for bit. Version one matches 20,618/20,992 original pixels on one processor and 20,455/20,992 on eight, with maximum one U16 code. Its ordinary saves match 2,799/2,816, maximum 5.96046448e−8. Version two matches 20,904/20,992 on both processor counts and 4,273/4,352 on saves, with respective maxima 1.19209290e−7 and 5.96046448e−8. Both whole roots remain in progress. [Original settings and previous buffers](#undefined-components-in-a-computed-quadrant-tint) + +Both new regressions failed on the preceding implementation. All 504 release tests for the node library and graph evaluator pass with the fix. Formatting, strict workspace Clippy, dependency layers and WebAssembly also pass. + ## 2026-11-24 root comparisons ### Undefined components in a computed quadrant tint diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index e0fb7dbd..0c64c2ab 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -35,11 +35,11 @@ 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 **480 Parity**, **66 In progress** and **0 Too hard**. The November 17–24 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) · [November 24 measurements](parity-fixes.md#2026-11-24-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–25 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) · [November 24 measurements](parity-fixes.md#2026-11-24-root-comparisons) · [November 25 measurements](parity-fixes.md#2026-11-25-root-comparisons) -Computed quadrant tints with undefined channels match 70,656/70,656 pixels across original squares, ordinary saves, Gaussian and ramp shapes and connected images. A separate first-read discrepancy in writable variables remains. The eleven whole-graph settings rechecked for each version of Noise BNW Spots 1 retain their previous results. [Four-format counts and outstanding differences](parity-fixes.md#undefined-components-in-a-computed-quadrant-tint) +Writable quadrant tints now match 16,896/16,896 pixels in 44 settings across four output formats, up from 4,608. Fixed and published inputs through a graph instance match 3,840/3,840 original and 3,840/3,840 reopened pixels. Live float4 and integer initial values remain open. The earlier explicit undefined-tint controls covered 70,656 pixels across original squares, ordinary saves, Gaussian and ramp shapes and connected images. [November 25 measurements](parity-fixes.md#first-reads-of-writable-quadrant-floats) · [Explicit undefined tints](parity-fixes.md#undefined-components-in-a-computed-quadrant-tint) -Noise BNW Spots 1 still matches 403/512 pixels in the repeatable 16 × 32 F32 setting. Signed-square measurements reproduce the final differing pixel of a 511/512 diagnostic replay. In a separate nested-quadrant comparison, all three fixed-argument cases match, and two published-argument cases differ in the first square. [Draw-order measurements](parity-fixes.md#the-remaining-sample-in-a-dense-draw-order-replay) · [Original and reopened graph instances](parity-fixes.md#writable-first-reads-through-graph-instances) +Noise BNW Spots 1 still matches 403/512 pixels in the repeatable 16 × 32 F32 setting. Signed-square measurements reproduce the final differing pixel of a 511/512 diagnostic replay. The dense draw order remains open. [Draw-order measurements](parity-fixes.md#the-remaining-sample-in-a-dense-draw-order-replay) 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)