From cf0a32dd1cf713a856c63cbe3234ce83294a7465 Mon Sep 17 00:00:00 2001 From: PiJellyPin Date: Fri, 13 Nov 2026 00:12:41 +0100 Subject: [PATCH] Fixing node pairity loading images to slow --- crates/engine/src/lib.rs | 1 + crates/engine/src/library_preview.rs | 82 ++++++++++ crates/engine/src/node_library.test.rs | 14 ++ crates/engine/tests/it/function_instances.rs | 13 +- crates/engine/tests/it/parameter_functions.rs | 7 + crates/eval/src/node_execution.rs | 8 +- crates/eval/src/parameter_function.rs | 31 +++- crates/eval/src/resolved_base_parameters.rs | 21 ++- crates/eval/src/tests.rs | 47 ++++++ crates/formats/src/sbs/filter_map.rs | 8 +- crates/nodes/src/atomic/pattern_map.rs | 1 + crates/nodes/src/function/compile.rs | 100 ++++++++++-- .../nodes/src/function/evaluation_context.rs | 6 +- crates/nodes/src/function/evaluation_state.rs | 2 + crates/nodes/src/function/evaluation_step.rs | 18 ++- crates/nodes/src/function/function_call.rs | 2 + crates/nodes/src/function/instruction.rs | 3 +- crates/nodes/src/function/mod.rs | 3 +- crates/nodes/src/function/operation.rs | 1 + crates/nodes/src/function/processor.rs | 3 +- crates/nodes/src/function/program.rs | 43 ++++- .../nodes/src/function/resolve_instances.rs | 4 +- crates/nodes/src/function/tests.rs | 124 +++++++++++++- crates/nodes/src/pattern/evaluation.rs | 20 ++- crates/nodes/src/pattern/pattern_visit.rs | 4 - crates/nodes/src/pattern/raster.rs | 17 +- crates/nodes/src/pattern/tests.rs | 90 +++++++++++ crates/ui-egui/src/function/geometry.rs | 7 +- crates/ui-egui/src/function/mod.rs | 1 + crates/ui-egui/src/function/node_canvas.rs | 13 +- crates/ui-egui/src/function/node_face.rs | 151 ++++++++++++++++++ crates/ui-egui/src/function/render.rs | 18 +-- crates/ui-egui/src/graph/canvas.rs | 19 +-- crates/ui-egui/src/graph/interaction_tests.rs | 3 +- crates/ui-egui/src/graph/mod.rs | 3 +- crates/ui-egui/src/graph/navigation.rs | 4 +- crates/ui-egui/src/graph/node_card.rs | 39 ++++- crates/ui-egui/src/graph/node_style.rs | 5 + crates/ui-egui/src/graph/value_text.rs | 56 +++++++ crates/ui-egui/src/library.rs | 55 ++++++- crates/ui-egui/src/library.test.rs | 8 + crates/ui-egui/src/state/ui_state.rs | 3 + crates/ui-egui/src/thumbs.rs | 100 ++++++++++++ crates/ui-egui/src/value_editor.rs | 79 ++++++--- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/node_look.rs | 81 ++++++++++ crates/ui-egui/tests/snapshot.rs | 3 + crates/ui-egui/tests/snapshot/node_look.rs | 90 +++++++++++ 48 files changed, 1291 insertions(+), 121 deletions(-) create mode 100644 crates/engine/src/library_preview.rs create mode 100644 crates/ui-egui/src/function/node_face.rs create mode 100644 crates/ui-egui/src/graph/value_text.rs create mode 100644 crates/ui-egui/tests/it/node_look.rs create mode 100644 crates/ui-egui/tests/snapshot/node_look.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7557cc8..e99c7f1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -77,6 +77,7 @@ mod color_space; mod connection_commands; mod export_request; mod export_size; +mod library_preview; pub use clip::Clip; pub use color_space::ColorSpace; pub use export_request::ExportRequest; diff --git a/crates/engine/src/library_preview.rs b/crates/engine/src/library_preview.rs new file mode 100644 index 0000000..fb51457 --- /dev/null +++ b/crates/engine/src/library_preview.rs @@ -0,0 +1,82 @@ +//! Library previews: a small image of what a library graph makes from sample inputs + +use std::collections::BTreeMap; +use std::sync::Arc; + +use materialcraft_core::Package; +use materialcraft_image::{Image, Kind}; + +use crate::{NodeLibrary, Session}; + +/// Smallest spread between an image's darkest and brightest sample that still shows something +const FLAT_SPREAD: f32 = 0.01; +/// Side in pixels a graph is cooked at before it is scaled down to the preview +const COOKED_SIZE: u32 = 128; + +impl NodeLibrary { + /// What graph `graph` of package `package` makes at `size` pixels, from a wave height, its + /// colors and its normal map on the graph's inputs. `None` when the graph has no output that + /// cooks or its image is one flat value + pub fn preview(library: &Arc, package: &str, graph: &str, size: u32) -> Option { + let source = library.packages.get(package)?; + let index = source.graphs.iter().position(|candidate| candidate.function.is_none() && candidate.sbs_path() == graph)?; + + // A session links the graph's instances and functions to the library, as an opened package gets + let session = Session::with_library(Package::clone(source), library.clone()); + let graph = session.pkg.graphs.get(index)?; + let decode = session.resource_decoder(); + let mut options = materialcraft_eval::Options::new(&decode); + // Thin lines and fine grain vanish when cooked at thumbnail size, so the graph cooks larger and is scaled down + let cooked_size = size.max(COOKED_SIZE); + options.max_size = Some(cooked_size); + options.inputs = sample_inputs(graph, cooked_size); + let cooked = materialcraft_eval::cook(&session.pkg, index, &options, &session.cache); + + let outputs = materialcraft_eval::outputs(graph, &cooked); + let base_color = outputs.iter().find(|(_, usage, _, image)| *usage == "baseColor" && image.is_some()); + let image = base_color.or_else(|| outputs.iter().find(|output| output.3.is_some()))?.3?; + (!is_flat(image)).then(|| image.resize(size.min(image.w), size.min(image.h), false)) + } +} + +/// An image for every input node of `graph`, by identifier: normals for normal inputs, colors for color inputs, the height for the rest +fn sample_inputs(graph: &materialcraft_core::Graph, size: u32) -> BTreeMap { + let height = Image::generate_uv(size, size, Kind::Gray, |u, v| { + [0.5 + 0.25 * (u * std::f32::consts::TAU).sin() + 0.25 * (v * std::f32::consts::TAU).cos(), 0.0, 0.0, 0.0] + }); + let color = height.map(Kind::Color, |pixel| [0.15 + 0.7 * pixel[0], 0.35 + 0.3 * pixel[0], 0.8 - 0.5 * pixel[0], 1.0]); + let normal = materialcraft_nodes::atomic::height_to_normal(&height, 4.0, false, true, false); + + graph + .nodes + .iter() + .filter(|node| matches!(node.def.as_str(), "input_color" | "input_grayscale")) + .map(|node| { + let identifier = materialcraft_eval::identifier(node); + let image = if identifier.to_ascii_lowercase().contains("normal") { + &normal + } else if node.def == "input_color" { + &color + } else { + &height + }; + (identifier, image.clone()) + }) + .collect() +} + +/// Whether every pixel of `image` has nearly the same value +fn is_flat(image: &Image) -> bool { + let mut low = [f32::INFINITY; 3]; + let mut high = [f32::NEG_INFINITY; 3]; + for y in 0..i64::from(image.h) { + for x in 0..i64::from(image.w) { + let pixel = image.get(x, y, false); + for channel in 0..3 { + low[channel] = low[channel].min(pixel[channel]); + high[channel] = high[channel].max(pixel[channel]); + } + } + } + (0..3).all(|channel| high[channel] - low[channel] < FLAT_SPREAD) +} diff --git a/crates/engine/src/node_library.test.rs b/crates/engine/src/node_library.test.rs index 7def12e..8b98445 100644 --- a/crates/engine/src/node_library.test.rs +++ b/crates/engine/src/node_library.test.rs @@ -291,3 +291,17 @@ fn function_tags_choose_library_filters_before_path_fallbacks() { assert_eq!(categories("Tagged"), ["Functions/Comparison", "Functions/Easings"]); assert_eq!(categories("Fallback"), ["Functions/Maths"]); } + +/// Library graphs render a preview from sample inputs; graphs that make no image give none. +#[test] +fn library_graphs_cook_previews_from_sample_inputs() { + let library = Arc::new(NodeLibrary::load(&library::files())); + let preview = |package: &str, graph: &str| NodeLibrary::preview(&library, package, graph, 32); + + let filter = preview("sbs://blur_hq.sbs", "blur_hq").unwrap(); + assert_eq!((filter.w, filter.h), (32, 32)); + assert!(preview("sbs://materials/pbr/bricks_001.sbs", "bricks_001").is_some()); + assert!(preview("sbs://noise_bnw_spots_1.sbs", "bnw_spots_1").is_some(), "an FX-Map noise reads the variables its size function sets"); + assert!(preview("sbs://blur_hq.sbs", "no_such_graph").is_none()); + assert!(preview("sbs://functions.sbs", "Functions/Math/Pi").is_none(), "a function has no image"); +} diff --git a/crates/engine/tests/it/function_instances.rs b/crates/engine/tests/it/function_instances.rs index 7b3a7b7..0103d54 100644 --- a/crates/engine/tests/it/function_instances.rs +++ b/crates/engine/tests/it/function_instances.rs @@ -86,7 +86,7 @@ fn function_expansion_allows_several_bounded_bodies_but_still_caps_total_work() let mut allowed = caller(3); function::resolve_instances(&mut allowed, &package, &BTreeMap::new()); assert_eq!(evaluate(&allowed), Value::Float(3.0)); - let mut oversized = caller(4); + let mut oversized = caller(32); function::resolve_instances(&mut oversized, &package, &BTreeMap::new()); assert!(function::compile(&oversized, 0).err().unwrap().contains("limit")); // Compiling a pre-resolved tree must enforce its own budget too. @@ -251,7 +251,7 @@ fn function_calls_reject_wrong_canvas_cycles_and_outputless_sources() { } #[test] -fn calls_isolate_variables_and_evaluate_arguments_once() { +fn calls_evaluate_arguments_once_and_share_the_variables_they_set() { let mut package = source(); let mut source = FunctionGraph::default(); let input = source.add("get_float1", &[], Some(Value::Text("amount".into()))); @@ -278,7 +278,14 @@ fn calls_isolate_variables_and_evaluate_arguments_once() { let total = caller.add("add", &[call, get], None); caller.output = Some(caller.add("sequence", &[init, total], None)); function::resolve_instances(&mut caller, &package, &BTreeMap::new()); - assert_eq!(evaluate(&caller), Value::Float(6.0)); + // The Get node ran once, before the argument's Set: 1; the call doubles its argument 2 + assert_eq!(evaluate(&caller), Value::Float(5.0)); + + // A Get node that runs after the call reads what the called graph set, as the library's size helpers rely on + let after = caller.add("get_float1", &[], Some(Value::Text("private".into()))); + let read_after = caller.add("sequence", &[call, after], None); + caller.output = Some(caller.add("sequence", &[init, read_after], None)); + assert_eq!(evaluate(&caller), Value::Float(99.0)); } #[test] diff --git a/crates/engine/tests/it/parameter_functions.rs b/crates/engine/tests/it/parameter_functions.rs index bac6a12..094a129 100644 --- a/crates/engine/tests/it/parameter_functions.rs +++ b/crates/engine/tests/it/parameter_functions.rs @@ -296,6 +296,13 @@ fn color_boolean_enum_and_text_parameters_use_typed_function_outputs() { let owner = node(&mut session, "uniform"); command(&mut session, "graph.node.function", json!({"id": owner, "param": "color", "function": FunctionGraph::constant(Value::Float(0.5))})); + // A gray level fills the color channels, as the library's uniform colors rely on + let result = &session.cook().nodes[&owner]; + assert_eq!(result.error, None); + assert_eq!(result.parameters["color"].as_vec4(), Some([0.5, 0.5, 0.5, 1.0])); + + let owner = node(&mut session, "uniform"); + command(&mut session, "graph.node.function", json!({"id": owner, "param": "color", "function": FunctionGraph::constant(Value::Int(1))})); assert!(session.cook().nodes[&owner].error.as_ref().unwrap().contains("Float4")); let bitmap = node(&mut session, "bitmap"); assert!(execute(&mut session, "graph.node.function", &json!({"id": bitmap, "param": "resource"})).is_err()); diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs index f94f790..85e8f4b 100644 --- a/crates/eval/src/node_execution.rs +++ b/crates/eval/src/node_execution.rs @@ -83,7 +83,13 @@ 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, &variables) { - Ok((base, values)) => (base, values, None), + Ok(evaluation) => { + if !evaluation.variables.is_empty() { + variables.to_mut().extend(evaluation.variables); + } + + (evaluation.base, evaluation.values, None) + } Err(error) => (crate::ResolvedBaseParameters::resolve(&node.base, input_base, prepared.parent_base), BTreeMap::new(), Some(error)), }; if node.disabled diff --git a/crates/eval/src/parameter_function.rs b/crates/eval/src/parameter_function.rs index 8a4bb21..2fcb0cc 100644 --- a/crates/eval/src/parameter_function.rs +++ b/crates/eval/src/parameter_function.rs @@ -9,15 +9,30 @@ pub(crate) fn evaluate( seed: u32, size: [u32; 2], allow_scalar: bool, +) -> Result { + evaluate_keeping_variables(function, expected, &mut variables.clone(), seed, size, allow_scalar) +} + +/// Like `evaluate`, and the user variables the function set stay in `variables` for the functions evaluated after it +pub(crate) fn evaluate_keeping_variables( + function: &FunctionGraph, + expected: ValueType, + variables: &mut BTreeMap, + seed: u32, + size: [u32; 2], + allow_scalar: bool, ) -> Result { let program = compile(function, seed)?; let scalar_channel = allow_scalar && expected == ValueType::Float4 && program.output_type() == ValueType::Float as u32; - if program.output_type() != expected as u32 && !scalar_channel { + // A color parameter also takes a gray level or an opaque RGB triple + let widened = expected == ValueType::Float4 && [ValueType::Float as u32, ValueType::Float3 as u32].contains(&program.output_type()); + if program.output_type() != expected as u32 && !scalar_channel && !widened { return Err(format!("output must be {}", expected.label())); } let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: size.map(|side| side as f32), images: &[], tile: true, variables }; - let value = program.evaluate(&context, &mut EvaluationState::default())?; + let mut state = EvaluationState::default(); + let value = program.evaluate(&context, &mut state)?; let finite = match &value { Value::Float(value) => value.is_finite(), Value::Float2(values) => values.iter().all(|value| value.is_finite()), @@ -29,5 +44,17 @@ pub(crate) fn evaluate( return Err("function returned a non-finite value".into()); } + let value = match value { + Value::Float(level) if !scalar_channel && widened => Value::Float4([level, level, level, 1.0]), + Value::Float3([red, green, blue]) if widened => Value::Float4([red, green, blue, 1.0]), + value => value, + }; + + for (name, set) in state.variables() { + if !name.starts_with('$') && variables.get(name) != Some(set) { + variables.insert(name.clone(), set.clone()); + } + } + Ok(value) } diff --git a/crates/eval/src/resolved_base_parameters.rs b/crates/eval/src/resolved_base_parameters.rs index 6f189d8..bc5ecde 100644 --- a/crates/eval/src/resolved_base_parameters.rs +++ b/crates/eval/src/resolved_base_parameters.rs @@ -50,10 +50,10 @@ pub(crate) fn evaluate( base: &BaseParameters, input: Option, parent: ResolvedBaseParameters, - variables: &BTreeMap, -) -> Result<(ResolvedBaseParameters, BTreeMap), String> { + inherited: &BTreeMap, +) -> Result { if base.functions.is_empty() { - return Ok((ResolvedBaseParameters::resolve(base, input, parent), BTreeMap::new())); + return Ok(BaseEvaluation { base: ResolvedBaseParameters::resolve(base, input, parent), values: BTreeMap::new(), variables: BTreeMap::new() }); } // Evaluation mutates literals while borrowing the attached function graphs @@ -73,7 +73,7 @@ pub(crate) fn evaluate( pixel_ratio_mode: base.pixel_ratio_mode, }; let mut values = BTreeMap::new(); - let mut variables = variables.clone(); + let mut variables = inherited.clone(); let mut resolved = ResolvedBaseParameters::resolve(&evaluated, input, parent); // Size and seed establish the context used by the remaining parameter functions @@ -92,7 +92,7 @@ pub(crate) fn evaluate( } else { resolved.size }; - let value = crate::parameter_function::evaluate(function, parameter.value_type(), &variables, resolved.seed, size, false) + let value = crate::parameter_function::evaluate_keeping_variables(function, parameter.value_type(), &mut variables, resolved.seed, size, false) .map_err(|error| format!("function of `{}`: {error}", parameter.identifier()))?; parameter.set_value(&mut evaluated, &value)?; parameter.set_inheritance(&mut evaluated, parameter.inheritance(base)); @@ -102,5 +102,14 @@ pub(crate) fn evaluate( values.insert(parameter, parameter.value(&evaluated)); } - Ok((resolved, values)) + variables.retain(|name, value| !name.starts_with('$') && inherited.get(name) != Some(value)); + Ok(BaseEvaluation { base: resolved, values, variables }) +} + +/// What a node's base parameter functions resolved to +pub(crate) struct BaseEvaluation { + pub(crate) base: ResolvedBaseParameters, + pub(crate) values: BTreeMap, + /// User variables the functions set; the node's other functions read them + pub(crate) variables: BTreeMap, } diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index aff7994..5c8bf4f 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -571,3 +571,50 @@ fn enabled_generators_use_parent_size_and_inherit_other_input_base_parameters() } } } + +#[test] +fn variables_set_by_a_base_parameter_function_reach_the_nodes_other_functions() { + use materialcraft_core::{BaseParameter, FunctionGraph}; + + let mut size = FunctionGraph::default(); + let grid = size.add_constant(Value::Int(2)); + let store = size.add("set", &[grid], Some(Value::Text("grid".into()))); + let unchanged = size.add_constant(Value::Int2([0, 0])); + size.output = Some(size.add("sequence", &[store, unchanged], None)); + + let mut roughness = FunctionGraph::default(); + let read = roughness.add("get_integer1", &[], Some(Value::Text("grid".into()))); + roughness.output = Some(roughness.add("tofloat", &[read], None)); + + let mut graph = Graph::new("Shared variables"); + let generator = graph.add_node("fx_map", [0.0; 2]); + let node = graph.node_mut(generator).unwrap(); + node.base.functions.insert(BaseParameter::OutputSize, size); + node.functions.insert("roughness".into(), roughness); + let mut package = Package::new("Shared variables"); + package.graphs.push(graph); + + let cooked = cook(&package, 0, &Options::new(&no_res), &Mutex::new(Cache::default())); + let result = &cooked.nodes[&generator]; + assert_eq!(result.error, None); + assert_eq!(result.parameters.get("roughness"), Some(&Value::Float(2.0))); +} + +#[test] +fn a_color_parameter_function_may_return_a_gray_level_or_an_rgb_triple() { + use materialcraft_core::FunctionGraph; + + for (value, expected) in [(Value::Float(0.25), [0.25, 0.25, 0.25, 1.0]), (Value::Float3([0.1, 0.2, 0.3]), [0.1, 0.2, 0.3, 1.0])] { + let mut graph = Graph::new("Color function"); + let uniform = graph.add_node("uniform", [0.0; 2]); + graph.node_mut(uniform).unwrap().functions.insert("color".into(), FunctionGraph::constant(value)); + let mut package = Package::new("Color function"); + package.graphs.push(graph); + + let cooked = cook(&package, 0, &Options::new(&no_res), &Mutex::new(Cache::default())); + let result = &cooked.nodes[&uniform]; + + assert_eq!(result.error, None); + assert_eq!(result.parameters.get("color").and_then(Value::as_vec4), Some(expected)); + } +} diff --git a/crates/formats/src/sbs/filter_map.rs b/crates/formats/src/sbs/filter_map.rs index 07b847c..70764a4 100644 --- a/crates/formats/src/sbs/filter_map.rs +++ b/crates/formats/src/sbs/filter_map.rs @@ -103,7 +103,13 @@ pub(super) const FILTERS: &[FilterMap] = &[ sbs: "fxmaps", def: "fx_map", inputs: &[("background", "background"), ("inputpattern", "pattern0"), ("input", "pattern0")], - params: &[("colorswitch", "color_mode"), ("background", "background"), ("hurst", "roughness"), ("opacitymult", "opacity")], + params: &[ + ("colorswitch", "color_mode"), + ("background", "background"), + ("hurst", "roughness"), + ("opacitymult", "opacity"), + ("renderroi", "render_region"), + ], }, ]; pub(super) const BASE_PARAMS: &[&str] = &["outputsize", "format", "randomseed", "tiling", "pixelsize", "pixelratio", "quality"]; diff --git a/crates/nodes/src/atomic/pattern_map.rs b/crates/nodes/src/atomic/pattern_map.rs index 3c45f32..7faae7f 100644 --- a/crates/nodes/src/atomic/pattern_map.rs +++ b/crates/nodes/src/atomic/pattern_map.rs @@ -14,6 +14,7 @@ pub(super) fn definition() -> NodeDefinition { .float("opacity", "Opacity", 1.0, 0.0, 10.0) .boolean("color_mode", "Color output", false) .color("background", "Background color", [0.0, 0.0, 0.0, 1.0]) + .float4("render_region", "Render region", [0.0, 1.0, 0.0, 1.0], -65536.0, 65536.0) .any_out() .cook(crate::pattern::cook) } diff --git a/crates/nodes/src/function/compile.rs b/crates/nodes/src/function/compile.rs index f9c8eaf..9fda789 100644 --- a/crates/nodes/src/function/compile.rs +++ b/crates/nodes/src/function/compile.rs @@ -11,8 +11,8 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu if graph.nodes.len() > 4096 { return Err("function exceeds the 4096-node graph limit".into()); } - if depth > 8 || graph.nodes.len() > *remaining { - return Err("function exceeds the 8-level or 8192-node expanded execution limit".into()); + if depth > super::MAX_CALL_DEPTH || graph.nodes.len() > *remaining { + return Err("function exceeds the 16-level or 65536-node expanded execution limit".into()); } *remaining -= graph.nodes.len(); let output = super::output_node(graph).ok_or("function has no result node")?.id; @@ -42,10 +42,11 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu catalog::definition(&node.op).ok_or_else(|| format!("unknown function `{}`", node.op))? }; let names: Vec<_> = super::input_identifiers(node).collect(); - let missing_input = names - .iter() - .zip(&node.inputs) - .any(|(name, input)| input.is_none() && !node.instance.as_ref().is_some_and(|instance| instance.defaults.contains_key(*name))); + // An operation computes with zero on an input nothing is connected to; a call needs a source default instead + let missing_input = node + .instance + .as_ref() + .is_some_and(|instance| names.iter().zip(&node.inputs).any(|(name, input)| input.is_none() && !instance.defaults.contains_key(*name))); if node.inputs.len() != names.len() || missing_input { return Err(format!("{} ({id}) requires connected inputs: {}", super::node_label(node), names.join(", "))); } @@ -68,8 +69,36 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu } active.remove(&id); - let inputs: Vec = + let connected: Vec = sources.iter().map(|input| indices.get(input).copied().ok_or("unresolved function input".to_string())).collect::>()?; + let inputs = if node.instance.is_some() || ports.iter().all(|(_, input)| input.is_some()) { + connected + } else { + let sibling = connected.first().and_then(|index| instructions.get(*index)).map(|instruction| instruction.type_code); + let mut connected = connected.into_iter(); + let mut inputs = Vec::with_capacity(ports.len()); + for (name, input) in &ports { + let index = match input { + Some(_) => connected.next().ok_or("unresolved function input")?, + None => { + let (definition, value) = unconnected(name, sibling.unwrap_or(node.type_code))?; + let type_code = super::value_type::type_code(&value); + instructions.push(Instruction { + id: 0, + definition, + inputs: Vec::new(), + value: Some(value), + type_code, + repeated: Vec::new(), + call: None, + }); + instructions.len() - 1 + } + }; + inputs.push(index); + } + inputs + }; let call = if let Some(instance) = &node.instance { let source = node.source.as_ref().ok_or_else(|| format!("unresolved Function Graph `{}`", instance.graph))?.as_ref().map_err(Clone::clone)?; let program = compile_nested(source, seed, depth + 1, remaining)?; @@ -86,7 +115,9 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu } } let inputs = ports.iter().filter(|(_, input)| input.is_some()).map(|(name, _)| (*name).to_string()).collect(); - Some(super::function_call::FunctionCall { program, inputs, defaults: instance.defaults.clone() }) + let exports = + program.instructions.iter().any(|instruction| instruction.definition.id == "set" || instruction.call.as_ref().is_some_and(|call| call.exports)); + Some(super::function_call::FunctionCall { program, inputs, defaults: instance.defaults.clone(), exports }) } else { None }; @@ -94,14 +125,57 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu let input_type = |index: usize| inputs.get(index).and_then(|index| instructions.get(*index)).map_or(256, |instruction| instruction.type_code); let inferred = super::inferred_type::inferred_type(&node.op, value.as_ref(), input_type); let type_code = call.as_ref().map_or_else(|| if node.type_code == 0 { inferred } else { node.type_code }, |call| call.program.output_type()); - let pure = call.is_none() - && !matches!(node.op.as_str(), "set" | "sequence" | "while" | "rand" | "isdefined") - && !node.op.starts_with("get_") - && inputs.iter().all(|index| instructions.get(*index).is_some_and(|instruction| instruction.pure)); indices.insert(id, instructions.len()); - instructions.push(Instruction { id, definition, inputs, value, type_code, pure, call }); + instructions.push(Instruction { id, definition, inputs, value, type_code, repeated: Vec::new(), call }); + } + + // Instructions come after their inputs, so walking back from a loop reaches its whole condition and body + for index in 0..instructions.len() { + if instructions.get(index).is_some_and(|instruction| instruction.definition.id == "while") { + let repeated = loop_members(&instructions, index); + if let Some(instruction) = instructions.get_mut(index) { + instruction.repeated = repeated; + } + } } let output = indices.get(&output).copied().ok_or("missing result instruction")?; Ok(Program { instructions, output, seed }) } + +/// The instructions the condition and the body of loop `index` evaluate again on every iteration +fn loop_members(instructions: &[Instruction], index: usize) -> Vec { + let mut member = vec![false; instructions.len()]; + let mut pending: Vec = instructions.get(index).map(|instruction| instruction.inputs.iter().skip(1).copied().collect()).unwrap_or_default(); + while let Some(next) = pending.pop() { + if let Some(seen) = member.get_mut(next) + && !*seen + { + *seen = true; + pending.extend(instructions.get(next).map(|instruction| instruction.inputs.as_slice()).unwrap_or_default()); + } + } + + member.iter().enumerate().filter(|(_, member)| **member).map(|(index, _)| index).collect() +} + +/// The constant an unconnected input `name` reads: false for a condition, otherwise zero of the type its node works with +fn unconnected(name: &str, type_code: u32) -> Result<(&'static super::FunctionDefinition, materialcraft_core::Value), String> { + use materialcraft_core::ValueType; + + let value_type = if matches!(name, "cond" | "condition") { ValueType::Boolean } else { ValueType::from_code(type_code).unwrap_or(ValueType::Float) }; + let operation = match value_type { + ValueType::Boolean => "const_bool", + ValueType::Integer => "const_int1", + ValueType::Integer2 => "const_int2", + ValueType::Integer3 => "const_int3", + ValueType::Integer4 => "const_int4", + ValueType::Float => "const_float1", + ValueType::Float2 => "const_float2", + ValueType::Float3 => "const_float3", + ValueType::Float4 => "const_float4", + ValueType::String => "const_string", + }; + let definition = catalog::definition(operation).ok_or("missing constant operation")?; + Ok((definition, value_type.default_value())) +} diff --git a/crates/nodes/src/function/evaluation_context.rs b/crates/nodes/src/function/evaluation_context.rs index 449b685..8b71ed5 100644 --- a/crates/nodes/src/function/evaluation_context.rs +++ b/crates/nodes/src/function/evaluation_context.rs @@ -19,6 +19,10 @@ impl EvaluationContext<'_> { return variable.resolve(self); } - Ok(local.get(name).or_else(|| self.variables.get(name)).cloned()) + // A drop-down parameter reads as the integer of its chosen option + Ok(local.get(name).or_else(|| self.variables.get(name)).map(|value| match value { + Value::Enum(option) => Value::Int(i32::try_from(*option).unwrap_or(i32::MAX)), + value => value.clone(), + })) } } diff --git a/crates/nodes/src/function/evaluation_state.rs b/crates/nodes/src/function/evaluation_state.rs index f89e4c6..2af936c 100644 --- a/crates/nodes/src/function/evaluation_state.rs +++ b/crates/nodes/src/function/evaluation_state.rs @@ -10,6 +10,8 @@ pub struct EvaluationState { pub(crate) registers: Vec>, pub(crate) variables: BTreeMap, pub(crate) random: u32, + /// Mixed into the seed of this evaluation, so every pixel of a processor draws its own random numbers + pub(crate) seed_offset: u32, pub(crate) calls: BTreeMap, } diff --git a/crates/nodes/src/function/evaluation_step.rs b/crates/nodes/src/function/evaluation_step.rs index dd98238..2d73f83 100644 --- a/crates/nodes/src/function/evaluation_step.rs +++ b/crates/nodes/src/function/evaluation_step.rs @@ -2,10 +2,22 @@ use materialcraft_core::Value; pub(crate) enum EvaluationStep { Enter(usize), - Apply { instruction: usize, base: usize }, + Apply { + instruction: usize, + base: usize, + }, Branch(usize), + /// Keep the value on top as the result of this instruction for the rest of the run + Store(usize), Sequence(usize), LoopStart(usize), - LoopCondition { instruction: usize, iteration: u32, last: Value }, - LoopBody { instruction: usize, iteration: u32 }, + LoopCondition { + instruction: usize, + iteration: u32, + last: Value, + }, + LoopBody { + instruction: usize, + iteration: u32, + }, } diff --git a/crates/nodes/src/function/function_call.rs b/crates/nodes/src/function/function_call.rs index 121b95b..0096b8d 100644 --- a/crates/nodes/src/function/function_call.rs +++ b/crates/nodes/src/function/function_call.rs @@ -6,4 +6,6 @@ pub(crate) struct FunctionCall { pub program: Program, pub inputs: Vec, pub defaults: std::collections::BTreeMap, + /// The called graph sets variables, directly or in a graph it calls; the caller reads them after the call + pub exports: bool, } diff --git a/crates/nodes/src/function/instruction.rs b/crates/nodes/src/function/instruction.rs index f6a7b33..e4d40d9 100644 --- a/crates/nodes/src/function/instruction.rs +++ b/crates/nodes/src/function/instruction.rs @@ -7,6 +7,7 @@ pub(crate) struct Instruction { pub inputs: Vec, pub value: Option, pub type_code: u32, - pub pure: bool, + /// For a loop: the instructions of its condition and body, evaluated again on every iteration + pub repeated: Vec, pub call: Option, } diff --git a/crates/nodes/src/function/mod.rs b/crates/nodes/src/function/mod.rs index cbd9c1c..52786da 100644 --- a/crates/nodes/src/function/mod.rs +++ b/crates/nodes/src/function/mod.rs @@ -2,7 +2,8 @@ // Individual graphs stay capped at 4096 nodes. Shared calls can expand beyond that size // (the bundled noise/render functions use 4426/6997), but must not grow without a ceiling. -const MAX_EXPANDED_NODES: usize = 8192; +const MAX_EXPANDED_NODES: usize = 65_536; +const MAX_CALL_DEPTH: usize = 16; mod arithmetic; mod catalog; diff --git a/crates/nodes/src/function/operation.rs b/crates/nodes/src/function/operation.rs index f83052d..bbe24b6 100644 --- a/crates/nodes/src/function/operation.rs +++ b/crates/nodes/src/function/operation.rs @@ -79,6 +79,7 @@ pub(crate) fn evaluate( let ordering = match (left, right) { (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), _ => return Err("comparison requires numeric inputs".into()), } .ok_or("cannot compare non-finite values")?; diff --git a/crates/nodes/src/function/processor.rs b/crates/nodes/src/function/processor.rs index 801bd2b..4365e19 100644 --- a/crates/nodes/src/function/processor.rs +++ b/crates/nodes/src/function/processor.rs @@ -39,7 +39,8 @@ pub(crate) fn pixel_processor(context: &CookContext) -> CookResult { variables: context.vars, }; - let result = pixel(program.evaluate_pixel(&evaluation, state)?, gray)?; + let index = (y as u32).wrapping_mul(width).wrapping_add(x as u32); + let result = pixel(program.evaluate_pixel(&evaluation, state, index)?, gray)?; target.copy_from_slice(result.get(..channels).ok_or("invalid output channels")?); } Ok(()) diff --git a/crates/nodes/src/function/program.rs b/crates/nodes/src/function/program.rs index 16b2d50..c2e793b 100644 --- a/crates/nodes/src/function/program.rs +++ b/crates/nodes/src/function/program.rs @@ -29,13 +29,15 @@ impl Program { pub fn evaluate(&self, context: &EvaluationContext<'_>, state: &mut EvaluationState) -> Result { state.variables.clone_from(context.variables); + state.seed_offset = 0; let mut remaining = MAX_EVALUATION_STEPS; self.run(context, state, &mut remaining) } // Pixel assignments are local; only the general evaluator exports the complete environment - pub(super) fn evaluate_pixel(&self, context: &EvaluationContext<'_>, state: &mut EvaluationState) -> Result { + pub(super) fn evaluate_pixel(&self, context: &EvaluationContext<'_>, state: &mut EvaluationState, pixel: u32) -> Result { state.variables.clear(); + state.seed_offset = crate::random::hash(pixel); let mut remaining = MAX_EVALUATION_STEPS; self.run(context, state, &mut remaining) } @@ -47,7 +49,7 @@ impl Program { state.values.clear(); state.registers.clear(); state.registers.resize(self.instructions.len(), None); - state.random = context.variables.get("$randomseed").and_then(Value::as_i32).map_or(self.seed, |seed| seed as u32); + state.random = context.variables.get("$randomseed").and_then(Value::as_i32).map_or(self.seed, |seed| seed as u32) ^ state.seed_offset; state.steps.push(Enter(self.output)); while let Some(step) = state.steps.pop() { @@ -84,21 +86,32 @@ impl Program { let arguments = state.values.get(base..).ok_or("invalid function operands")?; let result = if let Some(call) = &instruction.call { let storage = state.calls.entry(index).or_default(); + storage.seed_offset = state.seed_offset; storage.variables.clone_from(&state.variables); storage.variables.extend(call.defaults.clone()); for (name, value) in call.inputs.iter().zip(arguments) { storage.variables.insert(name.clone(), value.clone()); } - call.program.run(context, storage, remaining_steps) + let result = call.program.run(context, storage, remaining_steps); + + // Variables the called graph set stay set for its caller; its own inputs do not leak out + if call.exports && result.is_ok() { + for (name, value) in &storage.variables { + if !call.defaults.contains_key(name) && !call.inputs.contains(name) { + state.variables.insert(name.clone(), value.clone()); + } + } + } + + result } else { operation::evaluate(instruction, arguments, &mut state.variables, &mut state.random, context) } .map_err(|error| format!("{} ({}): {error}", instruction.definition.label, instruction.id))?; state.values.truncate(base); - if instruction.pure - && let Some(register) = state.registers.get_mut(index) - { + // A node runs once per evaluation, so every reader of a Set or a Get sees the same value + if let Some(register) = state.registers.get_mut(index) { *register = Some(result.clone()); } @@ -108,12 +121,20 @@ impl Program { let condition = state.values.pop().ok_or("missing branch condition")?; let slot = if value_type::boolean(&condition)? { 1 } else { 2 }; + state.steps.push(Store(index)); state.steps.push(Enter(self.input(index, slot)?)); } Sequence(index) => { state.values.pop().ok_or("missing sequence result")?; + state.steps.push(Store(index)); state.steps.push(Enter(self.input(index, 1)?)); } + Store(index) => { + let result = state.values.last().ok_or("missing result to keep")?.clone(); + if let Some(register) = state.registers.get_mut(index) { + *register = Some(result); + } + } LoopStart(index) => { let last = state.values.pop().ok_or("missing loop initialization")?; state.steps.push(LoopCondition { instruction: index, iteration: 0, last }); @@ -123,6 +144,9 @@ impl Program { let exit = value_type::boolean(&state.values.pop().ok_or("missing loop condition")?)?; let maximum = self.instruction(index)?.value.as_ref().and_then(Value::as_i32).unwrap_or(100); if exit || (maximum >= 0 && iteration >= maximum as u32) { + if let Some(register) = state.registers.get_mut(index) { + *register = Some(last.clone()); + } state.values.push(last); } else { state.steps.push(LoopBody { instruction: index, iteration: iteration.saturating_add(1) }); @@ -131,6 +155,13 @@ impl Program { } LoopBody { instruction: index, iteration } => { let last = state.values.pop().ok_or("missing loop body result")?; + + // The next iteration evaluates the condition and the body again + for repeated in &self.instruction(index)?.repeated { + if let Some(register) = state.registers.get_mut(*repeated) { + *register = None; + } + } state.steps.push(LoopCondition { instruction: index, iteration, last }); state.steps.push(Enter(self.input(index, 1)?)); } diff --git a/crates/nodes/src/function/resolve_instances.rs b/crates/nodes/src/function/resolve_instances.rs index 3728404..2bbc10a 100644 --- a/crates/nodes/src/function/resolve_instances.rs +++ b/crates/nodes/src/function/resolve_instances.rs @@ -29,8 +29,8 @@ fn resolve(function: &mut FunctionGraph, local: &Package, sources: &BTreeMap 4096 { return Err("Function Graph exceeds the 4096-node graph limit".into()); } - if stack.len() >= 8 || body.nodes.len() > *remaining { - return Err("Function instances exceed the 8-level or 8192-node expanded limit".into()); + if stack.len() >= super::MAX_CALL_DEPTH || body.nodes.len() > *remaining { + return Err("Function instances exceed the 16-level or 65536-node expanded limit".into()); } if graph.exposed.len() > 4096 diff --git a/crates/nodes/src/function/tests.rs b/crates/nodes/src/function/tests.rs index 244a36e..aee9df0 100644 --- a/crates/nodes/src/function/tests.rs +++ b/crates/nodes/src/function/tests.rs @@ -153,7 +153,7 @@ fn time_and_tiling_variables_have_typed_defaults_and_host_overrides() { let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables }; let program = compile(&graph, 0).unwrap(); assert_eq!(program.evaluate(&context, &mut EvaluationState::default()).unwrap(), *expected); - assert_eq!(program.evaluate_pixel(&context, &mut EvaluationState::default()).unwrap(), *expected); + assert_eq!(program.evaluate_pixel(&context, &mut EvaluationState::default(), 0).unwrap(), *expected); } assert!(evaluate(&graph, &BTreeMap::from([(name.into(), Value::Bool(false))])).unwrap_err().contains("wrong type")); @@ -225,7 +225,7 @@ fn pixel_assignments_are_local_and_match_exported_evaluation() { let mut exported = EvaluationState::default(); let expected = program.evaluate(&context, &mut exported).unwrap(); for _ in 0..2 { - assert_eq!(program.evaluate_pixel(&context, &mut pixel_state).unwrap(), expected); + assert_eq!(program.evaluate_pixel(&context, &mut pixel_state, 0).unwrap(), expected); } assert_eq!(expected, Value::Float(initial + 1.0)); assert_eq!(variables["counter"], Value::Float(initial)); @@ -235,7 +235,7 @@ fn pixel_assignments_are_local_and_match_exported_evaluation() { let read_only = compile(&FunctionGraph::constant(Value::Float(0.5)), 7).unwrap(); let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &BTreeMap::new() }; - assert_eq!(read_only.evaluate_pixel(&context, &mut pixel_state).unwrap(), Value::Float(0.5)); + assert_eq!(read_only.evaluate_pixel(&context, &mut pixel_state, 0).unwrap(), Value::Float(0.5)); assert!(pixel_state.variables().is_empty()); } @@ -252,6 +252,122 @@ fn pixel_random_seed_and_defined_variables_match_general_evaluation() { for variables in [BTreeMap::from([("$randomseed".into(), Value::Int(42)), ("known".into(), Value::Bool(true))]), BTreeMap::new()] { let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables }; let expected = program.evaluate(&context, &mut EvaluationState::default()).unwrap(); - assert_eq!(program.evaluate_pixel(&context, &mut state).unwrap(), expected); + assert_eq!(program.evaluate_pixel(&context, &mut state, 0).unwrap(), expected); } } + +#[test] +fn a_node_runs_once_so_readers_before_and_after_a_set_share_its_value() { + let mut graph = FunctionGraph::default(); + let read = graph.add("get_integer1", &[], Some(Value::Text("count".into()))); + let one = graph.add_constant(Value::Int(1)); + let next = graph.add("add", &[read, one], None); + let store = graph.add("set", &[next], Some(Value::Text("count".into()))); + graph.output = Some(graph.add("sequence", &[store, read], None)); + + let variables = BTreeMap::from([("count".to_string(), Value::Int(4))]); + assert_eq!(evaluate(&graph, &variables).unwrap(), Value::Int(4), "the Get node read 4 before the Set and keeps it"); + + // A second Get node reads the variable when it runs, after the Set + let later = graph.add("get_integer1", &[], Some(Value::Text("count".into()))); + graph.output = Some(graph.add("sequence", &[store, later], None)); + assert_eq!(evaluate(&graph, &variables).unwrap(), Value::Int(5)); +} + +#[test] +fn a_loop_evaluates_its_condition_and_body_again_on_every_iteration() { + let mut graph = FunctionGraph::default(); + let zero = graph.add_constant(Value::Int(0)); + let start = graph.add("set", &[zero], Some(Value::Text("count".into()))); + let read = graph.add("get_integer1", &[], Some(Value::Text("count".into()))); + let limit = graph.add_constant(Value::Int(3)); + let reached = graph.add("gteq", &[read, limit], None); + let one = graph.add_constant(Value::Int(1)); + let next = graph.add("add", &[read, one], None); + let step = graph.add("set", &[next], Some(Value::Text("count".into()))); + graph.output = Some(graph.add("while", &[start, reached, step], Some(Value::Int(100)))); + + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(3)); +} + +#[test] +fn variables_a_called_graph_sets_reach_its_caller_but_its_inputs_do_not() { + let mut called = FunctionGraph::default(); + let input = called.add("get_integer1", &[], Some(Value::Text("amount".into()))); + called.output = Some(called.add("set", &[input], Some(Value::Text("shared".into())))); + + let mut caller = FunctionGraph::default(); + let call = caller.add("instance", &[], None); + let node = caller.nodes.last_mut().unwrap(); + node.instance = Some(materialcraft_core::GraphInstance { + label: String::new(), + package: String::new(), + graph: "called".into(), + inputs: vec![materialcraft_core::GraphPort { identifier: "amount".into(), type_code: 16 }], + outputs: vec![materialcraft_core::GraphPort { identifier: "output".into(), type_code: 16 }], + defaults: BTreeMap::from([("amount".to_string(), Value::Int(9))]), + }); + node.inputs = vec![None]; + node.source = Some(Ok(std::sync::Arc::new(called))); + let shared = caller.add("get_integer1", &[], Some(Value::Text("shared".into()))); + caller.output = Some(caller.add("sequence", &[call, shared], None)); + assert_eq!(evaluate(&caller, &BTreeMap::new()).unwrap(), Value::Int(9)); + + let leaked = caller.add("get_integer1", &[], Some(Value::Text("amount".into()))); + caller.output = Some(caller.add("sequence", &[call, leaked], None)); + assert!(evaluate(&caller, &BTreeMap::new()).unwrap_err().contains("undefined variable `amount`")); +} + +#[test] +fn a_drop_down_parameter_reads_as_the_integer_of_its_option() { + let mut graph = FunctionGraph::default(); + let option = graph.add("get_integer1", &[], Some(Value::Text("mode".into()))); + let two = graph.add_constant(Value::Int(2)); + graph.output = Some(graph.add("gteq", &[option, two], None)); + + assert_eq!(evaluate(&graph, &BTreeMap::from([("mode".to_string(), Value::Enum(3))])).unwrap(), Value::Bool(true)); +} + +#[test] +fn an_unconnected_input_computes_with_zero_and_a_loop_without_a_condition_runs_its_limit() { + let mut graph = FunctionGraph::default(); + let high = graph.add_constant(Value::Float(8.0)); + let half = graph.add_constant(Value::Float(0.5)); + graph.output = Some(graph.add("lerp", &[high, high, half], None)); + graph.nodes.last_mut().unwrap().inputs = vec![None, Some(high), Some(half)]; + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(4.0), "halfway between zero and 8"); + + let mut graph = FunctionGraph::default(); + let zero = graph.add_constant(Value::Int(0)); + let start = graph.add("set", &[zero], Some(Value::Text("count".into()))); + let read = graph.add("get_integer1", &[], Some(Value::Text("count".into()))); + let one = graph.add_constant(Value::Int(1)); + let next = graph.add("add", &[read, one], None); + let step = graph.add("set", &[next], Some(Value::Text("count".into()))); + graph.output = Some(graph.add("while", &[start, start, step], Some(Value::Int(3)))); + graph.nodes.last_mut().unwrap().inputs = vec![Some(start), None, Some(step)]; + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(3)); +} + +#[test] +fn booleans_compare_in_order() { + assert_eq!(operation("gt", &[Value::Bool(true), Value::Bool(false)], None).unwrap(), Value::Bool(true)); + assert_eq!(operation("lreq", &[Value::Bool(true), Value::Bool(false)], None).unwrap(), Value::Bool(false)); +} + +#[test] +fn every_pixel_of_a_processor_draws_its_own_random_numbers() { + let mut function = FunctionGraph::default(); + let range = function.add_constant(Value::Float(1.0)); + function.output = Some(function.add("rand", &[range], None)); + let definition = crate::find("pixel_processor").unwrap(); + let parameters = crate::resolve_params(definition, &BTreeMap::from([("function".into(), Value::Function(Box::new(function)))])); + let variables = BTreeMap::new(); + let context = crate::CookContext { w: 8, h: 8, seed: 3, tile: true, inputs: &[], params: ¶meters, resource: &|_| None, vars: &variables }; + + let image = (definition.cook)(&context).unwrap().remove(0); + + let first = image.get(0, 0, false)[0]; + let different = (0..8).flat_map(|y| (0..8).map(move |x| (x, y))).filter(|(x, y)| (image.get(*x, *y, false)[0] - first).abs() > 1e-4).count(); + assert!(different > 56, "{different} of 64 pixels differ from the first"); +} diff --git a/crates/nodes/src/pattern/evaluation.rs b/crates/nodes/src/pattern/evaluation.rs index 4b68c94..0d0d467 100644 --- a/crates/nodes/src/pattern/evaluation.rs +++ b/crates/nodes/src/pattern/evaluation.rs @@ -27,12 +27,15 @@ pub(crate) fn cook(context: &CookContext) -> CookResult { let mut pending = Vec::new(); if let Some(root) = graph.root { - pending.push(PatternVisit { node: root, center: [0.5; 2], extent: 1.0, depth: 0, number: 0, seed: context.seed, variables: context.vars.clone() }); + pending.push(PatternVisit { node: root, center: [0.5; 2], extent: 1.0, depth: 0, number: 0, seed: context.seed }); } + // One set of user variables follows the walk in visiting order: an Iterate child reads what the previous iteration set + let mut variables = context.vars.clone(); let mut stamps = Vec::new(); let mut state = EvaluationState::default(); let mut remaining = MAX_VISITS; + let mut visits = 0_u32; while let Some(mut visit) = pending.pop() { remaining = remaining.checked_sub(1).ok_or("pattern graph exceeded its execution budget")?; let node = nodes.get(&visit.node).ok_or("missing pattern node")?; @@ -48,10 +51,13 @@ pub(crate) fn cook(context: &CookContext) -> CookResult { if node.parameters.get("randominherited").and_then(Value::as_bool) == Some(false) { visit.seed = node.parameters.get("randomseed").and_then(Value::as_i32).unwrap_or(0) as u32; } - visit.variables.insert("$randomseed".into(), Value::Int(visit.seed as i32)); - visit.variables.insert("$depth".into(), Value::Float(visit.depth as f32)); - visit.variables.insert("$depthpow2".into(), Value::Float(visit.extent)); - visit.variables.insert("$number".into(), Value::Float(visit.number as f32)); + // Every visit draws its own random numbers from the seed it inherited + visits = visits.wrapping_add(1); + let random = visit.seed.wrapping_mul(0x9E37_79B9) ^ visits.wrapping_mul(0x85EB_CA6B); + variables.insert("$randomseed".into(), Value::Int(random as i32)); + variables.insert("$depth".into(), Value::Float(visit.depth as f32)); + variables.insert("$depthpow2".into(), Value::Float(visit.extent)); + variables.insert("$number".into(), Value::Float(visit.number as f32)); let mut parameters = BTreeMap::new(); for parameter in &definition.params { @@ -63,11 +69,11 @@ pub(crate) fn cook(context: &CookContext) -> CookResult { size: [context.w as f32, context.h as f32], images: context.inputs.get(1..).unwrap_or(&[]), tile: context.tile, - variables: &visit.variables, + variables: &variables, }; let value = program.evaluate(&evaluation, &mut state)?; - visit.variables.clone_from(state.variables()); + variables.clone_from(state.variables()); value } None => node.parameters.get(parameter.id).unwrap_or(¶meter.default).clone(), diff --git a/crates/nodes/src/pattern/pattern_visit.rs b/crates/nodes/src/pattern/pattern_visit.rs index 348eb54..f4a95e3 100644 --- a/crates/nodes/src/pattern/pattern_visit.rs +++ b/crates/nodes/src/pattern/pattern_visit.rs @@ -1,6 +1,3 @@ -use materialcraft_core::Value; -use std::collections::BTreeMap; - #[derive(Clone)] pub(super) struct PatternVisit { pub node: u32, @@ -9,5 +6,4 @@ pub(super) struct PatternVisit { pub depth: u32, pub number: u32, pub seed: u32, - pub variables: BTreeMap, } diff --git a/crates/nodes/src/pattern/raster.rs b/crates/nodes/src/pattern/raster.rs index 077aeaf..197781b 100644 --- a/crates/nodes/src/pattern/raster.rs +++ b/crates/nodes/src/pattern/raster.rs @@ -18,10 +18,24 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp]) -> Result Result 1.0) { + // The far edges belong to the neighbor, so a pixel on the seam of two patterns is drawn once + if local.iter().any(|coordinate| !(-1.0..1.0).contains(coordinate)) { continue; } diff --git a/crates/nodes/src/pattern/tests.rs b/crates/nodes/src/pattern/tests.rs index 0c4d020..8faa62e 100644 --- a/crates/nodes/src/pattern/tests.rs +++ b/crates/nodes/src/pattern/tests.rs @@ -171,3 +171,93 @@ fn a_full_nine_level_quadtree_renders_one_pattern_per_pixel() { let images = (definition.cook)(&context).unwrap(); assert!(images[0].data.iter().all(|value| (*value - 1.0).abs() < 1e-6)); } + +fn square(graph: &mut PatternGraph, node: usize) { + graph.nodes[node].parameters.insert("patterntype".into(), Value::Int(2)); +} + +#[test] +fn an_iteration_reads_the_variables_the_previous_iteration_set() { + let mut graph = PatternGraph::default(); + let iterate = graph.add(PatternNodeKind::Iterate).unwrap(); + let quadrant = graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.root = Some(iterate); + graph.nodes[0].parameters.insert("numberadded".into(), Value::Int(3)); + graph.nodes[0].children[1] = Some(quadrant); + square(&mut graph, 1); + + let mut function = FunctionGraph::default(); + let total = function.add("get_float1", &[], Some(Value::Text("total".into()))); + let step = function.add_constant(Value::Float(0.25)); + let next = function.add("add", &[total, step], None); + function.output = Some(function.add("set", &[next], Some(Value::Text("total".into())))); + graph.nodes[1].parameters.insert("opacity".into(), Value::Function(Box::new(function))); + + let image = cook_with_variables(graph, &BTreeMap::from([("total".into(), Value::Float(0.0))])).unwrap().remove(0); + + // 0.25, 0.5 and 0.75 add up; three separate copies of the variable would add 0.25 three times + assert!((image.mean()[0] - 1.5).abs() < 1e-5, "{}", image.mean()[0]); +} + +#[test] +fn the_render_region_is_the_part_of_pattern_space_the_image_shows() { + let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); + square(&mut graph, 0); + let definition = find("fx_map").unwrap(); + let parameters = resolve_params( + definition, + &BTreeMap::from([("pattern".into(), Value::PatternGraph(Box::new(graph))), ("render_region".into(), Value::Float4([0.0, 2.0, 0.0, 2.0]))]), + ); + let context = CookContext { w: 16, h: 16, seed: 7, tile: false, inputs: &[], params: ¶meters, resource: &|_| None, vars: &BTreeMap::new() }; + + let image = (definition.cook)(&context).unwrap().remove(0); + + // The unit square fills the top-left quarter of a region twice as wide and tall + assert!((image.mean()[0] - 0.25).abs() < 1e-5, "{}", image.mean()[0]); + assert_eq!(image.get(3, 3, false)[0], 1.0); + assert_eq!(image.get(12, 12, false)[0], 0.0); +} + +#[test] +fn every_visit_draws_its_own_random_numbers() { + let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); + graph.nodes[0].parameters.insert("patterntype".into(), Value::Int(0)); + let child = graph.add(PatternNodeKind::Quadrant).unwrap(); + for slot in 0..4 { + graph.nodes[0].children[slot] = Some(child); + } + square(&mut graph, 1); + let mut function = FunctionGraph::default(); + let range = function.add_constant(Value::Float(1.0)); + function.output = Some(function.add("rand", &[range], None)); + graph.nodes[1].parameters.insert("opacity".into(), Value::Function(Box::new(function))); + + let image = cook(graph).unwrap().remove(0); + + let quarters = [image.get(4, 4, false)[0], image.get(12, 4, false)[0], image.get(4, 12, false)[0], image.get(12, 12, false)[0]]; + assert!(quarters.windows(2).all(|pair| (pair[0] - pair[1]).abs() > 1e-4), "{quarters:?}"); +} + +#[test] +fn a_pixel_on_the_seam_of_two_patterns_is_drawn_once() { + let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); + graph.nodes[0].parameters.insert("patterntype".into(), Value::Int(0)); + let child = graph.add(PatternNodeKind::Quadrant).unwrap(); + let grandchild = graph.add(PatternNodeKind::Quadrant).unwrap(); + for slot in 0..4 { + graph.nodes[0].children[slot] = Some(child); + graph.nodes[1].children[slot] = Some(grandchild); + } + graph.nodes[1].parameters.insert("patterntype".into(), Value::Int(0)); + square(&mut graph, 2); + let definition = find("fx_map").unwrap(); + let parameters = resolve_params(definition, &BTreeMap::from([("pattern".into(), Value::PatternGraph(Box::new(graph)))])); + let variables = BTreeMap::new(); + // Two pixels a side put every pixel center on the corner of four of the sixteen squares + let context = CookContext { w: 2, h: 2, seed: 7, tile: true, inputs: &[], params: ¶meters, resource: &|_| None, vars: &variables }; + + let image = (definition.cook)(&context).unwrap().remove(0); + + assert_eq!(image.get(0, 0, false)[0], 1.0); + assert_eq!(image.get(1, 1, false)[0], 1.0); +} diff --git a/crates/ui-egui/src/function/geometry.rs b/crates/ui-egui/src/function/geometry.rs index e08fe20..d701731 100644 --- a/crates/ui-egui/src/function/geometry.rs +++ b/crates/ui-egui/src/function/geometry.rs @@ -19,8 +19,9 @@ fn input_count(node: &FunctionNode) -> usize { materialcraft_engine::nodes::function::input_identifiers(node).count() } -pub(super) fn node_rect(node: &FunctionNode, previews: bool) -> Rect { - node_card::bounds(node.pos, input_count(node), 1, previews, node.op == "passthrough") +/// Function nodes show a value or a symbol, never a preview, so their body only fits that +pub(super) fn node_rect(node: &FunctionNode) -> Rect { + node_card::bounds_with_body(node.pos, input_count(node), 1, super::node_face::height(node), node.op == "passthrough") } pub(super) fn in_port(node: &FunctionNode, bounds: Rect, index: usize) -> Pos2 { @@ -32,7 +33,7 @@ pub(super) fn out_port(node: &FunctionNode, bounds: Rect) -> Pos2 { } pub(super) fn preview_rect(app: &MaterialCraftApp, editor: &FunctionEditor, node: &FunctionNode, snap: bool, selected: bool) -> Rect { - let mut bounds = node_rect(node, app.ui.prefs.thumbnails); + let mut bounds = node_rect(node); if let Some(FunctionDrag::Node(d, delta)) = &editor.drag && (*d == node.id || selected) { diff --git a/crates/ui-egui/src/function/mod.rs b/crates/ui-egui/src/function/mod.rs index 11aa133..b50c26e 100644 --- a/crates/ui-egui/src/function/mod.rs +++ b/crates/ui-egui/src/function/mod.rs @@ -22,6 +22,7 @@ mod actions; mod geometry; mod input; mod node_canvas; +mod node_face; mod panel; mod function_canvas; diff --git a/crates/ui-egui/src/function/node_canvas.rs b/crates/ui-egui/src/function/node_canvas.rs index aeff705..ea40fd1 100644 --- a/crates/ui-egui/src/function/node_canvas.rs +++ b/crates/ui-egui/src/function/node_canvas.rs @@ -46,10 +46,17 @@ pub(super) fn paint( } node_card::outline(painter, bounds, zoom, Stroke::new(if selected { 2.0 } else { 1.0 }, outline)); + let text_color = if output { Color32::from_gray(0x20) } else { tokens.text }; if missing { painter.text(body.center(), Align2::CENTER_CENTER, crate::i18n::tr("MISSING"), FontId::proportional(15.0 * zoom), Color32::WHITE); - } else if node.value.is_none() { - let text_color = if output { Color32::from_gray(0x20) } else { tokens.text_dim }; - painter.text(body.center(), Align2::CENTER_CENTER, egui_phosphor::regular::CODE, FontId::proportional(30.0 * zoom), text_color); + } else if let Some(value) = &node.value { + // The fields are too small to use from far away, so the value is only shown + if !super::node_face::editable(zoom) { + node_card::paint_symbol(painter, body, zoom, &crate::graph::value_text::value_text(value), text_color); + } + } else if node.instance.is_some() { + node_card::paint_symbol(painter, body, zoom, egui_phosphor::regular::FUNCTION, text_color); + } else { + node_card::paint_symbol(painter, body, zoom, super::node_face::symbol(&node.op), text_color); } } diff --git a/crates/ui-egui/src/function/node_face.rs b/crates/ui-egui/src/function/node_face.rs new file mode 100644 index 0000000..e9efa0c --- /dev/null +++ b/crates/ui-egui/src/function/node_face.rs @@ -0,0 +1,151 @@ +//! What a function node shows in its body: its editable value, or the symbol of its operation + +use egui::{Rect, Ui, vec2}; +use egui_phosphor::regular as icon; +use materialcraft_engine::core::{FunctionNode, Value}; + +/// Graph-space height of one value field, and the gap between two fields +const ROW_HEIGHT: f32 = 20.0; +const ROW_GAP: f32 = 3.0; +const PADDING: f32 = 6.0; +/// Body height of a node that shows a symbol +const SYMBOL_HEIGHT: f32 = 40.0; +/// Below this zoom the fields are too small to use, so the value is drawn as text +const MIN_EDIT_ZOOM: f32 = 0.45; +const MAX_EDIT_ZOOM: f32 = 1.6; + +/// The sign or short word that stands for `operation` on its node +pub(super) fn symbol(operation: &str) -> &'static str { + match operation { + "add" => "+", + "sub" => "\u{2212}", + "mul" => "\u{d7}", + "mulscalar" => "k\u{d7}", + "div" => "\u{f7}", + "neg" => "\u{2212}a", + "mod" => icon::PERCENT, + "dot" => "a\u{b7}b", + "and" => "AND", + "or" => "OR", + "not" => "NOT", + "eq" => icon::EQUALS, + "noteq" => icon::NOT_EQUALS, + "gt" => icon::GREATER_THAN, + "gteq" => icon::GREATER_THAN_OR_EQUAL, + "lr" => icon::LESS_THAN, + "lreq" => icon::LESS_THAN_OR_EQUAL, + "abs" => "|x|", + "floor" => "floor", + "ceil" => "ceil", + "cos" => "cos", + "sin" => "sin", + "tan" => "tan", + "atan2" => "atan2", + "cartesian" => "polar", + "sqrt" => icon::RADICAL, + "log" => "log", + "exp" => "exp", + "log2" => "log2", + "pow2" => "2^x", + "pow" => "a^b", + "lerp" => "lerp", + "min" => "min", + "max" => "max", + "rand" => icon::DICE_FIVE, + "sequence" => icon::LIST_NUMBERS, + "ifelse" => "if", + "while" => icon::REPEAT, + "vector2" | "ivector2" => "xy", + "vector3" | "ivector3" => "xyz", + "vector4" | "ivector4" => "xyzw", + "tofloat" => "float", + "tofloat2" => "float2", + "tofloat3" => "float3", + "tofloat4" => "float4", + "toint1" => "int", + "toint2" => "int2", + "toint3" => "int3", + "toint4" => "int4", + "samplelum" => icon::EYEDROPPER, + "samplecol" => icon::EYEDROPPER_SAMPLE, + _ => icon::FUNCTION, + } +} + +/// Graph-space height the body of `node` needs for its value fields or its symbol +pub(super) fn height(node: &FunctionNode) -> f32 { + match &node.value { + Some(value) if node.missing.is_none() => { + let rows = crate::value_editor::rows(value) as f32; + rows * ROW_HEIGHT + (rows - 1.0) * ROW_GAP + PADDING * 2.0 + } + _ => SYMBOL_HEIGHT, + } +} + +/// Whether the value of a node is edited on its face at `zoom`; it is drawn as text otherwise +pub(super) fn editable(zoom: f32) -> bool { + zoom >= MIN_EDIT_ZOOM +} + +/// The value fields of a node inside `body`, sized with the canvas zoom; true when `value` changed +pub(super) fn edit(ui: &mut Ui, body: Rect, clip: Rect, zoom: f32, value: &mut Value) -> bool { + let scale = zoom.clamp(MIN_EDIT_ZOOM, MAX_EDIT_ZOOM); + let content = body.shrink(PADDING * zoom); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(content)); + child.set_clip_rect(content.expand(1.0).intersect(clip)); + + let style = child.style_mut(); + style.override_font_id = Some(egui::FontId::proportional(12.0 * scale)); + style.spacing.interact_size = vec2(24.0 * scale, ROW_HEIGHT * zoom); + style.spacing.item_spacing = vec2(4.0 * scale, ROW_GAP * zoom); + style.spacing.button_padding = vec2(4.0 * scale, 0.0); + style.spacing.icon_width = 14.0 * scale; + style.spacing.icon_width_inner = 8.0 * scale; + style.spacing.icon_spacing = 4.0 * scale; + + crate::value_editor::show_stacked(&mut child, value) +} + +#[cfg(test)] +mod tests { + use super::*; + use materialcraft_engine::nodes::function::{FUNCTIONS, default_value}; + + fn node(operation: &str) -> FunctionNode { + FunctionNode { + id: 1, + type_code: 0, + op: operation.into(), + missing: None, + missing_data: String::new(), + instance: None, + source: None, + inputs: Vec::new(), + value: default_value(operation), + pos: [0.0; 2], + } + } + + #[test] + fn every_operation_without_a_value_has_its_own_symbol() { + for definition in FUNCTIONS { + if definition.id == "passthrough" || default_value(definition.id).is_some() { + continue; + } + + assert_ne!(symbol(definition.id), icon::FUNCTION, "{} has no symbol", definition.id); + } + } + + #[test] + fn a_body_grows_with_the_components_of_its_value() { + let single = height(&node("const_float1")); + assert_eq!(height(&node("const_float4")), single + 3.0 * (ROW_HEIGHT + ROW_GAP)); + assert_eq!(height(&node("add")), SYMBOL_HEIGHT); + + let mut unavailable = node("const_float4"); + unavailable.missing = Some(Vec::new()); + assert_eq!(height(&unavailable), SYMBOL_HEIGHT); + } +} diff --git a/crates/ui-egui/src/function/render.rs b/crates/ui-egui/src/function/render.rs index e172532..c9f3542 100644 --- a/crates/ui-egui/src/function/render.rs +++ b/crates/ui-egui/src/function/render.rs @@ -41,7 +41,7 @@ pub(super) fn paint(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: .nodes .iter() .filter(|node| !selected_only || selected.contains(&node.id)) - .map(|node| node_rect(node, app.ui.prefs.thumbnails)) + .map(node_rect) .fold(Rect::NOTHING, |combined, bounds| combined.union(bounds)); if !selected_only && let Some(document) = &document { for frame in &document.frames { @@ -146,15 +146,13 @@ pub(super) fn paint(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: let body = ui.interact(screen_rect, ui.scope_id().with(("fn-node", id)), Sense::click_and_drag()); crate::widgets::name(&body, egui::Role::Button, label); - if !dot && node.missing.is_none() && node.value.is_some() { - let content = node_card::body(screen_rect, editor.zoom).shrink(6.0 * editor.zoom); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(content)); - child.set_clip_rect(content.intersect(canvas_bounds)); - if let Some(mut value) = node.value.clone() - && crate::value_editor::show(&mut child, &mut value) - { - values.push((id, value)); - } + if !dot + && node.missing.is_none() + && super::node_face::editable(editor.zoom) + && let Some(mut value) = node.value.clone() + && super::node_face::edit(ui, node_card::body(screen_rect, editor.zoom), canvas_bounds, editor.zoom, &mut value) + { + values.push((id, value)); } if (body.contains_pointer() && ui.input(|input| input.pointer.primary_pressed() && !input.modifiers.alt)) || body.secondary_clicked() { diff --git a/crates/ui-egui/src/graph/canvas.rs b/crates/ui-egui/src/graph/canvas.rs index 850b382..2e75b6e 100644 --- a/crates/ui-egui/src/graph/canvas.rs +++ b/crates/ui-egui/src/graph/canvas.rs @@ -1,4 +1,4 @@ -use super::node_style::{PORT_RADIUS, header_color, node_label, node_rect, port_color}; +use super::node_style::{PORT_RADIUS, header_color, node_label, node_rect, port_color, shows_preview}; use super::{GraphCamera, GraphDrag, PortHit, WireRef}; use super::{ navigation::frame, @@ -84,7 +84,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let mut layouts: Vec = Vec::with_capacity(graph.nodes.len()); for node in &graph.nodes { let (ins, outs) = materialcraft_engine::eval::ports_with_connections(&app.session.pkg, node, index.incoming(node.id).iter().copied()); - let mut r = node_rect(node, ins.len(), outs.len(), show_thumbnails); + let mut r = node_rect(node, ins.len(), outs.len(), show_thumbnails && shows_preview(&outs)); if selection.contains(&node.id) && node_delta.length() > 0.5 { let position = materialcraft_engine::graph_grid::translate(node.pos, node_delta.into(), app.ui.prefs.snap_to_grid); r = r.translate(vec2(position[0] - node.pos[0], position[1] - node.pos[1])); @@ -184,7 +184,6 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { app.graph.wires = wires; // Nodes - let font = FontId::proportional((10.5 * camera.zoom).clamp(6.0, 16.0)); let small = FontId::proportional((9.0 * camera.zoom).clamp(5.5, 13.0)); let mut node_responses: Vec<(NodeId, egui::Response)> = Vec::new(); let mut dot_grabs: Vec = Vec::new(); @@ -218,18 +217,16 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { { let side = body.width().min(body.height()) - 6.0 * camera.zoom; let tr_ = Rect::from_center_size(body.center(), vec2(side, side)); + node_card::paint_well(&painter, tr_.expand(camera.zoom), camera.zoom); let tex = app.thumbs.node(&ctx, r0.key, 0, img); painter.image(tex, tr_, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), if node.disabled { Color32::from_gray(90) } else { Color32::WHITE }); } else if let Some(value) = result.and_then(|result| result.outputs.first()).and_then(materialcraft_engine::eval::NodeOutput::as_value) { - let text = match value { - materialcraft_engine::core::Value::Float(value) => value.to_string(), - _ => serde_json::to_value(value).ok().and_then(|value| value.get("v").map(ToString::to_string)).unwrap_or_default(), - }; - - let text = crate::widgets::elided(&painter, text, font.size, theme.text, body.width() - 8.0); - painter.galley(body.center() - text.size() * 0.5, text, theme.text); + node_card::paint_well(&painter, body.shrink(4.0 * camera.zoom), camera.zoom); + node_card::paint_symbol(&painter, body, camera.zoom, &super::value_text::value_text(value), theme.text_strong); + } else if error.is_some() { + node_card::paint_symbol(&painter, body, camera.zoom, icon::WARNING, theme.danger); } else if result.is_none() { - painter.text(body.center(), Align2::CENTER_CENTER, icon::HOURGLASS_MEDIUM, small.clone(), theme.text_dim); + node_card::paint_symbol(&painter, body, camera.zoom, icon::HOURGLASS_MEDIUM, theme.text_dim); } // Footer: size and format let footer = Rect::from_min_max(pos2(screen_rect.left(), body.bottom()), screen_rect.max); diff --git a/crates/ui-egui/src/graph/interaction_tests.rs b/crates/ui-egui/src/graph/interaction_tests.rs index 44d0146..05e5dc2 100644 --- a/crates/ui-egui/src/graph/interaction_tests.rs +++ b/crates/ui-egui/src/graph/interaction_tests.rs @@ -406,7 +406,8 @@ fn function_dots_wire_move_and_save_with_regular_card_geometry() { let card = frames.app.graph.rects.iter().find(|(id, _)| id.0 == u64::from(multiply)).unwrap().1; assert!((dot_bounds.width() / zoom - 14.0).abs() < 0.01); assert!((card.width() / zoom - 100.0).abs() < 0.01); - assert!((card.height() / zoom - 132.0).abs() < 0.01); + // An operator shows its symbol in a body that only fits its two inputs + assert!((card.height() / zoom - 76.0).abs() < 0.01); assert!(!frames.canvas_text.iter().any(|text| text.contains("Reroute"))); let dot_ports: Vec<_> = frames.app.graph.ports.iter().filter(|port| port.node.0 == u64::from(dot)).collect(); assert_eq!(dot_ports.len(), 2); diff --git a/crates/ui-egui/src/graph/mod.rs b/crates/ui-egui/src/graph/mod.rs index b569c97..be1bed3 100644 --- a/crates/ui-egui/src/graph/mod.rs +++ b/crates/ui-egui/src/graph/mod.rs @@ -34,7 +34,7 @@ pub use graph_view::GraphView; pub use library_drag::LibraryDrag; pub use navigation::{add_entry_in_view, add_node_near_selection}; use node_search::NodeSearch; -pub use node_style::{NODE_W, header_color, node_label, node_rect, port_color}; +pub use node_style::{NODE_W, header_color, node_label, node_rect, port_color, shows_preview}; pub use port_hit::PortHit; pub use wire_actions::{delete_selected_wires, swap_selected_wires}; pub type WireRef = (materialcraft_engine::core::NodeId, String); @@ -48,6 +48,7 @@ mod node_style; mod search; pub(crate) mod selection_commands; pub(crate) mod toolbar; +pub(crate) mod value_text; pub(crate) mod wire_actions; pub(crate) mod wire_geometry; pub(crate) mod wire_selection; diff --git a/crates/ui-egui/src/graph/navigation.rs b/crates/ui-egui/src/graph/navigation.rs index 98033c6..1452a45 100644 --- a/crates/ui-egui/src/graph/navigation.rs +++ b/crates/ui-egui/src/graph/navigation.rs @@ -1,4 +1,4 @@ -use super::{NODE_W, node_rect}; +use super::{NODE_W, node_rect, shows_preview}; use crate::MaterialCraftApp; use egui::{Pos2, Rect, pos2, vec2}; use serde_json::json; @@ -42,7 +42,7 @@ pub(super) fn frame(app: &mut MaterialCraftApp, view: Rect, only_selection: bool } let (inputs, outputs) = materialcraft_engine::eval::ports(&app.session.pkg, g, n); - r = r.union(node_rect(n, inputs.len(), outputs.len(), thumbs)); + r = r.union(node_rect(n, inputs.len(), outputs.len(), thumbs && shows_preview(&outputs))); } for f in &g.frames { if !only_selection { diff --git a/crates/ui-egui/src/graph/node_card.rs b/crates/ui-egui/src/graph/node_card.rs index 6a65dc4..e0788c2 100644 --- a/crates/ui-egui/src/graph/node_card.rs +++ b/crates/ui-egui/src/graph/node_card.rs @@ -7,16 +7,25 @@ const PORT_GAP: f32 = 18.0; const DOT_RADIUS: f32 = 7.0; /// Smallest on-screen side of a dot's grab area, in points const DOT_MIN_GRAB: f32 = 16.0; +const CARD_COLOR: Color32 = Color32::from_rgb(0x1e, 0x20, 0x24); +const WELL_COLOR: Color32 = Color32::from_rgb(0x14, 0x15, 0x18); + +/// Body height of a node that shows no preview and has at most one port a side +const BARE_BODY_HEIGHT: f32 = 26.0; pub(crate) fn bounds(position: [f32; 2], inputs: usize, outputs: usize, previews: bool, dot: bool) -> Rect { + bounds_with_body(position, inputs, outputs, if previews { WIDTH } else { BARE_BODY_HEIGHT }, dot) +} + +/// A card whose body is at least `body_height` tall and fits its ports +pub(crate) fn bounds_with_body(position: [f32; 2], inputs: usize, outputs: usize, body_height: f32, dot: bool) -> Rect { let position = pos2(position[0], position[1]); if dot { return Rect::from_center_size(position, vec2(DOT_RADIUS * 2.0, DOT_RADIUS * 2.0)); } let ports = inputs.max(outputs) as f32 * PORT_GAP + 8.0; - let body = if previews { WIDTH.max(ports) } else { ports.max(26.0) }; - Rect::from_min_size(position, vec2(WIDTH, HEADER_HEIGHT + body + FOOTER_HEIGHT)) + Rect::from_min_size(position, vec2(WIDTH, HEADER_HEIGHT + body_height.max(ports) + FOOTER_HEIGHT)) } /// The on-screen area that picks up dot `bounds`: at least `DOT_MIN_GRAB` wide, so it stays easy to grab when zoomed out @@ -46,11 +55,29 @@ pub(crate) fn body(bounds: Rect, zoom: f32) -> Rect { pub(crate) fn paint(painter: &Painter, bounds: Rect, zoom: f32, label: &str, color: Color32) { let radius = (5.0 * zoom).clamp(1.0, 6.0) as u8; let header = header(bounds, zoom); - painter.rect_filled(bounds, radius, Color32::from_rgb(0x1e, 0x20, 0x24)); + painter.rect_filled(bounds, radius, CARD_COLOR); painter.rect_filled(header, CornerRadius { nw: radius, ne: radius, sw: 0, se: 0 }, color); - let font = FontId::proportional((10.5 * zoom).clamp(6.0, 16.0)); - let title = crate::widgets::elided(painter, label, font.size, Color32::WHITE, header.width() - 8.0); - painter.galley(header.left_center() + vec2(4.0, -title.size().y * 0.5), title, Color32::WHITE); + painter.line_segment([header.left_bottom(), header.right_bottom()], Stroke::new(1.0, Color32::from_black_alpha(110))); + + let font = FontId::proportional((11.0 * zoom).clamp(7.0, 16.0)); + let title = crate::widgets::elided(painter, label, font.size, Color32::WHITE, header.width() - 10.0 * zoom); + painter.galley(header.left_center() + vec2(5.0 * zoom, -title.size().y * 0.5), title, Color32::WHITE); +} + +/// The dark well a preview or a value sits in, inside `body` +pub(crate) fn paint_well(painter: &Painter, well: Rect, zoom: f32) { + painter.rect_filled(well, (3.0 * zoom).clamp(1.0, 4.0) as u8, WELL_COLOR); +} + +/// A short symbol or word centered in `body`, as large as its length allows +pub(crate) fn paint_symbol(painter: &Painter, body: Rect, zoom: f32, symbol: &str, color: Color32) { + let size = match symbol.chars().count() { + 0..=2 => 24.0, + 3..=4 => 17.0, + _ => 13.0, + }; + let text = crate::widgets::elided(painter, symbol, size * zoom, color, body.width() - 12.0 * zoom); + painter.galley(body.center() - text.size() * 0.5, text, color); } pub(crate) fn outline(painter: &Painter, bounds: Rect, zoom: f32, stroke: Stroke) { diff --git a/crates/ui-egui/src/graph/node_style.rs b/crates/ui-egui/src/graph/node_style.rs index 51da361..e841be5 100644 --- a/crates/ui-egui/src/graph/node_style.rs +++ b/crates/ui-egui/src/graph/node_style.rs @@ -68,6 +68,11 @@ pub fn node_label(n: &Node) -> String { }) } +/// Whether a node with these outputs has a picture to show; a node that only outputs values shows its number in a short body +pub fn shows_preview(outputs: &[materialcraft_engine::eval::Port]) -> bool { + outputs.is_empty() || outputs.iter().any(|port| port.kind != PortKind::Value) +} + /// Graph-space rectangle of a node card pub fn node_rect(node: &Node, inputs: usize, outputs: usize, previews: bool) -> Rect { node_card::bounds(node.pos, inputs, outputs, previews, node.def == "dot") diff --git a/crates/ui-egui/src/graph/value_text.rs b/crates/ui-egui/src/graph/value_text.rs new file mode 100644 index 0000000..fe59a42 --- /dev/null +++ b/crates/ui-egui/src/graph/value_text.rs @@ -0,0 +1,56 @@ +use materialcraft_engine::core::Value; + +/// `value` as a node face shows it: short numbers, vector components separated by commas +pub(crate) fn value_text(value: &Value) -> String { + match value { + Value::Float(value) => number(*value), + Value::Float2(values) => numbers(values), + Value::Float3(values) => numbers(values), + Value::Float4(values) | Value::Color(values) => numbers(values), + Value::Int(value) => value.to_string(), + Value::Int2(values) => integers(values), + Value::Int3(values) => integers(values), + Value::Int4(values) => integers(values), + Value::Bool(value) => crate::i18n::tr(if *value { "True" } else { "False" }).into(), + Value::Enum(value) => value.to_string(), + Value::Text(value) => value.clone(), + Value::Curve(_) | Value::Gradient(_) | Value::Function(_) | Value::PatternGraph(_) => String::new(), + } +} + +/// At most three decimals, without trailing zeros +fn number(value: f32) -> String { + if !value.is_finite() { + return value.to_string(); + } + + let text = format!("{value:.3}"); + let text = text.trim_end_matches('0').trim_end_matches('.'); + if text == "-0" { "0".into() } else { text.into() } +} + +fn numbers(values: &[f32]) -> String { + values.iter().map(|value| number(*value)).collect::>().join(", ") +} + +fn integers(values: &[i32]) -> String { + values.iter().map(ToString::to_string).collect::>().join(", ") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn numbers_are_short_and_vectors_list_their_components() { + assert_eq!(value_text(&Value::Float(0.5)), "0.5"); + assert_eq!(value_text(&Value::Float(2.0)), "2"); + assert_eq!(value_text(&Value::Float(-0.0001)), "0"); + assert_eq!(value_text(&Value::Float(1.0 / 3.0)), "0.333"); + assert_eq!(value_text(&Value::Float(f32::NAN)), "NaN"); + assert_eq!(value_text(&Value::Float3([1.0, 0.25, -3.5])), "1, 0.25, -3.5"); + assert_eq!(value_text(&Value::Int2([4, -7])), "4, -7"); + assert_eq!(value_text(&Value::Bool(true)), "True"); + assert_eq!(value_text(&Value::Text("size".into())), "size"); + } +} diff --git a/crates/ui-egui/src/library.rs b/crates/ui-egui/src/library.rs index 6048677..23af2ca 100644 --- a/crates/ui-egui/src/library.rs +++ b/crates/ui-egui/src/library.rs @@ -128,20 +128,63 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { ui.add_space(2.0); let available_size = ui.available_size(); - // The tree takes what the tiles leave: one column of tiles in a narrow panel - let tree_width = (available_size.x * 0.6).clamp(120.0, 230.0).min(available_size.x - 92.0).max(80.0); + // Unless dragged, the tree takes what the tiles leave: one column of tiles in a narrow panel + let automatic = (available_size.x * 0.6).clamp(120.0, 230.0); + let chosen = if app.ui.library_tree_width > 0.0 { app.ui.library_tree_width } else { automatic }; + let tree_width = tree_width(chosen, available_size.x); let top_down = egui::Layout::top_down(egui::Align::Min); ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; ui.allocate_ui_with_layout(vec2(tree_width, available_size.y), top_down, |ui| { egui::ScrollArea::vertical().id_salt("lib-tree").auto_shrink([false, false]).show(ui, |ui| category_tree(app, ui, &all)); }); - ui.separator(); + match divider(ui, tree_width, available_size.y) { + Some(Divider::Dragged(width)) => app.ui.library_tree_width = self::tree_width(width, available_size.x), + Some(Divider::Reset) => app.ui.library_tree_width = 0.0, + None => {} + } ui.allocate_ui_with_layout(vec2(ui.available_width(), available_size.y), top_down, |ui| { egui::ScrollArea::vertical().id_salt("lib-items").auto_shrink([false, false]).show(ui, |ui| items(app, ui, &all, &target)); }); }); } +/// The tree's width in a panel `available` wide: neither the tree nor the tiles close completely +fn tree_width(chosen: f32, available: f32) -> f32 { + const NARROWEST_TREE: f32 = 60.0; + const NARROWEST_TILES: f32 = 92.0; + + chosen.min(available - NARROWEST_TILES).max(NARROWEST_TREE) +} + +/// What the pointer did to the Library's divider +enum Divider { + /// Dragged to this tree width + Dragged(f32), + /// Double-clicked: back to the automatic width + Reset, +} + +/// The draggable bar between the tree and the tiles +fn divider(ui: &mut Ui, tree_width: f32, height: f32) -> Option { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(9.0, height), Sense::click_and_drag()); + crate::widgets::name(&response, egui::Role::Splitter, "Library divider"); + let response = response.on_hover_cursor(egui::CursorIcon::ResizeHorizontal); + if response.dragged() { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); + } + + let active = response.hovered() || response.dragged(); + let line = Rect::from_center_size(rect.center(), vec2(if active { 2.0 } else { 1.0 }, height)); + ui.painter().rect_filled(line, 0.0, if active { tokens.accent } else { tokens.text_dim.gamma_multiply(0.35) }); + + if response.double_clicked() { + return Some(Divider::Reset); + } + response.dragged().then(|| Divider::Dragged(tree_width + response.drag_delta().x)) +} + /// Expose availability and canvas filters without changing the selected category. fn filter_menu(app: &mut MaterialCraftApp, ui: &mut Ui) { let filtered = !app.ui.library_show_missing || !app.ui.library_show_other; @@ -366,11 +409,15 @@ fn items(app: &mut MaterialCraftApp, ui: &mut Ui, entries: &[LibraryEntry], targ } } -/// The entry's thumbnail: a cooked preview for native nodes, its category's icon otherwise +/// The entry's thumbnail: a cooked preview for native nodes and library graphs, its category's icon otherwise fn preview(app: &mut MaterialCraftApp, ui: &Ui, ctx: &egui::Context, entry: &LibraryEntry, rect: Rect, fade: f32) { let painter = ui.painter(); let (texture, color) = match &entry.item { LibraryItem::Node { def } if entry.missing.is_none() && def != "dot" => (app.thumbs.library(ctx, def), header_color(def)), + // Only tiles on screen ask for their graph to be cooked + LibraryItem::Instance { package, graph } if entry.missing.is_none() && ui.is_rect_visible(rect) => { + (app.thumbs.graph(ctx, &app.session.library, package, graph), category_color(&entry.category)) + } _ => (None, category_color(&entry.category)), }; match texture { diff --git a/crates/ui-egui/src/library.test.rs b/crates/ui-egui/src/library.test.rs index 03f38c4..ca661dd 100644 --- a/crates/ui-egui/src/library.test.rs +++ b/crates/ui-egui/src/library.test.rs @@ -165,3 +165,11 @@ fn graph_items_are_available_and_insertable_in_every_editor() { assert_eq!((items.comments.len(), items.frames.len(), items.pins.len()), (1, 1, 1), "{kind}"); } } + +#[test] +fn the_divider_leaves_room_for_the_tree_and_the_tiles() { + assert_eq!(tree_width(150.0, 400.0), 150.0); + assert_eq!(tree_width(5.0, 400.0), 60.0, "the tree never closes"); + assert_eq!(tree_width(390.0, 400.0), 308.0, "the tiles keep one column"); + assert_eq!(tree_width(200.0, 100.0), 60.0, "a panel too narrow for both keeps the tree"); +} diff --git a/crates/ui-egui/src/state/ui_state.rs b/crates/ui-egui/src/state/ui_state.rs index 13a576d..f07467b 100644 --- a/crates/ui-egui/src/state/ui_state.rs +++ b/crates/ui-egui/src/state/ui_state.rs @@ -26,6 +26,8 @@ pub struct UiState { /// The library entry last clicked #[serde(skip)] pub library_selected: Option, + /// Width of the Library's category tree, set by dragging its divider; 0 = automatic + pub library_tree_width: f32, /// Recently opened or saved packages, newest first pub recent: Vec, /// New graph dialog fields @@ -59,6 +61,7 @@ impl Default for UiState { library_show_missing: true, library_show_other: true, library_selected: None, + library_tree_width: 0.0, recent: Vec::new(), new_graph_kind: materialcraft_engine::core::GraphKind::Material, new_graph_template: "pbr".into(), diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 9b16b40..a180232 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -19,6 +19,7 @@ pub struct Thumbs { library: HashMap, library_rx: Option>, library_started: bool, + graphs: GraphPreviews, frame: u64, } @@ -28,6 +29,92 @@ pub fn color_image(img: &Image, side: u32) -> ColorImage { ColorImage::from_rgba_unmultiplied([side as usize, side as usize], &small.to_rgba8_display()) } +/// Previews of library graphs: one worker cooks the requested graphs, newest request first +#[derive(Default)] +struct GraphPreviews { + /// The library the previews were cooked from; a reload starts over + library: Option>, + /// Requested graphs: `None` while cooking and for graphs without an image + textures: HashMap<(String, String), Option>, + requests: GraphRequests, + results: GraphResults, +} + +impl GraphPreviews { + fn get(&mut self, ctx: &egui::Context, library: &std::sync::Arc, package: &str, graph: &str) -> Option { + if !self.library.as_ref().is_some_and(|current| std::sync::Arc::ptr_eq(current, library)) { + *self = GraphPreviews { library: Some(library.clone()), ..GraphPreviews::default() }; + (self.requests, self.results) = spawn_graph_previews(ctx.clone(), library.clone()); + } + + let key = (package.to_string(), graph.to_string()); + if let Some(texture) = self.textures.get(&key) { + return texture.as_ref().map(TextureHandle::id); + } + + if let Some(requests) = &self.requests { + let _ = requests.send(key.clone()); + } + self.textures.insert(key, None); + None + } + + /// Upload the previews the worker finished since the last frame + fn collect(&mut self, ctx: &egui::Context) { + let Some(results) = &self.results else { return }; + + for ((package, graph), rgba) in results.try_iter() { + let texture = rgba.map(|rgba| { + let image = ColorImage::from_rgba_unmultiplied([LIBRARY_PREVIEW_SIZE as usize, LIBRARY_PREVIEW_SIZE as usize], &rgba); + ctx.load_texture(format!("library-graph-{package}#{graph}"), image, TextureOptions::LINEAR) + }); + self.textures.insert((package, graph), texture); + } + } +} + +type GraphRequests = Option>; +type GraphResults = Option>)>>; + +/// Start the worker that cooks requested library graphs; it ends when the requests' sender is dropped +#[cfg(not(target_arch = "wasm32"))] +fn spawn_graph_previews(ctx: egui::Context, library: std::sync::Arc) -> (GraphRequests, GraphResults) { + let (request_tx, request_rx) = std::sync::mpsc::channel::<(String, String)>(); + let (result_tx, result_rx) = std::sync::mpsc::channel(); + let worker = std::thread::Builder::new().name("materialcraft-library-graphs".into()).spawn(move || { + let mut waiting = Vec::new(); + loop { + // The tiles scrolled into view last are cooked first + waiting.extend(request_rx.try_iter()); + let next = match waiting.pop() { + Some(next) => next, + None => match request_rx.recv() { + Ok(next) => next, + Err(_) => return, + }, + }; + + let image = materialcraft_engine::NodeLibrary::preview(&library, &next.0, &next.1, LIBRARY_PREVIEW_SIZE); + let rgba = image.map(|image| image.resize(LIBRARY_PREVIEW_SIZE, LIBRARY_PREVIEW_SIZE, true).to_rgba8_display()); + if result_tx.send((next, rgba)).is_err() { + return; + } + ctx.request_repaint(); + } + }); + + match worker { + Ok(_) => (Some(request_tx), Some(result_rx)), + Err(_) => (None, None), + } +} + +/// The browser build has no worker thread: library graphs keep their category icon +#[cfg(target_arch = "wasm32")] +fn spawn_graph_previews(_ctx: egui::Context, _library: std::sync::Arc) -> (GraphRequests, GraphResults) { + (None, None) +} + impl Thumbs { pub fn clear_nodes(&mut self) { self.nodes.clear(); @@ -62,6 +149,19 @@ impl Thumbs { } self.library_rx = None; } + self.graphs.collect(ctx); + } + + /// The preview of library graph `graph` of `package`, cooked in the background on first use; + /// `None` until it is ready and for graphs that make no image + pub fn graph( + &mut self, + ctx: &egui::Context, + library: &std::sync::Arc, + package: &str, + graph: &str, + ) -> Option { + self.graphs.get(ctx, library, package, graph) } /// The library preview of node `def` (generated in the background on first use) diff --git a/crates/ui-egui/src/value_editor.rs b/crates/ui-egui/src/value_editor.rs index 575a9b4..bf505cc 100644 --- a/crates/ui-egui/src/value_editor.rs +++ b/crates/ui-egui/src/value_editor.rs @@ -3,18 +3,44 @@ use materialcraft_engine::core::Value; /// Edit a function value within the available width pub(crate) fn show(ui: &mut Ui, value: &mut Value) -> bool { - ui.horizontal_wrapped(|ui| match value { - Value::Float(value) => float(ui, value, "Value"), - Value::Float2(values) => floats(ui, values, &["X", "Y"]), - Value::Float3(values) => floats(ui, values, &["X", "Y", "Z"]), - Value::Float4(values) => floats(ui, values, &["X", "Y", "Z", "W"]), - Value::Color(values) => floats(ui, values, &["Red", "Green", "Blue", "Alpha"]), - Value::Int(value) => integer(ui, value, "Value"), - Value::Int2(values) => integers(ui, values), - Value::Int3(values) => integers(ui, values), - Value::Int4(values) => integers(ui, values), + ui.horizontal_wrapped(|ui| fields(ui, value, false)).inner +} + +/// Edit a function value with one full-width field per component, as a node face shows it +pub(crate) fn show_stacked(ui: &mut Ui, value: &mut Value) -> bool { + ui.vertical(|ui| fields(ui, value, true)).inner +} + +/// How many fields `show_stacked` lays out for `value` +pub(crate) fn rows(value: &Value) -> usize { + match value { + Value::Float2(_) | Value::Int2(_) => 2, + Value::Float3(_) | Value::Int3(_) => 3, + Value::Float4(_) | Value::Int4(_) | Value::Color(_) => 4, + _ => 1, + } +} + +fn fields(ui: &mut Ui, value: &mut Value, stacked: bool) -> bool { + match value { + Value::Float(value) => float(ui, value, "Value", stacked), + Value::Float2(values) => floats(ui, values, &["X", "Y"], stacked), + Value::Float3(values) => floats(ui, values, &["X", "Y", "Z"], stacked), + Value::Float4(values) => floats(ui, values, &["X", "Y", "Z", "W"], stacked), + Value::Color(values) => floats(ui, values, &["Red", "Green", "Blue", "Alpha"], stacked), + Value::Int(value) => integer(ui, value, "Value", stacked), + Value::Int2(values) => integers(ui, values, stacked), + Value::Int3(values) => integers(ui, values, stacked), + Value::Int4(values) => integers(ui, values, stacked), Value::Bool(value) => { - let response = ui.checkbox(value, ""); + let text = if !stacked { + "" + } else if *value { + "True" + } else { + "False" + }; + let response = ui.checkbox(value, crate::i18n::tr(text)); crate::widgets::name(&response, egui::Role::CheckBox, "Value"); response.changed() } @@ -24,34 +50,41 @@ pub(crate) fn show(ui: &mut Ui, value: &mut Value) -> bool { response.changed() } _ => false, - }) - .inner + } } -fn float(ui: &mut Ui, value: &mut f32, label: &str) -> bool { - let response = ui.add(egui::DragValue::new(value).speed(0.01).max_decimals(3)); +/// A stacked field fills the row and names its component in front of the number +fn field(ui: &mut Ui, drag: egui::DragValue<'_>, label: &str, stacked: bool) -> bool { + let response = if stacked { + let drag = if label == "Value" { drag } else { drag.prefix(format!("{} ", label.chars().next().unwrap_or(' '))) }; + ui.add_sized([ui.available_width(), ui.spacing().interact_size.y], drag) + } else { + ui.add(drag) + }; crate::widgets::name(&response, egui::Role::SpinButton, label); response.changed() } -fn floats(ui: &mut Ui, values: &mut [f32], labels: &[&str]) -> bool { +fn float(ui: &mut Ui, value: &mut f32, label: &str, stacked: bool) -> bool { + field(ui, egui::DragValue::new(value).speed(0.01).max_decimals(3), label, stacked) +} + +fn floats(ui: &mut Ui, values: &mut [f32], labels: &[&str], stacked: bool) -> bool { let mut changed = false; for (value, label) in values.iter_mut().zip(labels) { - changed |= float(ui, value, label); + changed |= float(ui, value, label, stacked); } changed } -fn integer(ui: &mut Ui, value: &mut i32, label: &str) -> bool { - let response = ui.add(egui::DragValue::new(value).speed(0.1)); - crate::widgets::name(&response, egui::Role::SpinButton, label); - response.changed() +fn integer(ui: &mut Ui, value: &mut i32, label: &str, stacked: bool) -> bool { + field(ui, egui::DragValue::new(value).speed(0.1), label, stacked) } -fn integers(ui: &mut Ui, values: &mut [i32]) -> bool { +fn integers(ui: &mut Ui, values: &mut [i32], stacked: bool) -> bool { let mut changed = false; for (value, label) in values.iter_mut().zip(["X", "Y", "Z", "W"]) { - changed |= integer(ui, value, label); + changed |= integer(ui, value, label, stacked); } changed } diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index f3b75da..590df83 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -6,6 +6,7 @@ mod dialogs; mod export_window; mod graph_properties; mod interface_scale; +mod node_look; mod normal_maps; mod numeric_input; mod preview_resolution; diff --git a/crates/ui-egui/tests/it/node_look.rs b/crates/ui-egui/tests/it/node_look.rs new file mode 100644 index 0000000..6f71983 --- /dev/null +++ b/crates/ui-egui/tests/it/node_look.rs @@ -0,0 +1,81 @@ +//! The Library's draggable divider and the faces of function nodes + +use egui::accesskit::Role; +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{By, Queryable}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; +use serde_json::json; + +fn harness(app: MaterialCraftApp) -> Harness<'static, MaterialCraftApp> { + // Short steps keep two clicks within the double-click delay + let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).with_step_dt(0.05).build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + harness.run_steps(6); + harness +} + +fn press(harness: &mut Harness<'static, MaterialCraftApp>, at: Pos2, pressed: bool) { + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + harness.step(); +} + +fn divider(harness: &Harness<'static, MaterialCraftApp>) -> Pos2 { + harness.get(By::new().role(Role::Splitter).label("Library divider")).rect().center() +} + +#[test] +fn the_library_divider_drags_the_tree_narrower_and_a_double_click_resets_it() { + let mut harness = harness(MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default())); + assert_eq!(harness.state().ui.library_tree_width, 0.0, "the tree starts at its automatic width"); + let start = divider(&harness); + + harness.event(Event::PointerMoved(start)); + harness.step(); + press(&mut harness, start, true); + for step in 1..=6 { + harness.event(Event::PointerMoved(start - vec2(10.0 * step as f32, 0.0))); + harness.step(); + } + press(&mut harness, start - vec2(60.0, 0.0), false); + harness.run_steps(3); + + let dragged = harness.state().ui.library_tree_width; + assert!(dragged > 0.0, "a drag chooses a width"); + let moved = start.x - divider(&harness).x; + assert!((40.0..=62.0).contains(&moved), "the divider follows the pointer, moved {moved}"); + + let at = divider(&harness); + harness.event(Event::PointerMoved(at)); + harness.step(); + for pressed in [true, false, true, false] { + press(&mut harness, at, pressed); + } + harness.run_steps(3); + assert_eq!(harness.state().ui.library_tree_width, 0.0, "a double click returns to the automatic width"); + assert!((divider(&harness).x - start.x).abs() < 1.0); +} + +#[test] +fn a_constant_node_fits_a_field_for_each_component() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.run("file.new", json!({"kind": "function", "name": "Faces"})).unwrap(); + app.run("graph.function.edit", json!({"edit": {"action": "add", "operation": "const_float4", "at": [0, 0]}})).unwrap(); + app.run("graph.function.edit", json!({"edit": {"action": "add", "operation": "add", "at": [200, 0]}})).unwrap(); + let harness = harness(app); + + let card = harness.get(By::new().role(Role::Button).label("Float4")).rect(); + for component in ["X", "Y", "Z", "W"] { + let field = harness.get(By::new().role(Role::SpinButton).label(component)).rect(); + assert!(card.contains_rect(field), "{component} lies inside its node: {field:?} in {card:?}"); + } + + let operator = harness.get(By::new().role(Role::Button).label("Add")).rect(); + assert!(operator.height() < card.height(), "an operator is a compact node"); + assert!(operator.height() < operator.width(), "an operator has no empty preview square"); +} diff --git a/crates/ui-egui/tests/snapshot.rs b/crates/ui-egui/tests/snapshot.rs index 5a07eef..3004ca0 100644 --- a/crates/ui-egui/tests/snapshot.rs +++ b/crates/ui-egui/tests/snapshot.rs @@ -10,6 +10,9 @@ mod explorer; #[path = "snapshot/export.rs"] mod export; +#[path = "snapshot/node_look.rs"] +mod node_look; + #[path = "snapshot/function_instances.rs"] mod function_instances; diff --git a/crates/ui-egui/tests/snapshot/node_look.rs b/crates/ui-egui/tests/snapshot/node_look.rs new file mode 100644 index 0000000..4198fff --- /dev/null +++ b/crates/ui-egui/tests/snapshot/node_look.rs @@ -0,0 +1,90 @@ +use super::{By, MaterialCraftApp, Queryable, UiState, harness, json, save, settle}; +use egui::accesskit::Role; + +fn directory() -> std::path::PathBuf { + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + directory +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn function_nodes_show_their_values_and_symbols() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.run("file.new", json!({"kind": "function", "name": "Look"})).unwrap(); + let operations = [ + ("const_float1", [0, 0]), + ("const_float2", [0, 120]), + ("const_float4", [0, 260]), + ("const_int1", [0, 420]), + ("const_bool", [0, 520]), + ("get_float1", [160, 0]), + ("add", [160, 120]), + ("mul", [160, 240]), + ("div", [160, 360]), + ("gt", [320, 0]), + ("sqrt", [320, 120]), + ("lerp", [320, 240]), + ("ifelse", [320, 380]), + ("vector3", [480, 0]), + ("swizzle2", [480, 120]), + ("sin", [480, 240]), + ("min", [480, 360]), + ]; + for (operation, at) in operations { + app.run("graph.function.edit", json!({"edit": {"action": "add", "operation": operation, "at": at}})).unwrap(); + } + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 8); + + save(&mut harness, &directory(), "look-function-nodes"); +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn library_nodes_and_tiles_show_previews() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + let entries = [ + ("node:uniform", [0, 0]), + ("node:blur", [160, 0]), + ("sbs://blur_hq.sbs#blur_hq", [320, 0]), + ("sbs://edge_detect.sbs#edge_detect", [480, 0]), + ("sbs://materials/pbr/bricks_001.sbs#bricks_001", [0, 220]), + ("sbs://pattern_tile_sampler.sbs#tile_sampler", [200, 220]), + ("sbs://mg_mask_builder.sbs#mg_mask_builder_2", [400, 220]), + ("node:input_value", [640, 0]), + ("node:value_processor", [640, 100]), + ]; + for (entry, at) in entries { + app.run("library.add", json!({"entry": entry, "at": at})).unwrap(); + } + let mut harness = harness(app, 1600.0, 960.0); + // The graph cooks on a worker + for _ in 0..480 { + std::thread::sleep(std::time::Duration::from_millis(250)); + settle(&mut harness, 2); + let session = &harness.state().session; + if session.graph().is_ok_and(|graph| session.cooked.nodes.len() >= graph.nodes.len()) { + break; + } + } + save(&mut harness, &directory(), "look-library-nodes"); + + for (top, sub, name) in + [("Filters", "Blurs", "look-library-blurs"), ("PBR materials", "Bricks", "look-library-bricks"), ("Functions", "Constant", "look-library-functions")] + { + harness.get(By::new().role(Role::TreeItem).label(top)).click(); + settle(&mut harness, 3); + harness.get_all(By::new().role(Role::TreeItem).label(sub)).next().unwrap().click(); + // Previews cook on a worker + for _ in 0..40 { + std::thread::sleep(std::time::Duration::from_millis(250)); + settle(&mut harness, 2); + } + save(&mut harness, &directory(), name); + harness.get(By::new().role(Role::TreeItem).label(top)).click(); + settle(&mut harness, 2); + harness.get(By::new().role(Role::TreeItem).label(top)).click(); + settle(&mut harness, 2); + } +}