diff --git a/crates/eval/src/parameter.rs b/crates/eval/src/parameter.rs index 934dc4ac..61deec27 100644 --- a/crates/eval/src/parameter.rs +++ b/crates/eval/src/parameter.rs @@ -10,6 +10,15 @@ pub(crate) struct ResolvedParameters { pub dynamic_blend_opacity: bool, } +// The color cook needs the operand's original width and whether its channels were folded. +fn uniform_color_operand(value: &Value, literal: bool) -> Option { + match value { + Value::Float(_) | Value::Float3(_) => Some(value.clone()), + Value::Float4(rgba) | Value::Color(rgba) => Some(if literal { Value::Color(*rgba) } else { Value::Float4(*rgba) }), + _ => None, + } +} + pub(crate) fn resolve_parameters( package: &Package, node: &Node, @@ -37,7 +46,11 @@ pub(crate) fn resolve_parameters( let mut dynamic = std::collections::BTreeSet::new(); let mut dynamic_blend_opacity = false; + let mut uniform_color = None; for (parameter, exposed) in &node.bindings { + if node.def == "uniform" && parameter == "color" { + uniform_color = variables.get(exposed).and_then(|value| uniform_color_operand(value, false)); + } if node.def == "graph_instance" && !literal_inputs.contains(exposed) { dynamic.insert(parameter); } @@ -56,6 +69,7 @@ pub(crate) fn resolve_parameters( let current = parameters.get(parameter).ok_or_else(|| format!("unknown function parameter `{parameter}`"))?; let expected = ValueType::of(current).ok_or_else(|| format!("parameter `{parameter}` cannot have a function"))?; let channels = match (node.def.as_str(), parameter.as_str(), base.format) { + ("uniform", "color", _) => ChannelMode::UniformColor, ("levels", name, format) if accepts_scalar_function("levels", name) => { ChannelMode::Levels { normalized: name != "in_mid" && matches!(format, OutputFormat::U8 | OutputFormat::U16 | OutputFormat::Inherit) } } @@ -71,6 +85,10 @@ pub(crate) fn resolve_parameters( crate::parameter_function::evaluate(&program, expected, variables.to_mut(), base.size, channels, Some(current)) }) .map_err(|error| format!("function of `{parameter}`: {error}"))?; + if matches!(channels, ChannelMode::UniformColor) { + uniform_color = uniform_color_operand(&value, literal); + continue; + } if matches!(channels, ChannelMode::GrayPatternOpacity) { // Keep the result in floating point until blending. JSON and slider limits lose signed infinities. gray_pattern_opacity = Some(value); @@ -91,6 +109,9 @@ pub(crate) fn resolve_parameters( parameters.insert(parameter.clone(), value); } + if let Some(color) = uniform_color { + parameters.insert("color".into(), color); + } // Catalog limits keep values from files and functions within safe cook bounds if let Some(definition) = definition && node.def != "graph_instance" @@ -111,6 +132,14 @@ pub(crate) fn resolve_parameters( pub(crate) fn inspection_parameters(node: &Node, parameters: &mut BTreeMap) { parameters.retain(|name, value| { + if node.def == "uniform" && name == "color" { + match value { + Value::Float(level) => *value = Value::Color([*level, *level, *level, 1.0]), + Value::Float3([r, g, b]) => *value = Value::Color([*r, *g, *b, 1.0]), + Value::Float4(rgba) => *value = Value::Color(*rgba), + _ => {} + } + } if let Value::Float(level) = value && node.def == "levels" && accepts_scalar_function("levels", name) @@ -127,6 +156,106 @@ mod tests { use materialcraft_core::{FunctionGraph, Graph, Package, Value, ValueType}; use std::sync::Mutex; + #[test] + fn uniform_gray_preserves_the_precision_of_its_color_source() { + use materialcraft_core::OutputFormat; + + let mut graph = Graph::new("Uniform precision"); + graph.size = [2; 2]; + graph.format = OutputFormat::F32; + let uniform = graph.add_node("uniform", [0.0; 2]); + graph.node_mut(uniform).unwrap().params.insert("color_mode".into(), Value::Bool(false)); + let mut package = Package::new("Uniform precision"); + package.graphs.push(graph); + let cache = Mutex::new(Cache::default()); + let mut options = Options::new(&|_| None); + let scalar = Value::Float(f32::from_bits(0x3ed5_1632)); + let rgba = Value::Float4([1.0, f32::EPSILON, -1.0, 0.59375]); + for (value, bound, expected) in [ + (rgba.clone(), false, 0x332a_aaab), + (rgba.clone(), true, 0x3300_0000), + (scalar, true, 0x3ed5_1632), + (Value::Float3([0.125, 0.3125, 0.6875]), true, 0), + (Value::Float4([-65536.0, 65536.0, 0.001953125, 0.5]), false, 0x3a2a_aaab), + (rgba, false, 0x332a_aaab), + ] { + let function = if bound { + let get = FunctionGraph::input("ink", ValueType::of(&value).unwrap()); + options.overrides.insert("ink".into(), value); + get + } else { + FunctionGraph::constant(value) + }; + package.graphs[0].node_mut(uniform).unwrap().functions.insert("color".into(), function); + let cooked = cook(&package, 0, &options, &cache); + assert_eq!(cooked.nodes[&uniform].error, None); + assert_eq!(cooked.image(uniform, 0).unwrap().get_gray(0, 0, false).to_bits(), expected); + } + } + + #[test] + fn grayscale_uniform_distinguishes_image_size_from_an_exposed_color_read() { + use materialcraft_core::OutputFormat; + + let mut graph = Graph::new("Uniform sources"); + graph.size = [2; 2]; + graph.format = OutputFormat::F32; + let uniform = graph.add_node("uniform", [0.0; 2]); + graph.node_mut(uniform).unwrap().params.insert("color_mode".into(), Value::Bool(false)); + let mut package = Package::new("Uniform sources"); + package.graphs.push(graph); + let cache = Mutex::new(Cache::default()); + let mut options = Options::new(&|_| None); + options.overrides.insert("ink".into(), Value::Float4([0.25; 4])); + + for (variable, ty, expected) in [ + ("$size", ValueType::Float2, 0x332a_aaab), + ("$pixelratio", ValueType::Integer, 0x332a_aaab), + ("$uvtile", ValueType::Integer2, 0x332a_aaab), + ("$physicalsize", ValueType::Float3, 0x332a_aaab), + ("unbound_color", ValueType::Float, 0x332a_aaab), + ("$time", ValueType::Float, 0x3300_0000), + ("$normalformat", ValueType::Integer, 0x3300_0000), + ("ink", ValueType::Float4, 0x3300_0000), + ] { + let mut function = FunctionGraph::input(variable, ty); + let read = function.output.unwrap(); + let rgba = function.add_constant(Value::Float4([1.0, f32::EPSILON, -1.0, 0.59375])); + function.output = Some(function.add("sequence", &[read, rgba], None)); + package.graphs[0].node_mut(uniform).unwrap().functions.insert("color".into(), function); + let cooked = cook(&package, 0, &options, &cache); + assert_eq!(cooked.nodes[&uniform].error, None); + assert_eq!(cooked.image(uniform, 0).unwrap().get_gray(0, 0, false).to_bits(), expected); + } + } + + #[test] + fn uniform_color_keeps_hdr_channels_and_distinguishes_an_explicit_alpha() { + use materialcraft_core::OutputFormat; + + let mut graph = Graph::new("Uniform channels"); + graph.size = [2; 2]; + graph.format = OutputFormat::F32; + let uniform = graph.add_node("uniform", [0.0; 2]); + let mut package = Package::new("Uniform channels"); + package.graphs.push(graph); + let cache = Mutex::new(Cache::default()); + let mut options = Options::new(&|_| None); + let rgb = [-65536.0, 65536.0, 0.001953125]; + options.overrides.insert("ink".into(), Value::Float3(rgb)); + let direct = FunctionGraph::input("ink", ValueType::Float3); + let mut with_alpha = direct.clone(); + let color = with_alpha.output.unwrap(); + let alpha = with_alpha.add_constant(Value::Float(0.59375)); + with_alpha.output = Some(with_alpha.add("vector4", &[color, alpha], None)); + for (function, expected) in [(direct, [0.0, 0.0, 0.0, 1.0]), (with_alpha, [rgb[0], rgb[1], rgb[2], 0.59375])] { + package.graphs[0].node_mut(uniform).unwrap().functions.insert("color".into(), function); + let cooked = cook(&package, 0, &options, &cache); + assert_eq!(cooked.nodes[&uniform].error, None); + assert_eq!(cooked.image(uniform, 0).unwrap().get(0, 0, false), expected); + } + } + #[test] fn gray_levels_keep_scalar_endpoints_distinct_from_equal_rgb_controls() { use craft_texture::Image; diff --git a/crates/eval/src/parameter_function.rs b/crates/eval/src/parameter_function.rs index d6c5438f..37b51c06 100644 --- a/crates/eval/src/parameter_function.rs +++ b/crates/eval/src/parameter_function.rs @@ -6,6 +6,7 @@ use std::collections::BTreeMap; pub(crate) enum ChannelMode { Opaque, Broadcast, + UniformColor, GrayPatternOpacity, Levels { normalized: bool }, } @@ -26,7 +27,7 @@ pub(crate) fn evaluate( if let Some(value) = fallback && program.input_identifier().is_some_and(|name| !name.starts_with('$') && !variables.contains_key(name)) { - return Ok((value.clone(), false)); + return Ok((value.clone(), matches!(channels, ChannelMode::UniformColor))); } let context = EvaluationContext { @@ -47,6 +48,7 @@ pub(crate) fn evaluate( // A scalar level is already luminance. Its RGB expansion would introduce a second rounding. let scalar_level = matches!(channels, ChannelMode::Levels { .. }) && program.output_type() == ValueType::Float as u32; let value = match value { + value if matches!(channels, ChannelMode::UniformColor) => value, Value::Float(level) | Value::Float4([level, _, _, _]) if scalar_level => Value::Float(level), Value::Float(level) if widened && matches!(channels, ChannelMode::Broadcast) => Value::Float4([level; 4]), Value::Float(level) if widened => Value::Float4([level, level, level, 1.0]), @@ -54,7 +56,10 @@ pub(crate) fn evaluate( value => value, }; + let fixed = match channels { + ChannelMode::UniformColor => program.uses_fixed_uniform_color(variables), + _ => program.output_is_literal(), + }; variables.extend(state.assignments().clone()); - - Ok((value, program.output_is_literal())) + Ok((value, fixed)) } diff --git a/crates/nodes/src/atomic/uniform.rs b/crates/nodes/src/atomic/uniform.rs index 1c94da7c..ec1e5b6e 100644 --- a/crates/nodes/src/atomic/uniform.rs +++ b/crates/nodes/src/atomic/uniform.rs @@ -1,6 +1,7 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; use craft_texture::{Image, Kind}; +use materialcraft_core::Value; pub(super) fn definition() -> NodeDefinition { node("uniform", "Uniform color", ATOMIC) @@ -14,10 +15,18 @@ pub(super) fn definition() -> NodeDefinition { } fn uniform(context: &CookContext) -> CookResult { - let color = context.v4("color"); + let source = context.value("color"); + // A three-component function needs an explicit alpha to supply this property. + let color = if matches!(source, Some(Value::Float3(_))) { [0.0, 0.0, 0.0, 1.0] } else { context.v4("color") }; Ok(vec![if !context.b("color_mode") { - Image::filled(context.w, context.h, Kind::Gray, [(color[0] + color[1] + color[2]) / 3.0; 4]) + let gray = match source { + Some(Value::Float(level)) => *level, + // Runtime RGBA rounds each channel's contribution before accumulating the three. + Some(Value::Float4([r, g, b, _])) => r * (1.0 / 3.0) + g * (1.0 / 3.0) + b * (1.0 / 3.0), + _ => (color[0] + color[1] + color[2]) / 3.0, + }; + Image::filled(context.w, context.h, Kind::Gray, [gray; 4]) } else { Image::filled(context.w, context.h, Kind::Color, color) }]) diff --git a/crates/nodes/src/function/program.rs b/crates/nodes/src/function/program.rs index b275d86c..f7697592 100644 --- a/crates/nodes/src/function/program.rs +++ b/crates/nodes/src/function/program.rs @@ -32,6 +32,25 @@ impl Program { self.instructions.get(self.output).is_some_and(|instruction| instruction.literal) } + /// A grayscale Uniform folds its channel mean when its property has only fixed operands. + pub fn uses_fixed_uniform_color(&self, variables: &std::collections::BTreeMap) -> bool { + self.instructions.iter().all(|op| { + op.literal + || op.depends_only_on_operands() + || op.definition.id == "isdefined" + || match (&op.value, op.definition.id) { + (Some(Value::Text(name)), getter) if getter.starts_with("get_") && !name.starts_with('$') => !variables.contains_key(name), + (Some(Value::Text(name)), "get_float2") => matches!(name.as_str(), "$size" | "$sizelog2"), + (Some(Value::Text(name)), "get_integer1") => { + matches!(name.as_str(), "$tiling" | "$pixelratio") || super::SystemVariable::named(name).is_none() + } + (Some(Value::Text(name)), "get_integer2") => name == "$uvtile", + (Some(Value::Text(name)), "get_float3") => name == "$physicalsize", + _ => false, + } + }) + } + /// 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.instructions.iter().any(|op| { diff --git a/crates/nodes/src/parameter.rs b/crates/nodes/src/parameter.rs index 0e993ea2..74974dd8 100644 --- a/crates/nodes/src/parameter.rs +++ b/crates/nodes/src/parameter.rs @@ -41,9 +41,10 @@ pub fn clamp_params(definition: &NodeDefinition, params: &mut BTreeMap