From aebb4813ae5142015df50ddb53c78a07d4fc6c70 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Thu, 19 Nov 2026 13:44:08 -0500 Subject: [PATCH] Preserve folded scalar integer semantics through graph instances --- crates/engine/tests/it/optimization_perf.rs | 2 +- crates/eval/src/cache_key.rs | 13 +++--- crates/eval/src/graph_instance.rs | 8 ++++ crates/eval/src/node_execution.rs | 41 ++++++++++++++----- crates/eval/src/options.rs | 3 ++ crates/eval/src/parameter.rs | 26 ++++++++++-- crates/eval/src/parameter_function.rs | 5 ++- crates/eval/src/resolved_base_parameters.rs | 2 + crates/eval/src/tests.rs | 44 +++++++++++++++++++++ crates/eval/src/value_execution.rs | 8 ++-- crates/nodes/src/cook_context.rs | 24 ++++++++++- crates/nodes/src/function/compile.rs | 7 +++- crates/nodes/src/function/mod.rs | 2 +- crates/nodes/src/function/operation.rs | 8 ++++ crates/nodes/src/function/processor.rs | 7 ++-- crates/nodes/src/function/tests.rs | 20 ++++++++++ crates/nodes/src/lib.rs | 2 +- crates/nodes/src/pattern/evaluation.rs | 6 +-- docs/parity-fixes.md | 34 ++++++++++++++++ docs/sbs-root-nodes.md | 2 +- 20 files changed, 227 insertions(+), 37 deletions(-) diff --git a/crates/engine/tests/it/optimization_perf.rs b/crates/engine/tests/it/optimization_perf.rs index bcef863..1ed661f 100644 --- a/crates/engine/tests/it/optimization_perf.rs +++ b/crates/engine/tests/it/optimization_perf.rs @@ -41,7 +41,7 @@ fn optimization_baseline() { parameters.insert("color_mode".into(), Value::Bool(false)); for size in [512, 2048] { for count in [0, 16] { - let variables = (0..count).map(|index| (format!("input_{index}"), Value::Float(index as f32))).collect(); + let variables: BTreeMap<_, _> = (0..count).map(|index| (format!("input_{index}"), Value::Float(index as f32))).collect(); let context = CookContext { input_formats: &[], format: materialcraft_core::OutputFormat::F32, diff --git a/crates/eval/src/cache_key.rs b/crates/eval/src/cache_key.rs index 40e0b74..5d21e1f 100644 --- a/crates/eval/src/cache_key.rs +++ b/crates/eval/src/cache_key.rs @@ -93,7 +93,7 @@ pub(crate) fn graph_tree_hash_with_registry(registry: &Package, package: &Packag hasher.finish() } -pub(crate) fn variable_key(node: &Node, parameters: &BTreeMap, variables: &BTreeMap) -> u64 { +pub(crate) fn variable_key(node: &Node, parameters: &BTreeMap, variables: &dyn materialcraft_nodes::GraphVariables) -> u64 { let mut hasher = DefaultHasher::new(); let mut names = std::collections::BTreeSet::new(); let mut pending: Vec<&Value> = parameters.values().collect(); @@ -114,10 +114,12 @@ pub(crate) fn variable_key(node: &Node, parameters: &BTreeMap, va Some(Err(error)) => error.hash(&mut hasher), None => {} } - if (function_node.op.starts_with("get_") || function_node.op == "isdefined") - && let Some(Value::Text(name)) = &function_node.value - { - names.insert(name.as_str()); + if let Some(Value::Text(name)) = &function_node.value { + if function_node.op.starts_with("get_") { + names.insert(name.strip_prefix('%').unwrap_or(name)); + } else if function_node.op == "isdefined" { + names.insert(name.as_str()); + } } } } @@ -137,6 +139,7 @@ pub(crate) fn variable_key(node: &Node, parameters: &BTreeMap, va for name in names { name.hash(&mut hasher); variables.get(name).map(|value| serde_json::to_string(value).unwrap_or_default()).hash(&mut hasher); + variables.literal_inputs().iter().any(|input| input == name).hash(&mut hasher); } hasher.finish() diff --git a/crates/eval/src/graph_instance.rs b/crates/eval/src/graph_instance.rs index 064c66d..c357ca2 100644 --- a/crates/eval/src/graph_instance.rs +++ b/crates/eval/src/graph_instance.rs @@ -44,6 +44,7 @@ pub(crate) fn cook_instance( output_ports: &[Port], inputs: &[Option<(&NodeOutput, OutputFormat)>], params: &BTreeMap, + fixed: &[String], base: crate::resolved_base_parameters::ResolvedBaseParameters, options: &Options, cache: &Mutex, @@ -85,6 +86,12 @@ pub(crate) fn cook_instance( source_options.graph_stack.push(identity); source_options.only = Some(source_graph.nodes.iter().filter(|node| node.def == "output").map(|node| node.id).collect()); source_options.overrides = params.iter().filter(|(k, _)| source_graph.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect(); + for exposed in &source_graph.exposed { + let name = &exposed.id; + if fixed.contains(name) || (!params.contains_key(name) && matches!(source_graph.input_value(name), Some(Value::Int(_)))) { + source_options.literal_inputs.push(name.clone()); + } + } for (port, input) in input_ports.iter().zip(inputs) { let Some((output, format)) = input else { continue }; if let Some((image, texture_format)) = output.texture(*format) { @@ -92,6 +99,7 @@ pub(crate) fn cook_instance( source_options.input_formats.insert(port.id.clone(), texture_format); } else if let Some(value) = output.as_value() { source_options.overrides.insert(port.id.clone(), value.clone()); + source_options.literal_inputs.retain(|name| name != &port.id); } } let cooked = cook(source, source_graph_index, &source_options, cache); diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs index 4df1630..9d95fcc 100644 --- a/crates/eval/src/node_execution.rs +++ b/crates/eval/src/node_execution.rs @@ -8,12 +8,27 @@ use crate::{ }; use craft_texture::{Image, Kind}; use materialcraft_core::{Node, OutputFormat, Package, Value}; -use materialcraft_nodes::{CookContext, find}; +use materialcraft_nodes::{CookContext, GraphVariables, find}; use std::{ collections::BTreeMap, sync::{Arc, Mutex}, }; +struct BoundVariables<'a> { + values: &'a BTreeMap, + fixed: &'a [String], +} + +impl GraphVariables for BoundVariables<'_> { + fn graph_values(&self) -> &BTreeMap { + self.values + } + + fn literal_inputs(&self) -> &[String] { + self.fixed + } +} + /// The magenta image a failed node shows pub fn error_image(w: u32, h: u32) -> Image { Image::filled(w, h, Kind::Color, [1.0, 0.0, 1.0, 1.0]) @@ -43,6 +58,7 @@ pub(crate) fn cook_node( let mut incoming = Vec::new(); let mut input_keys = Vec::new(); let mut variables = std::borrow::Cow::Borrowed(graph_variables); + let mut fixed = std::borrow::Cow::Borrowed(options.literal_inputs.as_slice()); let mut input_error = None; for port in input_ports { let connection = prepared.index.input_of(node.id, &port.id); @@ -73,6 +89,9 @@ pub(crate) fn cook_node( }; variables.to_mut().insert(port.id.clone(), value); + if fixed.contains(&port.id) { + fixed.to_mut().retain(|name| name != &port.id); + } } else { if output.as_ref().is_some_and(|output| output.as_value().is_some()) && !matches!(node.def.as_str(), "output" | "dot") { input_error = Some(format!("input `{}` requires an image", port.id)); @@ -93,10 +112,11 @@ pub(crate) fn cook_node( } let input_base = prepared.input_base(node.id, cooked); - let (mut base, base_values, base_error) = match crate::resolved_base_parameters::evaluate(&node.base, input_base, prepared.parent_base, &mut variables) { - Ok((base, values)) => (base, values, None), - Err(error) => (crate::ResolvedBaseParameters::resolve(&node.base, input_base, prepared.parent_base), BTreeMap::new(), Some(error)), - }; + let (mut base, base_values, base_error) = + match crate::resolved_base_parameters::evaluate(&node.base, input_base, prepared.parent_base, &mut variables, &fixed) { + Ok((base, values)) => (base, values, None), + Err(error) => (crate::ResolvedBaseParameters::resolve(&node.base, input_base, prepared.parent_base), BTreeMap::new(), Some(error)), + }; if node.disabled && let Some(input) = input_base @@ -144,7 +164,7 @@ pub(crate) fn cook_node( } let seed = base.seed; - let mut parameters = match resolve_parameters(package, node, definition, &mut variables, base) { + let (mut parameters, instance_literals) = match resolve_parameters(package, node, definition, &mut variables, base, &fixed) { Ok(parameters) => parameters, Err(error) => return fail(error, 0), }; @@ -152,6 +172,7 @@ pub(crate) fn cook_node( variables.to_mut().insert("$pixelsize".into(), Value::Float2(base.pixel_size)); } let variables = &variables; + let bindings = BoundVariables { values: variables, fixed: &fixed }; let tile = base.tiling[0] && base.tiling[1]; @@ -204,7 +225,7 @@ pub(crate) fn cook_node( // A cached graph instance includes results evaluated with its host environment (node.def == "graph_instance").then(|| serde_json::to_string(&options.environment).unwrap_or_default()), input_image.as_ref().map(|(image, upstream, bitmap)| (image_key(image, cache), upstream, bitmap, wired)), - variable_key(node, ¶meters, variables), + (variable_key(node, ¶meters, &bindings), &instance_literals), )); if let Some(outputs) = lock(cache).get(key) { parameters.retain(|_, value| materialcraft_core::ValueType::of(value).is_some()); @@ -226,7 +247,7 @@ pub(crate) fn cook_node( let value = variables.get(&identifier(node)).or_else(|| parameters.get("default")).cloned().unwrap_or(Value::Float(0.0)); Ok(vec![NodeOutput::Value(value)]) } else if node.def == "value_processor" { - evaluate_value(¶meters, variables, seed, [w, h], &inputs, &input_formats, tile).map(|value| vec![NodeOutput::Value(value)]) + evaluate_value(¶meters, &bindings, seed, [w, h], &inputs, &input_formats, tile).map(|value| vec![NodeOutput::Value(value)]) } else if matches!(node.def.as_str(), "output" | "dot") && let Some(Some((output, _))) = incoming.first() && (output.as_value().is_some() || matches!(output, NodeOutput::BoundBitmap { stored, .. } if (stored.width(), stored.height()) == (w, h))) @@ -244,7 +265,7 @@ pub(crate) fn cook_node( Err(format!("unsupported node `{name}`")) } else if node.def == "graph_instance" { - cook_instance(package, graph_index, node, input_ports, output_ports, &incoming, ¶meters, base, options, cache).map(|ports| { + cook_instance(package, graph_index, node, input_ports, output_ports, &incoming, ¶meters, &instance_literals, base, options, cache).map(|ports| { let (values, bases): (Vec<_>, Vec<_>) = ports.into_iter().unzip(); output_bases = Some(bases.into()); values @@ -272,7 +293,7 @@ pub(crate) fn cook_node( inputs: &inputs, params: ¶meters, resource: options.resource, - vars: variables, + vars: &bindings, }; (definition.cook)(&context).map(|images| { images diff --git a/crates/eval/src/options.rs b/crates/eval/src/options.rs index 66fc167..07ae7c1 100644 --- a/crates/eval/src/options.rs +++ b/crates/eval/src/options.rs @@ -21,6 +21,8 @@ pub struct Options<'a> { pub bitmap_formats: BTreeMap, /// Values for the graph's exposed parameters (graph instances), over the graph's own pub overrides: BTreeMap, + /// Scalar integer inputs fixed by the enclosing graph instance. + pub literal_inputs: Vec, /// Decodes a package resource (bitmap) by name pub resource: &'a crate::ResourceDecoder<'a>, /// Set from another thread to stop between nodes @@ -46,6 +48,7 @@ impl<'a> Options<'a> { input_formats: BTreeMap::new(), bitmap_formats: BTreeMap::new(), overrides: BTreeMap::new(), + literal_inputs: Vec::new(), resource, cancel: None, depth: 0, diff --git a/crates/eval/src/parameter.rs b/crates/eval/src/parameter.rs index e5ed055..30a4a69 100644 --- a/crates/eval/src/parameter.rs +++ b/crates/eval/src/parameter.rs @@ -9,7 +9,8 @@ pub(crate) fn resolve_parameters( definition: Option<&NodeDefinition>, variables: &mut std::borrow::Cow<'_, BTreeMap>, base: ResolvedBaseParameters, -) -> Result, String> { + literal_inputs: &[String], +) -> Result<(BTreeMap, Vec), String> { let mut parameters = match definition { Some(definition) if node.def != "graph_instance" => resolve_params(definition, &node.params), _ => { @@ -27,7 +28,11 @@ pub(crate) fn resolve_parameters( } } + let mut dynamic = std::collections::BTreeSet::new(); for (parameter, exposed) in &node.bindings { + if node.def == "graph_instance" && !literal_inputs.contains(exposed) { + dynamic.insert(parameter); + } if let (Some(value), Some(current)) = (variables.get(exposed), parameters.get(parameter)) && let Some(coerced) = current.coerce_json(&serde_json::to_value(value).unwrap_or_default()) { @@ -43,8 +48,16 @@ pub(crate) fn resolve_parameters( ("fx_map", "background", _) if matches!(current, Value::Float4(_)) => ChannelMode::Broadcast, _ => ChannelMode::Opaque, }; - let (value, _) = crate::parameter_function::evaluate(function, expected, variables.to_mut(), base.seed, base.size, channels, Some(current)) - .map_err(|error| format!("function of `{parameter}`: {error}"))?; + let (value, literal) = + crate::parameter_function::evaluate(function, expected, variables.to_mut(), base.seed, base.size, channels, Some(current), literal_inputs) + .map_err(|error| format!("function of `{parameter}`: {error}"))?; + if node.def == "graph_instance" { + if literal { + dynamic.remove(parameter); + } else { + dynamic.insert(parameter); + } + } let value = current.coerce_json(&serde_json::to_value(value).unwrap_or_default()).ok_or_else(|| format!("invalid function value for `{parameter}`"))?; parameters.insert(parameter.clone(), value); } @@ -56,7 +69,12 @@ pub(crate) fn resolve_parameters( clamp_params(definition, &mut parameters); } - Ok(parameters) + let fixed = if node.def == "graph_instance" { + parameters.iter().filter(|(name, value)| matches!(value, Value::Int(_)) && !dynamic.contains(*name)).map(|(name, _)| name.clone()).collect() + } else { + Vec::new() + }; + Ok((parameters, fixed)) } #[cfg(test)] diff --git a/crates/eval/src/parameter_function.rs b/crates/eval/src/parameter_function.rs index 8f0f0ff..3879d8d 100644 --- a/crates/eval/src/parameter_function.rs +++ b/crates/eval/src/parameter_function.rs @@ -1,5 +1,5 @@ use materialcraft_core::{FunctionGraph, Value, ValueType}; -use materialcraft_nodes::function::{EvaluationContext, EvaluationState, compile}; +use materialcraft_nodes::function::{EvaluationContext, EvaluationState, compile_with_literal_inputs}; use std::collections::BTreeMap; #[derive(Clone, Copy)] @@ -17,8 +17,9 @@ pub(crate) fn evaluate( size: [u32; 2], channels: ChannelMode, fallback: Option<&Value>, + literal_inputs: &[String], ) -> Result<(Value, bool), String> { - let program = compile(function, seed)?; + let program = compile_with_literal_inputs(function, seed, literal_inputs)?; let widened = expected == ValueType::Float4 && [ValueType::Float as u32, ValueType::Float3 as u32].contains(&program.output_type()); if program.output_type() != expected as u32 && !widened { return Err(format!("output must be {}", expected.label())); diff --git a/crates/eval/src/resolved_base_parameters.rs b/crates/eval/src/resolved_base_parameters.rs index 01dc044..449ce44 100644 --- a/crates/eval/src/resolved_base_parameters.rs +++ b/crates/eval/src/resolved_base_parameters.rs @@ -82,6 +82,7 @@ pub(crate) fn evaluate( input: Option, parent: ResolvedBaseParameters, variables: &mut std::borrow::Cow<'_, BTreeMap>, + literal_inputs: &[String], ) -> Result<(ResolvedBaseParameters, BTreeMap), String> { if base.functions.is_empty() { return Ok((ResolvedBaseParameters::resolve(base, input, parent), BTreeMap::new())); @@ -134,6 +135,7 @@ pub(crate) fn evaluate( size, crate::parameter_function::ChannelMode::Opaque, None, + literal_inputs, ) .map_err(|error| format!("function of `{}`: {error}", parameter.identifier()))?; if parameter == BaseParameter::OutputSize { diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index d395c81..a428079 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -201,6 +201,50 @@ fn preview_cap_and_unknown_nodes() { assert!(c.nodes[&bad].error.is_some()); } +#[test] +fn cached_instances_distinguish_fixed_and_bound_integer_arguments() { + use materialcraft_core::{ExposedParameter, FunctionGraph, ValueType}; + let (parent, instance) = instancing("Parent", "Selector"); + let mut child = Graph::new("Selector"); + child.exposed.push(ExposedParameter { + id: "index".into(), + label: "Index".into(), + default: Value::Int(0), + description: String::new(), + group: String::new(), + editor: None, + clamp: false, + step: None, + min: -8.0, + max: 8.0, + options: Vec::new(), + }); + let mut function = FunctionGraph::input("%index", ValueType::Integer); + let input = function.output.unwrap(); + function.output = Some(function.add("tofloat", &[input], None)); + let processor = child.add_node("value_processor", [0.0; 2]); + child.node_mut(processor).unwrap().params.insert("function".into(), Value::Function(Box::new(function))); + let output = child.add_node("output", [0.0; 2]); + child.connect(processor, "output", output, "input").unwrap(); + let mut package = Package::new("Integer arguments"); + package.graphs.extend([parent, child]); + let mut options = Options::new(&no_res); + options.overrides.insert("driver".into(), Value::Int(-5)); + let cache = Mutex::new(Cache::default()); + for bound in [false, true, false] { + let node = package.graphs[0].node_mut(instance).unwrap(); + node.params.insert("index".into(), Value::Int(-5)); + if bound { + node.bindings.insert("index".into(), "driver".into()); + } else { + node.bindings.remove("index"); + } + let result = cook(&package, 0, &options, &cache); + assert_eq!(result.nodes[&instance].error, None); + assert_eq!(result.nodes[&instance].outputs[0].as_value(), Some(&Value::Float(if bound { -5.0 } else { 4_294_967_296.0 }))); + } +} + #[test] fn graph_instances_cook_their_subgraph() { let (mut p, ..) = sample(); diff --git a/crates/eval/src/value_execution.rs b/crates/eval/src/value_execution.rs index 3d09f29..f9a1f75 100644 --- a/crates/eval/src/value_execution.rs +++ b/crates/eval/src/value_execution.rs @@ -4,20 +4,20 @@ use std::collections::BTreeMap; pub(crate) fn evaluate_value( parameters: &BTreeMap, - variables: &BTreeMap, + variables: &dyn materialcraft_nodes::GraphVariables, seed: u32, size: [u32; 2], images: &[Option], image_formats: &[OutputFormat], tile: bool, ) -> Result { - use materialcraft_nodes::function::{EvaluationContext, EvaluationState, FunctionScope, compile}; + use materialcraft_nodes::function::{EvaluationContext, EvaluationState, FunctionScope, compile_with_literal_inputs}; let Some(Value::Function(graph)) = parameters.get("function") else { return Err("missing value function".into()); }; - let program = compile(graph, seed)?; + let program = compile_with_literal_inputs(graph, seed, variables.literal_inputs())?; let context = EvaluationContext { image_formats, scope: FunctionScope::ValueProcessor, @@ -25,7 +25,7 @@ pub(crate) fn evaluate_value( size: size.map(|side| side as f32), images, tile, - variables, + variables: variables.graph_values(), }; let value = program.evaluate(&context, &mut EvaluationState::default())?; diff --git a/crates/nodes/src/cook_context.rs b/crates/nodes/src/cook_context.rs index 73e0a00..58a0a37 100644 --- a/crates/nodes/src/cook_context.rs +++ b/crates/nodes/src/cook_context.rs @@ -2,6 +2,28 @@ use craft_texture::{Image, Kind}; use materialcraft_core::{Curve, FunctionGraph, Gradient, Value}; use std::collections::BTreeMap; +/// Graph inputs available to a cook, including any fixed by its enclosing instance. +pub trait GraphVariables: Sync { + fn graph_values(&self) -> &BTreeMap; + fn literal_inputs(&self) -> &[String] { + &[] + } +} + +impl GraphVariables for BTreeMap { + fn graph_values(&self) -> &BTreeMap { + self + } +} + +impl std::ops::Deref for dyn GraphVariables + '_ { + type Target = BTreeMap; + + fn deref(&self) -> &Self::Target { + self.graph_values() + } +} + /// Where a cook runs: output size, seed, tiling, inputs and resolved parameters pub struct CookContext<'a> { pub w: u32, @@ -17,7 +39,7 @@ pub struct CookContext<'a> { /// The package's bitmap resources, decoded on demand pub resource: &'a (dyn Fn(&str) -> Option + Sync), /// Exposed graph inputs (for `get_*` nodes in function graphs) - pub vars: &'a BTreeMap, + pub vars: &'a dyn GraphVariables, } impl CookContext<'_> { diff --git a/crates/nodes/src/function/compile.rs b/crates/nodes/src/function/compile.rs index c8b17cb..bf219bb 100644 --- a/crates/nodes/src/function/compile.rs +++ b/crates/nodes/src/function/compile.rs @@ -3,9 +3,14 @@ use materialcraft_core::FunctionGraph; use std::collections::{BTreeMap, BTreeSet}; pub fn compile(graph: &FunctionGraph, seed: u32) -> Result { + compile_with_literal_inputs(graph, seed, &[]) +} + +/// Compile with the named inputs fixed by an enclosing graph instance. +pub fn compile_with_literal_inputs(graph: &FunctionGraph, seed: u32, literal_inputs: &[String]) -> Result { let mut remaining = super::MAX_EXPANDED_NODES; let mut program = compile_nested(graph, seed, 0, &mut remaining)?; - mark_literals(&mut program, BTreeSet::new()); + mark_literals(&mut program, literal_inputs.iter().map(String::as_str).collect()); Ok(program) } diff --git a/crates/nodes/src/function/mod.rs b/crates/nodes/src/function/mod.rs index 04c2b23..086c8d8 100644 --- a/crates/nodes/src/function/mod.rs +++ b/crates/nodes/src/function/mod.rs @@ -45,7 +45,7 @@ mod warnings; pub(crate) use binary_exponential::{exp2 as pixel_exp2, signed_pixel_power}; pub use catalog::{FUNCTIONS, default_value, definition}; -pub use compile::compile; +pub use compile::{compile, compile_with_literal_inputs}; pub use evaluation_context::EvaluationContext; pub use evaluation_state::EvaluationState; pub(crate) use fixed_point::truncate_float; diff --git a/crates/nodes/src/function/operation.rs b/crates/nodes/src/function/operation.rs index 130193b..a8402d0 100644 --- a/crates/nodes/src/function/operation.rs +++ b/crates/nodes/src/function/operation.rs @@ -64,6 +64,13 @@ pub(crate) fn evaluate( return value_type::canonical(value); } + // A folded scalar cast interprets the 32-bit word as unsigned. Vector casts use signed lanes. + if op == "tofloat" + && instruction.literal + && let Value::Int(value) = first()? + { + return Ok(Value::Float(*value as u32 as f32)); + } if op.starts_with("to") || op.contains("vector") || op.contains("swizzle") { return super::vector::evaluate(op, arguments, instruction.value.as_ref()); } @@ -102,6 +109,7 @@ pub(crate) fn evaluate( } let ordering = match (left, right) { + (Value::Int(a), Value::Int(b)) if instruction.literal => Some((*a as u32).cmp(&(*b as u32))), (Value::Int(a), Value::Int(b)) => a.partial_cmp(b), (Value::Float(a), Value::Float(b)) => a.partial_cmp(b), (Value::Bool(a), Value::Bool(b)) => a.partial_cmp(b), diff --git a/crates/nodes/src/function/processor.rs b/crates/nodes/src/function/processor.rs index 957f475..7046489 100644 --- a/crates/nodes/src/function/processor.rs +++ b/crates/nodes/src/function/processor.rs @@ -1,4 +1,4 @@ -use super::{EvaluationContext, EvaluationState, compile}; +use super::{EvaluationContext, EvaluationState, compile_with_literal_inputs}; use crate::{CookContext, CookResult}; use craft_texture::{Image, Kind, Limits}; use materialcraft_core::Value; @@ -31,7 +31,8 @@ fn pixel(value: Value, gray: bool) -> Result<[f32; 4], String> { pub(crate) fn pixel_processor(context: &CookContext) -> CookResult { let graph = context.function("function").ok_or("missing pixel function")?; - let program = compile(graph, context.seed)?; + let program = compile_with_literal_inputs(graph, context.seed, context.vars.literal_inputs())?; + let variables = context.vars.graph_values(); let gray = !context.b("color_mode"); let kind = if gray { Kind::Gray } else { Kind::Color }; @@ -47,7 +48,7 @@ pub(crate) fn pixel_processor(context: &CookContext) -> CookResult { size: [width as f32, height as f32], images: context.inputs, tile: context.tile, - variables: context.vars, + variables, }; let result = pixel(program.evaluate_pixel(&evaluation, state)?, gray)?; diff --git a/crates/nodes/src/function/tests.rs b/crates/nodes/src/function/tests.rs index bf1a50b..170f125 100644 --- a/crates/nodes/src/function/tests.rs +++ b/crates/nodes/src/function/tests.rs @@ -25,6 +25,26 @@ fn operation(name: &str, arguments: &[Value], setting: Option) -> Result< evaluate(&graph, &BTreeMap::new()) } +#[test] +fn folded_integers_use_word_order_and_convert_unsigned_magnitudes() { + let variables = BTreeMap::from([("lhs".into(), Value::Int(-5)), ("rhs".into(), Value::Int(2))]); + for (left_literal, right_literal) in [(true, true), (true, false), (false, true), (false, false)] { + let mut graph = FunctionGraph::default(); + let mut operand = |name: &str, value, literal| { + if literal { graph.add_constant(Value::Int(value)) } else { graph.add("get_integer1", &[], Some(Value::Text(name.into()))) } + }; + let left = operand("lhs", -5, left_literal); + let right = operand("rhs", 2, right_literal); + let unsigned = left_literal && right_literal; + for (op, expected) in [("lr", !unsigned), ("lreq", !unsigned), ("gt", unsigned), ("gteq", unsigned)] { + graph.output = Some(graph.add(op, &[left, right], None)); + assert_eq!(evaluate(&graph, &variables).unwrap(), Value::Bool(expected), "{op} with literal operands {left_literal}/{right_literal}"); + } + graph.output = Some(graph.add("tofloat", &[left], None)); + assert_eq!(evaluate(&graph, &variables).unwrap(), Value::Float(if left_literal { 4_294_967_296.0 } else { -5.0 })); + } +} + #[test] fn variable_reads_consume_one_reference_marker() { let variables = BTreeMap::from([("level".into(), Value::Float(0.1875))]); diff --git a/crates/nodes/src/lib.rs b/crates/nodes/src/lib.rs index 043c2de..cc26405 100644 --- a/crates/nodes/src/lib.rs +++ b/crates/nodes/src/lib.rs @@ -24,7 +24,7 @@ mod random; mod texture_sampler; pub use catalog::{catalog, categories, find}; -pub use cook_context::CookContext; +pub use cook_context::{CookContext, GraphVariables}; pub use image_input::{MAX_IMAGE_INPUTS, image_input_prefix}; pub use node_definition::NodeDefinition; pub(crate) use node_definition_builder::node; diff --git a/crates/nodes/src/pattern/evaluation.rs b/crates/nodes/src/pattern/evaluation.rs index 1ac21ca..6c4d213 100644 --- a/crates/nodes/src/pattern/evaluation.rs +++ b/crates/nodes/src/pattern/evaluation.rs @@ -2,7 +2,7 @@ use materialcraft_core::{PatternNodeKind, Value}; use std::collections::{BTreeMap, BTreeSet}; use super::{catalog, pattern_stamp::PatternStamp, pattern_visit::PatternVisit, raster}; -use crate::function::{EvaluationContext, EvaluationState, compile}; +use crate::function::{EvaluationContext, EvaluationState, compile_with_literal_inputs}; use crate::random::FunctionRandom; use crate::{CookContext, CookResult}; @@ -23,7 +23,7 @@ pub(crate) fn cook(context: &CookContext) -> CookResult { let mut fixed = node.kind == PatternNodeKind::Switch && node.children.contains(&None); for (name, value) in &node.parameters { if let Value::Function(function) = value { - let program = compile(function, context.seed)?; + let program = compile_with_literal_inputs(function, context.seed, context.vars.literal_inputs())?; fixed = fixed && name == "switch" && program.depends_only_on_image_size(); functions.insert((node.id, name.as_str()), program); } @@ -43,7 +43,7 @@ pub(crate) fn cook(context: &CookContext) -> CookResult { let mut stamps = Vec::new(); // Keep Set assignments across iterations within this FX-Map cook - let mut variables = context.vars.clone(); + let mut variables = context.vars.graph_values().clone(); variables.remove("$randomseed"); let mut max_depth = 0; let mut state = EvaluationState::default(); diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index 9e691fb..0fda439 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -114,6 +114,40 @@ The standalone Add Sub filter matches **59,904/59,904 pixels across 36 renders** To reproduce the filter controls use one graph per input layout, with foreground, background and optionally mask. In binding order use slot v=0,1,2 for foreground, background and mask. For each channel c use L=(53x+17y+7xy+35v+61c+3cy+3) mod 251. Use L/255 normally. For signed cases use (L−83.125)/53.5 for the images and (L−83.125)/101 for the mask. Masks and grayscale images take channel zero. Set image bridges to F32 for the color graphs and U8 for the grayscale graph. For each graph use 16² F32 at opacity 1, then 32² at opacity .5 in all four formats. At 64² F32 with signed inputs use .6875 with alpha blending disabled, then .3125 with it enabled. At 32² F32 and opacity .6137 run ignored, straight, premultiplied and source alpha. Finish with signed inputs at 16² F32 and opacity zero, followed by 64² F32 with unsigned inputs and opacity 1. Each series starts at seed 5113 and advances by 17. +### Fixed integer arguments and the UV debug marker + +The UV debug graph now matches all 217,088 pixels in its original 32 renders. The [square-root measurements](#uniform-square-roots-and-the-uv-debug-marker) previously had 194,522 exact. Sixteen additional renders with signed channel offsets match all 10,240 pixels. Six independently wired parents add 56,828/56,832 exact pixels. Compute Irradiance and Compute Ray Direction each retain all 217,088 exact pixels across 32 renders. + +| Debug hit UV storage | Renders | Exact RGBA pixels / compared | Maximum component error | +|---|---:|---:|---:| +| U8 | 13 | 120,832/120,832 | 0 | +| U16 | 9 | 18,429/18,432 | 1 level | +| F16 | 9 | 18,432/18,432 | 0 | +| F32 | 59 | 126,463/126,464 | .750555232 | + +For the 16 direct renders, use field channel c=((37x+41y+7xy+53×19+61c+5xc) mod 509)/508 as F32, with c from 0 through 3. Set the debug position to (.1875,.8125), sample index to 0 and count to 1. Sweep integer offsets −2 through 5 at 16² and 32² F32. Use seed 6481+17j+7t for offset index j and size index t, starting at zero. + +For the wired parents, drive the index and count through value processors. Use the following settings in row order. Within each row render the same field at 16² F32, 32² in U8/U16/F16/F32, 64² F32 with a 64×32 field, and 32² F32 with field values scaled by 2.5 and shifted by −.75. Use seed 4591+17j+13t for row j and render t. + +| Index | Count | Offset | Debug position | +|---:|---:|---:|---| +| 0 | 1 | −1 | (.1875,.8125) | +| 0 | 4 | −1 | (.671875,.328125) | +| 2 | 8 | −1 | (.25,.625) | +| 1 | 8 | 0 | (.421875,.765625) | +| 3 | 4 | 1 | (.71875,.15625) | +| 0 | 1 | 0 | (.375,.6875) | + +At (13,24) in the fourth row's 32² F32 output, the reference stores gray .1476394385. MaterialCraft also covers that pixel with the marker color (.43350938,.89819467,0,1). An isolated rectangle centered at (.42769217,.83190984), size (.13307922,.01), rotated .23604888 turns reproduces the extra pixel. In the final row at 32² U16 the reference stores red 15,899 at (9,19), (10,20) and (11,21). MaterialCraft stores 15,898. Both apps store 15,898 when an independent rectangle receives the literal red value .24259558. Integer storage also agrees on all 14,336 output pixels from 56 solid rectangle and uniform-color controls around half-level thresholds. + +A folded scalar integer is ordered and converted to F32 using its unsigned 32-bit value. A runtime scalar integer has signed ordering and conversion. For example a folded −5 becomes 4,294,967,296 in F32. With a runtime input of −5 it becomes −5. Compare −32,768 with 2, −5 with −2 in both orders, −1 with 0 in both orders, equal operands, opposite signs and −2³¹ with 1,024. Test less, less-or-equal, greater and greater-or-equal with two literals, two runtime inputs, either operand fixed, and an equivalent literal subtraction. Two serialized scalar integer types and the converted values are covered. All 84/84 returned F32 tuples match. Integer vectors of two, three and four lanes preserve signed conversion in all 12/12 additional typed controls. + +For the scope controls pack the four comparison flags into bits 0 through 3 and use bit 4 for float(left)>1,000,000. Divide by 32. With (−5,2), both fixed yield .875, a fixed left operand and runtime right operand yield .59375, and a runtime left operand with fixed right yields .09375. Use a property function, pixel processor, pattern function and value processor at 16² F32 and 32² in four formats with a positive and a negative argument. All 39,168 image pixels and 15 typed values match. + +An enclosing instance passes the fixed status of its scalar integer arguments through nested graphs and reusable functions. A value wire or exposed runtime control keeps its runtime status. Four original current-format packages with fixed, directly bound, computed and nested fixed inputs were saved by MaterialCraft and reopened in the reference app. All 20/20 typed F32 tuples match before and after saving and across applications, with error zero. + +Self-assignment remains open. Two separate programs assign an integer to the same identifier they read in the assignment, then read it again. With distinct graph identifiers and instruction IDs, 40/60 typed tuples match across those programs and four controls. The maximum F32 error in that capture was 2.65040882e25. Repeating the five identical seeds and inputs in the runtime self-assignment reproduced only one reference tuple. Assigning from a different input and assigning a constant to a local variable reproduced all 20/20 tuples, with error zero. + ### Uniform square roots and the UV debug marker The UV debug marker now cooks all **32** previously measured cases. The 27 cases that already cooked still match every pixel. Across all 32 renders **194,522/217,088 RGBA pixels** match. Maximum errors are 253 U8 levels, 0 U16 levels, 0 F16 and 1 F32. The five formerly rejected renders contribute 218/22,784 exact pixels. At 16² with index 0, count 1 and offset −1, the first output pixel has gray level .360237986 in the reference app and zero in MaterialCraft. At index 1, count 4 and offset 0, both store zero there. The input's first RGB and alpha components differ at this position. Both sibling roots, Compute Irradiance and Compute Ray Direction, retain 217,088/217,088 pixels each across 32 renders each, with error zero. [Wired sample inputs and seeds](#environment-rotation-and-wired-irradiance-samples) diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index 6c2ce04..eeb4402 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -505,7 +505,7 @@ The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard | [rt_caustics.sbs/rt_caustics_base](../assets/sbs/rt_caustics.sbs) | 3 | Yes | [In progress · 152,777/172,288 pixels in 19 renders](parity-fixes.md#paths-caustics-and-cell-fields-after-pattern-sampling) | | [rt_irradiance.sbs/compute_irradiance](../assets/sbs/rt_irradiance.sbs) | 5 | Yes | [Parity · 32 renders, all 217,088 RGBA pixels exact](parity-fixes.md#environment-rotation-and-wired-irradiance-samples) | | [rt_irradiance.sbs/compute_ray_direction](../assets/sbs/rt_irradiance.sbs) | 4 | Yes | [Parity · 32 renders, all 217,088 RGBA pixels exact](parity-fixes.md#environment-rotation-and-wired-irradiance-samples) | -| [rt_irradiance.sbs/debug_hit_uv](../assets/sbs/rt_irradiance.sbs) | 3 | Yes | [In progress · all 32 renders cook, 194,522/217,088 pixels exact](parity-fixes.md#uniform-square-roots-and-the-uv-debug-marker) | +| [rt_irradiance.sbs/debug_hit_uv](../assets/sbs/rt_irradiance.sbs) | 3 | Yes | [In progress · 284,156/284,160 pixels in 90 renders; four marker pixels differ](parity-fixes.md#fixed-integer-arguments-and-the-uv-debug-marker) | | [rt_irradiance.sbs/mip_max](../assets/sbs/rt_irradiance.sbs) | 1 | Yes | [Parity · 167,168 exact pixels in 17 cases](parity-fixes.md#pixel-processor-canvas-and-mip-maxima) | | [rt_irradiance.sbs/panoramic_lod](../assets/sbs/rt_irradiance.sbs) | 1 | Yes | [Parity · 18 cases, 186,624 exact pixels](parity-fixes.md#large-transform-offsets-and-additive-blends) | | [rt_irradiance.sbs/template/pp_template](../assets/sbs/rt_irradiance.sbs) | 3 | Yes | [Parity: 4 cases](parity-fixes.md#verified-cases) |