diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 631c6cf0..5a0400d8 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -32,7 +32,6 @@ images, materials, sample graphs, presets, environments) may ever be added. | `docs/images/materialcraft-levels-editor.png` | Docs screenshot: the Levels editor with the input histogram | MaterialCraft contributors | Offscreen render of MaterialCraft's UI (`crates/ui-egui/tests/snapshot.rs`) | MIT OR Apache-2.0 | | `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) | | `crates/nodes/src/atomic/text.rs` (`GLYPHS`) | Single-stroke vector font of the Text node (A–Z, a–z, 0–9, punctuation) | MaterialCraft contributors | Original, designed as stroke data in code | MIT OR Apache-2.0 | -| `examples/atomic_sample.sbs` | Atomic sample graph | MaterialCraft contributors | Original graph built by `crates/engine/src/atomic_sample.rs` | MIT OR Apache-2.0 | ## Third-party assets compiled into the binary @@ -42,13 +41,3 @@ These come from Rust crate dependencies (not files in this repository) and keep |---|---|---|---|---| | Phosphor Icons (regular), via the `egui-phosphor` crate (vendored in `vendor/egui-phosphor` for egui 0.37) | Every UI icon (toolbars, panels, node quick-insert buttons) | Phosphor Icons (Helena Zhang, Tobias Fried) | https://phosphoricons.com, https://github.com/amPerl/egui-phosphor | MIT (icons); crate MIT OR Apache-2.0 | | egui default fonts (Ubuntu-Light, Hack, Noto Emoji, emoji-icon-font), via `epaint_default_fonts` | UI text | Canonical / Source Foundry / Google / Jessie Jung | https://github.com/emilk/egui | Ubuntu Font Licence 1.0, MIT + Bitstream Vera License, OFL 1.1, MIT | - -## Procedural content (no asset files) - -The node library's primitives (`crates/nodes`), the sample materials and graph templates -(`crates/engine/src/samples.rs`), the 3D view's environments (`crates/render/src/ibl.rs`, procedural -HDR skies and soft boxes), the built-in meshes (`crates/geom/src/primitives.rs`), the library's node -previews (`crates/ui-egui/src/thumbs.rs`, each node cooked on sample waves) and the New graph -dialog's template spheres (`crates/ui-egui/src/windows.rs`) are generated in code by MaterialCraft -contributors (MIT OR Apache-2.0). None of them is derived from another product's presets, -shaders, materials, sample graphs or images. diff --git a/ROADMAP.md b/ROADMAP.md index 0e97d7b7..37dcf3eb 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,6 +1,6 @@ # MaterialCraft roadmap -**Current focus (2026-11-05):** native primitive editing, evaluation and SBS save/load. +**Current focus (2026-11-08):** native primitive editing, reusable SBS functions and interoperable save/load. The old Rust procedural library has been removed. The main catalog has 30 entries: 26 native primitives and four graph input/output items. Functions have 85 operations; pattern graphs have @@ -13,13 +13,15 @@ rendering parity and arbitrary SBS round trips have not been established. 1. Verify the original atomic sample in the reference application 2. Compare primitive outputs and parameter semantics against reference results -3. Add SBS graph references with cycle-safe resolution -4. Build the library from SBS definitions instead of duplicate Rust nodes +3. Validate the converted standard library in the reference application and establish redistribution rights +4. Extend the SBS library beyond reusable functions to processing graphs ## Progress log | Date | What landed | |---|---| +| 2026-11-08 | Explorer folder hierarchy and package/folder/graph context menus, native SBS empty folders and resource paths, undoable copy/move/rename/remove, and package reload/save-copy actions | +| 2026-11-08 | Portable `sbs://` function instances in the Library, preserved package folders and missing references, and a converted library retaining all 171 supplied function bodies (2,334 nodes); external runtime equivalence and redistribution rights remain unverified | | 2026-11-02 | Cross-app materials: `.mcmat` portable materials, Send to TextureCraft, input-node preview images (mesh maps from TextureCraft), live re-cooks from TextureCraft through the CLI | | 2026-11-02 | Visual function editor, dynamic parameters, presets and groups, 105 more nodes (flood fill, FX-Map, SVG, Text, 3D noises, weathering, material blending), mesh import, browser file I/O, 2D histogram, CLI `--set`, better samples | | 2026-11-02 | First day: engine, ~120 nodes, cooking cache, packages, export, the full editor UI, 3D preview, CLI, control channel with synthetic input, MCP server, wasm builds | diff --git a/assets/sbs/functions.sbs b/assets/sbs/functions.sbs new file mode 100644 index 00000000..0294f74a --- /dev/null +++ b/assets/sbs/functions.sbs @@ -0,0 +1 @@ + diff --git a/crates/core/src/attributes.rs b/crates/core/src/attributes.rs index 1dc3b2bc..e8d20402 100644 --- a/crates/core/src/attributes.rs +++ b/crates/core/src/attributes.rs @@ -4,8 +4,12 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct Attributes { + pub label: String, pub category: String, pub description: String, pub author: String, + pub author_url: String, pub tags: String, + pub group: String, + pub user_data: String, } diff --git a/crates/core/src/base_parameters.rs b/crates/core/src/base_parameters.rs index 2eba06c5..ed0f58d9 100644 --- a/crates/core/src/base_parameters.rs +++ b/crates/core/src/base_parameters.rs @@ -1,6 +1,6 @@ use serde::{Deserialize, Serialize}; -use crate::{OutputFormat, SizeMode}; +use crate::{OutputFormat, ParameterInheritance, SizeMode}; /// Parameters every node has ("Base parameters") #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -14,10 +14,23 @@ pub struct BaseParameters { pub seed: i32, /// Whether sampling wraps at the edges (horizontal, vertical) pub tiling: [bool; 2], + pub tiling_mode: ParameterInheritance, + /// SBS pixel ratio: zero stretches the image; one keeps pixels square. + pub pixel_ratio: i32, + pub pixel_ratio_mode: ParameterInheritance, } impl Default for BaseParameters { fn default() -> Self { - BaseParameters { size_mode: SizeMode::RelativeToInput, size: [0, 0], format: OutputFormat::Inherit, seed: 0, tiling: [true, true] } + BaseParameters { + size_mode: SizeMode::RelativeToInput, + size: [0, 0], + format: OutputFormat::Inherit, + seed: 0, + tiling: [true, true], + tiling_mode: ParameterInheritance::default(), + pixel_ratio: 0, + pixel_ratio_mode: ParameterInheritance::default(), + } } } diff --git a/crates/core/src/evaluation_environment.rs b/crates/core/src/evaluation_environment.rs new file mode 100644 index 00000000..baf5620b --- /dev/null +++ b/crates/core/src/evaluation_environment.rs @@ -0,0 +1,11 @@ +use serde::{Deserialize, Serialize}; + +/// Host values shared by graph instances for one deterministic evaluation. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct EvaluationEnvironment { + pub time_seconds: f32, + pub uv_tile: [i32; 2], + /// Raw host convention code; the static authoring environment uses zero. + pub normal_format: i32, +} diff --git a/crates/core/src/function_graph.rs b/crates/core/src/function_graph.rs index fc663ba9..c3f43bc2 100644 --- a/crates/core/src/function_graph.rs +++ b/crates/core/src/function_graph.rs @@ -30,6 +30,8 @@ impl FunctionGraph { let horizontal_position = self.nodes.len() as f32 * 140.0; let node = FunctionNode { id, + missing: None, + missing_data: String::new(), instance: None, source: None, type_code: 0, diff --git a/crates/core/src/function_node.rs b/crates/core/src/function_node.rs index a81e094c..c171802a 100644 --- a/crates/core/src/function_node.rs +++ b/crates/core/src/function_node.rs @@ -9,6 +9,12 @@ pub struct FunctionNode { #[serde(default)] pub type_code: u32, pub op: String, + /// Connector names for an unavailable operation; its wires remain editable. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub missing: Option>, + /// Uninterpreted function data, retained for unavailable operations on save. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub missing_data: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub instance: Option, /// Resolved call body shared by cooks; SBS stores only the source reference diff --git a/crates/core/src/graph.rs b/crates/core/src/graph.rs index 98c9e848..a277554f 100644 --- a/crates/core/src/graph.rs +++ b/crates/core/src/graph.rs @@ -10,8 +10,14 @@ use crate::{Attributes, Comment, Connection, ExposedParameter, Frame, GraphKind, #[serde(rename_all = "camelCase")] pub struct Graph { pub name: String, + /// Package folder, retained so external SBS references keep their identity. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub folder: String, #[serde(default)] pub function: Option, + /// Declared SBS return type, including functions whose implementation is unavailable. + #[serde(default)] + pub function_type: u32, pub nodes: Vec, pub connections: Vec, #[serde(default)] @@ -27,6 +33,16 @@ pub struct Graph { #[serde(default)] pub seed: i32, #[serde(default)] + pub pixel_ratio: i32, + #[serde(default)] + pub pixel_ratio_mode: crate::ParameterInheritance, + #[serde(default = "default_tiling")] + pub tiling: [bool; 2], + #[serde(default)] + pub tiling_mode: crate::ParameterInheritance, + #[serde(default)] + pub physical_size: [f32; 3], + #[serde(default)] pub exposed: Vec, /// Current values of the exposed inputs (missing = default) #[serde(default)] @@ -49,10 +65,17 @@ pub const MIN_SIZE_LOG2: u32 = 4; pub const MAX_SIZE_LOG2: u32 = 13; impl Graph { + /// Display text never changes the identifier used by SBS references + pub fn display_name(&self) -> &str { + if self.attributes.label.is_empty() { &self.name } else { &self.attributes.label } + } + pub fn new(name: &str) -> Graph { Graph { name: name.into(), + folder: String::new(), function: None, + function_type: 0, nodes: Vec::new(), connections: Vec::new(), frames: Vec::new(), @@ -61,6 +84,11 @@ impl Graph { size: [10, 10], format: OutputFormat::U16, seed: 0, + pixel_ratio: 0, + pixel_ratio_mode: crate::ParameterInheritance::default(), + tiling: [true, true], + tiling_mode: crate::ParameterInheritance::default(), + physical_size: [0.0; 3], exposed: Vec::new(), inputs: BTreeMap::new(), presets: Vec::new(), @@ -71,6 +99,10 @@ impl Graph { } } + pub fn sbs_path(&self) -> String { + if self.folder.is_empty() { self.name.clone() } else { format!("{}/{}", self.folder, self.name) } + } + /// All editable Function canvases, including processor and parameter functions pub fn functions(&self) -> impl Iterator { self.function.iter().chain(self.nodes.iter().flat_map(|node| node.functions.values().chain(node.params.values().flat_map(value_functions)))) @@ -196,6 +228,10 @@ impl Graph { } } +fn default_tiling() -> [bool; 2] { + [true, true] +} + fn value_functions(value: &Value) -> impl Iterator { let (function, pattern) = match value { Value::Function(function) => (Some(function.as_ref()), None), diff --git a/crates/core/src/graph_instance.rs b/crates/core/src/graph_instance.rs index afdabfed..5880054a 100644 --- a/crates/core/src/graph_instance.rs +++ b/crates/core/src/graph_instance.rs @@ -4,9 +4,15 @@ use serde::{Deserialize, Serialize}; /// An SBS graph reference and its last known interface, without a copy of its nodes #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GraphInstance { + /// Display label resolved from the source; the SBS reference keeps its identifier + #[serde(skip)] + pub label: String, /// Empty for a graph in the same package pub package: String, pub graph: String, pub inputs: Vec, pub outputs: Vec, + /// Resolved function input defaults; the source package remains authoritative + #[serde(skip)] + pub defaults: std::collections::BTreeMap, } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 2abda532..18105082 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -10,6 +10,7 @@ mod connection; mod core_error; mod curve; mod curve_point; +mod evaluation_environment; mod exposed_parameter; mod frame; mod function_graph; @@ -27,6 +28,7 @@ mod node; mod node_id; mod output_format; mod package; +mod parameter_inheritance; mod pattern_graph; mod pattern_node; mod pattern_node_kind; @@ -47,6 +49,7 @@ pub use connection::Connection; pub use core_error::CoreError; pub use curve::Curve; pub use curve_point::CurvePoint; +pub use evaluation_environment::EvaluationEnvironment; pub use exposed_parameter::ExposedParameter; pub use frame::Frame; pub use function_graph::FunctionGraph; @@ -64,6 +67,7 @@ pub use node::Node; pub use node_id::NodeId; pub use output_format::OutputFormat; pub use package::{PACKAGE_EXT, Package}; +pub use parameter_inheritance::ParameterInheritance; pub use pattern_graph::PatternGraph; pub use pattern_node::PatternNode; pub use pattern_node_kind::PatternNodeKind; diff --git a/crates/core/src/package.rs b/crates/core/src/package.rs index bb42b434..2e4bffc4 100644 --- a/crates/core/src/package.rs +++ b/crates/core/src/package.rs @@ -8,6 +8,9 @@ pub const PACKAGE_EXT: &str = "sbs"; pub struct Package { pub name: String, pub graphs: Vec, + /// Explicit SBS group paths, including folders without graphs + #[serde(default)] + pub folders: Vec, #[serde(default)] pub resources: Vec, /// Resolved source packages shared by cooks; SBS stores their file references instead @@ -24,7 +27,25 @@ fn version() -> u32 { impl Package { pub fn new(name: &str) -> Package { - Package { name: name.into(), graphs: Vec::new(), resources: Vec::new(), version: 1, dependencies: Default::default() } + Package { name: name.into(), graphs: Vec::new(), folders: Vec::new(), resources: Vec::new(), version: 1, dependencies: Default::default() } + } + + pub fn folder_paths(&self) -> std::collections::BTreeSet { + let mut folders = std::collections::BTreeSet::new(); + for path in self + .folders + .iter() + .map(String::as_str) + .chain(self.graphs.iter().map(|graph| graph.folder.as_str())) + .chain(self.resources.iter().map(|resource| resource.folder.as_str())) + { + let mut parent = path; + while !parent.is_empty() { + folders.insert(parent.to_string()); + parent = parent.rsplit_once('/').map_or("", |(parent, _)| parent); + } + } + folders } pub fn graph(&self, i: usize) -> Result<&Graph> { @@ -36,7 +57,11 @@ impl Package { } pub fn graph_by_name(&self, name: &str) -> Option<(usize, &Graph)> { - self.graphs.iter().enumerate().find(|(_, g)| g.name == name) + self.graphs.iter().enumerate().find(|(_, g)| g.sbs_path() == name).or_else(|| { + let mut matches = self.graphs.iter().enumerate().filter(|(_, g)| g.name == name); + let first = matches.next()?; + matches.next().is_none().then_some(first) + }) } pub fn resource(&self, name: &str) -> Option<&Resource> { @@ -46,10 +71,10 @@ impl Package { /// A name not used by any graph: `base`, `base_1`, `base_2`… pub fn unique_graph_name(&self, base: &str) -> String { let base = if base.trim().is_empty() { "Graph" } else { base.trim() }; - if self.graph_by_name(base).is_none() { + if !self.graphs.iter().any(|graph| graph.name == base) { return base.to_string(); } - (1..).map(|i| format!("{base}_{i}")).find(|n| self.graph_by_name(n).is_none()).unwrap_or_else(|| base.to_string()) + (1..).map(|index| format!("{base}_{index}")).find(|name| !self.graphs.iter().any(|graph| graph.name == *name)).unwrap_or_else(|| base.to_string()) } pub fn instance_package(&self, node: &crate::Node) -> Option<&Package> { diff --git a/crates/core/src/parameter_inheritance.rs b/crates/core/src/parameter_inheritance.rs new file mode 100644 index 00000000..b0866e9e --- /dev/null +++ b/crates/core/src/parameter_inheritance.rs @@ -0,0 +1,20 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ParameterInheritance { + Absolute, + #[default] + RelativeToInput, + RelativeToParent, +} + +impl ParameterInheritance { + pub fn resolve(self, absolute: T, input: Option, parent: T) -> T { + match self { + Self::Absolute => absolute, + Self::RelativeToInput => input.unwrap_or(parent), + Self::RelativeToParent => parent, + } + } +} diff --git a/crates/core/src/resource.rs b/crates/core/src/resource.rs index f7545736..c2e65b8c 100644 --- a/crates/core/src/resource.rs +++ b/crates/core/src/resource.rs @@ -6,8 +6,13 @@ use serde::{Deserialize, Serialize}; pub struct Resource { /// Unique name, referenced by nodes (`resource` parameter) pub name: String, + #[serde(default = "default_folder")] + pub folder: String, /// File name inside the package's `resources/` folder pub file: String, + /// Unavailable external asset retained for repair on a later load + #[serde(default, skip_serializing_if = "String::is_empty")] + pub source: String, /// The file's bytes (stored in the zip, not in `package.json`) #[serde(skip)] pub bytes: ResourceBytes, @@ -16,6 +21,14 @@ pub struct Resource { impl Resource { /// A resource named `name`, stored as `file` in the package pub fn new(name: impl Into, file: impl Into, bytes: ResourceBytes) -> Resource { - Resource { name: name.into(), file: file.into(), bytes } + Resource { name: name.into(), folder: default_folder(), file: file.into(), source: String::new(), bytes } + } + + pub fn sbs_path(&self) -> String { + if self.folder.is_empty() { self.name.clone() } else { format!("{}/{}", self.folder, self.name) } } } + +fn default_folder() -> String { + "Resources".into() +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 3a0a753e..330756a3 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -49,18 +49,25 @@ pub fn command_specs() -> &'static [CommandSpec] { let mut v = Vec::new(); v.extend(crate::file_cmds::specs()); v.extend(crate::package_commands::specs()); + v.extend(crate::package_file_commands::specs()); + v.extend(crate::folder_commands::specs()); + v.extend(crate::explorer_clipboard_commands::specs()); v.extend(crate::graph_instance_commands::specs()); + v.extend(crate::function_library_commands::specs()); v.extend(crate::node_info_commands::specs()); v.extend(crate::atomic_sample_commands::specs()); v.extend(crate::material_cmds::specs()); v.extend(crate::edit_cmds::specs()); v.extend(crate::embedded_edit_commands::specs()); v.extend(crate::graph_cmds::specs()); + v.extend(crate::graph_property_commands::specs()); v.extend(crate::alignment_commands::specs()); v.extend(crate::annotation_commands::specs()); v.extend(crate::frame_commands::specs()); v.extend(crate::function_commands::specs()); v.extend(crate::function_info_commands::specs()); + v.extend(crate::function_variable_commands::specs()); + v.extend(crate::evaluation_environment_commands::specs()); v.extend(crate::comment_commands::specs()); v.extend(crate::node_cmds::specs()); v.extend(crate::node_graph_commands::specs()); diff --git a/crates/engine/src/document_path.rs b/crates/engine/src/document_path.rs index 372797a8..0778f1d2 100644 --- a/crates/engine/src/document_path.rs +++ b/crates/engine/src/document_path.rs @@ -1,4 +1,7 @@ pub(crate) fn normalize(path: &str) -> String { + if path.contains("://") { + return path.to_string(); + } #[cfg(not(target_arch = "wasm32"))] { use std::path::{Component, PathBuf}; @@ -32,6 +35,12 @@ pub(crate) fn normalize(path: &str) -> String { } pub(crate) fn resolve(owner: &str, reference: &str) -> String { + if reference.contains("://") { + return reference.to_string(); + } + if owner.starts_with("sbs://") { + return materialcraft_formats::sbs::library::resolve(owner, reference).unwrap_or_else(|_| format!("sbs://{reference}")); + } let path = std::path::Path::new(reference); if path.is_absolute() { return normalize(reference); @@ -40,6 +49,9 @@ pub(crate) fn resolve(owner: &str, reference: &str) -> String { } pub(crate) fn relative(owner: &str, source: &str) -> String { + if source.contains("://") { + return source.to_string(); + } let folder = std::path::Path::new(owner).parent().unwrap_or(std::path::Path::new("")); let from: Vec<_> = folder.components().collect(); let to: Vec<_> = std::path::Path::new(source).components().collect(); diff --git a/crates/engine/src/evaluation_environment_commands.rs b/crates/engine/src/evaluation_environment_commands.rs new file mode 100644 index 00000000..f4b846c5 --- /dev/null +++ b/crates/engine/src/evaluation_environment_commands.rs @@ -0,0 +1,99 @@ +use crate::{ + Result, Session, cmd, + commands::{CommandSpec, always, bad, has_graph}, +}; +use serde_json::{Value as Json, json}; + +pub(crate) fn specs() -> Vec { + vec![ + cmd!( + "session.environment", + "Evaluation environment", + [], + None, + "{timeSeconds?: nonnegative float, uvTile?: [int, int], normalFormat?: int} updates host values; {} reads them; does not modify the package", + always, + environment + ), + cmd!( + "graph.context", + "Graph evaluation context", + [], + None, + "{physicalSize?: [x, y, z], pixelRatio?: 0|1, tiling?: [horizontal, vertical]} updates material-graph metadata used by system variables; {} reads it", + has_graph, + graph_context + ), + ] +} + +fn environment(session: &mut Session, parameters: &Json) -> Result { + let command = "session.environment"; + let mut environment = session.environment; + let fields = parameters.as_object().ok_or_else(|| bad(command, "expected an object"))?; + for (name, value) in fields { + match name.as_str() { + "timeSeconds" => environment.time_seconds = serde_json::from_value(value.clone()).map_err(|error| bad(command, error.to_string()))?, + "uvTile" => environment.uv_tile = serde_json::from_value(value.clone()).map_err(|error| bad(command, error.to_string()))?, + "normalFormat" => environment.normal_format = serde_json::from_value(value.clone()).map_err(|error| bad(command, error.to_string()))?, + _ => return Err(bad(command, format!("unknown environment field `{name}`"))), + } + } + + if !environment.time_seconds.is_finite() || environment.time_seconds < 0.0 { + return Err(bad(command, "timeSeconds must be finite and nonnegative")); + } + + if session.environment != environment { + session.environment = environment; + session.dirty = true; + session.cook_epoch = session.cook_epoch.wrapping_add(1); + } + Ok(json!(environment)) +} + +fn graph_context(session: &mut Session, parameters: &Json) -> Result { + let command = "graph.context"; + let graph = session.graph()?; + // Reusable functions receive these values from their caller and do not serialize base parameters + if graph.function.is_some() { + return Err(bad(command, "function graphs use their caller's evaluation context; edit the material graph")); + } + + let (mut physical_size, mut pixel_ratio, mut tiling) = (graph.physical_size, graph.pixel_ratio, graph.tiling); + let (mut pixel_ratio_mode, mut tiling_mode) = (graph.pixel_ratio_mode, graph.tiling_mode); + let fields = parameters.as_object().ok_or_else(|| bad(command, "expected an object"))?; + for (name, value) in fields { + match name.as_str() { + "physicalSize" => physical_size = serde_json::from_value(value.clone()).map_err(|error| bad(command, error.to_string()))?, + "pixelRatio" => { + pixel_ratio = serde_json::from_value(value.clone()).map_err(|error| bad(command, error.to_string()))?; + pixel_ratio_mode = materialcraft_core::ParameterInheritance::Absolute; + } + "tiling" => { + tiling = serde_json::from_value(value.clone()).map_err(|error| bad(command, error.to_string()))?; + tiling_mode = materialcraft_core::ParameterInheritance::Absolute; + } + _ => return Err(bad(command, format!("unknown graph context field `{name}`"))), + } + } + + if physical_size.iter().any(|value| !value.is_finite() || *value < 0.0) || !(0..=1).contains(&pixel_ratio) { + return Err(bad(command, "physicalSize must be finite and nonnegative; pixelRatio must be 0 or 1")); + } + + if (graph.physical_size, graph.pixel_ratio, graph.tiling, graph.pixel_ratio_mode, graph.tiling_mode) + != (physical_size, pixel_ratio, tiling, pixel_ratio_mode, tiling_mode) + { + session.edit("Graph evaluation context", |session| { + let graph = session.graph_mut()?; + graph.physical_size = physical_size; + graph.pixel_ratio = pixel_ratio; + graph.tiling = tiling; + graph.pixel_ratio_mode = pixel_ratio_mode; + graph.tiling_mode = tiling_mode; + Ok(()) + })?; + } + Ok(json!({"physicalSize": physical_size, "pixelRatio": pixel_ratio, "tiling": tiling})) +} diff --git a/crates/engine/src/explorer_clipboard.rs b/crates/engine/src/explorer_clipboard.rs new file mode 100644 index 00000000..6b8e30c6 --- /dev/null +++ b/crates/engine/src/explorer_clipboard.rs @@ -0,0 +1,10 @@ +use materialcraft_core::Package; + +#[derive(Clone, Debug)] +pub struct ExplorerClipboard { + pub(crate) source: Package, + pub(crate) document: u64, + pub(crate) path: Option, + pub(crate) graph: Option, + pub(crate) folder: Option, +} diff --git a/crates/engine/src/explorer_clipboard_commands.rs b/crates/engine/src/explorer_clipboard_commands.rs new file mode 100644 index 00000000..158b2ac3 --- /dev/null +++ b/crates/engine/src/explorer_clipboard_commands.rs @@ -0,0 +1,206 @@ +use crate::{ + ExplorerClipboard, Result, Session, cmd, + commands::{CommandSpec, always, bad, strp}, + folder_path, +}; +use materialcraft_core::{Package, Value as GraphValue}; +use serde_json::{Value, json}; +use std::collections::{BTreeMap, BTreeSet}; + +pub(crate) fn specs() -> Vec { + vec![ + cmd!("explorer.copy", "Copy Explorer item", [], None, "{graph? index, folder?} copies a graph, folder subtree, or package contents", always, copy), + cmd!( + "explorer.paste", + "Paste Explorer item", + [], + None, + "{folder?} pastes into a folder or the package root, with unique names", + |session| { if session.explorer_clipboard.is_some() { Ok(()) } else { Err("the Explorer clipboard is empty".into()) } }, + paste + ), + ] +} + +fn copy(session: &mut Session, parameters: &Value) -> Result { + let graph = parameters + .get("graph") + .map(|value| value.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad("explorer.copy", "graph must be an index"))) + .transpose()?; + let folder = strp(parameters, "folder").map(str::to_string); + if graph.is_some() && folder.is_some() { + return Err(bad("explorer.copy", "select one graph or folder")); + } + if let Some(index) = graph { + session.pkg.graph(index)?; + } + if let Some(folder) = &folder { + folder_path::require(&session.pkg, folder)?; + } + + session.explorer_clipboard = + Some(ExplorerClipboard { source: session.pkg.clone(), document: session.document_id, path: session.path.clone(), graph, folder }); + Ok(Value::Null) +} + +fn paste(session: &mut Session, parameters: &Value) -> Result { + let parent = strp(parameters, "folder").unwrap_or(""); + folder_path::require(&session.pkg, parent)?; + let clipboard = session.explorer_clipboard.as_ref().ok_or_else(|| bad("explorer.paste", "the Explorer clipboard is empty"))?; + let mut incoming = clipboard.source.clone(); + incoming.graphs = clipboard + .source + .graphs + .iter() + .enumerate() + .filter(|(index, graph)| { + clipboard.graph.is_none_or(|selected| selected == *index) + && clipboard.folder.as_ref().is_none_or(|folder| folder.is_empty() || folder_path::contains(folder, &graph.folder)) + }) + .map(|(_, graph)| graph.clone()) + .collect(); + let folders: BTreeSet<_> = if clipboard.graph.is_some() { + BTreeSet::new() + } else { + clipboard + .source + .folder_paths() + .into_iter() + .filter(|path| clipboard.folder.as_ref().is_none_or(|folder| folder.is_empty() || folder_path::contains(folder, path))) + .collect() + }; + if session.pkg.graphs.len().saturating_add(incoming.graphs.len()) > 4096 || session.pkg.folder_paths().len().saturating_add(folders.len()) > 16384 { + return Err(bad("explorer.paste", "a package supports at most 4096 graphs and 16384 folders")); + } + + let mut destination = session.pkg.clone(); + let mut folder_names = BTreeMap::new(); + for folder in &folders { + let (source_parent, leaf) = folder.rsplit_once('/').unwrap_or(("", folder)); + let target_parent = folder_names.get(source_parent).map(String::as_str).unwrap_or(parent); + let new = folder_path::join(target_parent, &folder_path::unique(&destination, target_parent, leaf)); + folder_path::validate(&new)?; + destination.folders.push(new.clone()); + folder_names.insert(folder.clone(), new); + } + incoming.folders = folder_names.values().cloned().collect(); + let mut paths = BTreeMap::new(); + for graph in &mut incoming.graphs { + let old = graph.sbs_path(); + graph.folder = folder_names.get(&graph.folder).cloned().unwrap_or_else(|| parent.to_string()); + graph.name = folder_path::unique(&destination, &graph.folder, &graph.name); + paths.insert(old, graph.sbs_path()); + destination.graphs.push(graph.clone()); + } + let names = crate::graph_references::with_leaf_names(&clipboard.source, &paths); + for graph in &mut incoming.graphs { + for instance in graph.instances_mut() { + if !instance.package.is_empty() { + continue; + } + if let Some(new) = names.get(&instance.graph) { + instance.graph = new.clone(); + } else if clipboard.document != session.document_id { + instance.package = + clipboard.path.clone().ok_or_else(|| bad("explorer.paste", "save the source package or copy the referenced graphs together"))?; + if let Some((_, source)) = clipboard.source.graph_by_name(&instance.graph) { + instance.graph = source.sbs_path(); + } + } + } + for node in graph.nodes.iter_mut().filter(|node| node.def == "graph_instance" && node.instance.is_none()) { + if let Some(GraphValue::Text(name)) = node.params.get_mut("graph") { + if let Some(new) = names.get(name) { + *name = new.clone(); + } else if clipboard.document != session.document_id { + let package = + clipboard.path.clone().ok_or_else(|| bad("explorer.paste", "save the source package or copy the referenced graphs together"))?; + node.instance = Some(materialcraft_core::GraphInstance { + label: String::new(), + package, + graph: name.clone(), + inputs: Vec::new(), + outputs: Vec::new(), + defaults: Default::default(), + }); + } + } + } + } + for resource in &mut incoming.resources { + if let Some(folder) = folder_names.get(&resource.folder) { + resource.folder = folder.clone(); + } else if clipboard.graph.is_none() && resource.folder.is_empty() { + resource.folder = parent.into(); + } + } + transfer_resources( + &mut incoming, + &destination, + clipboard.graph.is_none() && clipboard.folder.is_none(), + clipboard.folder.as_deref().and_then(|path| folder_names.get(path)).map(String::as_str), + ); + let dependencies = incoming.dependencies.clone(); + let result = session.edit("Paste Explorer item", |session| { + let first = session.pkg.graphs.len(); + let count = incoming.graphs.len(); + session.pkg.graphs.extend(incoming.graphs); + session.pkg.folders.extend(incoming.folders); + session.pkg.resources.extend(incoming.resources); + if count > 0 { + session.graph = first; + session.open_material_preview(); + session.selection.clear(); + session.annotation_selection = None; + } + Ok(json!({"graph": (count > 0).then_some(first), "graphs": count})) + })?; + session.linked_sources.extend(dependencies); + session.refresh_links(); + Ok(result) +} + +fn transfer_resources(incoming: &mut Package, destination: &Package, all: bool, folder: Option<&str>) { + let used: BTreeSet<_> = incoming + .graphs + .iter() + .flat_map(|graph| { + graph.input_images.values().cloned().chain(graph.nodes.iter().filter_map(|node| match node.params.get("resource") { + Some(GraphValue::Text(name)) => Some(name.clone()), + _ => None, + })) + }) + .collect(); + incoming.resources.retain(|resource| all || used.contains(&resource.name) || folder.is_some_and(|folder| folder_path::contains(folder, &resource.folder))); + let mut occupied: BTreeSet<_> = destination.resources.iter().map(|resource| resource.name.clone()).collect(); + let occupied_paths: BTreeSet<_> = destination.folder_paths().into_iter().chain(destination.graphs.iter().map(|graph| graph.sbs_path())).collect(); + let mut names = BTreeMap::new(); + incoming.resources.retain_mut(|resource| { + if destination.resources.iter().any(|existing| existing == resource) { + return false; + } + + let original = resource.name.clone(); + let free = |name: &str| !occupied.contains(name) && !occupied_paths.contains(&folder_path::join(&resource.folder, name)); + if !free(&original) { + resource.name = (1..).map(|index| format!("{original}_{index}")).find(|name| free(name)).unwrap_or_else(|| original.clone()); + names.insert(original, resource.name.clone()); + } + occupied.insert(resource.name.clone()); + true + }); + for graph in &mut incoming.graphs { + for resource in graph.input_images.values_mut() { + if let Some(new) = names.get(resource) { + *resource = new.clone(); + } + } + for node in &mut graph.nodes { + if let Some(GraphValue::Text(name)) = node.params.get_mut("resource") + && let Some(new) = names.get(name) + { + *name = new.clone(); + } + } + } +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 0898ed4b..99480ae6 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -1,4 +1,5 @@ pub use crate::Exported; +pub use crate::linked_resource::reader as linked_files; use serde_json::{Value as J, json}; @@ -16,7 +17,7 @@ pub(crate) fn specs() -> Vec { "Graph...", ["File", "New"], Some("Ctrl+N"), - "{name?, kind? (material|function), template? (see graph.templates), size? (px, power of two)} adds a new graph to the package and opens it", + "{name?, folder?, kind? (material|function), template? (see graph.templates), size? (px, power of two)} adds a new graph to the package and opens it", always, new_graph ), @@ -71,16 +72,20 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result { let size = u64p(parameters, "size").unwrap_or(1024).clamp(16, 8192); let log2 = 63 - size.leading_zeros(); let base = strp(parameters, "name").map(str::to_string).unwrap_or_else(|| label.replace(' ', "_")); + let folder = strp(parameters, "folder").unwrap_or(""); + crate::folder_path::require(&session.pkg, folder)?; + let base = crate::folder_path::name(&base)?; session.edit("New graph", |session| { - let name = session.pkg.unique_graph_name(&base); - let graph = if kind == materialcraft_core::GraphKind::Function { + let name = crate::folder_path::unique(&session.pkg, folder, base); + let mut graph = if kind == materialcraft_core::GraphKind::Function { let mut graph = materialcraft_core::Graph::new(&name); graph.function = Some(materialcraft_core::FunctionGraph::default()); graph } else { template(template_id, &name, log2)? }; + graph.folder = folder.into(); session.pkg.graphs.push(graph); session.graph = session.pkg.graphs.len() - 1; session.open_material_preview(); @@ -149,10 +154,8 @@ pub fn open_bytes_linked(session: &mut Session, bytes: &[u8], name: Option Result> { save_bytes_at(session, session.path.as_deref()) } -fn save_bytes_at(session: &Session, path: Option<&str>) -> Result> { +pub(crate) fn save_bytes_at(session: &Session, path: Option<&str>) -> Result> { let mut package = session.pkg.clone(); if let Some(path) = path { + for resource in &mut package.resources { + if !resource.source.is_empty() { + resource.source = crate::document_path::relative(path, &resource.source); + } + } + for instance in package.graphs.iter_mut().flat_map(|graph| graph.instances_mut()) { if !instance.package.is_empty() { instance.package = crate::document_path::relative(path, &instance.package); @@ -178,36 +187,14 @@ fn save_bytes_at(session: &Session, path: Option<&str>) -> Result> { Ok(materialcraft_formats::sbs::write_sbs(&package)?) } -/// Largest file an SBS package may link to -#[cfg(not(target_arch = "wasm32"))] -const MAX_LINKED_FILE_BYTES: u64 = 256 << 20; - -/// Reads files an SBS package at `path` links to: plain relative paths that resolve inside its folder -#[cfg(not(target_arch = "wasm32"))] -pub fn linked_files(path: &str) -> impl Fn(&str) -> Option> + use<> { - let parent = std::path::Path::new(path).parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(std::path::Path::new(".")); - let folder = std::fs::canonicalize(parent).ok(); - - move |relative: &str| { - let relative = relative.trim().replace('\\', "/"); - let plain = !relative.is_empty() && !relative.contains(':') && !relative.starts_with('/'); - if !plain || std::path::Path::new(&relative).components().any(|c| !matches!(c, std::path::Component::Normal(_))) { - return None; - } - - let folder = folder.as_ref()?; - let file = std::fs::canonicalize(folder.join(&relative)).ok()?; - let metadata = std::fs::metadata(&file).ok()?; - if !file.starts_with(folder) || !metadata.is_file() || metadata.len() > MAX_LINKED_FILE_BYTES { - return None; - } - std::fs::read(file).ok() - } -} - /// Open the package file at `path` (native), with the bitmaps an SBS package keeps next to it #[cfg(not(target_arch = "wasm32"))] pub fn open_file(s: &mut Session, path: &str) -> Result<()> { + if path.starts_with("sbs://") { + let bytes = materialcraft_formats::sbs::library::read(path).map_err(|error| bad("file.open", error))?; + return open_bytes_linked(s, &bytes, Some(path.into()), &linked_files(path)); + } + let bytes = std::fs::read(path).map_err(|e| bad("file.open", format!("{path}: {e}")))?; open_bytes_linked(s, &bytes, Some(path.to_string()), &linked_files(path)) } @@ -221,8 +208,14 @@ fn open(s: &mut Session, p: &J) -> Result { } #[cfg(target_arch = "wasm32")] -fn open(_: &mut Session, _: &J) -> Result { - Err(bad("file.open", "the browser opens files with the file picker")) +fn open(session: &mut Session, parameters: &J) -> Result { + let path = strp(parameters, "path") + .filter(|path| path.starts_with("sbs://")) + .ok_or_else(|| bad("file.open", "the browser opens local files with the file picker"))?; + let bytes = materialcraft_formats::sbs::library::read(path).map_err(|error| bad("file.open", error))?; + open_bytes_linked(session, &bytes, Some(path.into()), &linked_files(path))?; + + Ok(json!({"name": session.pkg.name, "graphs": session.pkg.graphs.len(), "path": session.path, "warnings": session.load_warnings})) } #[cfg(not(target_arch = "wasm32"))] @@ -233,6 +226,10 @@ fn save(s: &mut Session, p: &J) -> Result { }; let path = crate::document_path::normalize(&path); + if path.contains("://") { + return Err(bad("file.save", "library aliases cannot be overwritten; save to a local .sbs path")); + } + if s.open_packages().into_iter().any(|entry| entry.0 != s.document_id && entry.2 == Some(path.as_str())) { return Err(bad("file.save", "another open package already uses this file")); } @@ -263,7 +260,9 @@ pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: O } let g = pkg.graph(gi)?; let dec = s.resource_decoder(); - let cooked = materialcraft_eval::cook(&pkg, gi, &materialcraft_eval::Options::new(&dec), &s.cache); + let mut options = materialcraft_eval::Options::new(&dec); + options.environment = s.environment; + let cooked = materialcraft_eval::cook(&pkg, gi, &options, &s.cache); let mut out = Vec::new(); let mut names = std::collections::HashSet::new(); for (id, usage, ident, img) in materialcraft_eval::outputs(g, &cooked) { diff --git a/crates/engine/src/folder_commands.rs b/crates/engine/src/folder_commands.rs new file mode 100644 index 00000000..0377cad6 --- /dev/null +++ b/crates/engine/src/folder_commands.rs @@ -0,0 +1,137 @@ +use crate::{ + Result, Session, cmd, + commands::{CommandSpec, always, bad, strp}, + folder_path, +}; +use serde_json::{Value, json}; + +pub(crate) fn specs() -> Vec { + vec![ + cmd!("folder.create", "New folder", [], None, "{parent?, name?} creates an empty folder", always, create), + cmd!("folder.rename", "Rename folder", [], None, "{folder, name} renames a folder and updates local graph references", always, rename), + cmd!("folder.remove", "Remove folder", [], None, "{folder} removes a folder and its contents, with undo", always, remove), + cmd!("explorer.move", "Move Explorer item", [], None, "{graph? index, folder?, parent?} moves a graph or folder within its package", always, move_item), + ] +} + +fn create(session: &mut Session, parameters: &Value) -> Result { + let parent = strp(parameters, "parent").unwrap_or(""); + folder_path::require(&session.pkg, parent)?; + let name = folder_path::name(strp(parameters, "name").unwrap_or("Untitled_Folder"))?; + let path = folder_path::join(parent, &folder_path::unique(&session.pkg, parent, name)); + folder_path::validate(&path)?; + session.edit("New folder", |session| { + session.pkg.folders.push(path.clone()); + Ok(json!({"folder": path})) + }) +} + +fn source<'a>(session: &Session, parameters: &'a Value) -> Result<&'a str> { + let path = strp(parameters, "folder").filter(|path| !path.is_empty()).ok_or_else(|| bad("folder", "folder is required"))?; + folder_path::require(&session.pkg, path)?; + Ok(path) +} + +fn rename(session: &mut Session, parameters: &Value) -> Result { + let old = source(session, parameters)?; + let name = folder_path::name(strp(parameters, "name").ok_or_else(|| bad("folder.rename", "name is required"))?)?; + let parent = old.rsplit_once('/').map_or("", |(parent, _)| parent); + relocate_folder(session, old, &folder_path::join(parent, name)) +} + +fn relocate_folder(session: &mut Session, old: &str, new: &str) -> Result { + folder_path::validate(new)?; + if old == new { + return Ok(json!({"folder": new})); + } + if folder_path::contains(old, new) + || session.pkg.folder_paths().contains(new) + || session.pkg.graphs.iter().any(|graph| graph.sbs_path() == new) + || session.pkg.resources.iter().any(|resource| resource.sbs_path() == new) + { + return Err(bad("folder", "the destination already exists or is inside the source folder")); + } + + let replace = |path: &str| format!("{new}{}", path.strip_prefix(old).unwrap_or("")); + let folders = session.pkg.folder_paths().into_iter().map(|path| if folder_path::contains(old, &path) { replace(&path) } else { path }).collect::>(); + for folder in &folders { + folder_path::validate(folder)?; + } + let paths = session + .pkg + .graphs + .iter() + .filter(|graph| folder_path::contains(old, &graph.folder)) + .map(|graph| (graph.sbs_path(), folder_path::join(&replace(&graph.folder), &graph.name))) + .collect(); + let names = crate::graph_references::with_leaf_names(&session.pkg, &paths); + session.edit("Move or rename folder", |session| { + for graph in &mut session.pkg.graphs { + if folder_path::contains(old, &graph.folder) { + graph.folder = replace(&graph.folder); + } + } + session.pkg.folders = folders; + for resource in &mut session.pkg.resources { + if folder_path::contains(old, &resource.folder) { + resource.folder = replace(&resource.folder); + } + } + crate::graph_references::remap(&mut session.pkg, &names); + Ok(json!({"folder": new})) + }) +} + +fn remove(session: &mut Session, parameters: &Value) -> Result { + let folder = source(session, parameters)?; + session.edit("Remove folder", |session| { + session.pkg.folders = session.pkg.folder_paths().into_iter().filter(|path| !folder_path::contains(folder, path)).collect(); + let indices: Vec<_> = + session.pkg.graphs.iter().enumerate().filter(|(_, graph)| folder_path::contains(folder, &graph.folder)).map(|(index, _)| index).collect(); + for index in indices.into_iter().rev() { + session.pkg.graphs.remove(index); + session.material_preview.remove_graph(index); + if index < session.graph { + session.graph -= 1; + } + } + session.pkg.resources.retain(|resource| !folder_path::contains(folder, &resource.folder)); + session.graph = session.graph.min(session.pkg.graphs.len().saturating_sub(1)); + session.selection.clear(); + session.annotation_selection = None; + session.view2d.node = None; + session.clear_preview_results(); + Ok(Value::Null) + }) +} + +fn move_item(session: &mut Session, parameters: &Value) -> Result { + let parent = strp(parameters, "parent").unwrap_or(""); + folder_path::require(&session.pkg, parent)?; + if let Some(index) = parameters.get("graph").and_then(Value::as_u64).and_then(|index| usize::try_from(index).ok()) { + let graph = session.pkg.graph(index)?; + let new = folder_path::join(parent, &graph.name); + if graph.folder == parent { + return Ok(json!({"graph": index})); + } + if session.pkg.graphs.iter().any(|graph| graph.sbs_path() == new) + || session.pkg.folder_paths().contains(&new) + || session.pkg.resources.iter().any(|resource| resource.sbs_path() == new) + { + return Err(bad("explorer.move", "the destination already contains an item with this name")); + } + + let paths = [(graph.sbs_path(), new)].into(); + let names = crate::graph_references::with_leaf_names(&session.pkg, &paths); + return session.edit("Move graph", |session| { + session.pkg.folders = session.pkg.folder_paths().into_iter().collect(); + session.pkg.graph_mut(index)?.folder = parent.into(); + crate::graph_references::remap(&mut session.pkg, &names); + Ok(json!({"graph": index})) + }); + } + + let old = source(session, parameters)?; + let name = old.rsplit('/').next().unwrap_or(old); + relocate_folder(session, old, &folder_path::join(parent, name)) +} diff --git a/crates/engine/src/folder_path.rs b/crates/engine/src/folder_path.rs new file mode 100644 index 00000000..673c71ba --- /dev/null +++ b/crates/engine/src/folder_path.rs @@ -0,0 +1,63 @@ +use crate::{Result, commands::bad}; +use materialcraft_core::Package; + +pub(crate) fn name(value: &str) -> Result<&str> { + let value = value.trim(); + if value.is_empty() || value.len() > 256 || matches!(value, "." | "..") || value.contains(['/', '\\']) || value.chars().any(char::is_control) { + return Err(bad("explorer", "names must be nonempty, at most 256 bytes, and contain no path separators or control characters")); + } + Ok(value) +} + +pub(crate) fn validate(path: &str) -> Result<()> { + if path.len() > 4096 || path.split('/').count() > 64 { + return Err(bad("explorer", "folder paths must be at most 4096 bytes and 64 levels deep")); + } + if !path.is_empty() { + for component in path.split('/') { + if name(component)? != component { + return Err(bad("explorer", "folder names cannot start or end with whitespace")); + } + } + } + Ok(()) +} + +pub(crate) fn require(package: &Package, path: &str) -> Result<()> { + validate(path)?; + if !path.is_empty() && !package.folder_paths().contains(path) { + return Err(bad("explorer", format!("no folder `{path}`"))); + } + Ok(()) +} + +pub(crate) fn join(parent: &str, name: &str) -> String { + if parent.is_empty() { name.into() } else { format!("{parent}/{name}") } +} + +pub(crate) fn contains(parent: &str, path: &str) -> bool { + path == parent || path.strip_prefix(parent).is_some_and(|suffix| suffix.starts_with('/')) +} + +pub(crate) fn unique(package: &Package, parent: &str, base: &str) -> String { + let occupied = package.folder_paths(); + let free = |name: &str| { + !occupied.contains(&join(parent, name)) + && !package.graphs.iter().any(|graph| graph.folder == parent && graph.name == name) + && !package.resources.iter().any(|resource| resource.folder == parent && resource.name == name) + }; + if free(base) { + return base.to_string(); + } + + let numbered = base.rsplit_once('_').and_then(|(stem, number)| number.parse::().ok().map(|number| (stem, number))); + // One more candidate than occupied items guarantees a free name without an unbounded search + let attempts = occupied.len().saturating_add(package.graphs.len()).saturating_add(package.resources.len()).saturating_add(1); + (1..=attempts) + .map(|index| match numbered.and_then(|(stem, number)| number.checked_add(index as u64).map(|next| (stem, next))) { + Some((stem, next)) => format!("{stem}_{next}"), + None => format!("{base}_{index}"), + }) + .find(|candidate| free(candidate)) + .unwrap_or_else(|| base.to_string()) +} diff --git a/crates/engine/src/function_edit.rs b/crates/engine/src/function_edit.rs index e1716e78..abd03406 100644 --- a/crates/engine/src/function_edit.rs +++ b/crates/engine/src/function_edit.rs @@ -42,6 +42,8 @@ impl FunctionEdit { let definition = materialcraft_nodes::function::definition(operation).ok_or("unknown function operation")?; let id = graph.next_id(); graph.nodes.push(FunctionNode { + missing: None, + missing_data: String::new(), instance: None, source: None, id, @@ -84,7 +86,7 @@ impl FunctionEdit { } Self::Value { id, value } => { let node = graph.nodes.iter_mut().find(|node| node.id == *id).ok_or("missing function node")?; - if node.value.is_none() { + if node.value.is_none() || node.missing.is_some() { return Err("the operation has no editable value".into()); } diff --git a/crates/engine/src/function_graph_target.rs b/crates/engine/src/function_graph_target.rs index 883355ad..5e7f8c1f 100644 --- a/crates/engine/src/function_graph_target.rs +++ b/crates/engine/src/function_graph_target.rs @@ -23,6 +23,10 @@ pub enum FunctionGraphTarget { } impl FunctionGraphTarget { + pub fn variables(&self, session: &Session, id: u32) -> Result> { + crate::function_variables::suggestions(self, session, id) + } + pub fn available_operations(&self, session: &Session) -> impl Iterator + use<> { let value_processor = matches!(self, Self::Parameter { node, parameter } if parameter == "function" && session.graph().ok().and_then(|graph| graph.node(*node).ok()).is_some_and(|node| node.def == "value_processor")); diff --git a/crates/engine/src/function_library.rs b/crates/engine/src/function_library.rs new file mode 100644 index 00000000..ad55a8b1 --- /dev/null +++ b/crates/engine/src/function_library.rs @@ -0,0 +1,21 @@ +use materialcraft_core::Package; +use std::{collections::BTreeMap, sync::Arc}; + +pub(crate) const STANDARD_PACKAGE: &str = "sbs://functions.sbs"; + +pub(crate) struct FunctionLibrary { + pub packages: BTreeMap>, + pub warnings: Vec, +} + +pub(crate) fn load() -> Result { + let bytes = materialcraft_formats::sbs::library::read(STANDARD_PACKAGE)?; + let mut read = + materialcraft_formats::sbs::read_sbs(&bytes, STANDARD_PACKAGE, &crate::file_cmds::linked_files(STANDARD_PACKAGE)).map_err(|error| error.to_string())?; + crate::linked_files::normalize_references(&mut read.pkg, STANDARD_PACKAGE); + read.warnings.extend(crate::linked_files::load(&mut read.pkg)); + + let mut packages = std::mem::take(&mut read.pkg.dependencies); + packages.insert(STANDARD_PACKAGE.into(), Arc::new(read.pkg)); + Ok(FunctionLibrary { packages, warnings: read.warnings }) +} diff --git a/crates/engine/src/function_library_commands.rs b/crates/engine/src/function_library_commands.rs new file mode 100644 index 00000000..785db1e9 --- /dev/null +++ b/crates/engine/src/function_library_commands.rs @@ -0,0 +1,62 @@ +use crate::{ + Result, Session, cmd, + commands::{CommandSpec, always, strp}, +}; +use serde_json::{Value, json}; + +pub(crate) fn specs() -> Vec { + vec![ + cmd!("library.functions", "List library functions", [], None, "{filter?} lists reusable SBS functions with source paths and interfaces", always, list), + cmd!( + "library.function.add", + "Add library function", + [], + None, + "{graph, package? (sbs://functions.sbs), function?: FunctionGraphTarget, at?, snapToGrid?} adds a function instance to the active Function or processor canvas", + crate::commands::has_graph, + add + ), + ] +} + +fn list(session: &mut Session, parameters: &Value) -> Result { + let filter = strp(parameters, "filter").unwrap_or("").to_lowercase(); + let mut entries = Vec::new(); + for (path, package) in &session.pkg.dependencies { + if !path.starts_with("sbs://") { + continue; + } + + for graph in &package.graphs { + let Some(function) = &graph.function else { continue }; + let identifier = graph.sbs_path(); + if !filter.is_empty() && !identifier.to_lowercase().contains(&filter) && !graph.display_name().to_lowercase().contains(&filter) { + continue; + } + + let ports = materialcraft_nodes::function::graph_ports(graph); + let error = ports.as_ref().err().cloned(); + let (inputs, outputs) = ports.unwrap_or_default(); + let category = if graph.attributes.category.is_empty() { &graph.folder } else { &graph.attributes.category }; + entries.push(json!({"package": path, "graph": identifier, "label": graph.display_name(), + "category": category, "description": graph.attributes.description, + "inputs": inputs, "outputs": outputs, "error": error, + "missing": function.output.is_none() || function.nodes.iter().any(|node| node.missing.is_some())})); + } + } + Ok(json!(entries)) +} + +fn add(session: &mut Session, parameters: &Value) -> Result { + let mut parameters = parameters.clone(); + let object = parameters.as_object_mut().ok_or_else(|| crate::commands::bad("library.function.add", "expected an object"))?; + object.entry("package").or_insert_with(|| json!(crate::function_library::STANDARD_PACKAGE)); + + let package = strp(¶meters, "package").and_then(|path| session.pkg.dependencies.get(path)); + let graph = strp(¶meters, "graph").and_then(|name| package?.graph_by_name(name)); + if graph.is_none_or(|(_, graph)| graph.function.is_none()) { + return Err(crate::commands::bad("library.function.add", "the library function is unavailable")); + } + + crate::graph_instance_commands::add(session, ¶meters) +} diff --git a/crates/engine/src/function_variable.rs b/crates/engine/src/function_variable.rs new file mode 100644 index 00000000..4d508991 --- /dev/null +++ b/crates/engine/src/function_variable.rs @@ -0,0 +1,10 @@ +use materialcraft_core::ValueType; +use serde::Serialize; + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FunctionVariable { + pub name: String, + pub value_type: ValueType, + pub system: bool, +} diff --git a/crates/engine/src/function_variable_commands.rs b/crates/engine/src/function_variable_commands.rs new file mode 100644 index 00000000..4c007536 --- /dev/null +++ b/crates/engine/src/function_variable_commands.rs @@ -0,0 +1,25 @@ +use crate::{ + FunctionGraphTarget, Result, Session, cmd, + commands::{CommandSpec, bad, has_graph}, +}; +use serde_json::{Value as Json, json}; + +pub(crate) fn specs() -> Vec { + vec![cmd!( + "graph.function.variables", + "List function variables", + [], + None, + "{id, target?: FunctionGraphTarget} lists variable suggestions matching the selected Get node's type and caller context", + has_graph, + variables + )] +} + +fn variables(session: &mut Session, parameters: &Json) -> Result { + let command = "graph.function.variables"; + let target: FunctionGraphTarget = serde_json::from_value(parameters.get("target").cloned().unwrap_or_else(|| json!({"kind": "graph"}))) + .map_err(|error| bad(command, error.to_string()))?; + let id = parameters.get("id").and_then(Json::as_u64).and_then(|id| u32::try_from(id).ok()).ok_or_else(|| bad(command, "id must be a function node id"))?; + Ok(json!({"variables": target.variables(session, id)?})) +} diff --git a/crates/engine/src/function_variables.rs b/crates/engine/src/function_variables.rs new file mode 100644 index 00000000..676f607b --- /dev/null +++ b/crates/engine/src/function_variables.rs @@ -0,0 +1,72 @@ +use std::collections::BTreeMap; + +use materialcraft_core::{Value, ValueType}; +use materialcraft_nodes::function::{FunctionScope, SystemVariable, node_types}; + +use crate::{FunctionGraphTarget, FunctionVariable, Result, Session, commands::bad}; + +fn variable_scope(target: &FunctionGraphTarget, session: &Session) -> FunctionScope { + match target { + FunctionGraphTarget::Pattern { .. } => FunctionScope::FxMap, + FunctionGraphTarget::Parameter { node, parameter } + if parameter == "function" && session.graph().ok().and_then(|graph| graph.node(*node).ok()).is_some_and(|node| node.def == "pixel_processor") => + { + FunctionScope::PixelProcessor + } + _ => FunctionScope::Node, + } +} + +/// Suggestions preserve typed names, even while a graph is being assembled. +pub(crate) fn suggestions(target: &FunctionGraphTarget, session: &Session, id: u32) -> Result> { + let command = "graph.function.variables"; + let function = target.current(session)?; + let node = function.node(id).ok_or_else(|| bad(command, "missing function node"))?; + if !node.op.starts_with("get_") && node.op != "isdefined" { + return Err(bad(command, "select a Get or Is Defined node")); + } + + let types = node_types(function).map_err(|error| bad(command, error))?; + let expected = (node.op != "isdefined").then(|| types.get(&id).and_then(|code| ValueType::from_code(*code))).flatten(); + let scope = variable_scope(target, session); + let mut variables: Vec<_> = SystemVariable::ALL + .into_iter() + .filter(|variable| variable.available_in(scope) && expected.is_none_or(|expected| expected == variable.value_type())) + .map(|variable| FunctionVariable { name: variable.name().into(), value_type: variable.value_type(), system: true }) + .collect(); + + let document = session.graph()?; + let mut custom = BTreeMap::new(); + for input in &document.exposed { + if let Some(value_type) = ValueType::of(&input.default) { + custom.insert(input.id.clone(), value_type); + } + } + + let owner = match target { + FunctionGraphTarget::Parameter { node, .. } | FunctionGraphTarget::Dynamic { node, .. } => Some(*node), + FunctionGraphTarget::Pattern { owner, .. } => Some(*owner), + FunctionGraphTarget::Graph => None, + }; + if let Some(owner) = owner { + custom.extend(document.node(owner)?.input_values.iter().map(|(name, value_type)| (name.clone(), *value_type))); + } + + for candidate in &function.nodes { + if (candidate.op.starts_with("get_") || candidate.op == "set") + && let Some(Value::Text(name)) = &candidate.value + && let Some(value_type) = types.get(&candidate.id).and_then(|code| ValueType::from_code(*code)) + && expected.is_none_or(|expected| expected == value_type) + { + custom.entry(name.clone()).or_insert(value_type); + } + } + + variables.extend( + custom + .into_iter() + .filter(|(name, value_type)| !name.is_empty() && SystemVariable::named(name).is_none() && expected.is_none_or(|expected| expected == *value_type)) + .map(|(name, value_type)| FunctionVariable { name, value_type, system: false }), + ); + Ok(variables) +} diff --git a/crates/engine/src/graph_cmds.rs b/crates/engine/src/graph_cmds.rs index 975bdae8..f6dcdd42 100644 --- a/crates/engine/src/graph_cmds.rs +++ b/crates/engine/src/graph_cmds.rs @@ -10,20 +10,26 @@ use crate::{Result, Session, cmd}; pub(crate) fn specs() -> Vec { vec![ cmd!("graph.open", "Open graph", [], None, "{graph: index or name}", always, open), - cmd!("graph.rename", "Rename graph", [], None, "{name, graph?}", has_graph, rename), cmd!("graph.delete", "Delete graph", [], None, "{graph?}", has_graph, delete), cmd!("graph.duplicate", "Duplicate graph", [], None, "{graph?}", has_graph, duplicate), - cmd!("graph.size", "Graph size", [], None, "{width, height} in pixels (powers of two, 16..8192) or {log2: [w, h]}", has_graph, size), - cmd!("graph.seed", "Random seed", [], None, "{seed}", has_graph, |s, p| { + cmd!("graph.size", "Graph size", [], None, "{graph?, document?, width, height} in pixels (powers of two, 16..8192) or {log2: [w, h]}", always, size), + cmd!("graph.seed", "Random seed", [], None, "{seed, graph?, document?}", always, |s, p| { let seed = i64p(p, "seed").ok_or_else(|| bad("graph.seed", "`seed` is required"))?.clamp(0, i32::MAX as i64) as i32; - s.edit_merged("graph.seed", "Random seed", |s| { - s.graph_mut()?.seed = seed; + let target = crate::GraphTarget::resolve(s, p)?; + if target.document != s.document_id { + return target.edit(s, "Random seed", |package| { + package.graph_mut(target.graph)?.seed = seed; + Ok(J::Null) + }); + } + + s.edit_merged(&format!("graph.seed:{}:{}", target.document, target.graph), "Random seed", |s| { + s.pkg.graph_mut(target.graph)?.seed = seed; Ok(J::Null) }) }), - cmd!("graph.format", "Output format", [], None, "{format: u8|u16|f16|f32}", has_graph, format), + cmd!("graph.format", "Output format", [], None, "{format: u8|u16|f16|f32, graph?, document?}", always, format), cmd!("graph.cook", "Compute graph", [], None, "{full?: bool} cooks now; returns per-node timings and errors", has_graph, cook), - cmd!("graph.attributes", "Graph attributes", [], None, "{category?, description?, author?, tags?}", has_graph, attributes), cmd!("graph.pin.add", "Add Navigation pin", [], None, "{name?, at? [x, y]}", has_graph, pin_add), cmd!("graph.pin.delete", "Delete pin", [], None, "{id}", has_graph, pin_delete), cmd!( @@ -86,34 +92,10 @@ fn open(s: &mut Session, p: &J) -> Result { Ok(json!({"graph": i, "name": s.pkg.graphs.get(i).map(|g| g.name.clone())})) } -fn rename(s: &mut Session, p: &J) -> Result { - let i = graph_index(s, p)?; - let name = strp(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("graph.rename", "`name` is required"))?.to_string(); - if s.pkg.graphs.iter().enumerate().any(|(j, g)| j != i && g.name == name) { - return Err(bad("graph.rename", format!("a graph is already called `{name}`"))); - } - s.edit("Rename graph", |s| { - let old = std::mem::replace(&mut s.pkg.graph_mut(i)?.name, name.clone()); - // Instances follow the rename - for g in &mut s.pkg.graphs { - for instance in g.instances_mut() { - if instance.package.is_empty() && instance.graph == old { - instance.graph = name.clone(); - } - } - for n in g.nodes.iter_mut().filter(|n| n.def == "graph_instance") { - if n.params.get("graph") == Some(&Value::Text(old.clone())) { - n.params.insert("graph".into(), Value::Text(name.clone())); - } - } - } - Ok(json!({"name": name})) - }) -} - fn delete(s: &mut Session, p: &J) -> Result { let i = graph_index(s, p)?; s.edit("Delete graph", |s| { + s.pkg.folders = s.pkg.folder_paths().into_iter().collect(); s.pkg.graphs.remove(i); if i < s.graph { s.graph -= 1; @@ -145,6 +127,7 @@ fn duplicate(s: &mut Session, p: &J) -> Result { } fn size(s: &mut Session, p: &J) -> Result { + let target = crate::GraphTarget::resolve(s, p)?; let log = |px: u64| 63 - px.clamp(1, 1 << 20).leading_zeros(); let (w, h) = if let Some(a) = p.get("log2").and_then(J::as_array) { (a.first().and_then(J::as_u64).unwrap_or(10) as u32, a.get(1).and_then(J::as_u64).unwrap_or(10) as u32) @@ -154,13 +137,14 @@ fn size(s: &mut Session, p: &J) -> Result { }; let (w, h) = (w.clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2), h.clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2)); - s.edit("Graph size", |s| { - s.graph_mut()?.size = [w, h]; + target.edit(s, "Graph size", |package| { + package.graph_mut(target.graph)?.size = [w, h]; Ok(json!({"width": 1u32 << w, "height": 1u32 << h})) }) } fn format(s: &mut Session, p: &J) -> Result { + let target = crate::GraphTarget::resolve(s, p)?; let f = match strp(p, "format") { Some("u8" | "8") => OutputFormat::U8, Some("u16" | "16") => OutputFormat::U16, @@ -169,8 +153,8 @@ fn format(s: &mut Session, p: &J) -> Result { _ => return Err(bad("graph.format", "`format` is u8, u16, f16 or f32")), }; - s.edit("Output format", |s| { - s.graph_mut()?.format = f; + target.edit(s, "Output format", |package| { + package.graph_mut(target.graph)?.format = f; Ok(J::Null) }) } @@ -188,18 +172,6 @@ fn cook(s: &mut Session, p: &J) -> Result { })) } -fn attributes(s: &mut Session, p: &J) -> Result { - s.edit("Graph attributes", |s| { - let a = &mut s.graph_mut()?.attributes; - for (k, slot) in [("category", &mut a.category), ("description", &mut a.description), ("author", &mut a.author), ("tags", &mut a.tags)] { - if let Some(v) = strp(p, k) { - *slot = v.into(); - } - } - Ok(J::Null) - }) -} - /// Graph-space bounding rect of nodes `ids` (node cards are about 96×110) pub fn nodes_rect(s: &Session, ids: &[NodeId]) -> Option<[f32; 4]> { let g = s.graph().ok()?; diff --git a/crates/engine/src/graph_instance_commands.rs b/crates/engine/src/graph_instance_commands.rs index 20a3f54f..5614fb8c 100644 --- a/crates/engine/src/graph_instance_commands.rs +++ b/crates/engine/src/graph_instance_commands.rs @@ -65,7 +65,7 @@ fn reaches( false } -fn add(session: &mut Session, parameters: &Value) -> Result { +pub(crate) fn add(session: &mut Session, parameters: &Value) -> Result { if parameters.get("pattern").is_some() { return Err(bad(COMMAND, "FX-Map graphs do not accept graph instances")); } @@ -79,10 +79,20 @@ fn add(session: &mut Session, parameters: &Value) -> Result { if let Some(target) = &target { target.current(session)?; } - let document = u64p(parameters, "document").ok_or_else(|| bad(COMMAND, "document is required"))?; let name = strp(parameters, "graph").ok_or_else(|| bad(COMMAND, "graph is required"))?; let packages = session.open_packages(); - let (_, source, path, _) = packages.iter().find(|entry| entry.0 == document).copied().ok_or_else(|| bad(COMMAND, "the source package is not open"))?; + let document = u64p(parameters, "document"); + let (source, path) = if let Some(path) = strp(parameters, "package") { + if !path.starts_with("sbs://") { + return Err(bad(COMMAND, "library instances require an sbs:// package")); + } + + (session.pkg.dependencies.get(path).map(AsRef::as_ref).ok_or_else(|| bad(COMMAND, "the library package is missing"))?, Some(path)) + } else { + let document = document.ok_or_else(|| bad(COMMAND, "document is required"))?; + let (_, source, path, _) = packages.iter().find(|entry| entry.0 == document).copied().ok_or_else(|| bad(COMMAND, "the source package is not open"))?; + (source, path) + }; let (_, graph) = source.graph_by_name(name).ok_or_else(|| bad(COMMAND, "the source graph no longer exists"))?; if graph.function.is_some() != target.is_some() { return Err(bad(COMMAND, "Function instances require a Function canvas; main instances require a main graph")); @@ -100,17 +110,18 @@ fn add(session: &mut Session, parameters: &Value) -> Result { return Err(bad(COMMAND, "source connector identifiers must be unique")); } } - let file = if document == session.document_id { + let file = if document == Some(session.document_id) && parameters.get("package").is_none() { "" } else { path.ok_or_else(|| bad(COMMAND, "save the source SBS file before instancing its graph in another package"))? }; - let source_file = path.map(str::to_string).unwrap_or_else(|| format!("unsaved:{document}")); + let source_file = path.map(str::to_string).unwrap_or_else(|| format!("unsaved:{}", document.unwrap_or(session.document_id))); let target_file = session.path.clone().unwrap_or_else(|| format!("unsaved:{}", session.document_id)); - if reaches(source, &source_file, name, &target_file, &session.graph()?.name, &session.pkg.dependencies) { + if reaches(source, &source_file, &graph.sbs_path(), &target_file, &session.graph()?.sbs_path(), &session.pkg.dependencies) { return Err(bad(COMMAND, "the instance would create a graph dependency cycle")); } - let instance = GraphInstance { package: file.into(), graph: name.into(), inputs, outputs }; + let instance = + GraphInstance { label: graph.display_name().into(), defaults: Default::default(), package: file.into(), graph: graph.sbs_path(), inputs, outputs }; let at = crate::graph_grid::snap_position(point(parameters, "at").unwrap_or([0.0; 2]), parameters.get("snapToGrid").and_then(Value::as_bool).unwrap_or(false)); session.edit("Add graph instance", |session| { @@ -122,6 +133,8 @@ fn add(session: &mut Session, parameters: &Value) -> Result { let id = function.next_id(); function.nodes.push(materialcraft_core::FunctionNode { id, + missing: None, + missing_data: String::new(), op: "instance".into(), type_code: instance.outputs.first().map_or(0, |port| port.type_code), inputs: vec![None; instance.inputs.len()], diff --git a/crates/engine/src/graph_property_commands.rs b/crates/engine/src/graph_property_commands.rs new file mode 100644 index 00000000..018d417d --- /dev/null +++ b/crates/engine/src/graph_property_commands.rs @@ -0,0 +1,72 @@ +use crate::{ + GraphTarget, Result, Session, cmd, + commands::{CommandSpec, always, bad, strp}, +}; +use serde_json::{Value, json}; + +pub(crate) fn specs() -> Vec { + vec![ + cmd!("graph.rename", "Rename graph", [], None, "{name, graph?, document?}", always, rename), + cmd!("graph.properties", "Inspect graph properties", [], None, "{graph?, document?}", always, |session, parameters| { + let target = GraphTarget::resolve(session, parameters)?; + let graph = target.get(session)?; + Ok(json!({"document": target.document, "graph": target.graph, "identifier": graph.name, "attributes": graph.attributes})) + }), + cmd!( + "graph.attributes", + "Graph attributes", + [], + None, + "{graph?, document?, label?, category?, description?, author?, authorUrl?, tags?, group?, userData?}", + always, + attributes + ), + ] +} + +fn attributes(session: &mut Session, parameters: &Value) -> Result { + let target = GraphTarget::resolve(session, parameters)?; + target.edit(session, "Graph attributes", |package| { + let attributes = &mut package.graph_mut(target.graph)?.attributes; + for (key, slot) in [ + ("label", &mut attributes.label), + ("category", &mut attributes.category), + ("description", &mut attributes.description), + ("author", &mut attributes.author), + ("authorUrl", &mut attributes.author_url), + ("tags", &mut attributes.tags), + ("group", &mut attributes.group), + ("userData", &mut attributes.user_data), + ] { + if let Some(value) = parameters.get(key) { + *slot = value.as_str().ok_or_else(|| bad("graph.attributes", format!("`{key}` must be text")))?.into(); + } + } + Ok(Value::Null) + }) +} + +fn rename(session: &mut Session, parameters: &Value) -> Result { + let target = GraphTarget::resolve(session, parameters)?; + let index = target.graph; + let package = target.package(session)?; + let name = strp(parameters, "name").map(str::trim).filter(|name| !name.is_empty()).ok_or_else(|| bad("graph.rename", "`name` is required"))?.to_string(); + let source = package.graph(index)?; + if package.graphs.iter().enumerate().any(|(other, graph)| other != index && graph.folder == source.folder && graph.name == name) { + return Err(bad("graph.rename", format!("a graph is already called `{name}`"))); + } + + crate::folder_path::name(&name)?; + let new_path = crate::folder_path::join(&source.folder, &name); + if package.folder_paths().contains(&new_path) || package.resources.iter().any(|resource| resource.sbs_path() == new_path) { + return Err(bad("graph.rename", "a folder or resource already has that name")); + } + + let paths = [(source.sbs_path(), new_path)].into(); + let names = crate::graph_references::with_leaf_names(package, &paths); + target.edit(session, "Rename graph", |package| { + package.graph_mut(index)?.name = name.clone(); + crate::graph_references::remap(package, &names); + Ok(json!({"name": name})) + }) +} diff --git a/crates/engine/src/graph_references.rs b/crates/engine/src/graph_references.rs new file mode 100644 index 00000000..f95cea2a --- /dev/null +++ b/crates/engine/src/graph_references.rs @@ -0,0 +1,34 @@ +use materialcraft_core::{Package, Value}; +use std::collections::BTreeMap; + +pub(crate) fn with_leaf_names(package: &Package, paths: &BTreeMap) -> BTreeMap { + let mut names = paths.clone(); + for (old, new) in paths { + let leaf = old.rsplit('/').next().unwrap_or(old); + if package.graph_by_name(leaf).is_some_and(|(_, graph)| graph.sbs_path() == *old) { + names.entry(leaf.into()).or_insert_with(|| new.clone()); + } + } + names +} + +pub(crate) fn remap(package: &mut Package, names: &BTreeMap) { + for graph in &mut package.graphs { + for instance in graph.instances_mut() { + if instance.package.is_empty() + && let Some(new) = names.get(&instance.graph) + { + instance.graph = new.clone(); + } + } + for node in + graph.nodes.iter_mut().filter(|node| node.def == "graph_instance" && node.instance.as_ref().is_none_or(|instance| instance.package.is_empty())) + { + if let Some(Value::Text(old)) = node.params.get_mut("graph") + && let Some(new) = names.get(old) + { + *old = new.clone(); + } + } + } +} diff --git a/crates/engine/src/graph_target.rs b/crates/engine/src/graph_target.rs new file mode 100644 index 00000000..ef47fab4 --- /dev/null +++ b/crates/engine/src/graph_target.rs @@ -0,0 +1,56 @@ +use crate::{Result, Session, commands::bad}; +use materialcraft_core::{Graph, Package}; +use serde_json::Value; + +/// A graph being inspected, independent of the active canvas +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct GraphTarget { + pub document: u64, + pub graph: usize, +} + +impl GraphTarget { + pub fn active(session: &Session) -> Self { + Self { document: session.document_id, graph: session.graph } + } + + pub(crate) fn resolve(session: &Session, parameters: &Value) -> Result { + let document = match parameters.get("document") { + None | Some(Value::Null) => session.document_id, + Some(value) => value.as_u64().ok_or_else(|| bad("graph", "`document` must be an open document id"))?, + }; + let mut target = Self { document, graph: session.graph }; + let package = target.package(session)?; + target.graph = match parameters.get("graph") { + None | Some(Value::Null) if document == session.document_id => session.graph, + None | Some(Value::Null) => session.documents.get(&document).map_or(0, |document| document.graph), + Some(Value::String(name)) => package.graph_by_name(name).map(|(index, _)| index).ok_or_else(|| bad("graph", format!("no graph `{name}`")))?, + Some(value) => value.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad("graph", "`graph` must be an index or name"))?, + }; + target.get(session)?; + Ok(target) + } + + pub fn package(self, session: &Session) -> Result<&Package> { + if self.document == session.document_id { + return Ok(&session.pkg); + } + + session.documents.get(&self.document).map(|document| &document.pkg).ok_or_else(|| bad("graph", "the inspected package is no longer open")) + } + + pub fn get(self, session: &Session) -> Result<&Graph> { + Ok(self.package(session)?.graph(self.graph)?) + } + + pub(crate) fn edit(self, session: &mut Session, label: &str, edit: impl FnOnce(&mut Package) -> Result) -> Result { + if self.document == session.document_id { + return session.edit(label, |session| edit(&mut session.pkg)); + } + + let document = session.documents.get_mut(&self.document).ok_or_else(|| bad("graph", "the inspected package is no longer open"))?; + let result = document.edit(label, edit)?; + session.refresh_links(); + Ok(result) + } +} diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 4e489f01..9f4d272b 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -9,9 +9,10 @@ pub fn session(s: &Session, graph: Option) -> J { let g = s.pkg.graphs.get(gi); let cooked = (gi == s.graph).then_some(&s.cooked); let graph_json = g.map(|g| { - json!({ + let mut result = json!({ "index": gi, "name": g.name, + "path": g.sbs_path(), "kind": g.kind(), "function": g.function, "functionWarnings": crate::function_inspection::warnings(g).into_iter().map(|(target, messages)| json!({"target": target, "messages": messages})).collect::>(), @@ -54,12 +55,18 @@ pub fn session(s: &Session, graph: Option) -> J { "frames": g.frames, "comments": g.comments, "pins": g.pins, - }) + }); + result["physicalSize"] = json!(g.physical_size); + result["pixelRatio"] = json!(g.pixel_ratio); + result["pixelRatioMode"] = json!(g.pixel_ratio_mode); + result["tiling"] = json!(g.tiling); + result["tilingMode"] = json!(g.tiling_mode); + result }); json!({ "documents": s.inspect_documents(), - "package": {"name": s.pkg.name, "path": s.path, "modified": s.modified, "warnings": s.load_warnings, "resources": s.pkg.resources.iter().map(|r| json!({"name": r.name, "bytes": r.bytes.len()})).collect::>()}, - "graphs": s.pkg.graphs.iter().enumerate().map(|(i, g)| json!({"index": i, "name": g.name, "nodes": g.nodes.len(), "kind": g.kind()})).collect::>(), + "package": {"name": s.pkg.name, "path": s.path, "modified": s.modified, "folders": s.pkg.folder_paths(), "warnings": s.load_warnings, "resources": s.pkg.resources.iter().map(|r| json!({"name": r.name, "bytes": r.bytes.len()})).collect::>()}, + "graphs": s.pkg.graphs.iter().enumerate().map(|(i, g)| json!({"index": i, "name": g.name, "path": g.sbs_path(), "nodes": g.nodes.len(), "kind": g.kind()})).collect::>(), "openGraph": s.graph, "graph": graph_json, "annotationSelection": s.annotation_selection, @@ -75,6 +82,7 @@ pub fn session(s: &Session, graph: Option) -> J { }, "previewSize": s.preview_size, "camera": s.camera, + "environment": s.environment, "cookMs": s.cooked.ms, "dirty": s.dirty, "history": s.history(), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8b591f14..dfd2831c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -2,15 +2,30 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod document_path; +mod evaluation_environment_commands; +mod explorer_clipboard; +mod explorer_clipboard_commands; +mod folder_commands; +mod folder_path; +pub use explorer_clipboard::ExplorerClipboard; +mod function_library; +mod function_library_commands; +mod function_variable; +mod function_variable_commands; +mod function_variables; +pub use function_variable::FunctionVariable; mod graph_instance_commands; +mod graph_references; mod linked_files; mod linked_packages; +mod linked_resource; mod material_preview; mod material_preview_commands; mod material_source; mod node_info_commands; mod open_document; mod package_commands; +mod package_file_commands; mod preview_cook; pub use material_preview::MaterialPreview; pub use material_source::MaterialSource; @@ -28,6 +43,9 @@ pub mod commands; pub mod edit_cmds; pub mod file_cmds; pub mod graph_cmds; +mod graph_property_commands; +mod graph_target; +pub use graph_target::GraphTarget; pub mod graph_edit; pub mod graph_grid; pub mod inspect; diff --git a/crates/engine/src/linked_files.rs b/crates/engine/src/linked_files.rs index 4de4a65d..4c4417a4 100644 --- a/crates/engine/src/linked_files.rs +++ b/crates/engine/src/linked_files.rs @@ -2,6 +2,12 @@ use crate::document_path; use materialcraft_core::Package; pub(crate) fn normalize_references(package: &mut Package, path: &str) { + for resource in &mut package.resources { + if !resource.source.is_empty() { + resource.source = document_path::resolve(path, &resource.source); + } + } + for instance in package.graphs.iter_mut().flat_map(|graph| graph.instances_mut()) { if !instance.package.is_empty() { instance.package = document_path::resolve(path, &instance.package); @@ -31,7 +37,6 @@ impl crate::Session { } } -#[cfg(not(target_arch = "wasm32"))] pub(crate) fn load(package: &mut Package) -> Vec { use std::{collections::BTreeSet, sync::Arc}; let references = |package: &Package| { @@ -60,23 +65,40 @@ pub(crate) fn load(package: &mut Package) -> Vec { continue; } let mut read = || -> std::result::Result { - let size = std::fs::metadata(&path).map_err(|error| error.to_string())?.len(); - if size > remaining { - return Err("linked package exceeds the remaining file budget".into()); + if path.starts_with("sbs://") { + let bytes = materialcraft_formats::sbs::library::read(&path)?; + if bytes.len() as u64 > remaining { + return Err("linked package exceeds the remaining file budget".into()); + } + remaining -= bytes.len() as u64; + let read = materialcraft_formats::sbs::read_sbs(&bytes, &path, &crate::file_cmds::linked_files(&path)).map_err(|error| error.to_string())?; + warnings.extend(read.warnings); + return Ok(read.pkg); } - // Bound the read even if the file grows after the metadata check - use std::io::Read; - let mut bytes = Vec::new(); - std::fs::File::open(&path).map_err(|error| error.to_string())?.take(remaining + 1).read_to_end(&mut bytes).map_err(|error| error.to_string())?; - if bytes.len() as u64 > remaining { - return Err("linked package exceeds the remaining file budget".into()); + #[cfg(target_arch = "wasm32")] + return Err("external file is unavailable in the browser".into()); + #[cfg(not(target_arch = "wasm32"))] + { + let size = std::fs::metadata(&path).map_err(|error| error.to_string())?.len(); + if size > remaining { + return Err("linked package exceeds the remaining file budget".into()); + } + // Bound the read even if the file grows after the metadata check + use std::io::Read; + let mut bytes = Vec::new(); + std::fs::File::open(&path) + .map_err(|error| error.to_string())? + .take(remaining + 1) + .read_to_end(&mut bytes) + .map_err(|error| error.to_string())?; + if bytes.len() as u64 > remaining { + return Err("linked package exceeds the remaining file budget".into()); + } + remaining -= bytes.len() as u64; + let read = materialcraft_formats::sbs::read_sbs(&bytes, &path, &crate::file_cmds::linked_files(&path)).map_err(|error| error.to_string())?; + warnings.extend(read.warnings); + Ok(read.pkg) } - remaining -= bytes.len() as u64; - let read = materialcraft_formats::sbs::read_sbs(&bytes, &path, &crate::file_cmds::linked_files(&path)).map_err(|error| error.to_string())?; - if !read.warnings.is_empty() { - return Err(read.warnings.join("; ")); - } - Ok(read.pkg) }; match read() { Ok(mut source) => { diff --git a/crates/engine/src/linked_packages.rs b/crates/engine/src/linked_packages.rs index 23e676fe..01fad15e 100644 --- a/crates/engine/src/linked_packages.rs +++ b/crates/engine/src/linked_packages.rs @@ -38,7 +38,14 @@ fn interfaces(package: &mut Package, sources: &BTreeMap>) - return None; } let materialcraft_core::Value::Text(name) = node.params.get("graph")? else { return None }; - Some(GraphInstance { package: String::new(), graph: name.clone(), inputs: Vec::new(), outputs: Vec::new() }) + Some(GraphInstance { + label: String::new(), + defaults: Default::default(), + package: String::new(), + graph: name.clone(), + inputs: Vec::new(), + outputs: Vec::new(), + }) })?; let source = if instance.package.is_empty() { &*package } else { sources.get(&instance.package)?.as_ref() }; let (_, graph) = source.graph_by_name(&instance.graph)?; @@ -63,6 +70,7 @@ fn interfaces(package: &mut Package, sources: &BTreeMap>) - } instance.inputs = inputs; instance.outputs = outputs; + instance.label = graph.display_name().into(); (node.instance.as_ref() != Some(&instance)).then_some((graph_index, node_index, instance)) }) .collect(); diff --git a/crates/engine/src/linked_resource.rs b/crates/engine/src/linked_resource.rs new file mode 100644 index 00000000..5d0361a2 --- /dev/null +++ b/crates/engine/src/linked_resource.rs @@ -0,0 +1,45 @@ +/// Read resource paths relative to an SBS package, including portable library aliases. +pub fn reader(path: &str) -> impl Fn(&str) -> Option> + use<> { + let owner = path.to_string(); + #[cfg(not(target_arch = "wasm32"))] + let folder = { + let parent = std::path::Path::new(path).parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or(std::path::Path::new(".")); + std::fs::canonicalize(parent).ok() + }; + + move |reference: &str| { + if reference.starts_with("sbs://") { + return materialcraft_formats::sbs::library::read(reference).ok(); + } + + if owner.starts_with("sbs://") { + let uri = materialcraft_formats::sbs::library::resolve(&owner, reference).ok()?; + return materialcraft_formats::sbs::library::read(&uri).ok(); + } + + #[cfg(not(target_arch = "wasm32"))] + { + use std::io::Read; + const MAX_LINKED_FILE_BYTES: u64 = 256 << 20; + let relative = reference.trim().replace('\\', "/"); + let plain = !relative.is_empty() && !relative.contains(':') && !relative.starts_with('/'); + if !plain || std::path::Path::new(&relative).components().any(|part| !matches!(part, std::path::Component::Normal(_))) { + return None; + } + + let folder = folder.as_ref()?; + let file = std::fs::canonicalize(folder.join(&relative)).ok()?; + let metadata = std::fs::metadata(&file).ok()?; + if !file.starts_with(folder) || !metadata.is_file() || metadata.len() > MAX_LINKED_FILE_BYTES { + return None; + } + + // Bound the read even if a linked file grows after the metadata check + let mut bytes = Vec::new(); + std::fs::File::open(file).ok()?.take(MAX_LINKED_FILE_BYTES + 1).read_to_end(&mut bytes).ok()?; + (bytes.len() as u64 <= MAX_LINKED_FILE_BYTES).then_some(bytes) + } + #[cfg(target_arch = "wasm32")] + None + } +} diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index e4fb3f70..d262c674 100644 --- a/crates/engine/src/material_cmds.rs +++ b/crates/engine/src/material_cmds.rs @@ -66,6 +66,7 @@ pub fn material_bytes(s: &Session, gi: usize, o: &MaterialOptions) -> Result)> = Vec::new(); diff --git a/crates/engine/src/node_cmds.rs b/crates/engine/src/node_cmds.rs index fbc2af9e..66a590f1 100644 --- a/crates/engine/src/node_cmds.rs +++ b/crates/engine/src/node_cmds.rs @@ -2,7 +2,7 @@ use serde_json::{Value as J, json}; -use materialcraft_core::{FunctionGraph, NodeId, OutputFormat, SizeMode, Value, ValueType}; +use materialcraft_core::{NodeId, OutputFormat, SizeMode, Value, ValueType}; use crate::connection_commands::connection_input; use crate::graph_grid::snap_position; @@ -39,7 +39,7 @@ pub(crate) fn specs() -> Vec { "Set base parameters", [], None, - "{id?, sizeMode? (relativeToInput|relativeToParent|absolute), size? [w, h] (log2 offset, or log2 size when absolute), format? (inherit|u8|u16|f16|f32), seed?, tiling? bool}", + "{id?, sizeMode? (relativeToInput|relativeToParent|absolute), size? [w, h] (log2 offset, or log2 size when absolute), format? (inherit|u8|u16|f16|f32), seed?, tiling?: bool|[bool,bool], pixelRatio?: 0|1, tilingMode?, pixelRatioMode? (relativeToInput|relativeToParent|absolute)}", has_selection, base ), @@ -56,68 +56,69 @@ pub(crate) fn specs() -> Vec { ] } -fn add(s: &mut Session, p: &J) -> Result { - if s.graph()?.function.is_some() { +fn add(session: &mut Session, parameters: &J) -> Result { + if session.graph()?.function.is_some() { return Err(bad("graph.node.add", "use function operations in a Function Graph")); } - let def = strp(p, "def").ok_or_else(|| bad("graph.node.add", "`def` is required (see library.list)"))?.to_string(); - let catalog = materialcraft_nodes::find(&def); - if catalog.is_none() { - return Err(bad("graph.node.add", format!("unknown node `{def}`"))); - } + let definition = strp(parameters, "def").ok_or_else(|| bad("graph.node.add", "`def` is required (see library.list)"))?.to_string(); + let catalog = materialcraft_nodes::find(&definition).ok_or_else(|| bad("graph.node.add", format!("unknown node `{definition}`")))?; + // Typed parameter values, checked against the catalog - let mut params = Vec::new(); - if let Some(obj) = p.get("params").and_then(J::as_object) { - for (k, v) in obj { - let v = if def == "graph_instance" && k == "graph" { - Value::Text(v.as_str().ok_or_else(|| bad("graph.node.add", "`graph` is a graph name"))?.into()) - } else if def == "input_value" && k == "default" { - serde_json::from_value::(v.clone()) + let mut parameter_values = Vec::new(); + if let Some(values) = parameters.get("params").and_then(J::as_object) { + for (identifier, value) in values { + let value = if definition == "graph_instance" && identifier == "graph" { + Value::Text(value.as_str().ok_or_else(|| bad("graph.node.add", "`graph` is a graph name"))?.into()) + } else if definition == "input_value" && identifier == "default" { + serde_json::from_value::(value.clone()) .ok() - .or_else(|| Value::Float(0.0).coerce_json(v)) - .filter(|value| materialcraft_core::ValueType::of(value).is_some()) + .or_else(|| Value::Float(0.0).coerce_json(value)) + .filter(|value| ValueType::of(value).is_some()) .ok_or_else(|| bad("graph.node.add", "default must be a scalar or vector value"))? } else { - let pd = catalog.and_then(|d| d.param(k)).ok_or_else(|| bad("graph.node.add", format!("`{def}` has no parameter `{k}`")))?; - pd.default.coerce_json(v).ok_or_else(|| bad("graph.node.add", format!("`{k}` takes a {}", pd.default.type_name())))? + let parameter = catalog.param(identifier).ok_or_else(|| bad("graph.node.add", format!("`{definition}` has no parameter `{identifier}`")))?; + parameter + .default + .coerce_json(value) + .ok_or_else(|| bad("graph.node.add", format!("`{identifier}` takes a {}", parameter.default.type_name())))? }; - crate::graph_validation::value(&v).map_err(|error| bad("graph.node.add", error))?; - params.push((k.clone(), v)); + crate::graph_validation::value(&value).map_err(|error| bad("graph.node.add", error))?; + parameter_values.push((identifier.clone(), value)); } } - let from = p.get("connectFrom").and_then(|c| Some((NodeId(c.get("node")?.as_u64()?), c.get("port").and_then(J::as_str).unwrap_or("output").to_string()))); - let at = point(p, "at").unwrap_or_else(|| { - let g = s.graph().ok(); - let src = from.as_ref().and_then(|(n, _)| g.and_then(|g| g.node(*n).ok())); - src.map_or([0.0, 0.0], |n| [n.pos[0] + 150.0, n.pos[1]]) + + let source = parameters + .get("connectFrom") + .and_then(|connection| Some((NodeId(connection.get("node")?.as_u64()?), connection.get("port").and_then(J::as_str).unwrap_or("output").to_string()))); + let position = point(parameters, "at").unwrap_or_else(|| { + let graph = session.graph().ok(); + let source = source.as_ref().and_then(|(node, _)| graph.and_then(|graph| graph.node(*node).ok())); + source.map_or([0.0, 0.0], |node| [node.pos[0] + 150.0, node.pos[1]]) }); - let at = snap_position(at, boolp(p, "snapToGrid").unwrap_or(false)); - let label = strp(p, "label").unwrap_or("").to_string(); - s.edit("Add node", |s| { - let g = s.graph_mut()?; - let id = g.add_node(&def, at); - let n = g.node_mut(id)?; - n.label = label; - if let Some(parameter) = catalog.and_then(|definition| definition.param("pattern")) { - n.params.insert("pattern".into(), parameter.default.clone()); + let position = snap_position(position, boolp(parameters, "snapToGrid").unwrap_or(false)); + let label = strp(parameters, "label").unwrap_or("").to_string(); + + session.edit("Add node", |session| { + let graph = session.graph_mut()?; + let id = graph.add_node(&definition, position); + let node = graph.node_mut(id)?; + node.label = label; + if let Some(parameter) = catalog.param("pattern") { + node.params.insert("pattern".into(), parameter.default.clone()); } - if def == "value_processor" { - n.input_values.insert("value1".into(), ValueType::Float); - let mut function = FunctionGraph::default(); - function.output = Some(function.add("get_float1", &[], Some(Value::Text("value1".into())))); - n.params.insert("function".into(), Value::Function(Box::new(function))); + if definition == "value_processor" { + node.input_values.insert("value1".into(), ValueType::Float); } + node.params.extend(parameter_values); - n.params.extend(params); - - if let Some((src, port)) = from { - let first = connection_input(s, src, &port, id)?; - s.graph_mut()?.connect(src, &port, id, &first)?; + if let Some((source, port)) = source { + let input = connection_input(session, source, &port, id)?; + session.graph_mut()?.connect(source, &port, id, &input)?; } - s.selection = vec![id]; + session.selection = vec![id]; Ok(json!({"id": id.0})) }) } @@ -228,49 +229,82 @@ fn reset(s: &mut Session, p: &J) -> Result { }) } -fn base(s: &mut Session, p: &J) -> Result { - let id = node_param(s, "graph.node.base", p, "id")?; - let mode = match strp(p, "sizeMode") { +fn base(session: &mut Session, parameters: &J) -> Result { + let id = node_param(session, "graph.node.base", parameters, "id")?; + let mode = match strp(parameters, "sizeMode") { None => None, Some("relativeToInput") => Some(SizeMode::RelativeToInput), Some("relativeToParent") => Some(SizeMode::RelativeToParent), Some("absolute") => Some(SizeMode::Absolute), - Some(o) => return Err(bad("graph.node.base", format!("unknown sizeMode `{o}`"))), + Some(unknown) => return Err(bad("graph.node.base", format!("unknown sizeMode `{unknown}`"))), }; - let format = match strp(p, "format") { + let format = match strp(parameters, "format") { None => None, Some("inherit") => Some(OutputFormat::Inherit), Some("u8") => Some(OutputFormat::U8), Some("u16") => Some(OutputFormat::U16), Some("f16") => Some(OutputFormat::F16), Some("f32") => Some(OutputFormat::F32), - Some(o) => return Err(bad("graph.node.base", format!("unknown format `{o}`"))), + Some(unknown) => return Err(bad("graph.node.base", format!("unknown format `{unknown}`"))), }; - let size = p - .get("size") - .and_then(J::as_array) - .map(|a| [a.first().and_then(J::as_i64).unwrap_or(0).clamp(-12, 13) as i32, a.get(1).and_then(J::as_i64).unwrap_or(0).clamp(-12, 13) as i32]); - let seed = i64p(p, "seed").map(|v| v.clamp(0, i32::MAX as i64) as i32); - let tiling = boolp(p, "tiling"); - s.edit_merged(&format!("base:{}", id.0), "Set base parameters", |s| { - let b = &mut s.graph_mut()?.node_mut(id)?.base; - if let Some(m) = mode { - b.size_mode = m; + let size = parameters.get("size").and_then(J::as_array).map(|components| { + [components.first().and_then(J::as_i64).unwrap_or(0).clamp(-12, 13) as i32, components.get(1).and_then(J::as_i64).unwrap_or(0).clamp(-12, 13) as i32] + }); + let seed = i64p(parameters, "seed").map(|value| value.clamp(0, i32::MAX as i64) as i32); + let tiling = parameters + .get("tiling") + .map(|value| match value.as_bool() { + Some(value) => Ok([value, value]), + None => serde_json::from_value::<[bool; 2]>(value.clone()).map_err(|error| bad("graph.node.base", error.to_string())), + }) + .transpose()?; + let tiling_mode = parameters + .get("tilingMode") + .map(|value| serde_json::from_value(value.clone()).map_err(|error| bad("graph.node.base", error.to_string()))) + .transpose()?; + let pixel_ratio_mode = parameters + .get("pixelRatioMode") + .map(|value| serde_json::from_value(value.clone()).map_err(|error| bad("graph.node.base", error.to_string()))) + .transpose()?; + let pixel_ratio = parameters + .get("pixelRatio") + .map(|value| serde_json::from_value::(value.clone()).map_err(|error| bad("graph.node.base", error.to_string()))) + .transpose()?; + if pixel_ratio.is_some_and(|value| !(0..=1).contains(&value)) { + return Err(bad("graph.node.base", "pixelRatio must be 0 or 1")); + } + + session.edit_merged(&format!("base:{}", id.0), "Set base parameters", |session| { + let base = &mut session.graph_mut()?.node_mut(id)?.base; + if let Some(size_mode) = mode { + base.size_mode = size_mode; } - if let Some(sz) = size { - b.size = sz; + if let Some(size) = size { + base.size = size; } - if let Some(f) = format { - b.format = f; + if let Some(format) = format { + base.format = format; } - if let Some(sd) = seed { - b.seed = sd; + if let Some(seed) = seed { + base.seed = seed; } - if let Some(t) = tiling { - b.tiling = [t, t]; + if let Some(tiling) = tiling { + base.tiling = tiling; + base.tiling_mode = materialcraft_core::ParameterInheritance::Absolute; } + if let Some(mode) = tiling_mode { + base.tiling_mode = mode; + } + if let Some(value) = pixel_ratio { + base.pixel_ratio = value; + base.pixel_ratio_mode = materialcraft_core::ParameterInheritance::Absolute; + } + if let Some(mode) = pixel_ratio_mode { + base.pixel_ratio_mode = mode; + } + Ok(J::Null) }) } diff --git a/crates/engine/src/open_document.rs b/crates/engine/src/open_document.rs index 3ee514ad..7cc12062 100644 --- a/crates/engine/src/open_document.rs +++ b/crates/engine/src/open_document.rs @@ -21,6 +21,30 @@ pub struct OpenDocument { } impl OpenDocument { + pub(crate) fn edit(&mut self, label: &str, edit: impl FnOnce(&mut Package) -> crate::Result) -> crate::Result { + let mut package = self.pkg.clone(); + let result = edit(&mut package)?; + let snapshot = Snapshot { + pkg: std::mem::replace(&mut self.pkg, package), + graph: self.graph, + selection: self.selection.clone(), + annotation_selection: self.annotation_selection, + material_preview: self.material_preview.clone(), + label: label.into(), + modified: self.modified, + // The active document's cook cache cannot be reused after activation + dirty: true, + cook_epoch: 0, + }; + self.undo.push(snapshot); + if self.undo.len() > crate::session::MAX_UNDO { + self.undo.remove(0); + } + self.redo.clear(); + self.modified = true; + Ok(result) + } + pub(crate) fn new(id: u64, pkg: Package, path: Option) -> Self { Self { id, diff --git a/crates/engine/src/package_commands.rs b/crates/engine/src/package_commands.rs index bf2681e1..e8ac1855 100644 --- a/crates/engine/src/package_commands.rs +++ b/crates/engine/src/package_commands.rs @@ -116,7 +116,8 @@ impl Session { json!(self.open_packages().into_iter().map(|(id, package, path, modified)| json!({ "id": id, "name": package.name, "path": path, "modified": modified, "active": id == self.document_id, - "graphs": package.graphs.iter().enumerate().map(|(index, graph)| json!({"index": index, "name": graph.name, "kind": graph.kind()})).collect::>() + "folders": package.folder_paths(), + "graphs": package.graphs.iter().enumerate().map(|(index, graph)| json!({"index": index, "name": graph.name, "path": graph.sbs_path(), "kind": graph.kind()})).collect::>() })).collect::>()) } } diff --git a/crates/engine/src/package_file_commands.rs b/crates/engine/src/package_file_commands.rs new file mode 100644 index 00000000..a70ed82f --- /dev/null +++ b/crates/engine/src/package_file_commands.rs @@ -0,0 +1,77 @@ +use crate::{ + Result, Session, cmd, + commands::{CommandSpec, always, bad}, +}; +use serde_json::{Value, json}; + +pub(crate) fn specs() -> Vec { + vec![ + cmd!( + "file.reload", + "Reload package", + [], + None, + "{discard?: bool} reloads the current package; unsaved changes require explicit discard", + |session| { session.path.as_ref().map(|_| ()).ok_or_else(|| "the package has no file to reload".into()) }, + reload + ), + cmd!("file.saveCopyAs", "Save a copy as...", [], None, "{path} writes an SBS copy without changing the current path or saved state", always, save_copy), + ] +} + +fn reload(session: &mut Session, parameters: &Value) -> Result { + if session.modified && parameters.get("discard").and_then(Value::as_bool) != Some(true) { + return Err(bad("file.reload", "save the package or explicitly discard its edits")); + } + let path = session.path.clone().ok_or_else(|| bad("file.reload", "the package has no file to reload"))?; + let bytes = read_package(&path)?; + let linked = crate::file_cmds::linked_files(&path); + let mut read = materialcraft_formats::sbs::read_sbs(&bytes, &path, &linked)?; + crate::linked_files::normalize_references(&mut read.pkg, &path); + read.pkg.dependencies = session.pkg.dependencies.clone(); + let safe_path = read.warnings.is_empty().then_some(path.clone()); + read.warnings.extend(crate::linked_files::load(&mut read.pkg)); + + crate::file_cmds::replace_package(session, read.pkg, safe_path); + session.load_warnings = read.warnings; + session.refresh_links(); + session.modified = false; + Ok(json!({"path": session.path, "warnings": session.load_warnings})) +} + +fn read_package(path: &str) -> Result> { + if path.starts_with("sbs://") { + return materialcraft_formats::sbs::library::read(path).map_err(|error| bad("file.reload", error)); + } + #[cfg(not(target_arch = "wasm32"))] + { + use std::io::Read; + let mut bytes = Vec::new(); + std::fs::File::open(path).and_then(|file| file.take((256 << 20) + 1).read_to_end(&mut bytes)).map_err(|error| bad("file.reload", error.to_string()))?; + if bytes.len() > 256 << 20 { + return Err(bad("file.reload", "the package exceeds 256 MiB")); + } + Ok(bytes) + } + #[cfg(target_arch = "wasm32")] + Err(bad("file.reload", "reopen local browser files with the file picker")) +} + +#[cfg(not(target_arch = "wasm32"))] +fn save_copy(session: &mut Session, parameters: &Value) -> Result { + let path = crate::commands::strp(parameters, "path") + .filter(|path| !path.trim().is_empty()) + .ok_or_else(|| bad("file.saveCopyAs", "a nonempty path is required"))?; + let path = crate::document_path::normalize(&crate::file_cmds::package_path(path)); + if path.contains("://") || session.open_packages().iter().any(|entry| entry.2 == Some(path.as_str())) { + return Err(bad("file.saveCopyAs", "choose a local file that is not already open")); + } + let bytes = crate::file_cmds::save_bytes_at(session, Some(&path))?; + materialcraft_formats::write_atomic(std::path::Path::new(&path), &bytes)?; + Ok(json!({"path": path, "bytes": bytes.len()})) +} + +#[cfg(target_arch = "wasm32")] +fn save_copy(_: &mut Session, _: &Value) -> Result { + Err(bad("file.saveCopyAs", "the browser saves copies with a download")) +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index b6db6e09..c99a0323 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -13,7 +13,7 @@ use crate::snapshot::Snapshot; use crate::{AnnotationSelection, Clip, EngineError, Result}; /// Undo keeps this many steps. -const MAX_UNDO: usize = 200; +pub(crate) const MAX_UNDO: usize = 200; /// The 3D view's scene and look. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -119,6 +119,7 @@ pub struct View2d { pub const WARNING_PREFIX: &str = "Warning: "; pub struct Session { + pub environment: materialcraft_core::EvaluationEnvironment, pub document_id: u64, pub(crate) next_document_id: u64, pub(crate) documents: std::collections::BTreeMap, @@ -145,6 +146,7 @@ pub struct Session { pub load_warnings: Vec, pub clipboard: Option, pub embedded_clipboard: Option, + pub explorer_clipboard: Option, /// The last cook of the open graph. pub cooked: Cooked, /// Set when the graph changed and needs cooking. @@ -164,8 +166,15 @@ pub struct Session { } impl Session { - pub fn new(pkg: Package) -> Session { + pub fn new(mut pkg: Package) -> Session { + let library = crate::function_library::load(); + if let Ok(library) = &library { + for (path, package) in &library.packages { + pkg.dependencies.entry(path.clone()).or_insert_with(|| package.clone()); + } + } let mut session = Session { + environment: Default::default(), document_id: 0, next_document_id: 1, documents: std::collections::BTreeMap::new(), @@ -187,6 +196,7 @@ impl Session { load_warnings: Vec::new(), clipboard: None, embedded_clipboard: None, + explorer_clipboard: None, cooked: Cooked::default(), dirty: true, cook_epoch: 0, @@ -199,6 +209,14 @@ impl Session { decoded: Arc::new(Mutex::new(HashMap::new())), }; session.refresh_links(); + match library { + Ok(library) => { + for warning in library.warnings { + session.warn(warning); + } + } + Err(error) => session.warn(format!("Missing function library: {error}")), + } session } @@ -432,6 +450,7 @@ impl Session { pub fn cook(&mut self) -> &Cooked { let dec = self.resource_decoder(); let mut opts = Options::new(&dec); + opts.environment = self.environment; opts.max_size = self.preview_size; let cooked = crate::PreviewCook::run(&self.pkg, self.graph, &self.material_preview.graphs(), &opts, &self.cache); self.accept_preview(cooked); @@ -453,7 +472,8 @@ impl Session { /// Cook graph `gi` at full size, without touching the preview results. pub fn cook_full(&self, gi: usize) -> Cooked { let dec = self.resource_decoder(); - let opts = Options::new(&dec); + let mut opts = Options::new(&dec); + opts.environment = self.environment; materialcraft_eval::cook(&self.pkg, gi, &opts, &self.cache) } diff --git a/crates/engine/src/session.test.rs b/crates/engine/src/session.test.rs index d254c555..9b64c363 100644 --- a/crates/engine/src/session.test.rs +++ b/crates/engine/src/session.test.rs @@ -7,7 +7,7 @@ use crate::session::Session; fn normal_map_session() -> Session { let mut pkg = Package::new("T"); let png = encode(&Image::filled(4, 4, Kind::Color, [0.5, 0.5, 1.0, 1.0]), "png", Depth::U8, false).unwrap(); - pkg.resources.push(Resource { name: "n".into(), file: "n.png".into(), bytes: materialcraft_core::ResourceBytes::new(png) }); + pkg.resources.push(Resource::new("n", "n.png", materialcraft_core::ResourceBytes::new(png))); Session::new(pkg) } diff --git a/crates/engine/tests/atomics.rs b/crates/engine/tests/atomics.rs index 7a5db0c4..968fab93 100644 --- a/crates/engine/tests/atomics.rs +++ b/crates/engine/tests/atomics.rs @@ -6,6 +6,42 @@ use materialcraft_engine::{ }; use serde_json::json; +#[test] +fn new_processors_start_with_empty_functions_and_preserve_them_in_sbs() { + use materialcraft_engine::{FunctionGraphTarget, core::NodeId}; + + for definition in ["pixel_processor", "value_processor"] { + let mut session = materialcraft_engine::new_session(); + let node = NodeId(execute(&mut session, "graph.node.add", &json!({"def": definition})).unwrap()["id"].as_u64().unwrap()); + let target = FunctionGraphTarget::Parameter { node, parameter: "function".into() }; + + assert_eq!(target.current(&session).unwrap(), &FunctionGraph::default(), "{definition}"); + session.preview_size = Some(16); + session.cook(); + assert_eq!(session.cooked.nodes[&node].error.as_deref(), Some("function has no result node"), "{definition}"); + + let loaded = read_sbs(&write_sbs(&session.pkg).unwrap(), "empty_processors.sbs", &|_| None).unwrap(); + assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings); + let session = Session::new(loaded.pkg); + let node = session.graph().unwrap().nodes[0].id; + let target = FunctionGraphTarget::Parameter { node, parameter: "function".into() }; + assert_eq!(target.current(&session).unwrap(), &FunctionGraph::default(), "{definition}"); + } +} + +#[test] +fn new_fx_map_starts_with_a_quadrant_output() { + use materialcraft_engine::core::{NodeId, PatternGraph, PatternNodeKind}; + + let mut session = materialcraft_engine::new_session(); + let node = NodeId(execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + + assert_eq!( + session.graph().unwrap().node(node).unwrap().params.get("pattern"), + Some(&Value::PatternGraph(Box::new(PatternGraph::with_root(PatternNodeKind::Quadrant)))) + ); +} + #[test] fn atomic_sample_round_trips_through_native_fields_and_cooks_identically() { let mut original = Session::new(atomic_sample().unwrap()); @@ -55,7 +91,7 @@ fn every_catalog_entry_has_a_native_sbs_representation() { let bytes = write_sbs(&package).unwrap(); let loaded = read_sbs(&bytes, "primitives.sbs", &|_| None).unwrap(); assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings); - assert_eq!(loaded.pkg.graphs[0].nodes.len(), 30); + assert_eq!(loaded.pkg.graphs[0].nodes.len(), 29); for (before, after) in package.graphs[0].nodes.iter().zip(&loaded.pkg.graphs[0].nodes) { assert_eq!(before.def, after.def); } diff --git a/crates/engine/tests/embedded_edit.rs b/crates/engine/tests/embedded_edit.rs index 6af8baa4..32bf8adc 100644 --- a/crates/engine/tests/embedded_edit.rs +++ b/crates/engine/tests/embedded_edit.rs @@ -27,13 +27,16 @@ fn function_session(kind: &str) -> (Session, FunctionGraphTarget) { .unwrap(), ); if kind == "dynamic" { - session.graph_mut().unwrap().node_mut(node).unwrap().functions.insert("test".into(), FunctionGraph::default()); + let owner = session.graph_mut().unwrap().node_mut(node).unwrap(); + owner.params.insert("function".into(), Value::Function(Box::new(FunctionGraph::constant(Value::Float4([0.5; 4]))))); + owner.functions.insert("test".into(), FunctionGraph::default()); FunctionGraphTarget::Dynamic { node, parameter: "test".into() } } else { FunctionGraphTarget::Parameter { node, parameter: "function".into() } } } }; + execute(&mut session, "graph.function.set", &json!({"target": target, "function": FunctionGraph::default()})).unwrap(); session.reset_history(); (session, target) diff --git a/crates/engine/tests/explorer.rs b/crates/engine/tests/explorer.rs new file mode 100644 index 00000000..ae059284 --- /dev/null +++ b/crates/engine/tests/explorer.rs @@ -0,0 +1,234 @@ +use materialcraft_engine::{Session, core::Package, execute}; +use serde_json::{Value, json}; + +fn run(session: &mut Session, command: &str, parameters: Value) -> Value { + execute(session, command, ¶meters).unwrap() +} + +#[test] +fn folders_contain_both_graph_kinds_and_removal_is_undoable() { + let mut session = Session::new(Package::new("Explorer")); + run(&mut session, "folder.create", json!({"name": "Tools"})); + run(&mut session, "folder.create", json!({"parent": "Tools", "name": "Math"})); + run(&mut session, "file.new", json!({"folder": "Tools", "name": "Surface", "template": "empty"})); + run(&mut session, "file.new", json!({"folder": "Tools/Math", "name": "Helper", "kind": "function"})); + + assert!(session.pkg.graph_by_name("Tools/Surface").is_some()); + assert!(session.pkg.graph_by_name("Tools/Math/Helper").is_some()); + let before = session.pkg.clone(); + run(&mut session, "folder.remove", json!({"folder": "Tools"})); + assert!(session.pkg.graphs.is_empty()); + + run(&mut session, "edit.undo", json!({})); + assert_eq!(session.pkg, before); +} + +#[test] +fn numbered_explorer_names_increment_across_conflicts() { + let mut session = Session::new(Package::new("Names")); + run(&mut session, "folder.create", json!({"name": "Tools"})); + run(&mut session, "folder.create", json!({"parent": "Tools", "name": "Untitled_Graph_2"})); + + for (kind, prefix) in [("material", "Untitled_Graph"), ("function", "Untitled_Function_Graph")] { + for expected in if kind == "material" { [1, 3] } else { [1, 2] } { + let result = run(&mut session, "file.new", json!({"folder": "Tools", "name": format!("{prefix}_1"), "kind": kind, "template": "empty"})); + assert_eq!(result["name"], format!("{prefix}_{expected}")); + } + } + for expected in [1, 2] { + let result = run(&mut session, "folder.create", json!({"parent": "Tools", "name": "Untitled_Folder_1"})); + assert_eq!(result["folder"], format!("Tools/Untitled_Folder_{expected}")); + } + let result = run(&mut session, "folder.create", json!({"name": "Untitled_Folder_1"})); + assert_eq!(result["folder"], "Untitled_Folder_1"); +} + +#[test] +fn explorer_moves_and_renames_cannot_collide_with_resources() { + use materialcraft_engine::core::{Resource, ResourceBytes}; + let mut session = Session::new(Package::new("Names")); + run(&mut session, "folder.create", json!({"name": "Folder"})); + run(&mut session, "file.new", json!({"name": "Graph", "template": "empty"})); + for (folder, name) in [("", "Taken"), ("Folder", "Graph")] { + let mut resource = Resource::new(name, "tile.png", ResourceBytes::new(vec![1])); + resource.folder = folder.into(); + session.pkg.resources.push(resource); + } + let before = materialcraft_engine::file_cmds::save_bytes(&session).unwrap(); + + assert!(execute(&mut session, "folder.rename", &json!({"folder": "Folder", "name": "Taken"})).is_err()); + assert!(execute(&mut session, "graph.rename", &json!({"graph": 0, "name": "Taken"})).is_err()); + assert!(execute(&mut session, "explorer.move", &json!({"graph": 0, "parent": "Folder"})).is_err()); + assert_eq!(materialcraft_engine::file_cmds::save_bytes(&session).unwrap(), before); +} + +#[test] +fn package_paste_places_root_resources_in_the_destination_folder() { + use materialcraft_engine::core::{Resource, ResourceBytes}; + let mut session = Session::new(Package::new("Copy")); + let mut resource = Resource::new("Tile", "tile.png", ResourceBytes::new(vec![1])); + resource.folder = String::new(); + session.pkg.resources.push(resource); + run(&mut session, "explorer.copy", json!({})); + run(&mut session, "file.newPackage", json!({})); + run(&mut session, "folder.create", json!({"name": "Destination"})); + run(&mut session, "file.new", json!({"folder": "Destination", "name": "Tile", "template": "empty"})); + + run(&mut session, "explorer.paste", json!({"folder": "Destination"})); + + assert_eq!(session.pkg.resources[0].sbs_path(), "Destination/Tile_1"); +} + +fn linked_functions() -> Session { + use materialcraft_engine::core::{FunctionGraph, Graph, Value as GraphValue}; + let mut package = Package::new("Linked functions"); + let mut source = Graph::new("Source"); + source.folder = "Tools/Math".into(); + source.function = Some(FunctionGraph::constant(GraphValue::Float(0.5))); + package.graphs.push(source); + let mut session = Session::new(package); + run(&mut session, "file.new", json!({"kind": "function", "name": "Caller", "folder": "Tools"})); + run(&mut session, "graph.instance.add", json!({"document": 0, "graph": "Tools/Math/Source"})); + session +} + +#[test] +fn renamed_and_moved_folders_rewrite_nested_function_references() { + let mut session = linked_functions(); + run(&mut session, "folder.rename", json!({"folder": "Tools", "name": "Helpers"})); + let caller = &session.pkg.graphs[1].function.as_ref().unwrap().nodes[0]; + assert_eq!(caller.instance.as_ref().unwrap().graph, "Helpers/Math/Source"); + assert!(matches!(caller.source, Some(Ok(_)))); + + run(&mut session, "explorer.move", json!({"folder": "Helpers/Math", "parent": ""})); + assert_eq!(session.pkg.graphs[0].folder, "Math"); + let caller = &session.pkg.graphs[1].function.as_ref().unwrap().nodes[0]; + assert_eq!(caller.instance.as_ref().unwrap().graph, "Math/Source"); + assert!(matches!(caller.source, Some(Ok(_)))); + assert!(session.pkg.folder_paths().contains("Helpers")); + + let before = session.pkg.clone(); + assert!(execute(&mut session, "explorer.move", &json!({"folder": "Math", "parent": "Math"})).is_err()); + assert_eq!(session.pkg, before); +} + +#[test] +fn folder_copy_keeps_empty_descendants_and_retargets_its_internal_instances() { + let mut session = linked_functions(); + run(&mut session, "folder.create", json!({"parent": "Tools", "name": "Empty"})); + run(&mut session, "explorer.copy", json!({"folder": "Tools"})); + let before = session.pkg.clone(); + + run(&mut session, "explorer.paste", json!({})); + + assert!(session.pkg.folder_paths().contains("Tools_1/Empty")); + let (_, caller) = session.pkg.graph_by_name("Tools_1/Caller").unwrap(); + let node = &caller.function.as_ref().unwrap().nodes[0]; + assert_eq!(node.instance.as_ref().unwrap().graph, "Tools_1/Math/Source"); + assert!(matches!(node.source, Some(Ok(_)))); + run(&mut session, "edit.undo", json!({})); + assert_eq!(session.pkg, before); +} + +#[test] +fn explorer_clipboard_survives_document_switch_and_checks_external_references() { + let mut session = linked_functions(); + run(&mut session, "explorer.copy", json!({"graph": 1})); + run(&mut session, "file.newPackage", json!({"name": "Destination"})); + let destination = session.document_id; + let before = session.pkg.clone(); + + assert!(execute(&mut session, "explorer.paste", &json!({})).is_err()); + assert_eq!(session.pkg, before); + run(&mut session, "package.activate", json!({"document": 0})); + run(&mut session, "explorer.copy", json!({"folder": "Tools"})); + run(&mut session, "package.activate", json!({"document": destination})); + run(&mut session, "explorer.paste", json!({})); + + let (_, caller) = session.pkg.graph_by_name("Tools/Caller").unwrap(); + assert!(matches!(caller.function.as_ref().unwrap().nodes[0].source, Some(Ok(_)))); +} + +#[test] +fn folder_removal_does_not_remove_similarly_named_siblings() { + let mut session = Session::new(Package::new("Siblings")); + for folder in ["A", "AB"] { + run(&mut session, "folder.create", json!({"name": folder})); + run(&mut session, "file.new", json!({"folder": folder, "name": "Graph", "template": "empty"})); + } + run(&mut session, "folder.remove", json!({"folder": "A"})); + + assert_eq!(session.pkg.graphs.len(), 1); + assert_eq!(session.pkg.graphs[0].sbs_path(), "AB/Graph"); + assert!(session.pkg.folder_paths().contains("AB")); +} + +#[test] +fn save_copy_keeps_document_identity_and_reload_is_atomic() { + let directory = std::env::temp_dir().join(format!("materialcraft-explorer-{}", std::process::id())); + std::fs::create_dir_all(&directory).unwrap(); + let original = directory.join("original.sbs"); + let copy = directory.join("copy.sbs"); + let mut session = linked_functions(); + for path in ["", " "] { + assert!(execute(&mut session, "file.saveCopyAs", &json!({"path": path})).is_err()); + } + + run(&mut session, "file.save", json!({"path": original})); + let document = session.document_id; + let path = session.path.clone(); + run(&mut session, "folder.create", json!({"name": "Unsaved"})); + let history = session.history().len(); + + run(&mut session, "file.saveCopyAs", json!({"path": copy})); + assert_eq!(session.path, path); + assert!(session.modified); + assert_eq!(session.history().len(), history); + let copied = materialcraft_engine::formats::sbs::read_sbs(&std::fs::read(©).unwrap(), "copy.sbs", &|_| None).unwrap(); + assert!(copied.pkg.folder_paths().contains("Unsaved")); + assert!(execute(&mut session, "file.reload", &json!({})).is_err()); + + run(&mut session, "file.reload", json!({"discard": true})); + assert_eq!(session.document_id, document); + assert!(!session.modified); + assert!(!session.pkg.folder_paths().contains("Unsaved")); + let before = session.pkg.clone(); + std::fs::write(&original, "broken package").unwrap(); + assert!(execute(&mut session, "file.reload", &json!({})).is_err()); + assert_eq!(session.pkg, before); + std::fs::remove_dir_all(directory).unwrap(); +} + +#[test] +fn folder_names_and_depth_are_bounded() { + let mut session = Session::new(Package::new("Validation")); + run(&mut session, "file.new", json!({"name": " Surface ", "template": "empty"})); + assert_eq!(session.graph().unwrap().name, "Surface"); + + for name in ["", "../escape", "A/B", "A\\B", ".", "\0"] { + assert!(execute(&mut session, "folder.create", &json!({"name": name})).is_err(), "{name:?}"); + } + let path = std::iter::repeat_n("A", 64).collect::>().join("/"); + session.pkg.folders.push(path.clone()); + assert!(execute(&mut session, "folder.create", &json!({"parent": path})).is_err()); +} + +#[test] +fn copied_folders_keep_unreferenced_resources_in_the_copied_subtree() { + use materialcraft_engine::core::{Resource, ResourceBytes}; + let mut package = Package::new("Resources"); + let mut resource = Resource::new("Mask", "mask.png", ResourceBytes::new(vec![1, 2, 3])); + resource.folder = "Tools/Images".into(); + package.resources.push(resource); + let mut session = Session::new(package); + run(&mut session, "explorer.copy", json!({"folder": "Tools"})); + + run(&mut session, "explorer.paste", json!({})); + assert_eq!(session.pkg.resources.len(), 2); + assert_eq!(session.pkg.resources[1].folder, "Tools_1/Images"); + assert_eq!(session.pkg.resources[1].bytes.as_slice(), &[1, 2, 3]); + run(&mut session, "folder.rename", json!({"folder": "Tools_1", "name": "Copy"})); + assert_eq!(session.pkg.resources[1].folder, "Copy/Images"); + run(&mut session, "folder.remove", json!({"folder": "Copy"})); + assert_eq!(session.pkg.resources.len(), 1); +} diff --git a/crates/engine/tests/function_graph.rs b/crates/engine/tests/function_graph.rs index dac11466..f1deb9fd 100644 --- a/crates/engine/tests/function_graph.rs +++ b/crates/engine/tests/function_graph.rs @@ -62,6 +62,6 @@ fn standalone_function_creation_wiring_frame_movement_and_native_round_trip() { let function = graph.function.as_ref().unwrap(); assert_eq!(function.nodes[0].pos, [32.0, 64.0]); let variables = Default::default(); - let context = EvaluationContext { position: [0.0; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables }; + let context = EvaluationContext { scope: Default::default(), position: [0.0; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables }; assert_eq!(compile(function, 0).unwrap().evaluate(&context, &mut EvaluationState::default()).unwrap(), Value::Float(6.0)); } diff --git a/crates/engine/tests/function_instances.rs b/crates/engine/tests/function_instances.rs index ee944e06..2c95e065 100644 --- a/crates/engine/tests/function_instances.rs +++ b/crates/engine/tests/function_instances.rs @@ -43,12 +43,59 @@ fn evaluate(graph: &FunctionGraph) -> Value { function::compile(graph, 0) .unwrap() .evaluate( - &EvaluationContext { position: [0.5; 2], size: [16.0; 2], images: &[], tile: true, variables: &BTreeMap::new() }, + &EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [16.0; 2], images: &[], tile: true, variables: &BTreeMap::new() }, &mut EvaluationState::default(), ) .unwrap() } +#[test] +fn redundant_legacy_function_connectors_preserve_wires_without_repeating_evaluation() { + let mut package = source(); + let mut graph = Graph::new("Caller"); + let mut body = FunctionGraph::default(); + let maximum = body.add_constant(Value::Float(1.0)); + let random = body.add("rand", &[maximum], None); + let instance = body.add("instance", &[random], None); + let call = body.nodes.iter_mut().find(|node| node.id == instance).unwrap(); + call.instance = Some(GraphInstance { + label: String::new(), + package: String::new(), + graph: "Twice".into(), + inputs: vec![GraphPort { identifier: "amount".into(), type_code: 256 }], + outputs: vec![GraphPort { identifier: "output".into(), type_code: 256 }], + defaults: BTreeMap::new(), + }); + let next_random = body.add("rand", &[maximum], None); + body.output = Some(body.add("add", &[instance, next_random], None)); + graph.function = Some(body); + package.graphs.push(graph); + let canonical = Session::new(package.clone()); + let expected = evaluate(canonical.pkg.graph_by_name("Caller").unwrap().1.function.as_ref().unwrap()); + let caller = package.graphs.last_mut().unwrap().function.as_mut().unwrap(); + let call = caller.nodes.iter_mut().find(|node| node.id == instance).unwrap(); + call.instance.as_mut().unwrap().inputs.push(GraphPort { identifier: "old_amount".into(), type_code: 0 }); + call.inputs.push(Some(random)); + + let session = Session::new(package.clone()); + let function = session.pkg.graph_by_name("Caller").unwrap().1.function.as_ref().unwrap(); + assert_eq!(evaluate(function), expected); + assert!(function::warnings(function).is_empty()); + let saved = formats::sbs::write_sbs(&session.pkg).unwrap(); + let reopened = Session::new(formats::sbs::read_sbs(&saved, "caller.sbs", &|_| None).unwrap().pkg); + let function = reopened.pkg.graph_by_name("Caller").unwrap().1.function.as_ref().unwrap(); + let call = function.nodes.iter().find(|node| node.instance.is_some()).unwrap(); + assert_eq!(call.instance.as_ref().unwrap().inputs.iter().map(|port| port.identifier.as_str()).collect::>(), ["amount", "old_amount"]); + assert_eq!(call.inputs[0], call.inputs[1]); + assert_eq!(evaluate(function), expected); + + let caller = package.graphs.last_mut().unwrap().function.as_mut().unwrap(); + *caller.nodes.iter_mut().find(|node| node.id == instance).unwrap().inputs.last_mut().unwrap() = Some(maximum); + let conflicting = Session::new(package); + let function = conflicting.pkg.graph_by_name("Caller").unwrap().1.function.as_ref().unwrap(); + assert!(function::compile(function, 0).err().unwrap().contains("connected input no longer exists")); +} + #[test] fn functions_link_across_documents_and_keep_independent_undo() { let mut session = Session::new(source()); @@ -64,7 +111,7 @@ fn functions_link_across_documents_and_keep_independent_undo() { let constant = edit(&mut session, &target, json!({"action": "add", "operation": "const_float1", "at": [0,0]}))["id"].as_u64().unwrap(); edit(&mut session, &target, json!({"action": "value", "id": constant, "value": Value::Float(0.25)})); edit(&mut session, &target, json!({"action": "output", "id": instance})); - assert!(function::warnings(session.graph().unwrap().function.as_ref().unwrap())[0].contains("missing input")); + assert!(function::warnings(session.graph().unwrap().function.as_ref().unwrap()).is_empty()); edit(&mut session, &target, json!({"action": "connect", "from": constant, "to": instance, "input": 0})); assert_eq!(evaluate(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(0.5)); let history = session.history(); @@ -76,7 +123,7 @@ fn functions_link_across_documents_and_keep_independent_undo() { assert_eq!(session.history(), history); assert_eq!(evaluate(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(0.75)); execute(&mut session, "edit.undo", &json!({})).unwrap(); - assert!(function::compile(session.graph().unwrap().function.as_ref().unwrap(), 0).is_err()); + assert_eq!(evaluate(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(1.5)); execute(&mut session, "edit.redo", &json!({})).unwrap(); assert_eq!(evaluate(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(0.75)); } @@ -173,6 +220,8 @@ fn calls_isolate_variables_and_evaluate_arguments_once() { let argument = caller.add("set", &[next], Some(Value::Text("private".into()))); let call = caller.add("instance", &[argument], None); caller.nodes.last_mut().unwrap().instance = Some(GraphInstance { + label: String::new(), + defaults: Default::default(), package: String::new(), graph: "Twice".into(), inputs: vec![GraphPort { identifier: "amount".into(), type_code: 256 }], @@ -184,6 +233,19 @@ fn calls_isolate_variables_and_evaluate_arguments_once() { assert_eq!(evaluate(&caller), Value::Float(6.0)); } +#[test] +fn unconnected_instance_inputs_use_the_source_defaults() { + let mut session = Session::new(source()); + execute(&mut session, "file.new", &json!({"name": "Caller", "kind": "function"})).unwrap(); + let target = json!({"kind": "graph"}); + let instance = call(&mut session, 0, "Twice", &target); + edit(&mut session, &target, json!({"action": "output", "id": instance})); + + let graph = session.graph().unwrap().function.as_ref().unwrap(); + assert_eq!(evaluate(graph), Value::Float(1.0)); + assert!(function::warnings(graph).is_empty()); +} + #[test] fn connected_inputs_survive_source_interface_changes_and_missing_sources() { let mut session = Session::new(source()); @@ -312,6 +374,8 @@ fn cyclic_references_loaded_from_sbs_report_errors_without_recursing_forever() { let mut function = FunctionGraph::default(); let id = function.add("instance", &[], None); function.nodes[0].instance = Some(GraphInstance { + label: String::new(), + defaults: Default::default(), package: String::new(), graph: graph.name.clone(), inputs: Vec::new(), diff --git a/crates/engine/tests/function_library.rs b/crates/engine/tests/function_library.rs new file mode 100644 index 00000000..dd57176b --- /dev/null +++ b/crates/engine/tests/function_library.rs @@ -0,0 +1,281 @@ +use materialcraft_engine::{ + FunctionGraphTarget, Session, + core::{FunctionGraph, Graph, NodeId, Package, Value}, + execute, file_cmds, + nodes::function::{self, EvaluationContext, EvaluationState}, +}; +use serde_json::json; +use std::collections::BTreeMap; + +fn session() -> Session { + let mut package = Package::new("Library integration"); + let mut graph = Graph::new("Caller"); + graph.function = Some(FunctionGraph::default()); + package.graphs.push(graph); + Session::new(package) +} + +fn value(function: &FunctionGraph) -> Value { + let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [16.0; 2], images: &[], tile: true, variables: &BTreeMap::new() }; + function::compile(function, 0).unwrap().evaluate(&context, &mut EvaluationState::default()).unwrap() +} + +#[test] +fn library_instances_are_discoverable_undoable_and_portable() { + let mut session = session(); + let entries = execute(&mut session, "library.functions", &json!({})).unwrap(); + assert_eq!(entries.as_array().unwrap().len(), 171); + let pi = entries.as_array().unwrap().iter().find(|entry| entry["graph"] == "Functions/Math/Pi").unwrap(); + assert_eq!(pi["outputs"][0]["type_code"], 256); + + let node = execute(&mut session, "library.function.add", &json!({"graph": "Functions/Math/Pi", "at": [64.0, 128.0]})).unwrap()["id"].as_u64().unwrap(); + execute(&mut session, "graph.function.edit", &json!({"edit": {"action": "output", "id": node}})).unwrap(); + assert_eq!(value(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(std::f32::consts::PI)); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert!(session.graph().unwrap().function.as_ref().unwrap().nodes.is_empty()); + execute(&mut session, "edit.redo", &json!({})).unwrap(); + execute(&mut session, "edit.redo", &json!({})).unwrap(); + + let bytes = file_cmds::save_bytes(&session).unwrap(); + let xml = std::str::from_utf8(&bytes).unwrap(); + assert!(xml.contains("sbs://functions.sbs")); + assert!(!xml.contains("assets/sbs")); + assert!(!xml.contains(" = entries.iter().filter(|entry| entry["missing"] != false).map(|entry| &entry["graph"]).collect(); + + assert_eq!(entries.len(), 171); + assert!(missing.is_empty(), "missing bundled functions: {missing:?}"); + for entry in entries { + let mut caller = self::session(); + let identifier = execute(&mut caller, "library.function.add", &json!({"graph": entry["graph"]})).unwrap()["id"].as_u64().unwrap(); + execute(&mut caller, "graph.function.edit", &json!({"edit": {"action": "output", "id": identifier}})).unwrap(); + let function = caller.graph().unwrap().function.as_ref().unwrap(); + + assert!(matches!(function.nodes[0].source, Some(Ok(_))), "{}", entry["graph"]); + function::compile(function, 0).unwrap_or_else(|error| panic!("{}: {error}", entry["graph"])); + } +} + +#[test] +fn parity_library_instances_evaluate_connected_inputs_after_reopen() { + for (name, expected, default) in [ + ("EvenCount", Value::Float(3.0), Value::Float(0.0)), + ("OddCount", Value::Float(2.0), Value::Float(0.0)), + ("ParityTest", Value::Bool(true), Value::Bool(true)), + ] { + let mut session = session(); + let entries = execute(&mut session, "library.functions", &json!({"filter": name})).unwrap(); + assert_eq!(entries[0]["missing"], false, "{name} must be usable from the Library"); + + let instance = + execute(&mut session, "library.function.add", &json!({"graph": format!("Functions/Math/Parity/{name}")})).unwrap()["id"].as_u64().unwrap(); + execute(&mut session, "graph.function.edit", &json!({"edit": {"action": "output", "id": instance}})).unwrap(); + assert_eq!(value(session.graph().unwrap().function.as_ref().unwrap()), default); + let constant = execute(&mut session, "graph.function.edit", &json!({"edit": {"action": "add", "operation": "const_float1", "at": [-200.0, 0.0]}})) + .unwrap()["id"] + .as_u64() + .unwrap(); + execute(&mut session, "graph.function.edit", &json!({"edit": {"action": "value", "id": constant, "value": Value::Float(5.75)}})).unwrap(); + execute(&mut session, "graph.function.edit", &json!({"edit": {"action": "connect", "from": constant, "to": instance, "input": 0}})).unwrap(); + let bytes = file_cmds::save_bytes(&session).unwrap(); + let mut reopened = self::session(); + file_cmds::open_bytes(&mut reopened, &bytes, Some("parity-caller.sbs".into())).unwrap(); + + assert_eq!(value(session.graph().unwrap().function.as_ref().unwrap()), expected, "{name}"); + assert_eq!(value(reopened.graph().unwrap().function.as_ref().unwrap()), expected, "reopened {name}"); + } +} + +#[test] +fn missing_library_implementations_remain_instances_with_typed_ports() { + let mut session = session(); + let mut missing = session.pkg.dependencies["sbs://functions.sbs"].graph_by_name("Functions/Random/GlobalRandom").unwrap().1.clone(); + missing.name = "MissingFunction".into(); + missing.folder = "Functions/Test".into(); + missing.function = Some(FunctionGraph::default()); + let mut package = Package::new("Missing library"); + package.graphs.push(missing); + session.pkg.dependencies.insert("sbs://missing-functions.sbs".into(), std::sync::Arc::new(package)); + + let entries = execute(&mut session, "library.functions", &json!({"filter": "MissingFunction"})).unwrap(); + assert_eq!(entries[0]["missing"], true); + assert_eq!(entries[0]["inputs"].as_array().unwrap().len(), 2); + + let id = execute(&mut session, "library.function.add", &json!({"package": "sbs://missing-functions.sbs", "graph": "Functions/Test/MissingFunction"})) + .unwrap()["id"] + .as_u64() + .unwrap(); + let node = session.graph().unwrap().function.as_ref().unwrap().node(id as u32).unwrap(); + assert!(matches!(node.source, Some(Err(_)))); + assert_eq!(node.instance.as_ref().unwrap().inputs.len(), 2); + let saved = file_cmds::save_bytes(&session).unwrap(); + let mut reopened = self::session(); + file_cmds::open_bytes(&mut reopened, &saved, None).unwrap(); + assert!(matches!(reopened.graph().unwrap().function.as_ref().unwrap().nodes[0].source, Some(Err(_)))); +} + +#[test] +fn function_library_accepts_processor_canvases_and_rejects_material_canvases() { + let mut package = Package::new("Processors"); + package.graphs.push(Graph::new("Material")); + let mut session = Session::new(package); + assert!(execute(&mut session, "library.function.add", &json!({"graph": "Functions/Math/Pi"})).is_err()); + + for kind in ["pixel_processor", "value_processor"] { + let owner = execute(&mut session, "graph.node.add", &json!({"def": kind})).unwrap()["id"].as_u64().unwrap(); + if kind == "pixel_processor" { + execute(&mut session, "graph.node.param", &json!({"id": owner, "param": "color_mode", "value": false})).unwrap(); + } + + let target = FunctionGraphTarget::Parameter { node: NodeId(owner), parameter: "function".into() }; + let node = execute(&mut session, "library.function.add", &json!({"graph": "Functions/Math/Pi", "function": target})).unwrap()["id"].as_u64().unwrap(); + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "output", "id": node}})).unwrap(); + + assert_eq!(value(target.current(&session).unwrap()), Value::Float(std::f32::consts::PI)); + } +} + +#[test] +fn library_aliases_open_as_references_and_require_a_local_save_path() { + let mut session = session(); + file_cmds::open_file(&mut session, "sbs://functions.sbs").unwrap(); + + assert_eq!(session.pkg.graphs.len(), 171); + let error = execute(&mut session, "file.save", &json!({})).unwrap_err().to_string(); + assert!(error.contains("local .sbs"), "{error}"); +} + +#[test] +fn renaming_a_nested_source_updates_its_local_reference() { + let mut session = session(); + session.pkg.graphs[0].folder = "Functions/Local".into(); + session.pkg.graphs[0].function = Some(FunctionGraph::constant(Value::Float(0.75))); + execute(&mut session, "file.new", &json!({"kind": "function", "name": "Consumer"})).unwrap(); + execute(&mut session, "graph.instance.add", &json!({"document": 0, "graph": "Functions/Local/Caller"})).unwrap(); + + execute(&mut session, "graph.rename", &json!({"graph": 0, "name": "Renamed"})).unwrap(); + + let node = &session.graph().unwrap().function.as_ref().unwrap().nodes[0]; + assert_eq!(node.instance.as_ref().unwrap().graph, "Functions/Local/Renamed"); + assert!(matches!(node.source, Some(Ok(_)))); +} + +#[test] +#[ignore = "local interoperability input; set MC_FUNCTIONS_SBS to an external package"] +fn supplied_library_instances_resolve_all_function_paths() { + let path = std::env::var("MC_FUNCTIONS_SBS").unwrap(); + let bytes = std::fs::read(&path).unwrap(); + let read = materialcraft_engine::formats::sbs::read_sbs(&bytes, &path, &|_| None).unwrap(); + let session = Session::new(read.pkg); + let mut references = 0; + let mut unresolved = 0; + let mut compiled = 0; + + for graph in &session.pkg.graphs { + let function = graph.function.as_ref().unwrap(); + for node in function.nodes.iter().filter(|node| node.instance.is_some()) { + let source = node.source.as_ref().expect("every instance must be resolved or diagnosed"); + if let Err(error) = source { + unresolved += 1; + eprintln!("Unresolved instance in {}: {error}", graph.sbs_path()); + } + references += 1; + } + match function::compile(function, 0) { + Ok(_) => compiled += 1, + Err(error) => eprintln!("Could not compile {}: {error}", graph.sbs_path()), + } + } + + eprintln!("Resolved {} of {references} instances and compiled {compiled} functions", references - unresolved); + assert_eq!(unresolved, 0, "every supplied instance must resolve"); + assert_eq!(compiled, session.pkg.graphs.len(), "every supplied function must compile"); +} + +#[test] +#[ignore = "local interoperability input; set MC_FUNCTIONS_SBS to an external package"] +fn supplied_functions_evaluate_before_and_after_save() { + let path = std::env::var("MC_FUNCTIONS_SBS").unwrap(); + let read = materialcraft_engine::formats::sbs::read_sbs(&std::fs::read(&path).unwrap(), &path, &|_| None).unwrap(); + let before = Session::new(read.pkg); + let bytes = materialcraft_engine::formats::sbs::write_sbs(&before.pkg).unwrap(); + let after = Session::new(materialcraft_engine::formats::sbs::read_sbs(&bytes, "saved.sbs", &|_| None).unwrap().pkg); + let bundled = Session::new( + materialcraft_engine::formats::sbs::read_sbs(include_bytes!("../../../assets/sbs/functions.sbs"), "functions.sbs", &|_| None).unwrap().pkg, + ); + let mut failures = Vec::new(); + let mut defaults = 0; + + for graph in &before.pkg.graphs { + let source = function::compile(graph.function.as_ref().unwrap(), 0).unwrap(); + let saved = after.pkg.graph_by_name(&graph.sbs_path()).unwrap().1; + let saved = function::compile(saved.function.as_ref().unwrap(), 0).unwrap(); + let converted = bundled.pkg.graph_by_name(&graph.sbs_path()).unwrap().1; + let converted = function::compile(converted.function.as_ref().unwrap(), 0).unwrap(); + let mut errors = Vec::new(); + for profile in 0..4 { + let mut variables: BTreeMap<_, _> = graph + .exposed + .iter() + .enumerate() + .map(|(index, parameter)| { + let scalar = (profile as f32 + index as f32) * 0.25; + let value = if profile == 0 { + parameter.default.clone() + } else { + match parameter.default { + Value::Float(_) => Value::Float(scalar), + Value::Float2(_) => Value::Float2([scalar, scalar * 2.0]), + Value::Float3(_) => Value::Float3([scalar, scalar * 2.0, scalar * 3.0]), + Value::Float4(_) => Value::Float4([scalar, scalar * 2.0, scalar * 3.0, scalar * 4.0]), + Value::Int(_) => Value::Int(profile), + Value::Int2(_) => Value::Int2([profile, profile + 1]), + Value::Int3(_) => Value::Int3([profile, profile + 1, profile + 2]), + Value::Int4(_) => Value::Int4([profile, profile + 1, profile + 2, profile + 3]), + Value::Bool(_) => Value::Bool(profile % 2 != 0), + _ => parameter.default.clone(), + } + }; + (parameter.id.clone(), value) + }) + .collect(); + // This hidden helper requires a render region supplied by its caller + if graph.name == "compute_total_number" { + variables.insert("render_region".into(), Value::Float4([-0.5, 0.5, -0.5, 0.5])); + } + let context = + EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [256.0, 128.0], images: &[], tile: true, variables: &variables }; + match source.evaluate(&context, &mut EvaluationState::default()) { + Ok(expected) => { + assert_eq!(saved.evaluate(&context, &mut EvaluationState::default()).unwrap(), expected, "{}", graph.sbs_path()); + assert_eq!(converted.evaluate(&context, &mut EvaluationState::default()).unwrap(), expected, "converted {}", graph.sbs_path()); + defaults += usize::from(profile == 0); + errors.clear(); + break; + } + Err(error) => errors.push(error), + } + } + if !errors.is_empty() { + failures.push(format!("{}: {}", graph.sbs_path(), errors.join("; "))); + } + } + + eprintln!( + "Evaluated {} of {} supplied functions before/after save and in the converted library; {defaults} used their declared defaults", + before.pkg.graphs.len() - failures.len(), + before.pkg.graphs.len() + ); + assert!(failures.is_empty(), "{}", failures.join("\n")); +} diff --git a/crates/engine/tests/graph_edit.rs b/crates/engine/tests/graph_edit.rs index d7630985..deaa5635 100644 --- a/crates/engine/tests/graph_edit.rs +++ b/crates/engine/tests/graph_edit.rs @@ -97,6 +97,8 @@ fn connected_selection_performance() { let mut graph = FunctionGraph::default(); for id in 1..=4096 { graph.nodes.push(materialcraft_engine::core::FunctionNode { + missing: None, + missing_data: String::new(), instance: None, source: None, id, diff --git a/crates/engine/tests/graph_interaction.rs b/crates/engine/tests/graph_interaction.rs index 69061cca..2bf5dfb8 100644 --- a/crates/engine/tests/graph_interaction.rs +++ b/crates/engine/tests/graph_interaction.rs @@ -1,6 +1,6 @@ use materialcraft_engine::{ - Session, - core::{NodeId, Value}, + FunctionGraphTarget, Session, + core::{FunctionGraph, NodeId, Value}, execute, formats::sbs::{read_sbs, write_sbs}, new_session, @@ -12,7 +12,7 @@ fn add(session: &mut Session, definition: &str) -> NodeId { } #[test] -fn fresh_value_processors_accept_one_source_and_round_trip() { +fn value_inputs_feed_authored_processors_and_round_trip() { let mut session = new_session(); let input = add(&mut session, "input_value"); execute(&mut session, "graph.node.param", &json!({"id": input.0, "param": "default", "value": 0.35})).unwrap(); @@ -20,12 +20,22 @@ fn fresh_value_processors_accept_one_source_and_round_trip() { NodeId(execute(&mut session, "graph.node.add", &json!({"def": "value_processor", "connectFrom": {"node": input.0}})).unwrap()["id"].as_u64().unwrap()); let second = add(&mut session, "value_processor"); execute(&mut session, "graph.connect", &json!({"from": input.0, "to": second.0, "toPort": "value1"})).unwrap(); + assert_eq!(session.graph().unwrap().connections.len(), 2); assert!(session.undo().is_some()); assert_eq!(session.graph().unwrap().connections.len(), 1); assert_eq!(session.graph().unwrap().connections[0].to, first); assert!(session.redo().is_some()); + + for node in [first, second] { + let target = FunctionGraphTarget::Parameter { node, parameter: "function".into() }; + assert_eq!(target.current(&session).unwrap(), &FunctionGraph::default()); + let mut function = FunctionGraph::default(); + function.output = Some(function.add("get_float1", &[], Some(Value::Text("value1".into())))); + execute(&mut session, "graph.function.set", &json!({"target": target, "function": function})).unwrap(); + } + session.cook(); for node in [first, second] { assert_eq!(session.cooked.value(node, 0), Some(&Value::Float(0.35))); diff --git a/crates/engine/tests/graph_properties.rs b/crates/engine/tests/graph_properties.rs new file mode 100644 index 00000000..9fbb5b7d --- /dev/null +++ b/crates/engine/tests/graph_properties.rs @@ -0,0 +1,119 @@ +use materialcraft_engine::{ + Session, + core::{Graph, Package}, + execute, +}; +use serde_json::json; + +#[test] +fn attributes_target_an_unopened_graph_without_changing_the_canvas() { + let mut package = Package::new("Source"); + package.graphs = vec![Graph::new("Canvas"), Graph::new("Inspected")]; + let mut session = Session::new(package); + + execute(&mut session, "graph.attributes", &json!({"graph": "Inspected", "description": "Edited elsewhere", "label": "Readable name"})).unwrap(); + + assert_eq!(session.graph, 0); + assert!(session.pkg.graphs[0].attributes.description.is_empty()); + assert_eq!(session.pkg.graphs[1].attributes.description, "Edited elsewhere"); + assert_eq!(serde_json::to_value(&session.pkg.graphs[1].attributes).unwrap()["label"], "Readable name"); +} + +#[test] +fn another_documents_properties_have_their_own_undo_history() { + let mut package = Package::new("Source"); + package.graphs.push(Graph::new("Inspected")); + let mut session = Session::new(package); + let source = session.document_id; + execute(&mut session, "file.newPackage", &json!({"name": "Canvas"})).unwrap(); + execute(&mut session, "file.new", &json!({"template": "empty"})).unwrap(); + let active = session.document_id; + let history = session.history(); + let selection = session.selection.clone(); + + execute(&mut session, "graph.attributes", &json!({"document": source, "graph": 0, "description": "Saved on source"})).unwrap(); + + assert_eq!(session.document_id, active); + assert_eq!(session.history(), history); + assert_eq!(session.selection, selection); + assert!(session.graph().unwrap().attributes.description.is_empty()); + execute(&mut session, "package.activate", &json!({"document": source})).unwrap(); + assert_eq!(session.graph().unwrap().attributes.description, "Saved on source"); + assert!(session.modified); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert!(session.graph().unwrap().attributes.description.is_empty()); + assert!(!session.modified); + execute(&mut session, "edit.redo", &json!({})).unwrap(); + assert_eq!(session.graph().unwrap().attributes.description, "Saved on source"); +} + +#[test] +fn invalid_attribute_updates_are_atomic_in_inactive_documents() { + let mut package = Package::new("Source"); + package.graphs.push(Graph::new("Inspected")); + let mut session = Session::new(package); + let source = session.document_id; + execute(&mut session, "file.newPackage", &json!({"name": "Canvas"})).unwrap(); + let original = materialcraft_engine::GraphTarget { document: source, graph: 0 }.package(&session).unwrap().clone(); + + assert!(execute(&mut session, "graph.attributes", &json!({"document": source, "graph": 0, "label": "Partial edit", "description": 42})).is_err()); + + assert_eq!(*materialcraft_engine::GraphTarget { document: source, graph: 0 }.package(&session).unwrap(), original); + assert!(!session.open_packages().iter().find(|(id, _, _, _)| *id == source).unwrap().3); + assert!(execute(&mut session, "graph.properties", &json!({"document": u64::MAX})).is_err()); + assert!(execute(&mut session, "graph.properties", &json!({"document": source, "graph": u64::MAX})).is_err()); +} + +#[test] +fn inactive_material_base_parameters_and_identifier_target_the_inspected_graph() { + let mut package = Package::new("Source"); + package.graphs = vec![Graph::new("Canvas"), Graph::new("Inspected")]; + let mut session = Session::new(package); + let source = session.document_id; + execute(&mut session, "file.newPackage", &json!({"name": "Other"})).unwrap(); + + for (command, mut parameters) in [ + ("graph.size", json!({"log2": [8, 9]})), + ("graph.seed", json!({"seed": 12})), + ("graph.format", json!({"format": "f32"})), + ("graph.rename", json!({"name": "Renamed"})), + ] { + parameters["document"] = json!(source); + parameters["graph"] = json!(1); + execute(&mut session, command, ¶meters).unwrap(); + } + + let graph = materialcraft_engine::GraphTarget { document: source, graph: 1 }.get(&session).unwrap(); + assert_eq!(graph.name, "Renamed"); + assert_eq!(graph.size, [8, 9]); + assert_eq!(graph.seed, 12); + assert_eq!(graph.format, materialcraft_engine::core::OutputFormat::F32); + assert_eq!(execute(&mut session, "graph.properties", &json!({"document": source, "graph": "Renamed"})).unwrap()["identifier"], "Renamed"); + assert_ne!(session.document_id, source); +} + +#[test] +fn a_function_label_updates_instances_without_renaming_references() { + use materialcraft_engine::core::{FunctionGraph, Value}; + let mut source = Graph::new("Stable_identifier"); + source.function = Some(FunctionGraph::constant(Value::Float(1.0))); + let mut caller = Graph::new("Caller"); + caller.function = Some(FunctionGraph::default()); + let mut package = Package::new("Labels"); + package.graphs = vec![source, caller]; + let mut session = Session::new(package); + execute(&mut session, "graph.open", &json!({"graph": "Caller"})).unwrap(); + execute(&mut session, "graph.instance.add", &json!({"document": 0, "graph": "Stable_identifier"})).unwrap(); + + execute(&mut session, "graph.attributes", &json!({"graph": "Stable_identifier", "label": "Readable label"})).unwrap(); + + let function = session.graph().unwrap().function.as_ref().unwrap(); + let node = &function.nodes[0]; + assert_eq!(materialcraft_engine::nodes::function::node_label(node), "Readable label"); + assert_eq!(node.instance.as_ref().unwrap().graph, "Stable_identifier"); + let bytes = materialcraft_engine::file_cmds::save_bytes(&session).unwrap(); + let reopened = Session::new(materialcraft_engine::formats::sbs::read_sbs(&bytes, "labels.sbs", &|_| None).unwrap().pkg); + let node = &reopened.pkg.graphs[1].function.as_ref().unwrap().nodes[0]; + assert_eq!(materialcraft_engine::nodes::function::node_label(node), "Readable label"); + assert_eq!(node.instance.as_ref().unwrap().graph, "Stable_identifier"); +} diff --git a/crates/engine/tests/linked_resources.rs b/crates/engine/tests/linked_resources.rs new file mode 100644 index 00000000..d16468c2 --- /dev/null +++ b/crates/engine/tests/linked_resources.rs @@ -0,0 +1,94 @@ +use materialcraft_engine::{ + Session, + core::{FunctionGraph, Graph, Package, Resource, ResourceBytes, Value}, + execute, file_cmds, + formats::sbs, +}; +use serde_json::json; + +const TILE: &[u8] = br#""#; + +fn resource_package(source: &str) -> Package { + let mut package = Package::new("Resource resolution"); + let mut graph = Graph::new("Constant"); + graph.function = Some(FunctionGraph::constant(Value::Float(0.5))); + package.graphs.push(graph); + let mut resource = Resource::new("Tile", "tile.svg", ResourceBytes::new(Vec::new())); + resource.source = source.into(); + package.resources.push(resource); + package +} + +#[test] +fn library_resources_resolve_next_to_their_package() { + const CHILD_ROOT: &str = "MC_LINKED_RESOURCES_TEST_ROOT"; + if let Ok(root) = std::env::var(CHILD_ROOT) { + verify_library_resources(std::path::Path::new(&root)); + return; + } + + // A child process isolates the library root without mutating the test runner's environment + let root = std::env::temp_dir().join(format!("materialcraft-linked-resources-{}", std::process::id())); + std::fs::create_dir_all(root.join("assets/sbs/resources")).unwrap(); + std::fs::create_dir_all(root.join("assets/sbs/nested/resources")).unwrap(); + std::fs::write(root.join("assets/sbs/resources/tile.svg"), TILE).unwrap(); + std::fs::write(root.join("assets/sbs/nested/resources/tile.svg"), TILE).unwrap(); + let package = sbs::write_sbs(&resource_package("resources/tile.svg")).unwrap(); + std::fs::write(root.join("assets/sbs/functions.sbs"), &package).unwrap(); + std::fs::write(root.join("assets/sbs/nested/source.sbs"), &package).unwrap(); + + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "library_resources_resolve_next_to_their_package", "--nocapture"]) + .env(CHILD_ROOT, &root) + .env("MATERIALCRAFT_SBS_DIR", root.join("assets/sbs")) + .status() + .unwrap(); + std::fs::remove_dir_all(root).unwrap(); + + assert!(status.success()); +} + +fn verify_library_resources(root: &std::path::Path) { + let mut session = Session::new(Package::new("Caller")); + let library = session.pkg.dependencies.get("sbs://functions.sbs").unwrap(); + assert_eq!(library.resources[0].bytes.as_slice(), TILE); + + file_cmds::open_file(&mut session, "sbs://nested/source.sbs").unwrap(); + assert!(session.load_warnings.is_empty(), "{:?}", session.load_warnings); + assert_eq!(session.pkg.resources[0].bytes.as_slice(), TILE); + execute(&mut session, "file.reload", &json!({})).unwrap(); + assert_eq!(session.pkg.resources[0].bytes.as_slice(), TILE); + + let read = file_cmds::linked_files("sbs://nested/source.sbs"); + assert_eq!(read("resources/tile.svg").unwrap(), TILE); + assert_eq!(read("sbs://resources/tile.svg").unwrap(), TILE); + assert_eq!(read("../resources/tile.svg").unwrap(), TILE); + assert!(read("../../private.svg").is_none()); + assert!(read("resources/absent.svg").is_none()); + + // Saving embeds loaded resources so a relocated package remains self-contained + let saved = file_cmds::save_bytes(&session).unwrap(); + let reopened = sbs::read_sbs(&saved, "elsewhere/copy.sbs", &|_| None).unwrap(); + assert!(reopened.warnings.is_empty(), "{:?}", reopened.warnings); + assert_eq!(reopened.pkg.resources[0].bytes.as_slice(), TILE); + + let source_document = session.document_id; + execute(&mut session, "file.newPackage", &json!({})).unwrap(); + execute(&mut session, "file.new", &json!({"kind": "function"})).unwrap(); + execute(&mut session, "graph.instance.add", &json!({"document": source_document, "graph": "Constant"})).unwrap(); + let caller = file_cmds::save_bytes(&session).unwrap(); + let mut dependent = Session::new(Package::new("Dependent")); + file_cmds::open_bytes(&mut dependent, &caller, Some(root.join("dependent.sbs").to_string_lossy().into_owned())).unwrap(); + assert_eq!(dependent.pkg.dependencies["sbs://nested/source.sbs"].resources[0].bytes.as_slice(), TILE); + + let missing = sbs::write_sbs(&resource_package("resources/absent.svg")).unwrap(); + file_cmds::open_bytes_linked(&mut session, &missing, Some("sbs://nested/missing.sbs".into()), &read).unwrap(); + assert!(session.pkg.resources[0].bytes.is_empty()); + assert_eq!(session.pkg.resources[0].source, "sbs://nested/resources/absent.svg"); + assert!(!session.load_warnings.is_empty()); + + let local = root.join("caller.sbs"); + std::fs::write(&local, sbs::write_sbs(&resource_package("sbs://resources/tile.svg")).unwrap()).unwrap(); + file_cmds::open_file(&mut session, local.to_str().unwrap()).unwrap(); + assert_eq!(session.pkg.resources[0].bytes.as_slice(), TILE); +} diff --git a/crates/engine/tests/open_documents.rs b/crates/engine/tests/open_documents.rs index 49c7ee90..83366cc5 100644 --- a/crates/engine/tests/open_documents.rs +++ b/crates/engine/tests/open_documents.rs @@ -8,15 +8,19 @@ fn opening_another_package_preserves_edits_selection_and_undo() { let added = execute(&mut session, "graph.node.add", &json!({"def": "uniform"})).unwrap(); let history = session.history(); let selection = session.selection.clone(); - let original = session.pkg.clone(); + let original = file_cmds::save_bytes(&session).unwrap(); let bytes = formats::sbs::write_sbs(&Package::new("Second")).unwrap(); + file_cmds::open_bytes(&mut session, &bytes, Some("second.sbs".into())).unwrap(); + assert_eq!(inspect::session(&session, None)["documents"].as_array().unwrap().len(), 2); execute(&mut session, "package.activate", &json!({"document": 0})).unwrap(); - assert_eq!(session.pkg, original); + // Other open packages extend the runtime dependency registry without editing this document + assert_eq!(file_cmds::save_bytes(&session).unwrap(), original); assert_eq!(session.selection, selection); assert_eq!(session.history(), history); assert!(session.modified); + execute(&mut session, "edit.undo", &json!({})).unwrap(); assert!(session.graph().unwrap().nodes.iter().all(|node| node.id.0 != added["id"].as_u64().unwrap())); } diff --git a/crates/engine/tests/system_variables.rs b/crates/engine/tests/system_variables.rs new file mode 100644 index 00000000..5ccebbfc --- /dev/null +++ b/crates/engine/tests/system_variables.rs @@ -0,0 +1,270 @@ +use materialcraft_engine::{ + FunctionGraphTarget, Session, + core::{FunctionGraph, Graph, NodeId, Package, ParameterInheritance, Value}, + execute, + formats::sbs::{read_sbs, write_sbs}, + new_session, +}; +use serde_json::json; + +fn getter(operation: &str, name: &str) -> FunctionGraph { + let mut function = FunctionGraph::default(); + function.output = Some(function.add(operation, &[], Some(Value::Text(name.into())))); + function +} + +fn processor(graph: &mut Graph, operation: &str, name: &str) -> NodeId { + let id = graph.add_node("value_processor", [0.0; 2]); + graph.node_mut(id).unwrap().params.insert("function".into(), Value::Function(Box::new(getter(operation, name)))); + id +} + +#[test] +fn standalone_get_suggestions_match_each_type_and_order() { + let mut session = new_session(); + execute(&mut session, "file.new", &json!({"kind": "function", "name": "Variables"})).unwrap(); + for (operation, expected) in [ + ("get_string", vec![]), + ("get_bool", vec![]), + ("get_integer4", vec![]), + ("get_integer3", vec![]), + ("get_integer2", vec!["$uvtile"]), + ("get_integer1", vec!["$normalformat", "$tiling", "$pixelratio"]), + ("get_float4", vec![]), + ("get_float3", vec!["$physicalsize"]), + ("get_float2", vec!["$size", "$sizelog2"]), + ("get_float1", vec!["$time"]), + ] { + let function = getter(operation, "ITypedThis"); + let id = function.output.unwrap(); + execute(&mut session, "graph.function.set", &json!({"function": function})).unwrap(); + let before = session.pkg.clone(); + + let result = execute(&mut session, "graph.function.variables", &json!({"id": id})).unwrap(); + let variables = result["variables"].as_array().unwrap(); + let actual: Vec<_> = variables.iter().filter(|variable| variable["system"] == true).map(|variable| variable["name"].as_str().unwrap()).collect(); + + assert_eq!(actual, expected, "{operation}"); + assert_eq!(variables.last().unwrap()["name"], "ITypedThis"); + assert_eq!(session.pkg, before); + } +} + +#[test] +fn pixel_processor_suggestions_add_position_without_fx_variables() { + let mut graph = Graph::new("Pixels"); + let owner = graph.add_node("pixel_processor", [0.0; 2]); + graph.node_mut(owner).unwrap().params.insert("function".into(), Value::Function(Box::new(getter("get_float2", "")))); + let mut package = Package::new("Pixels"); + package.graphs.push(graph); + let session = Session::new(package); + let target = FunctionGraphTarget::Parameter { node: owner, parameter: "function".into() }; + + let variables = target.variables(&session, 1).unwrap(); + + assert_eq!(variables.iter().map(|variable| variable.name.as_str()).collect::>(), ["$size", "$sizelog2", "$pos"]); +} + +#[test] +fn graph_metadata_and_host_values_cook_and_round_trip_as_native_get_nodes() { + let mut graph = Graph::new("Context"); + graph.size = [5, 4]; + let cases = [ + ("get_float1", "$time", Value::Float(2.5)), + ("get_integer2", "$uvtile", Value::Int2([7, 11])), + ("get_integer1", "$normalformat", Value::Int(1)), + ("get_integer1", "$tiling", Value::Int(2)), + ("get_integer1", "$pixelratio", Value::Int(1)), + ("get_float3", "$physicalsize", Value::Float3([20.0, 10.0, 0.5])), + ("get_float2", "$size", Value::Float2([32.0, 16.0])), + ("get_float2", "$sizelog2", Value::Float2([5.0, 4.0])), + ]; + let ids: Vec<_> = cases.iter().map(|(operation, name, _)| processor(&mut graph, operation, name)).collect(); + let mut package = Package::new("Context"); + package.graphs.push(graph); + let mut session = Session::new(package); + execute(&mut session, "graph.context", &json!({"physicalSize": [20, 10, 0.5], "pixelRatio": 1, "tiling": [false, true]})).unwrap(); + let environment = json!({"timeSeconds": 2.5, "uvTile": [7, 11], "normalFormat": 1}); + execute(&mut session, "session.environment", &environment).unwrap(); + let bytes = write_sbs(&session.pkg).unwrap(); + let read = read_sbs(&bytes, "context.sbs", &|_| None).unwrap(); + assert!(read.warnings.is_empty(), "{:?}", read.warnings); + let mut reopened = Session::new(read.pkg); + execute(&mut reopened, "session.environment", &environment).unwrap(); + + for session in [&mut session, &mut reopened] { + let cooked = session.cook(); + for ((_, name, expected), id) in cases.iter().zip(&ids) { + let result = &cooked.nodes[id]; + assert_eq!(result.error, None, "{name}"); + assert_eq!(result.outputs[0].as_value(), Some(expected), "{name}"); + } + assert!(session.cook().nodes.values().all(|result| result.cached)); + let original = session.pkg.clone(); + execute(session, "session.environment", &json!({"timeSeconds": 4.0})).unwrap(); + let cooked = session.cook(); + assert_eq!(cooked.nodes[&ids[0]].outputs[0].as_value(), Some(&Value::Float(4.0))); + assert!(!cooked.nodes[&ids[0]].cached); + assert!(cooked.nodes[&ids[1]].cached, "unrelated host variables keep their cache entries"); + assert_eq!(session.pkg, original, "host values are not authored into the package"); + } +} + +#[test] +fn pixel_ratio_and_tiling_inherit_and_preserve_native_relative_modes() { + let mut graph = Graph::new("Inheritance"); + graph.size = [4, 4]; + graph.tiling = [true, true]; + let source = graph.add_node("uniform", [0.0; 2]); + let input = graph.node_mut(source).unwrap(); + input.base.pixel_ratio = 1; + input.base.pixel_ratio_mode = ParameterInheritance::Absolute; + input.base.tiling = [true, false]; + input.base.tiling_mode = ParameterInheritance::Absolute; + let pixel = graph.add_node("pixel_processor", [200.0, 0.0]); + let mut function = getter("get_integer1", "$pixelratio"); + let ratio = function.output.unwrap(); + let tiling = function.add("get_integer1", &[], Some(Value::Text("$tiling".into()))); + let value = function.add("add", &[ratio, tiling], None); + function.output = Some(function.add("tofloat", &[value], None)); + graph.node_mut(pixel).unwrap().params.insert("function".into(), Value::Function(Box::new(function))); + graph.connect(source, "output", pixel, "input0").unwrap(); + let mut package = Package::new("Inheritance"); + package.graphs.push(graph); + let mut session = Session::new(package); + session.selection = vec![pixel]; + + for (mode, expected) in [("relativeToInput", 2.0), ("relativeToParent", 3.0), ("absolute", 0.0)] { + execute(&mut session, "graph.node.base", &json!({"pixelRatio": 0, "tiling": false, "pixelRatioMode": mode, "tilingMode": mode})).unwrap(); + let bytes = write_sbs(&session.pkg).unwrap(); + let read = read_sbs(&bytes, "inheritance.sbs", &|_| None).unwrap(); + assert!(read.warnings.is_empty(), "{:?}", read.warnings); + assert_eq!(read.pkg.graphs[0].node(pixel).unwrap().base, session.pkg.graphs[0].node(pixel).unwrap().base); + let mut reopened = Session::new(read.pkg); + + for session in [&mut session, &mut reopened] { + let cooked = session.cook(); + assert_eq!(cooked.nodes[&pixel].error, None); + assert!((cooked.image(pixel, 0).unwrap().mean()[0] - expected).abs() < 1e-6, "{mode}"); + } + } +} + +#[test] +fn nested_graph_instances_inherit_host_values_and_invalidate_their_cache() { + let mut source = Graph::new("Source"); + source.size = [4, 4]; + let value = processor(&mut source, "get_float1", "$time"); + let output = source.add_node("output", [200.0, 0.0]); + source.connect(value, "output", output, "input").unwrap(); + let mut package = Package::new("Nested"); + package.graphs.push(source); + for (name, reference) in [("Middle", "Source"), ("Outer", "Middle")] { + let mut graph = Graph::new(name); + graph.size = [4, 4]; + let instance = graph.add_node("graph_instance", [0.0; 2]); + graph.node_mut(instance).unwrap().params.insert("graph".into(), Value::Text(reference.into())); + let output = graph.add_node("output", [200.0, 0.0]); + graph.connect(instance, "output", output, "input").unwrap(); + package.graphs.push(graph); + } + let mut session = Session::new(package); + session.graph = 2; + for seconds in [1.25, 8.5] { + execute(&mut session, "session.environment", &json!({"timeSeconds": seconds})).unwrap(); + + let cooked = session.cook(); + + for result in cooked.nodes.values() { + assert_eq!(result.error, None); + assert_eq!(result.outputs[0].as_value(), Some(&Value::Float(seconds))); + assert!(!result.cached); + } + assert!(session.cook().nodes.values().all(|result| result.cached)); + } +} + +fn function_instance(name: &str, type_code: u32) -> FunctionGraph { + let mut function = FunctionGraph::default(); + let id = function.add("instance", &[], None); + function.nodes[0].instance = Some(materialcraft_engine::core::GraphInstance { + label: String::new(), + package: String::new(), + graph: name.into(), + inputs: Vec::new(), + outputs: vec![materialcraft_engine::core::GraphPort { identifier: "output".into(), type_code }], + defaults: Default::default(), + }); + function.output = Some(id); + function +} + +#[test] +fn nested_function_instances_use_the_processing_callers_variable_scope() { + let mut package = Package::new("Caller scope"); + let mut source = Graph::new("Position"); + source.function = Some(getter("get_float2", "$pos")); + package.graphs.push(source); + let mut wrapper = Graph::new("NestedPosition"); + wrapper.function = Some(function_instance("Position", 512)); + package.graphs.push(wrapper); + let mut graph = Graph::new("Material"); + graph.size = [4, 4]; + let pixel = graph.add_node("pixel_processor", [0.0; 2]); + let value = graph.add_node("value_processor", [200.0, 0.0]); + for id in [pixel, value] { + graph.node_mut(id).unwrap().params.insert("function".into(), Value::Function(Box::new(function_instance("NestedPosition", 512)))); + } + package.graphs.push(graph); + let mut session = Session::new(package); + let bytes = write_sbs(&session.pkg).unwrap(); + let mut reopened = Session::new(read_sbs(&bytes, "scope.sbs", &|_| None).unwrap().pkg); + + for session in [&mut session, &mut reopened] { + session.graph = 2; + let cooked = session.cook(); + + assert_eq!(cooked.nodes[&pixel].error, None); + assert!(cooked.nodes[&value].error.as_deref().unwrap().contains("undefined variable `$pos`")); + let image = cooked.image(pixel, 0).unwrap(); + assert_eq!(&image.get(0, 0, false)[..2], &[0.03125; 2]); + assert_eq!(&image.get(15, 15, false)[..2], &[0.96875; 2]); + } +} + +#[test] +fn environment_errors_are_atomic_and_graph_context_is_undoable() { + let mut session = new_session(); + let original_environment = session.environment; + let original_package = session.pkg.clone(); + for parameters in [json!({"timeSeconds": -1}), json!({"timeSeconds": 1e100}), json!({"timeSeconds": 2, "uvTile": [1]}), json!({"normalFormat": "invalid"})] + { + assert!(execute(&mut session, "session.environment", ¶meters).is_err()); + assert_eq!(session.environment, original_environment); + assert_eq!(session.pkg, original_package); + } + for parameters in [json!({"physicalSize": [1, 2]}), json!({"physicalSize": [-1, 2, 3]}), json!({"pixelRatio": 3}), json!({"tiling": [true]})] { + assert!(execute(&mut session, "graph.context", ¶meters).is_err()); + assert_eq!(session.pkg, original_package); + } + + execute(&mut session, "graph.context", &json!({"physicalSize": [2, 3, 4], "pixelRatio": 0})).unwrap(); + assert_eq!(session.graph().unwrap().physical_size, [2.0, 3.0, 4.0]); + assert_eq!(session.graph().unwrap().pixel_ratio_mode, ParameterInheritance::Absolute); + session.undo().unwrap(); + assert_eq!(session.pkg, original_package); + session.redo().unwrap(); + assert_eq!(session.graph().unwrap().physical_size, [2.0, 3.0, 4.0]); +} + +#[test] +fn reusable_functions_cannot_author_context_that_belongs_to_their_caller() { + let mut session = new_session(); + execute(&mut session, "file.new", &json!({"kind": "function", "name": "Caller context"})).unwrap(); + let original = session.pkg.clone(); + + let error = execute(&mut session, "graph.context", &json!({"physicalSize": [1, 2, 3]})).unwrap_err(); + + assert!(error.to_string().contains("caller's evaluation context")); + assert_eq!(session.pkg, original); +} diff --git a/crates/eval/src/graph_execution.rs b/crates/eval/src/graph_execution.rs index a9c48c19..7a84fa08 100644 --- a/crates/eval/src/graph_execution.rs +++ b/crates/eval/src/graph_execution.rs @@ -29,7 +29,7 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu options }; - let prepared = PreparedGraph::new(package, graph, options.only.as_deref()); + let prepared = PreparedGraph::new(package, graph, options); // Exposed parameter values: the graph's own, then the caller's overrides let mut variables: BTreeMap = @@ -37,6 +37,11 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu for (name, value) in &options.overrides { variables.insert(name.clone(), value.clone()); } + variables.insert("$time".into(), Value::Float(options.environment.time_seconds)); + variables.insert("$uvtile".into(), Value::Int2(options.environment.uv_tile)); + variables.insert("$normalformat".into(), Value::Int(options.environment.normal_format)); + variables.insert("$physicalsize".into(), Value::Float3(graph.physical_size)); + for &id in &prepared.order { if options.cancel.is_some_and(|cancel| cancel.load(Ordering::Relaxed)) { cooked.cancelled = true; diff --git a/crates/eval/src/graph_instance.rs b/crates/eval/src/graph_instance.rs index 4ed35dce..d5928db7 100644 --- a/crates/eval/src/graph_instance.rs +++ b/crates/eval/src/graph_instance.rs @@ -45,6 +45,7 @@ pub(crate) fn cook_instance( inputs: &[Option<&NodeOutput>], params: &BTreeMap, size: (u32, u32), + base: crate::resolved_base_parameters::ResolvedBaseParameters, opts: &Options, cache: &Mutex, ) -> Result, String> { @@ -69,6 +70,9 @@ pub(crate) fn cook_instance( _ => (opts.resource)(name), }; let mut o = Options::new(&resource); + o.environment = opts.environment; + o.parent_tiling = Some(base.tiling); + o.parent_pixel_ratio = Some(base.pixel_ratio); o.registry = Some(registry); o.resource_root = Some(root_resource); o.max_size = opts.max_size; diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index 3fea0cce..aee73603 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -17,6 +17,7 @@ mod parameter; mod port; mod ports; mod prepared_graph; +mod resolved_base_parameters; mod resource_decoder; mod time; mod value_execution; diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs index dbe98ee4..de70ee85 100644 --- a/crates/eval/src/node_execution.rs +++ b/crates/eval/src/node_execution.rs @@ -80,6 +80,13 @@ pub(crate) fn cook_node( incoming.push(output); } + let base = prepared.base_parameters(node); + if !node.functions.is_empty() || matches!(node.def.as_str(), "pixel_processor" | "value_processor" | "fx_map") { + let tiling = i32::from(base.tiling[0]) | (i32::from(base.tiling[1]) << 1); + variables.to_mut().insert("$tiling".into(), Value::Int(tiling)); + variables.to_mut().insert("$pixelratio".into(), Value::Int(base.pixel_ratio)); + } + let vars = &variables; let first = prepared.first_input_size(node.id); let (w, h) = node_size(graph, def, node, first, opts.max_size); @@ -101,7 +108,7 @@ pub(crate) fn cook_node( Err(error) => return fail(error, 0), }; - let tile = node.base.tiling[0] && node.base.tiling[1]; + let tile = base.tiling[0] && base.tiling[1]; // Input nodes read the caller's image for their identifier let input_img = node.def.starts_with("input_").then(|| opts.inputs.get(&identifier(node))).flatten(); let res_hash = match params.get("resource") { @@ -119,10 +126,12 @@ pub(crate) fn cook_node( let key = hash_of(&( &node.def, serde_json::to_string(¶ms).unwrap_or_default(), - (w, h, seed, tile, node.disabled), + (w, h, seed, tile, node.disabled, base.tiling, base.pixel_ratio), &input_keys, res_hash, sub_hash, + // A cached graph instance includes results evaluated with its host environment + (node.def == "graph_instance").then(|| serde_json::to_string(&opts.environment).unwrap_or_default()), input_img.map(|image| image_key(image, cache)), variable_key(node, ¶ms, vars), )); @@ -150,7 +159,7 @@ pub(crate) fn cook_node( Err(format!("unsupported node `{name}`")) } else if node.def == "graph_instance" { - cook_instance(pkg, gi, node, in_ports, out_ports, &incoming, ¶ms, (w, h), opts, cache) + cook_instance(pkg, gi, node, in_ports, out_ports, &incoming, ¶ms, (w, h), base, opts, cache) } else if let Some(definition) = def { let context = CookContext { w, h, seed, tile, inputs: &inputs, params: ¶ms, resource: opts.resource, vars }; (definition.cook)(&context).map(|images| images.into_iter().map(NodeOutput::Image).collect()) diff --git a/crates/eval/src/options.rs b/crates/eval/src/options.rs index a28716c3..91d0bd56 100644 --- a/crates/eval/src/options.rs +++ b/crates/eval/src/options.rs @@ -5,6 +5,9 @@ use std::sync::atomic::AtomicBool; /// What to cook and how pub struct Options<'a> { + pub environment: materialcraft_core::EvaluationEnvironment, + pub parent_tiling: Option<[bool; 2]>, + pub parent_pixel_ratio: Option, /// Cap on the larger side of every node's output (previews); `None` = full size pub max_size: Option, /// Cook only these nodes and what they depend on (`None` = the whole graph) @@ -28,6 +31,9 @@ pub struct Options<'a> { impl<'a> Options<'a> { pub fn new(resource: &'a crate::ResourceDecoder<'a>) -> Options<'a> { Options { + environment: Default::default(), + parent_tiling: None, + parent_pixel_ratio: None, max_size: None, only: None, inputs: BTreeMap::new(), diff --git a/crates/eval/src/parameter.rs b/crates/eval/src/parameter.rs index 5d2a7b57..4005a931 100644 --- a/crates/eval/src/parameter.rs +++ b/crates/eval/src/parameter.rs @@ -29,6 +29,7 @@ pub(crate) fn resolve_parameters( match materialcraft_nodes::function::compile(f, seed) { Ok(prog) => { let context = materialcraft_nodes::function::EvaluationContext { + scope: Default::default(), position: [0.5; 2], size: size.map(|side| side as f32), images: &[], diff --git a/crates/eval/src/prepared_graph.rs b/crates/eval/src/prepared_graph.rs index d34d0c6e..615b69c9 100644 --- a/crates/eval/src/prepared_graph.rs +++ b/crates/eval/src/prepared_graph.rs @@ -7,13 +7,15 @@ pub(crate) struct PreparedGraph<'a> { pub index: GraphIndex<'a>, pub order: Vec, nominal_sizes: BTreeMap, + base_parameters: BTreeMap, + parent_base: crate::resolved_base_parameters::ResolvedBaseParameters, ports: BTreeMap, Vec)>, } impl<'a> PreparedGraph<'a> { - pub fn new(package: &Package, graph: &'a Graph, roots: Option<&[NodeId]>) -> Self { + pub fn new(package: &Package, graph: &'a Graph, options: &crate::Options<'_>) -> Self { let index = GraphIndex::new(graph); - let needed = roots.map(|roots| index.required_nodes(roots)); + let needed = options.only.as_deref().map(|roots| index.required_nodes(roots)); let order: Vec<_> = index.topo_order().into_iter().filter(|id| needed.as_ref().is_none_or(|needed| needed.contains(id))).collect(); let ports = order .iter() @@ -23,7 +25,8 @@ impl<'a> PreparedGraph<'a> { }) .collect(); - let mut prepared = Self { index, order, ports, nominal_sizes: BTreeMap::new() }; + let parent_base = crate::resolved_base_parameters::ResolvedBaseParameters::graph(graph, options); + let mut prepared = Self { index, order, ports, nominal_sizes: BTreeMap::new(), base_parameters: BTreeMap::new(), parent_base }; for &id in &prepared.order { let Some(node) = prepared.index.node(id) else { continue }; @@ -34,6 +37,12 @@ impl<'a> PreparedGraph<'a> { crate::node_size(graph, materialcraft_nodes::find(&node.def), node, input, None) }; prepared.nominal_sizes.insert(id, nominal); + let input_base = prepared.ports(id).0.iter().filter(|port| port.kind != materialcraft_nodes::PortKind::Value).find_map(|port| { + let connection = prepared.index.input_of(id, &port.id)?; + prepared.base_parameters.get(&connection.from).copied() + }); + let base = crate::resolved_base_parameters::ResolvedBaseParameters::resolve(&node.base, input_base, parent_base); + prepared.base_parameters.insert(id, base); } prepared } @@ -48,4 +57,11 @@ impl<'a> PreparedGraph<'a> { pub fn ports(&self, id: NodeId) -> (&[Port], &[Port]) { self.ports.get(&id).map_or((&[], &[]), |(inputs, outputs)| (inputs.as_slice(), outputs.as_slice())) } + + pub fn base_parameters(&self, node: &materialcraft_core::Node) -> crate::resolved_base_parameters::ResolvedBaseParameters { + self.base_parameters + .get(&node.id) + .copied() + .unwrap_or_else(|| crate::resolved_base_parameters::ResolvedBaseParameters::resolve(&node.base, None, self.parent_base)) + } } diff --git a/crates/eval/src/resolved_base_parameters.rs b/crates/eval/src/resolved_base_parameters.rs new file mode 100644 index 00000000..94baaa28 --- /dev/null +++ b/crates/eval/src/resolved_base_parameters.rs @@ -0,0 +1,23 @@ +use materialcraft_core::{BaseParameters, Graph}; + +#[derive(Clone, Copy)] +pub(crate) struct ResolvedBaseParameters { + pub tiling: [bool; 2], + pub pixel_ratio: i32, +} + +impl ResolvedBaseParameters { + pub fn graph(graph: &Graph, options: &crate::Options<'_>) -> Self { + Self { + tiling: graph.tiling_mode.resolve(graph.tiling, options.parent_tiling, options.parent_tiling.unwrap_or(graph.tiling)), + pixel_ratio: graph.pixel_ratio_mode.resolve(graph.pixel_ratio, options.parent_pixel_ratio, options.parent_pixel_ratio.unwrap_or(graph.pixel_ratio)), + } + } + + pub fn resolve(base: &BaseParameters, input: Option, parent: Self) -> Self { + Self { + tiling: base.tiling_mode.resolve(base.tiling, input.map(|input| input.tiling), parent.tiling), + pixel_ratio: base.pixel_ratio_mode.resolve(base.pixel_ratio, input.map(|input| input.pixel_ratio), parent.pixel_ratio), + } + } +} diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index f1271949..ee5991bb 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -42,6 +42,31 @@ fn cooks_and_caches() { assert_eq!(outputs(&p.graphs[0], &c).len(), 1); } +#[test] +fn processor_tiling_variable_tracks_both_axes_and_invalidates_cached_values() { + let mut function = materialcraft_core::FunctionGraph::default(); + function.output = Some(function.add("get_integer1", &[], Some(Value::Text("$tiling".into())))); + let mut graph = Graph::new("Tiling"); + let processor = graph.add_node("value_processor", [0.0; 2]); + graph.node_mut(processor).unwrap().params.insert("function".into(), Value::Function(Box::new(function))); + let mut package = Package::new("Tiling"); + package.graphs.push(graph); + let cache = Mutex::new(Cache::default()); + + for (tiling, expected) in [([false, false], 0), ([true, false], 1), ([false, true], 2), ([true, true], 3)] { + package.graphs[0].node_mut(processor).unwrap().base.tiling = tiling; + package.graphs[0].node_mut(processor).unwrap().base.tiling_mode = materialcraft_core::ParameterInheritance::Absolute; + let result = cook(&package, 0, &Options::new(&no_res), &cache); + + assert_eq!(result.nodes[&processor].error, None); + assert_eq!(result.nodes[&processor].outputs[0].as_value(), Some(&Value::Int(expected))); + assert!(!result.nodes[&processor].cached); + let cached = cook(&package, 0, &Options::new(&no_res), &cache); + assert!(cached.nodes[&processor].cached); + assert_eq!(cached.nodes[&processor].outputs[0].as_value(), Some(&Value::Int(expected))); + } +} + #[test] fn hostile_param_is_clamped_before_cooking() { let (mut p, noise, _, _) = sample(); @@ -229,6 +254,8 @@ fn input_change_recooks_only_readers() { let (mut p, noise, blur, out) = sample(); let reader = p.graphs[0].add_node("pixel_processor", [0.0, 100.0]); let get_a = FunctionNode { + missing: None, + missing_data: String::new(), instance: None, source: None, id: 1, diff --git a/crates/eval/src/value_execution.rs b/crates/eval/src/value_execution.rs index ee72c631..6ed651cf 100644 --- a/crates/eval/src/value_execution.rs +++ b/crates/eval/src/value_execution.rs @@ -17,7 +17,7 @@ pub(crate) fn evaluate_value( }; let program = compile(graph, seed)?; - let context = EvaluationContext { position: [0.5; 2], size: size.map(|side| side as f32), images, tile, variables }; + let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: size.map(|side| side as f32), images, tile, variables }; program.evaluate(&context, &mut EvaluationState::default()) } diff --git a/crates/formats/examples/standard_function_library/convert.rs b/crates/formats/examples/standard_function_library/convert.rs new file mode 100644 index 00000000..6c88540c --- /dev/null +++ b/crates/formats/examples/standard_function_library/convert.rs @@ -0,0 +1,46 @@ +use materialcraft_core::{Package, ValueType}; +use materialcraft_nodes::function; + +pub(super) fn package(bytes: &[u8], source: &str) -> Result> { + let imported = materialcraft_formats::sbs::read_sbs(bytes, source, &|_| None)?; + if !imported.warnings.is_empty() { + return Err(imported.warnings.join("\n").into()); + } + + if !imported.pkg.resources.is_empty() { + return Err("function library conversion does not copy resource assets".into()); + } + + let mut package = imported.pkg.clone(); + for graph in &mut package.graphs { + let path = graph.sbs_path(); + let body = graph.function.as_mut().ok_or_else(|| format!("{path}: expected a Function Graph"))?; + if body.nodes.iter().any(|node| node.missing.is_some()) { + return Err(format!("{path}: contains unsupported operations").into()); + } + + // Resolve a temporary body so validation cannot rewrite the source connector contract + let mut resolved = body.clone(); + function::resolve_instances(&mut resolved, &imported.pkg, &imported.pkg.dependencies); + function::compile(&resolved, 0).map_err(|error| format!("{path}: {error}"))?; + crate::layout::reposition(body).map_err(|error| format!("{path}: {error}"))?; + + let result = ValueType::from_code(graph.function_type).ok_or_else(|| format!("{path}: unknown result type"))?; + let inputs = if graph.exposed.is_empty() { + "none".to_string() + } else { + graph.exposed.iter().map(|parameter| parameter.id.as_str()).collect::>().join(", ") + }; + graph.attributes.description = format!("Evaluates the {} function graph. Result type: {}. Inputs: {inputs}.", graph.name, result.label()); + graph.attributes.category = graph.folder.clone(); + graph.attributes.author.clear(); + graph.attributes.author_url.clear(); + graph.attributes.user_data.clear(); + graph.attributes.tags.clear(); + graph.frames.clear(); + graph.comments.clear(); + graph.pins.clear(); + } + + Ok(package) +} diff --git a/crates/formats/examples/standard_function_library/layout.rs b/crates/formats/examples/standard_function_library/layout.rs new file mode 100644 index 00000000..d3b62298 --- /dev/null +++ b/crates/formats/examples/standard_function_library/layout.rs @@ -0,0 +1,56 @@ +use materialcraft_core::FunctionGraph; +use std::collections::{BTreeMap, VecDeque}; + +pub(super) fn reposition(function: &mut FunctionGraph) -> Result<(), String> { + if function.nodes.len() > 4096 { + return Err("function exceeds the 4096-node limit".into()); + } + + let mut pending = BTreeMap::new(); + let mut successors = BTreeMap::>::new(); + let mut columns = BTreeMap::::new(); + let mut ready = VecDeque::new(); + for node in &function.nodes { + if pending.insert(node.id, node.inputs.iter().flatten().count()).is_some() { + return Err("duplicate node identifier".into()); + } + + if node.inputs.iter().all(Option::is_none) { + ready.push_back(node.id); + } + for input in node.inputs.iter().flatten() { + successors.entry(*input).or_default().push(node.id); + } + } + if successors.keys().any(|identifier| !pending.contains_key(identifier)) { + return Err("connection references a missing node".into()); + } + + let mut visited = 0; + while let Some(identifier) = ready.pop_front() { + visited += 1; + let next_column = columns.get(&identifier).copied().unwrap_or(0) + 1; + for successor in successors.get(&identifier).into_iter().flatten() { + let column = columns.entry(*successor).or_default(); + *column = (*column).max(next_column); + let remaining = pending.get_mut(successor).ok_or("missing successor")?; + *remaining = remaining.checked_sub(1).ok_or("inconsistent connection count")?; + if *remaining == 0 { + ready.push_back(*successor); + } + } + } + if visited != function.nodes.len() { + return Err("function contains a connection cycle".into()); + } + + let mut heights = BTreeMap::::new(); + for node in &mut function.nodes { + let column = columns.get(&node.id).copied().unwrap_or(0); + let height = heights.entry(column).or_default(); + node.pos = [64.0 + column as f32 * 280.0, 64.0 + *height]; + *height += (80.0 + node.inputs.len() as f32 * 28.0).max(160.0); + } + + Ok(()) +} diff --git a/crates/formats/examples/standard_function_library/main.rs b/crates/formats/examples/standard_function_library/main.rs new file mode 100644 index 00000000..ef77427c --- /dev/null +++ b/crates/formats/examples/standard_function_library/main.rs @@ -0,0 +1,37 @@ +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod convert; +mod layout; + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests; + +use std::{io::Read, path::Path}; + +fn main() -> Result<(), Box> { + let mut arguments = std::env::args().skip(1); + let source = arguments.next().ok_or("usage: standard_function_library [destination.sbs]")?; + let destination = arguments.next().unwrap_or_else(|| "assets/sbs/functions.sbs".into()); + if arguments.next().is_some() { + return Err("usage: standard_function_library [destination.sbs]".into()); + } + + // Bound allocation before parsing potentially untrusted XML + const MAX_BYTES: u64 = 256 << 20; + let mut bytes = Vec::new(); + std::fs::File::open(&source)?.take(MAX_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_BYTES { + return Err("source package exceeds 256 MiB".into()); + } + + let package = convert::package(&bytes, &source)?; + let nodes: usize = package.graphs.iter().flat_map(|graph| graph.functions()).map(|function| function.nodes.len()).sum(); + let saved = materialcraft_formats::sbs::write_sbs(&package)?; + materialcraft_formats::write_atomic(Path::new(&destination), &saved)?; + + eprintln!("Saved {} function graphs and {nodes} nodes to {destination}", package.graphs.len()); + eprintln!("Descriptions and layout were rewritten; source graph rights are unchanged."); + Ok(()) +} diff --git a/crates/formats/examples/standard_function_library/tests.rs b/crates/formats/examples/standard_function_library/tests.rs new file mode 100644 index 00000000..45bcdff8 --- /dev/null +++ b/crates/formats/examples/standard_function_library/tests.rs @@ -0,0 +1,66 @@ +use materialcraft_core::{FunctionGraph, Graph, Package, Value}; +use materialcraft_formats::sbs::{read_sbs, write_sbs}; + +#[test] +fn conversion_preserves_function_bodies_and_replaces_presentation_metadata() { + let mut package = Package::new("Functions"); + let mut graph = Graph::new("AddOne"); + graph.folder = "Functions/Math".into(); + graph.attributes.description = "Source description".into(); + graph.attributes.author = "Source author".into(); + graph.attributes.author_url = "https://example.org/source".into(); + graph.attributes.user_data = "Source notes".into(); + graph.attributes.tags = "Source tags".into(); + graph.function_type = 256; + let mut body = FunctionGraph::default(); + let left = body.add_constant(Value::Float(1.0)); + let right = body.add_constant(Value::Float(2.0)); + body.output = Some(body.add("add", &[left, right], None)); + graph.function = Some(body); + package.graphs.push(graph); + let bytes = write_sbs(&package).unwrap(); + let imported = read_sbs(&bytes, "source.sbs", &|_| None).unwrap().pkg; + + let converted = super::convert::package(&bytes, "source.sbs").unwrap(); + let exported = write_sbs(&converted).unwrap(); + let reopened = read_sbs(&exported, "converted.sbs", &|_| None).unwrap().pkg; + + assert_eq!(converted.graphs[0].sbs_path(), "Functions/Math/AddOne"); + assert_ne!(converted.graphs[0].attributes.description, imported.graphs[0].attributes.description); + assert!(converted.graphs[0].attributes.author.is_empty()); + assert!(converted.graphs[0].attributes.author_url.is_empty()); + assert!(converted.graphs[0].attributes.user_data.is_empty()); + assert!(converted.graphs[0].attributes.tags.is_empty()); + assert_eq!(converted.graphs[0].function, reopened.graphs[0].function); + let mut restored = converted.graphs[0].function.clone().unwrap(); + let original = imported.graphs[0].function.as_ref().unwrap(); + for (node, source) in restored.nodes.iter_mut().zip(&original.nodes) { + assert_ne!(node.pos, source.pos); + node.pos = source.pos; + } + assert_eq!(&restored, original); + assert_eq!(exported, write_sbs(&super::convert::package(&bytes, "source.sbs").unwrap()).unwrap()); +} + +#[test] +fn layout_separates_nodes_and_rejects_invalid_connections_without_partial_edits() { + let mut function = FunctionGraph::default(); + let constant = function.add_constant(Value::Float(1.0)); + function.output = Some(function.add("add", &[constant, constant], None)); + let disconnected = function.add_constant(Value::Float(2.0)); + function.nodes.reverse(); + + super::layout::reposition(&mut function).unwrap(); + + let source = function.node(constant).unwrap(); + let result = function.node(function.output.unwrap()).unwrap(); + assert!(result.pos[0] > source.pos[0]); + assert_ne!(source.pos, function.node(disconnected).unwrap().pos); + function.nodes[0].inputs = vec![function.output]; + function.nodes[1].inputs = vec![Some(disconnected)]; + let cyclic = function.clone(); + assert!(super::layout::reposition(&mut function).unwrap_err().contains("cycle")); + assert_eq!(function, cyclic); + function.nodes[0].inputs = vec![Some(9999)]; + assert!(super::layout::reposition(&mut function).unwrap_err().contains("missing node")); +} diff --git a/crates/formats/src/sbs/base_parameters.rs b/crates/formats/src/sbs/base_parameters.rs index 812bffb1..93a2e295 100644 --- a/crates/formats/src/sbs/base_parameters.rs +++ b/crates/formats/src/sbs/base_parameters.rs @@ -1,6 +1,6 @@ use super::sbs_value::sbs_constant; use super::xml::{child_element, child_value, children_named}; -use materialcraft_core::{BaseParameters, MAX_SIZE_LOG2, OutputFormat, SizeMode}; +use materialcraft_core::{BaseParameters, MAX_SIZE_LOG2, OutputFormat, ParameterInheritance, SizeMode}; use roxmltree::Node as XmlNode; use std::fmt::Write as _; @@ -8,6 +8,17 @@ pub(super) fn read_base_params(params: Option) -> BaseParameters { let mut base = BaseParameters::default(); for param in params.into_iter().flat_map(|p| children_named(p, "parameter")) { let relative_to = child_value(param, "relativeTo").and_then(|r| r.trim().parse::().ok()).unwrap_or(1); + let inheritance = match relative_to { + 0 => ParameterInheritance::Absolute, + 2 => ParameterInheritance::RelativeToParent, + _ => ParameterInheritance::RelativeToInput, + }; + match child_value(param, "name") { + Some("tiling") => base.tiling_mode = inheritance, + Some("pixelratio") => base.pixel_ratio_mode = inheritance, + _ => {} + } + let Some(value) = child_element(param, "paramValue").and_then(sbs_constant) else { continue }; match child_value(param, "name") { @@ -31,7 +42,8 @@ pub(super) fn read_base_params(params: Option) -> BaseParameters { } } Some("randomseed") if relative_to == 0 => base.seed = value.int(0), - Some("tiling") if relative_to == 0 => base.tiling = [value.int(0) & 1 != 0, value.int(0) & 2 != 0], + Some("tiling") => base.tiling = [value.int(0) & 1 != 0, value.int(0) & 2 != 0], + Some("pixelratio") => base.pixel_ratio = value.int(0).clamp(0, 1), _ => {} } } @@ -74,9 +86,21 @@ pub(super) fn base_params_xml(base: &BaseParameters) -> String { base.seed ); } - if base.tiling != [true, true] { - let code = i32::from(base.tiling[0]) | (i32::from(base.tiling[1]) << 1); - out.push_str(&super::node_parameter::param_xml("tiling", &materialcraft_core::Value::Int(code)).unwrap_or_default()); + let tiling = i32::from(base.tiling[0]) | (i32::from(base.tiling[1]) << 1); + for (name, value, inheritance, default) in [("tiling", tiling, base.tiling_mode, 3), ("pixelratio", base.pixel_ratio, base.pixel_ratio_mode, 0)] { + if inheritance == ParameterInheritance::RelativeToInput && value == default { + continue; + } + + let relative_to = match inheritance { + ParameterInheritance::Absolute => 0, + ParameterInheritance::RelativeToInput => 1, + ParameterInheritance::RelativeToParent => 2, + }; + let _ = write!( + out, + "" + ); } out } diff --git a/crates/formats/src/sbs/filter_map.rs b/crates/formats/src/sbs/filter_map.rs index 9ddeed34..62f783b8 100644 --- a/crates/formats/src/sbs/filter_map.rs +++ b/crates/formats/src/sbs/filter_map.rs @@ -6,7 +6,6 @@ pub(super) struct FilterMap { } pub(super) const FILTERS: &[FilterMap] = &[ - FilterMap { sbs: "motionblur", def: "motion_blur", inputs: &[("input1", "input")], params: &[("intensity", "intensity"), ("shiftangle", "shiftangle")] }, FilterMap { sbs: "uniform", def: "uniform", inputs: &[], params: &[("outputcolor", "color"), ("colorswitch", "color_mode")] }, FilterMap { sbs: "blend", diff --git a/crates/formats/src/sbs/function_graph.rs b/crates/formats/src/sbs/function_graph.rs index 8f180312..f07c4ea7 100644 --- a/crates/formats/src/sbs/function_graph.rs +++ b/crates/formats/src/sbs/function_graph.rs @@ -27,26 +27,30 @@ pub(super) fn read(element: XmlNode<'_, '_>) -> Result { .map(|value| to_natural_value(&value)); let type_code = child_value(element, "type").and_then(|value| value.parse().ok()).unwrap_or(0); let mut instance = if op == "instance" { Some(super::function_instance::read(element, value.as_ref(), type_code)?) } else { None }; + let mut missing = instance.is_none() && function::definition(op).is_none(); let mut names: Vec = if let Some(instance) = &instance { instance.inputs.iter().map(|port| port.identifier.clone()).collect() } else { - function::definition(op).ok_or_else(|| format!("unsupported function `{op}`"))?.inputs.iter().map(|name| (*name).into()).collect() + function::definition(op).into_iter().flat_map(|definition| definition.inputs.iter().map(|name| (*name).into())).collect() }; let mut inputs = vec![None; names.len()]; for connection in child_element(element, "connections").into_iter().flat_map(|connections| children_named(connections, "connection")) { let port = child_value(connection, "identifier").unwrap_or(""); let index = if let Some(index) = names.iter().position(|name| name == port) { index - } else if let Some(instance) = &mut instance { + } else { if names.len() >= 4096 { return Err("Function instance exceeds the 4096-input limit".into()); } - instance.inputs.push(materialcraft_core::GraphPort { identifier: port.into(), type_code: 0 }); + if let Some(instance) = &mut instance { + instance.inputs.push(materialcraft_core::GraphPort { identifier: port.into(), type_code: 0 }); + } else { + // A newer connector contract must remain editable without running the older operation + missing = true; + } names.push(port.into()); inputs.push(None); names.len() - 1 - } else { - return Err(format!("{op}: unknown input `{port}`")); }; let source = child_value(connection, "connRef").and_then(|value| value.parse().ok()).ok_or("invalid function connection")?; let input = inputs.get_mut(index).ok_or("invalid input index")?; @@ -56,6 +60,12 @@ pub(super) fn read(element: XmlNode<'_, '_>) -> Result { } let position = child_element(element, "GUILayout").and_then(|layout| child_value(layout, "gpos")).map(parse_floats).unwrap_or_default(); graph.nodes.push(FunctionNode { + missing: missing.then_some(names), + missing_data: if missing { + child_element(element, "funcDatas").map(|data| element.document().input_text()[data.range()].to_string()).unwrap_or_default() + } else { + String::new() + }, instance, source: None, id, @@ -74,7 +84,7 @@ pub(super) fn read(element: XmlNode<'_, '_>) -> Result { return Err("function connection references a missing node".into()); } // Earlier files may designate a Dot; keep the graph editable without promoting another node - if graph.output.and_then(|id| graph.node(id)).is_some_and(|node| !function::can_be_output(&node.op)) { + if graph.output.and_then(|id| graph.node(id)).is_some_and(|node| node.missing.is_none() && !function::can_be_output(&node.op)) { graph.output = None; } Ok(graph) @@ -120,7 +130,21 @@ pub(super) fn write(graph: &FunctionGraph, writer: &mut SbsWriter) -> Result"); - if let Some(instance) = &node.instance { + if node.missing.is_some() && !node.missing_data.is_empty() { + // Only a bounded data element may be emitted; command input must not inject package XML + let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: 100_000 }; + if node.missing_data.len() > (1 << 20) { + return Err("invalid preserved function data".into()); + } + + let document = roxmltree::Document::parse_with_options(&node.missing_data, options).map_err(|_| "invalid preserved function data")?; + let root = document.root_element(); + if !root.has_tag_name("funcDatas") { + return Err("invalid preserved function data".into()); + } + + output.push_str(node.missing_data.get(root.range()).ok_or("invalid preserved function data")?); + } else if let Some(instance) = &node.instance { output.push_str(&super::function_instance::write(instance, writer)); } else if let Some(value) = &node.value { let constant = constant_xml(value).ok_or("function data must be a scalar or vector constant")?; diff --git a/crates/formats/src/sbs/function_instance.rs b/crates/formats/src/sbs/function_instance.rs index 5bd446c6..0b7543db 100644 --- a/crates/formats/src/sbs/function_instance.rs +++ b/crates/formats/src/sbs/function_instance.rs @@ -9,22 +9,8 @@ use std::fmt::Write; pub(super) fn read(element: XmlNode<'_, '_>, value: Option<&Value>, type_code: u32) -> Result { let Some(Value::Text(reference)) = value else { return Err("function instance has no source reference".into()) }; - let reference = reference.strip_prefix("pkg:///").ok_or("invalid function source reference")?; - let (graph, query) = reference.split_once('?').unwrap_or((reference, "")); - let dependency = query.split('&').find_map(|part| part.strip_prefix("dependency=")); - let package = if let Some(uid) = dependency { - child_element(element.document().root_element(), "dependencies") - .into_iter() - .flat_map(|dependencies| children_named(dependencies, "dependency")) - .find(|dependency| child_value(*dependency, "uid") == Some(uid)) - .and_then(|dependency| child_value(dependency, "filename")) - .ok_or("function source dependency is missing")? - } else { - SELF_DEPENDENCY - }; - if package != SELF_DEPENDENCY && (package.contains("://") || !package.to_ascii_lowercase().ends_with(".sbs")) { - return Err("function sources must be SBS files".into()); - } + let (package, graph) = source_reference(element, reference)?; + let inputs: Vec<_> = child_element(element, "materialcraftInterface") .into_iter() .flat_map(|interface| children_named(interface, "input")) @@ -42,13 +28,41 @@ pub(super) fn read(element: XmlNode<'_, '_>, value: Option<&Value>, type_code: u return Err("Duplicate Function input identifiers".into()); } Ok(GraphInstance { - package: if package == SELF_DEPENDENCY { String::new() } else { package.into() }, - graph: graph.into(), + label: String::new(), + defaults: Default::default(), + package, + graph, inputs, outputs: vec![GraphPort { identifier: "output".into(), type_code }], }) } +fn source_reference(element: XmlNode<'_, '_>, reference: &str) -> Result<(String, String), String> { + if let Some(reference) = reference.strip_prefix("pkg:///") { + let (graph, query) = reference.split_once('?').unwrap_or((reference, "")); + let dependency = query.split('&').find_map(|part| part.strip_prefix("dependency=")); + let package = dependency + .map(|uid| { + child_element(element.document().root_element(), "dependencies") + .into_iter() + .flat_map(|dependencies| children_named(dependencies, "dependency")) + .find(|dependency| child_value(*dependency, "uid") == Some(uid)) + .and_then(|dependency| child_value(dependency, "filename")) + .map(str::to_string) + .unwrap_or_else(|| format!("missing://dependency/{uid}")) + }) + .unwrap_or_default(); + + return Ok((if package == SELF_DEPENDENCY { String::new() } else { package }, graph.into())); + } + + if let Some((package, graph)) = reference.split_once(".sbs/") { + return Ok((format!("{package}.sbs"), graph.into())); + } + + Err("invalid function source reference".into()) +} + pub(super) fn write(instance: &GraphInstance, writer: &mut SbsWriter) -> String { let reference = if instance.package.is_empty() { format!("pkg:///{}", instance.graph) diff --git a/crates/formats/src/sbs/graph_attributes.rs b/crates/formats/src/sbs/graph_attributes.rs new file mode 100644 index 00000000..a345d8f7 --- /dev/null +++ b/crates/formats/src/sbs/graph_attributes.rs @@ -0,0 +1,42 @@ +use super::xml::{child_value, xml_escape}; +use materialcraft_core::{Attributes, Graph}; +use roxmltree::Node; +use std::fmt::Write; + +pub(super) fn read(element: Node<'_, '_>) -> Attributes { + let text = |tag| child_value(element, tag).unwrap_or_default().to_string(); + Attributes { + label: text("label"), + category: text("category"), + description: text("description"), + author: text("author"), + author_url: text("authorURL"), + tags: text("tags"), + group: text("group"), + user_data: text("userdata"), + } +} + +pub(super) fn write(output: &mut String, graph: &Graph) { + let attributes = &graph.attributes; + output.push_str(""); + for (tag, value) in [ + ("category", &attributes.category), + ("description", &attributes.description), + ("author", &attributes.author), + ("tags", &attributes.tags), + ("label", &attributes.label), + ("authorURL", &attributes.author_url), + ("group", &attributes.group), + ("userdata", &attributes.user_data), + ] { + if !value.is_empty() { + let _ = write!(output, "<{tag} v=\"{}\"/>", xml_escape(value)); + } + } + if graph.function.is_none() && graph.physical_size != [0.0; 3] { + let [x, y, z] = graph.physical_size; + let _ = write!(output, ""); + } + output.push_str(""); +} diff --git a/crates/formats/src/sbs/group_layout.rs b/crates/formats/src/sbs/group_layout.rs new file mode 100644 index 00000000..542f16e5 --- /dev/null +++ b/crates/formats/src/sbs/group_layout.rs @@ -0,0 +1,58 @@ +use super::{sbs_writer::SbsWriter, xml::xml_escape}; +use crate::{FormatError, Result}; +use materialcraft_core::Package; +use std::{collections::BTreeSet, fmt::Write}; + +pub(super) fn write(out: &mut String, package: &Package, writer: &mut SbsWriter, self_uid: u64) -> Result<()> { + let folders = package.folder_paths(); + // Bound recursion for hostile package folders supplied through commands or imported XML + if folders.iter().any(|path| path.split('/').count() > 64 || path.split('/').any(str::is_empty)) { + return Err(FormatError::BadPackage("SBS folders must be nonempty and at most 64 levels deep".into())); + } + + write_level(out, package, writer, self_uid, &folders, "") +} + +fn write_level(out: &mut String, package: &Package, writer: &mut SbsWriter, self_uid: u64, folders: &BTreeSet, parent: &str) -> Result<()> { + let prefix = if parent.is_empty() { String::new() } else { format!("{parent}/") }; + let mut written = BTreeSet::new(); + for graph in &package.graphs { + if graph.folder == parent { + if graph.function.is_some() { + super::standalone_function::write(out, graph, writer)?; + } else { + writer.write_graph(out, package, graph, self_uid)?; + } + } else if let Some(child) = graph.folder.strip_prefix(&prefix).and_then(|path| path.split('/').next()) + && written.insert(child.to_string()) + { + write_folder(out, package, writer, self_uid, folders, &prefix, child)?; + } + } + for resource in package.resources.iter().filter(|resource| resource.folder == parent) { + super::resource::write(out, resource, writer)?; + } + for path in folders { + if let Some(child) = path.strip_prefix(&prefix).filter(|path| !path.contains('/')) + && written.insert(child.to_string()) + { + write_folder(out, package, writer, self_uid, folders, &prefix, child)?; + } + } + Ok(()) +} + +fn write_folder( + out: &mut String, + package: &Package, + writer: &mut SbsWriter, + self_uid: u64, + folders: &BTreeSet, + prefix: &str, + name: &str, +) -> Result<()> { + let _ = write!(out, "", xml_escape(name), writer.next_uid()); + write_level(out, package, writer, self_uid, folders, &format!("{prefix}{name}"))?; + out.push_str(""); + Ok(()) +} diff --git a/crates/formats/src/sbs/library.rs b/crates/formats/src/sbs/library.rs new file mode 100644 index 00000000..61dece3e --- /dev/null +++ b/crates/formats/src/sbs/library.rs @@ -0,0 +1,88 @@ +//! Resolve the portable SBS library alias against the application's asset directory. + +/// Validate alias paths before joining a filesystem root. No package may escape the library. +pub fn relative_path(uri: &str) -> Result<&str, String> { + let path = uri.strip_prefix("sbs://").ok_or("not an SBS library alias")?; + if path.is_empty() + || path.len() > 4096 + || path.contains(['\\', ':', '?', '#', '%', '\0']) + || path.split('/').any(|part| part.is_empty() || matches!(part, "." | "..")) + { + return Err("invalid SBS library path".into()); + } + Ok(path) +} + +/// Resolve a package-relative resource or dependency without leaving the library root. +pub fn resolve(owner: &str, reference: &str) -> Result { + let owner = relative_path(owner)?; + if reference.starts_with("sbs://") { + relative_path(reference)?; + return Ok(reference.into()); + } + + let reference = reference.trim().replace('\\', "/"); + if reference.is_empty() || reference.len() > 4096 || reference.starts_with('/') || reference.contains([':', '?', '#', '%', '\0']) { + return Err("invalid relative SBS library path".into()); + } + + let mut parts: Vec<_> = owner.split('/').collect(); + parts.pop(); + for part in reference.split('/') { + match part { + "" | "." => {} + ".." => { + if parts.pop().is_none() { + return Err("SBS reference escapes its library directory".into()); + } + } + part => parts.push(part), + } + } + + let uri = format!("sbs://{}", parts.join("/")); + relative_path(&uri)?; + Ok(uri) +} + +/// The native asset root may be configured for installations with a separate data directory. +#[cfg(not(target_arch = "wasm32"))] +pub fn root() -> std::path::PathBuf { + if let Some(root) = std::env::var_os("MATERIALCRAFT_SBS_DIR") { + return root.into(); + } + if let Ok(executable) = std::env::current_exe() + && let Some(parent) = executable.parent() + && parent.join("assets/sbs").is_dir() + { + return parent.join("assets/sbs"); + } + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/sbs") +} + +pub fn read(uri: &str) -> Result, String> { + let relative = relative_path(uri)?; + #[cfg(not(target_arch = "wasm32"))] + { + use std::io::Read; + let root = root(); + if root.exists() || std::env::var_os("MATERIALCRAFT_SBS_DIR").is_some() { + let root = root.canonicalize().map_err(|error| error.to_string())?; + let file = root.join(relative).canonicalize().map_err(|error| format!("Missing library asset {uri}: {error}"))?; + if !file.starts_with(&root) { + return Err("SBS library symlink escapes its asset directory".into()); + } + let mut bytes = Vec::new(); + std::fs::File::open(file).map_err(|error| error.to_string())?.take((256 << 20) + 1).read_to_end(&mut bytes).map_err(|error| error.to_string())?; + if bytes.len() > 256 << 20 { + return Err("SBS library asset exceeds 256 MiB".into()); + } + return Ok(bytes); + } + } + // Installed and browser builds use the same bundled asset when no disk asset root exists + match relative { + "functions.sbs" => Ok(include_bytes!("../../../../assets/sbs/functions.sbs").to_vec()), + _ => Err(format!("Missing library asset {uri}")), + } +} diff --git a/crates/formats/src/sbs/mod.rs b/crates/formats/src/sbs/mod.rs index 17e53552..b86db61b 100644 --- a/crates/formats/src/sbs/mod.rs +++ b/crates/formats/src/sbs/mod.rs @@ -7,8 +7,11 @@ mod embedded; mod filter_map; mod function_graph; mod function_instance; +mod graph_attributes; +mod group_layout; mod image_input; mod input_bridge; +pub mod library; mod node_identifiers; mod node_parameter; mod output; @@ -37,3 +40,5 @@ mod read; mod write; mod preview_binding; + +mod resource; diff --git a/crates/formats/src/sbs/node_parameter.rs b/crates/formats/src/sbs/node_parameter.rs index 9137a455..0702c027 100644 --- a/crates/formats/src/sbs/node_parameter.rs +++ b/crates/formats/src/sbs/node_parameter.rs @@ -11,12 +11,20 @@ pub(super) fn text_param(node: &Node, key: &str, default: &str) -> String { pub(super) fn param_xml(name: &str, value: &Value) -> Option { Some(format!("{}", xml_escape(name), constant_xml(value)?)) } -pub(super) fn special_filter_params_xml<'a>(filter: &str, value_of: &dyn Fn(&str) -> Option<&'a Value>, self_uid: u64) -> String { +pub(super) fn special_filter_params_xml<'a>( + filter: &str, + value_of: &dyn Fn(&str) -> Option<&'a Value>, + self_uid: u64, + package: &materialcraft_core::Package, +) -> String { match filter { "bitmap" | "svg" => match value_of("resource") { Some(Value::Text(name)) if !name.is_empty() => param_xml( if filter == "svg" { "vectorresourcepath" } else { "bitmapresourcepath" }, - &Value::Text(format!("pkg:///Resources/{name}?dependency={self_uid}")), + &Value::Text(format!( + "pkg:///{}?dependency={self_uid}", + package.resource(name).map_or_else(|| format!("Resources/{name}"), |resource| resource.sbs_path()) + )), ) .unwrap_or_default(), _ => String::new(), diff --git a/crates/formats/src/sbs/read.rs b/crates/formats/src/sbs/read.rs index 003272b5..94aa466f 100644 --- a/crates/formats/src/sbs/read.rs +++ b/crates/formats/src/sbs/read.rs @@ -2,12 +2,12 @@ use super::{ constant::{MAX_GRAPHS, MAX_SBS_BYTES, MAX_XML_NODES, SNIFF_BYTES}, placeholder::report_placeholders, sbs_read::SbsRead, - sbs_reader::{SbsReader, unique_name}, + sbs_reader::SbsReader, warnings::Warnings, xml::{child_element, child_value, children_named}, }; use crate::{FormatError, Result}; -use materialcraft_core::{Graph, Package}; +use materialcraft_core::Package; use roxmltree::Node as XmlNode; use std::collections::HashMap; @@ -61,22 +61,19 @@ pub fn read_sbs(bytes: &[u8], name: &str, linked: &dyn Fn(&str) -> Option = Vec::new(); for (path, graph) in graph_elements.iter().take(MAX_GRAPHS) { let identifier = child_value(*graph, "identifier").unwrap_or("").trim(); - let unique = unique_name(&names, if identifier.is_empty() { "Graph" } else { identifier }); - reader.graph_names.insert(path.clone(), unique.clone()); - names.push(unique); + let name = if identifier.is_empty() { "Graph" } else { identifier }.to_string(); + reader.graph_names.insert(path.clone(), path.clone()); + names.push(name); } if graph_elements.len() > MAX_GRAPHS { reader.warnings.add(format!("only the first {MAX_GRAPHS} graphs were read")); } - for ((_, graph), name) in graph_elements.iter().zip(names) { - let graph = reader.read_graph(*graph, name); + for ((path, graph), name) in graph_elements.iter().zip(names) { + let mut graph = reader.read_graph(*graph, name); + graph.folder = path.rsplit_once('/').map_or("", |(folder, _)| folder).into(); pkg.graphs.push(graph); } - if pkg.graphs.is_empty() { - reader.warnings.add("the package has no graphs MaterialCraft can open; an empty graph was added"); - pkg.graphs.push(Graph::new("Graph")); - } report_placeholders(&pkg, reader.warnings); Ok(SbsRead { pkg, warnings: warnings.finish() }) diff --git a/crates/formats/src/sbs/resource.rs b/crates/formats/src/sbs/resource.rs new file mode 100644 index 00000000..29803d15 --- /dev/null +++ b/crates/formats/src/sbs/resource.rs @@ -0,0 +1,24 @@ +use super::{embedded::encode_embedded, sbs_writer::SbsWriter, xml::xml_escape}; +use crate::Result; +use materialcraft_core::Resource; +use std::fmt::Write; + +pub(super) fn write(content: &mut String, resource: &Resource, writer: &mut SbsWriter) -> Result<()> { + let svg = resource.file.to_ascii_lowercase().ends_with(".svg"); + let ext = resource.file.rsplit_once('.').map_or("png", |(_, e)| e); + let source = if !resource.source.is_empty() && resource.bytes.is_empty() { + format!("", xml_escape(&resource.source)) + } else { + format!("", resource.bytes.len(), encode_embedded(resource.bytes.as_slice())?) + }; + let _ = write!( + content, + "{source}", + xml_escape(&resource.name), + writer.next_uid(), + if svg { "svg" } else { "bitmap" }, + xml_escape(ext) + ); + + Ok(()) +} diff --git a/crates/formats/src/sbs/sbs_reader.rs b/crates/formats/src/sbs/sbs_reader.rs index 2933ae12..2d8ab5c1 100644 --- a/crates/formats/src/sbs/sbs_reader.rs +++ b/crates/formats/src/sbs/sbs_reader.rs @@ -48,6 +48,20 @@ impl<'text> SbsReader<'text, '_> { match item.tag_name().name() { "graph" | "function" => graphs.push((path, item)), "group" => { + if identifier.is_empty() || identifier.contains('/') { + self.warnings.add(format!("invalid folder `{path}` was flattened")); + if let Some(group_content) = child_element(item, "content") { + pending.push((folder.clone(), group_content)); + } + continue; + } + + if path.split('/').count() > 64 { + self.warnings.add(format!("excessively nested folder `{path}` was skipped")); + continue; + } + + pkg.folders.push(path.clone()); if let Some(group_content) = child_element(item, "content") { pending.push((path, group_content)); } @@ -66,6 +80,11 @@ impl<'text> SbsReader<'text, '_> { let kind = child_value(item, "type").unwrap_or("bitmap"); let format = child_value(item, "format").unwrap_or("png").trim().to_ascii_lowercase(); let source = child_element(item, "source"); + let external = source + .and_then(|source| child_element(source, "externalcopy")) + .and_then(|copy| child_value(copy, "filename")) + .filter(|path| !path.is_empty()) + .or_else(|| child_value(item, "filepath")); let mut bytes: Option> = None; let mut why_missing = String::new(); @@ -79,7 +98,7 @@ impl<'text> SbsReader<'text, '_> { if bytes.is_none() { let external_copy = source.and_then(|s| child_element(s, "externalcopy")).and_then(|e| child_value(e, "filename")); for file in [external_copy, child_value(item, "filepath")].into_iter().flatten().filter(|p| !p.trim().is_empty()) { - if file.contains("://") { + if file.contains("://") && !file.starts_with("sbs://") { why_missing = format!("it links to `{file}`, which is not available"); continue; } @@ -102,11 +121,17 @@ impl<'text> SbsReader<'text, '_> { self.resource_bytes += data.len(); let ext = if kind == "svg" { "svg".to_string() } else { format }; - pkg.resources.push(Resource::new(name.clone(), crate::safe_file_name(&format!("{name}.{ext}")), ResourceBytes::new(data))); + let mut resource = Resource::new(name.clone(), crate::safe_file_name(&format!("{name}.{ext}")), ResourceBytes::new(data)); + resource.folder = path.rsplit_once('/').map_or("", |(folder, _)| folder).into(); + pkg.resources.push(resource); } None => { let why = if why_missing.is_empty() { "it has no data".to_string() } else { why_missing }; - + let extension = if kind == "svg" { "svg" } else { &format }; + let mut resource = Resource::new(name.clone(), crate::safe_file_name(&format!("{name}.{extension}")), ResourceBytes::new(Vec::new())); + resource.source = external.unwrap_or("").into(); + resource.folder = path.rsplit_once('/').map_or("", |(folder, _)| folder).into(); + pkg.resources.push(resource); self.warnings.add(format!("resource `{path}` could not be loaded: {why}")); } } @@ -121,7 +146,12 @@ impl<'text> SbsReader<'text, '_> { pub(super) fn read_graph(&mut self, element: XmlNode<'_, 'text>, name: String) -> Graph { let mut graph = Graph::new(&name); - graph.seed = read_base_params(child_element(element, "baseParameters")).seed; + let base = read_base_params(child_element(element, "baseParameters")); + graph.seed = base.seed; + graph.pixel_ratio = base.pixel_ratio; + graph.pixel_ratio_mode = base.pixel_ratio_mode; + graph.tiling = base.tiling; + graph.tiling_mode = base.tiling_mode; // The default parent size option ("11x11", log2 sizes) for option in child_element(element, "options").into_iter().flat_map(|o| children_named(o, "option")) { @@ -135,14 +165,21 @@ impl<'text> SbsReader<'text, '_> { } if let Some(attributes) = child_element(element, "attributes") { - let text = |tag: &str| child_value(attributes, tag).unwrap_or("").to_string(); - graph.attributes.category = text("category"); - graph.attributes.description = text("description"); - graph.attributes.author = text("author"); - graph.attributes.tags = text("tags"); + graph.attributes = super::graph_attributes::read(attributes); + if let Some(size) = child_value(attributes, "physicalSize") { + let mut components = size.split_whitespace().map(str::parse::); + if let (Some(Ok(x)), Some(Ok(y)), Some(Ok(z)), None) = (components.next(), components.next(), components.next(), components.next()) + && [x, y, z].iter().all(|component| component.is_finite() && *component >= 0.0) + { + graph.physical_size = [x, y, z]; + } else { + self.warnings.add(format!("graph `{name}` has an invalid physical size")); + } + } } if element.has_tag_name("function") { + graph.function_type = child_value(element, "type").and_then(|code| code.parse().ok()).unwrap_or(0); self.read_graph_inputs(element, &mut graph); let dynamic = child_element(element, "paramValue").and_then(|value| child_element(value, "dynamicValue")); let function = dynamic.ok_or_else(|| "missing function body".to_string()).and_then(super::function_graph::read); @@ -397,6 +434,7 @@ impl<'text> SbsReader<'text, '_> { } } pub(super) fn read_instance(&mut self, graph: &mut Graph, implementation: XmlNode<'_, 'text>, pos: [f32; 2], output_uids: &[(String, bool)]) -> ReadNode { + let graph_name = graph.name.clone(); let (path, dependency) = self.resolve_reference(child_value(implementation, "path").unwrap_or("")); let params = child_element(implementation, "parameters"); let bridgings: Vec<(String, String)> = child_element(implementation, "outputBridgings") @@ -408,7 +446,7 @@ impl<'text> SbsReader<'text, '_> { || params.into_iter().flat_map(|p| children_named(p, "parameter")).filter(|p| !BASE_PARAMS.contains(&child_value(*p, "name").unwrap_or(""))); let own_graph = dependency.as_deref().is_none_or(|d| d == SELF_DEPENDENCY).then(|| self.graph_names.get(&path).cloned()).flatten(); - let external = dependency.as_deref().filter(|file| *file != SELF_DEPENDENCY && !file.contains("://") && file.to_ascii_lowercase().ends_with(".sbs")); + let external = dependency.as_deref().filter(|file| *file != SELF_DEPENDENCY && file.to_ascii_lowercase().ends_with(".sbs")); if own_graph.is_some() || external.is_some() { let (id, index, node) = push_node(graph, "graph_instance", pos); if let Some(node) = node { @@ -425,6 +463,8 @@ impl<'text> SbsReader<'text, '_> { }) .collect(); node.instance = Some(materialcraft_core::GraphInstance { + label: String::new(), + defaults: Default::default(), package: external.unwrap_or("").into(), graph: path.clone(), inputs: Vec::new(), @@ -440,6 +480,8 @@ impl<'text> SbsReader<'text, '_> { for param in instance_params() { if let Some(value) = child_element(param, "paramValue").and_then(sbs_constant) { node.params.insert(child_value(param, "name").unwrap_or("").to_string(), to_natural_value(&value)); + } else { + self.set_param(node, child_value(param, "name").unwrap_or(""), &Value::Float(0.0), 0, param, &graph_name); } } node.base = read_base_params(params); diff --git a/crates/formats/src/sbs/sbs_writer.rs b/crates/formats/src/sbs/sbs_writer.rs index 60afeac3..2e9304ba 100644 --- a/crates/formats/src/sbs/sbs_writer.rs +++ b/crates/formats/src/sbs/sbs_writer.rs @@ -65,17 +65,7 @@ impl SbsWriter { pub(super) fn write_graph(&mut self, out: &mut String, pkg: &Package, graph: &Graph, self_uid: u64) -> Result<()> { let _ = write!(out, "", xml_escape(&graph.name), self.next_uid()); - let attributes = &graph.attributes; - if !(attributes.category.is_empty() && attributes.description.is_empty() && attributes.author.is_empty() && attributes.tags.is_empty()) { - let _ = write!( - out, - "", - xml_escape(&attributes.category), - xml_escape(&attributes.description), - xml_escape(&attributes.author), - xml_escape(&attributes.tags) - ); - } + super::graph_attributes::write(out, graph); let mut node_uids: HashMap = HashMap::new(); let mut node_outputs: HashMap = HashMap::new(); @@ -148,11 +138,19 @@ impl SbsWriter { out.push_str(""); let ids = NodeIdentifiers { input_entry: input_entries.get(&node.id).copied(), graph_output: output_uids.get(&node.id).copied(), self_uid }; - self.write_implementation(out, node, outputs, ids)?; + self.write_implementation(out, node, outputs, ids, pkg)?; out.push_str(""); } out.push_str(""); out.push_str(¶m_xml("randomseed", &Value::Int(graph.seed)).unwrap_or_default()); + let base = materialcraft_core::BaseParameters { + pixel_ratio: graph.pixel_ratio, + pixel_ratio_mode: graph.pixel_ratio_mode, + tiling: graph.tiling, + tiling_mode: graph.tiling_mode, + ..Default::default() + }; + out.push_str(&super::base_parameters::base_params_xml(&base)); out.push_str(""); write_canvas_items(out, graph, self); @@ -236,7 +234,14 @@ impl SbsWriter { out.push_str(""); output_uids } - pub(super) fn write_implementation(&mut self, out: &mut String, node: &Node, outputs: &[(String, u32, u64)], ids: NodeIdentifiers) -> Result<()> { + pub(super) fn write_implementation( + &mut self, + out: &mut String, + node: &Node, + outputs: &[(String, u32, u64)], + ids: NodeIdentifiers, + package: &Package, + ) -> Result<()> { let base = base_params_xml(&node.base); match node.def.as_str() { @@ -253,7 +258,17 @@ impl SbsWriter { .as_ref() .filter(|instance| !instance.package.is_empty()) .map_or(ids.self_uid, |instance| self.external_package_uid(&instance.package)); - let params: String = node.params.iter().filter(|(k, _)| *k != "graph").filter_map(|(k, v)| param_xml(k, v)).collect(); + let mut params: String = node + .params + .iter() + .filter(|(name, _)| *name != "graph" && !node.functions.contains_key(*name)) + .filter_map(|(name, value)| param_xml(name, value)) + .collect(); + for (name, function) in &node.functions { + let body = function_graph::write(function, self).map_err(FormatError::Io)?; + let _ = write!(params, "{body}", xml_escape(name)); + } + let _ = write!( out, "{base}{params}", @@ -309,7 +324,7 @@ impl SbsWriter { } out.push_str(¶m_xml(sbs_name, value).unwrap_or_default()); } - out.push_str(&special_filter_params_xml(filter.sbs, &value_of, ids.self_uid)); + out.push_str(&special_filter_params_xml(filter.sbs, &value_of, ids.self_uid, package)); out.push_str(""); for parameter in ["curve", "gradient"] { if let Some(value) = value_of(parameter) { diff --git a/crates/formats/src/sbs/standalone_function.rs b/crates/formats/src/sbs/standalone_function.rs index 585253a8..7c802b30 100644 --- a/crates/formats/src/sbs/standalone_function.rs +++ b/crates/formats/src/sbs/standalone_function.rs @@ -1,27 +1,26 @@ use super::{canvas::write_canvas_items, function_graph, sbs_writer::SbsWriter, xml::xml_escape}; use crate::{FormatError, Result}; -use materialcraft_core::Graph; +use materialcraft_core::{Graph, ValueType}; use std::fmt::Write; pub(super) fn write(output: &mut String, graph: &Graph, writer: &mut SbsWriter) -> Result<()> { let function = graph.function.as_ref().ok_or_else(|| FormatError::Io("missing function graph".into()))?; let types = materialcraft_nodes::function::node_types(function).map_err(FormatError::Io)?; - let result_type = function.output.and_then(|id| types.get(&id)).copied().unwrap_or(256); + + // An unresolved instance may carry a type mask rather than the graph's concrete result type + let result_type = function + .output + .and_then(|identifier| types.get(&identifier)) + .copied() + .filter(|code| ValueType::from_code(*code).is_some()) + .unwrap_or(if graph.function_type == 0 { 256 } else { graph.function_type }); let mut body = function_graph::write(function, writer).map_err(FormatError::Io)?; body.truncate(body.len().saturating_sub("".len())); write_canvas_items(&mut body, graph, writer); body.push_str(""); let _ = write!(output, "", xml_escape(&graph.name), writer.next_uid()); - let attributes = &graph.attributes; - let _ = write!( - output, - "", - xml_escape(&attributes.category), - xml_escape(&attributes.description), - xml_escape(&attributes.author), - xml_escape(&attributes.tags) - ); + super::graph_attributes::write(output, graph); writer.write_graph_inputs(output, graph); let _ = write!(output, "{body}"); Ok(()) diff --git a/crates/formats/src/sbs/tests.rs b/crates/formats/src/sbs/tests.rs index d706f832..7d69010b 100644 --- a/crates/formats/src/sbs/tests.rs +++ b/crates/formats/src/sbs/tests.rs @@ -2,7 +2,7 @@ use super::embedded::{base64_engine, decode_embedded, encode_embedded}; use super::read::{is_sbs, read_sbs}; use super::write::write_sbs; use base64::Engine as _; -use materialcraft_core::{Frame, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Package, Resource, ResourceBytes, SizeMode, Value, missing_ports}; +use materialcraft_core::{Frame, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, Package, Resource, ResourceBytes, SizeMode, Value, missing_ports}; fn no_linked_files(_: &str) -> Option> { None @@ -135,11 +135,11 @@ fn native_data_is_the_saved_document() { } #[test] -fn missing_nodes_are_placeholders_that_survive_saving() { +fn external_references_and_unknown_filters_survive_saving() { let xml = r#" - + @@ -154,25 +154,32 @@ fn missing_nodes_are_placeholders_that_survive_saving() { assert_eq!(graph.connections.len(), 2); let fancy = &graph.nodes[0]; - assert_eq!(fancy.def, MISSING_NODE); - assert_eq!(fancy.label, "fancy_noise"); - assert_eq!(missing_ports(fancy).1, vec![("noise".to_string(), true)]); + assert_eq!(fancy.def, "graph_instance"); + let instance = fancy.instance.as_ref().unwrap(); + assert_eq!(instance.package, "sbs://noise_fancy.sbs"); + assert_eq!(instance.graph, "fancy_noise"); + assert_eq!(instance.outputs[0].identifier, "noise"); + assert_eq!(instance.outputs[0].type_code, 2); + assert_eq!(fancy.params.get("scale"), Some(&Value::Float(3.0))); assert_eq!(graph.nodes[1].params.get("intensity"), Some(&Value::Float(6.0))); assert_eq!(graph.input_of(graph.nodes[1].id, "input").map(|c| c.from_port.as_str()), Some("noise")); assert_eq!(missing_ports(&graph.nodes[2]).0, vec!["weird_in".to_string()]); - for expected in ["missing node `fancy_noise`", "missing node `futurefilter`", "bogus"] { + for expected in ["missing node `futurefilter`", "bogus"] { assert!(read.warnings.iter().any(|w| w.contains(expected)), "{expected}: {:?}", read.warnings); } - // Saved and read back from the SBS data alone, the placeholders are written as they came + // References and unavailable operations survive without embedding their implementations let text = String::from_utf8(write_sbs(&read.pkg).unwrap()).unwrap(); assert!(text.contains("sbs://noise_fancy.sbs")); assert!(text.contains("pkg:///fancy_noise?dependency=")); assert!(text.contains("")); let back = read_sbs(text.as_bytes(), "p.sbs", &no_linked_files).unwrap(); let back_graph = &back.pkg.graphs[0]; - assert_eq!(back_graph.nodes[0].def, MISSING_NODE); - assert_eq!(back_graph.nodes[0].params.get("sbs_parameters"), fancy.params.get("sbs_parameters")); + assert_eq!(back_graph.nodes[0].def, "graph_instance"); + assert_eq!(back_graph.nodes[0].instance, fancy.instance); + assert_eq!(back_graph.nodes[0].params, fancy.params); + assert_eq!(back_graph.nodes[0].functions["detail"].nodes.len(), 1); + assert_eq!(back_graph.nodes[0].functions["detail"].nodes[0].value, fancy.functions["detail"].nodes[0].value); assert_eq!(back_graph.connections.len(), 2); } @@ -220,7 +227,7 @@ fn hostile_input_is_an_error_or_a_warning_never_a_panic() { ]; for case in cases { if let Ok(read) = read_sbs(case.as_bytes(), "x.sbs", &no_linked_files) { - assert!(!read.pkg.graphs.is_empty(), "{case}"); + assert!(write_sbs(&read.pkg).is_ok(), "{case}"); } } assert!(read_sbs(b"\xff\xfe", "x.sbs", &no_linked_files).is_err()); @@ -242,7 +249,8 @@ fn linked_resources_load_through_the_callback() { assert_eq!(found.pkg.resources[0].bytes.as_slice(), &[1, 2, 3]); let not_found = read_sbs(xml.as_bytes(), "p.sbs", &no_linked_files).unwrap(); - assert!(not_found.pkg.resources.is_empty()); + assert!(not_found.pkg.resources[0].bytes.is_empty()); + assert_eq!(not_found.pkg.resources[0].source, "p.resources/img.png"); assert!(not_found.warnings.iter().any(|w| w.contains("img")), "{:?}", not_found.warnings); } diff --git a/crates/formats/src/sbs/write.rs b/crates/formats/src/sbs/write.rs index f98e2352..18895d6f 100644 --- a/crates/formats/src/sbs/write.rs +++ b/crates/formats/src/sbs/write.rs @@ -1,6 +1,5 @@ use super::{ constant::{FIRST_UID, FORMAT_VERSION, SELF_DEPENDENCY, UPDATER_VERSION}, - embedded::encode_embedded, sbs_writer::SbsWriter, xml::xml_escape, }; @@ -13,31 +12,7 @@ pub fn write_sbs(pkg: &Package) -> Result> { let self_uid = writer.next_uid(); let mut content = String::from(""); - for graph in &pkg.graphs { - if graph.function.is_some() { - super::standalone_function::write(&mut content, graph, &mut writer)?; - } else { - writer.write_graph(&mut content, pkg, graph, self_uid)?; - } - } - if !pkg.resources.is_empty() { - let _ = write!(content, "", writer.next_uid()); - for resource in &pkg.resources { - let svg = resource.file.to_ascii_lowercase().ends_with(".svg"); - let ext = resource.file.rsplit_once('.').map_or("png", |(_, e)| e); - let _ = write!( - content, - "", - xml_escape(&resource.name), - writer.next_uid(), - if svg { "svg" } else { "bitmap" }, - xml_escape(ext), - resource.bytes.len(), - encode_embedded(resource.bytes.as_slice())? - ); - } - content.push_str(""); - } + super::group_layout::write(&mut content, pkg, &mut writer, self_uid)?; content.push_str(""); let mut out = String::with_capacity(content.len() + 4096); diff --git a/crates/formats/tests/explorer_folders.rs b/crates/formats/tests/explorer_folders.rs new file mode 100644 index 00000000..393398f2 --- /dev/null +++ b/crates/formats/tests/explorer_folders.rs @@ -0,0 +1,119 @@ +use materialcraft_formats::sbs::{read_sbs, write_sbs}; + +#[test] +fn empty_nested_folders_survive_sbs_round_trip() { + let xml = br#""#; + let imported = read_sbs(xml, "folders.sbs", &|_| None).unwrap(); + + let saved = write_sbs(&imported.pkg).unwrap(); + let document = roxmltree::Document::parse(std::str::from_utf8(&saved).unwrap()).unwrap(); + let groups: Vec<_> = document.descendants().filter(|node| node.has_tag_name("group")).collect(); + + assert_eq!(groups.len(), 2); + assert!(groups[1].ancestors().any(|node| node == groups[0])); + assert!(imported.pkg.graphs.is_empty()); + assert!(imported.warnings.is_empty()); +} + +#[test] +fn nested_resource_paths_are_preserved_without_duplicate_groups() { + use materialcraft_core::{Graph, Package, Resource, ResourceBytes, Value}; + let mut package = Package::new("Resources"); + let mut resource = Resource::new("Mask", "mask.png", ResourceBytes::new(vec![1, 2, 3])); + resource.folder = "Tools/Images".into(); + package.resources.push(resource); + package.folders.push("Tools/Images".into()); + let mut graph = Graph::new("Surface"); + graph.folder = "Tools".into(); + let bitmap = graph.add_node("bitmap", [0.0; 2]); + graph.node_mut(bitmap).unwrap().params.insert("resource".into(), Value::Text("Mask".into())); + package.graphs.push(graph); + + let bytes = write_sbs(&package).unwrap(); + let xml = std::str::from_utf8(&bytes).unwrap(); + assert!(xml.contains("pkg:///Tools/Images/Mask?dependency=")); + let read = read_sbs(&bytes, "resources.sbs", &|_| None).unwrap(); + assert_eq!(read.pkg.resources[0].folder, "Tools/Images"); + assert_eq!(read.pkg.graphs[0].nodes[0].params["resource"], Value::Text("Mask".into())); + let bytes = write_sbs(&read.pkg).unwrap(); + let document = roxmltree::Document::parse(std::str::from_utf8(&bytes).unwrap()).unwrap(); + assert_eq!(document.descendants().filter(|node| node.has_tag_name("group")).count(), 2); +} + +#[test] +#[ignore = "local interoperability input; set MC_FUNCTIONS_SBS to an external package"] +fn supplied_package_folder_paths_round_trip() { + let path = std::env::var("MC_FUNCTIONS_SBS").unwrap(); + let bytes = std::fs::read(&path).unwrap(); + let document = roxmltree::Document::parse(std::str::from_utf8(&bytes).unwrap()).unwrap(); + let native_paths: std::collections::BTreeSet<_> = document + .descendants() + .filter(|node| node.has_tag_name("group")) + .map(|node| { + let mut parts: Vec<_> = node + .ancestors() + .filter(|node| node.has_tag_name("group")) + .map(|node| node.children().find(|node| node.has_tag_name("identifier")).unwrap().attribute("v").unwrap()) + .collect(); + parts.reverse(); + parts.join("/") + }) + .collect(); + + let imported = read_sbs(&bytes, &path, &|_| None).unwrap(); + assert_eq!(imported.pkg.folder_paths(), native_paths); + let saved = write_sbs(&imported.pkg).unwrap(); + let reopened = read_sbs(&saved, "roundtrip.sbs", &|_| None).unwrap(); + assert_eq!(reopened.pkg.folder_paths(), native_paths); + for graph in &imported.pkg.graphs { + assert!(reopened.pkg.graph_by_name(&graph.sbs_path()).is_some()); + } +} + +#[test] +fn empty_packages_round_trip_without_invented_graphs() { + let package = materialcraft_core::Package::new("Empty"); + let read = read_sbs(&write_sbs(&package).unwrap(), "empty.sbs", &|_| None).unwrap(); + assert!(read.pkg.graphs.is_empty()); + assert!(read.warnings.is_empty()); +} + +#[test] +#[ignore = "local interoperability inputs; set MC_SBS_PACKAGES to a package directory"] +fn supplied_packages_keep_native_folder_hierarchies() { + let mut pending = vec![std::path::PathBuf::from(std::env::var_os("MC_SBS_PACKAGES").unwrap())]; + let mut checked = 0; + while let Some(path) = pending.pop() { + if path.is_dir() { + pending.extend(std::fs::read_dir(path).unwrap().map(|entry| entry.unwrap().path())); + continue; + } + if path.extension().is_none_or(|extension| extension != "sbs") { + continue; + } + let bytes = std::fs::read(&path).unwrap(); + let document = roxmltree::Document::parse(std::str::from_utf8(&bytes).unwrap().trim_start_matches('\u{feff}')).unwrap(); + let is_folder = |node: &roxmltree::Node<'_, '_>| node.has_tag_name("group") && node.children().any(|child| child.has_tag_name("content")); + let paths: std::collections::BTreeSet<_> = document + .descendants() + .filter(is_folder) + .map(|node| { + let mut parts: Vec<_> = node + .ancestors() + .filter(is_folder) + .map(|node| node.children().find(|node| node.has_tag_name("identifier")).unwrap().attribute("v").unwrap()) + .collect(); + parts.reverse(); + parts.join("/") + }) + .collect(); + let imported = read_sbs(&bytes, &path.to_string_lossy(), &|_| None).unwrap(); + assert_eq!(imported.pkg.folder_paths(), paths, "{}: import", path.display()); + let saved = write_sbs(&imported.pkg).unwrap(); + let reopened = read_sbs(&saved, "roundtrip.sbs", &|_| None).unwrap(); + assert_eq!(reopened.pkg.folder_paths(), paths, "{}: export", path.display()); + checked += 1; + } + assert!(checked > 0); + println!("Verified native folder hierarchies in {checked} supplied SBS packages"); +} diff --git a/crates/formats/tests/function_library.rs b/crates/formats/tests/function_library.rs new file mode 100644 index 00000000..6e495380 --- /dev/null +++ b/crates/formats/tests/function_library.rs @@ -0,0 +1,254 @@ +use materialcraft_formats::sbs::{read_sbs, write_sbs}; + +const LIBRARY: &str = r#" + + + + + + + +"#; + +#[test] +fn unresolved_polymorphic_output_preserves_the_declared_function_type() { + let xml = LIBRARY.replace("", ""); + let source = read_sbs(xml.as_bytes(), "source.sbs", &|_| None).unwrap().pkg; + + let saved = read_sbs(&write_sbs(&source).unwrap(), "saved.sbs", &|_| None).unwrap().pkg; + + assert_eq!(saved.graph_by_name("Caller").unwrap().1.function_type, 256); + assert_eq!(saved.graph_by_name("Caller").unwrap().1.function.as_ref().unwrap().nodes[0].type_code, 118772); +} + +#[test] +fn nested_function_paths_and_library_aliases_survive_save() { + let read = read_sbs(LIBRARY.as_bytes(), "test.sbs", &|_| None).unwrap(); + assert!(read.warnings.is_empty(), "{:?}", read.warnings); + let (_, pi) = read.pkg.graph_by_name("Functions/Math/Pi").expect("package path must remain addressable"); + assert_eq!(pi.name, "Pi"); + let call = read.pkg.graph_by_name("Caller").unwrap().1.function.as_ref().unwrap(); + assert_eq!(call.nodes[0].instance.as_ref().unwrap().package, "sbs://functions.sbs"); + let bytes = write_sbs(&read.pkg).unwrap(); + let saved = read_sbs(&bytes, "saved.sbs", &|_| None).unwrap(); + assert!(saved.warnings.is_empty(), "{:?}", saved.warnings); + assert!(saved.pkg.graph_by_name("Functions/Math/Pi").is_some()); + assert!(String::from_utf8(bytes).unwrap().contains(&format!("".into(); + + let bytes = write_sbs(&package).unwrap(); + assert!(read_sbs(&bytes, "saved.sbs", &|_| None).is_ok()); + package.graphs[index].function.as_mut().unwrap().nodes[0].missing_data = "".into(); + assert!(write_sbs(&package).is_err()); +} + +#[test] +fn absent_dependency_records_do_not_erase_function_nodes() { + let xml = LIBRARY.replace("dependency=9", "dependency=404"); + let read = read_sbs(xml.as_bytes(), "missing.sbs", &|_| None).unwrap(); + + let function = read.pkg.graph_by_name("Caller").unwrap().1.function.as_ref().unwrap(); + assert_eq!(function.nodes.len(), 1); + assert_eq!(function.output, Some(2)); + assert!(function.nodes[0].instance.is_some()); +} + +#[test] +fn missing_resource_links_survive_save_and_can_be_repaired() { + let xml = r#""#; + let read = read_sbs(xml.as_bytes(), "missing.sbs", &|_| None).unwrap(); + + let bytes = write_sbs(&read.pkg).unwrap(); + let repaired = read_sbs(&bytes, "saved.sbs", &|path| (path == "sbs://missing.png").then(|| vec![1, 2, 3])).unwrap(); + + assert_eq!(repaired.pkg.resources.len(), 1); + assert_eq!(repaired.pkg.resources[0].bytes.as_slice(), &[1, 2, 3]); +} + +#[test] +#[ignore = "local interoperability input; set MC_FUNCTIONS_SBS to an external package"] +fn supplied_function_package_round_trip() { + let path = std::env::var("MC_FUNCTIONS_SBS").unwrap(); + let bytes = std::fs::read(&path).unwrap(); + let read = read_sbs(&bytes, &path, &|_| None).unwrap(); + assert!(read.warnings.is_empty(), "{:?}", read.warnings); + assert!(read.pkg.graphs.iter().all(|graph| graph.function.as_ref().is_some_and(|function| !function.nodes.is_empty()))); + let saved = read_sbs(&write_sbs(&read.pkg).unwrap(), "saved.sbs", &|_| None).unwrap(); + let bundled = read_sbs(include_bytes!("../../../assets/sbs/functions.sbs"), "functions.sbs", &|_| None).unwrap(); + assert!(saved.warnings.is_empty(), "{:?}", saved.warnings); + assert!(bundled.warnings.is_empty(), "{:?}", bundled.warnings); + assert_eq!(read.pkg.graphs.len(), 171); + assert_eq!(read.pkg.graphs.len(), bundled.pkg.graphs.len()); + assert_eq!(read.pkg.folder_paths(), bundled.pkg.folder_paths()); + for graph in &read.pkg.graphs { + let other = saved.pkg.graph_by_name(&graph.sbs_path()).unwrap().1; + let replacement = bundled.pkg.graph_by_name(&graph.sbs_path()).unwrap().1; + assert_eq!(graph.function_type, replacement.function_type, "{}", graph.sbs_path()); + assert_eq!(graph.function_type, other.function_type, "{}", graph.sbs_path()); + let interface = + |graph: &materialcraft_core::Graph| graph.exposed.iter().map(|parameter| (parameter.id.clone(), parameter.default.clone())).collect::>(); + assert_eq!(interface(graph), interface(replacement), "{}", graph.sbs_path()); + assert_eq!(graph.exposed, replacement.exposed, "{}", graph.sbs_path()); + assert_ne!(graph.attributes.description, replacement.attributes.description, "{}", graph.sbs_path()); + assert!(replacement.attributes.author.is_empty()); + assert!(replacement.attributes.tags.is_empty()); + assert!(replacement.frames.is_empty() && replacement.comments.is_empty() && replacement.pins.is_empty()); + assert_same_body(graph, replacement); + assert_eq!(graph.name, other.name); + assert_eq!(graph.exposed, other.exposed); + assert_eq!(graph.function.as_ref().unwrap().nodes.len(), other.function.as_ref().unwrap().nodes.len()); + let before = graph.function.as_ref().unwrap(); + let after = other.function.as_ref().unwrap(); + let ids: std::collections::BTreeMap<_, _> = before.nodes.iter().zip(&after.nodes).map(|(left, right)| (left.id, right.id)).collect(); + assert_eq!(before.output.map(|id| ids[&id]), after.output); + for (left, right) in before.nodes.iter().zip(&after.nodes) { + assert_eq!(left.op, right.op, "{}", graph.sbs_path()); + assert_eq!(left.value, right.value, "{}", graph.sbs_path()); + assert_eq!(left.type_code, right.type_code); + assert_eq!(left.pos, right.pos); + assert_eq!(left.instance, right.instance); + assert_eq!(left.inputs.iter().map(|id| id.map(|id| ids[&id])).collect::>(), right.inputs); + } + } + eprintln!("Round-tripped and compared all {} converted function bodies against the supplied package", read.pkg.graphs.len()); +} + +fn assert_same_body(source: &materialcraft_core::Graph, converted: &materialcraft_core::Graph) { + let before = source.function.as_ref().unwrap(); + let after = converted.function.as_ref().unwrap(); + assert_eq!(before.nodes.len(), after.nodes.len(), "{}", source.sbs_path()); + let identifiers: std::collections::BTreeMap<_, _> = before.nodes.iter().zip(&after.nodes).map(|(left, right)| (left.id, right.id)).collect(); + + assert_eq!(before.output.map(|identifier| identifiers[&identifier]), after.output); + for (left, right) in before.nodes.iter().zip(&after.nodes) { + assert_eq!(left.op, right.op, "{}", source.sbs_path()); + assert_eq!(left.value, right.value, "{}", source.sbs_path()); + assert_eq!(left.type_code, right.type_code); + assert_eq!(left.instance, right.instance); + assert_eq!(left.inputs.iter().map(|identifier| identifier.map(|identifier| identifiers[&identifier])).collect::>(), right.inputs); + assert_ne!(left.pos, right.pos, "layout was not replaced in {}", source.sbs_path()); + } +} + +#[test] +fn bundled_library_has_complete_bodies_and_current_export_metadata() { + let bytes = include_bytes!("../../../assets/sbs/functions.sbs"); + let read = read_sbs(bytes, "functions.sbs", &|_| None).unwrap(); + let xml = roxmltree::Document::parse(std::str::from_utf8(bytes).unwrap()).unwrap(); + let version = xml.descendants().find(|element| element.has_tag_name("updaterVersion")).unwrap().attribute("v").unwrap(); + + assert_eq!(version, env!("CARGO_PKG_VERSION")); + assert!(read.warnings.is_empty(), "{:?}", read.warnings); + assert_eq!(read.pkg.graphs.len(), 171); + assert_eq!(read.pkg.graphs.iter().flat_map(|graph| graph.functions()).map(|function| function.nodes.len()).sum::(), 2334); + for graph in &read.pkg.graphs { + let function = graph.function.as_ref().unwrap(); + assert!(function.output.is_some(), "{}", graph.sbs_path()); + assert!(function.nodes.iter().all(|node| node.missing.is_none()), "{}", graph.sbs_path()); + assert!(!graph.attributes.description.is_empty()); + assert!(graph.attributes.author.is_empty() && graph.attributes.tags.is_empty()); + assert!(graph.frames.is_empty() && graph.comments.is_empty() && graph.pins.is_empty()); + } + assert!(!xml.descendants().any(|element| element.has_tag_name("icon"))); +} + +#[test] +#[ignore = "local interoperability input; set MC_FUNCTIONS_SBS to an external package"] +fn supplied_parity_functions_match_bundled_graphs() { + use materialcraft_core::Value; + use materialcraft_nodes::function::{self, EvaluationContext, EvaluationState}; + use std::collections::BTreeMap; + + let path = std::env::var("MC_FUNCTIONS_SBS").unwrap(); + let supplied = read_sbs(&std::fs::read(&path).unwrap(), &path, &|_| None).unwrap().pkg; + let bundled = read_sbs(include_bytes!("../../../assets/sbs/functions.sbs"), "functions.sbs", &|_| None).unwrap().pkg; + let mut inputs: Vec = (-2048..=2048).map(|index| index as f32 / 8.0).collect(); + for boundary in [-16_777_216.0_f32, -2.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 16_777_216.0] { + inputs.extend([boundary.next_down(), boundary, boundary.next_up()]); + } + + for name in ["EvenCount", "OddCount", "ParityTest"] { + let compile = |package: &materialcraft_core::Package| { + let graph = package.graph_by_name(&format!("Functions/Math/Parity/{name}")).unwrap().1; + function::compile(graph.function.as_ref().unwrap(), 0).unwrap() + }; + let expected = compile(&supplied); + let actual = compile(&bundled); + for &input in &inputs { + let variables = BTreeMap::from([("Input".into(), Value::Float(input))]); + let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [16.0; 2], images: &[], tile: true, variables: &variables }; + let evaluate = |program: &function::Program| program.evaluate(&context, &mut EvaluationState::default()).unwrap(); + + assert_eq!(evaluate(&actual), evaluate(&expected), "{name}({input})"); + } + } + + eprintln!("Compared three parity functions against the supplied graphs at {} inputs each", inputs.len()); +} + +#[test] +fn library_aliases_reject_paths_outside_the_asset_root() { + use materialcraft_formats::sbs::library::relative_path; + + assert_eq!(relative_path("sbs://folder/file.sbs").unwrap(), "folder/file.sbs"); + for invalid in ["sbs://../private", "sbs:///etc/passwd", "sbs://folder/../../private", "sbs://%2e%2e/private", "sbs://C:/private", "sbs://folder\\private"] + { + assert!(relative_path(invalid).is_err(), "{invalid}"); + } +} + +#[test] +fn library_relative_resources_stay_with_the_owning_package() { + use materialcraft_formats::sbs::library::resolve; + + assert_eq!(resolve("sbs://functions.sbs", "resources/tile.png").unwrap(), "sbs://resources/tile.png"); + assert_eq!(resolve("sbs://nested/functions.sbs", "resources/tile.png").unwrap(), "sbs://nested/resources/tile.png"); + assert_eq!(resolve("sbs://nested/functions.sbs", "../resources/tile.png").unwrap(), "sbs://resources/tile.png"); + assert_eq!(resolve("sbs://functions.sbs", ".\\resources\\tile.png").unwrap(), "sbs://resources/tile.png"); + assert_eq!(resolve("sbs://nested/functions.sbs", "sbs://resources/tile.png").unwrap(), "sbs://resources/tile.png"); + for invalid in ["../private", "../../private", "/etc/passwd", "C:\\private", "https://example.com/image.png", "%2e%2e/private", ""] { + assert!(resolve("sbs://functions.sbs", invalid).is_err(), "{invalid}"); + } +} + +#[test] +fn duplicate_leaf_names_require_their_package_folder() { + let mut package = materialcraft_core::Package::new("Folders"); + for folder in ["A", "B"] { + let mut graph = materialcraft_core::Graph::new("Same"); + graph.folder = folder.into(); + graph.function = Some(materialcraft_core::FunctionGraph::constant(materialcraft_core::Value::Float(1.0))); + package.graphs.push(graph); + } + + let read = read_sbs(&write_sbs(&package).unwrap(), "folders.sbs", &|_| None).unwrap(); + + assert!(read.pkg.graph_by_name("Same").is_none()); + assert_eq!(read.pkg.unique_graph_name("Same"), "Same_1"); + assert_eq!(read.pkg.graph_by_name("A/Same").unwrap().1.folder, "A"); + assert_eq!(read.pkg.graph_by_name("B/Same").unwrap().1.folder, "B"); +} diff --git a/crates/formats/tests/graph_attributes.rs b/crates/formats/tests/graph_attributes.rs new file mode 100644 index 00000000..e52702c3 --- /dev/null +++ b/crates/formats/tests/graph_attributes.rs @@ -0,0 +1,30 @@ +use materialcraft_formats::sbs::{read_sbs, write_sbs}; +use serde_json::json; + +#[test] +fn native_graph_attributes_load_and_survive_sbs_save() { + for kind in ["graph", "function"] { + let body = if kind == "function" { "" } else { "" }; + let xml = format!( + r#"<{kind}> + {body}"# + ); + let imported = read_sbs(xml.as_bytes(), "attributes.sbs", &|_| None).unwrap().pkg; + let expected = json!({"label": "Readable & non-unique label", "description": "First line\n

Second line

", + "category": "Tools/Math", "author": "Example author", "authorUrl": "https://example.org/?a=1&b=2", + "tags": "math utility", "group": "Utilities", "userData": "pipeline=example"}); + + assert_eq!(serde_json::to_value(&imported.graphs[0].attributes).unwrap(), expected, "{kind} import"); + let bytes = write_sbs(&imported).unwrap(); + let saved = read_sbs(&bytes, "saved.sbs", &|_| None).unwrap().pkg; + + assert_eq!(saved.graphs[0].name, "Stable_identifier"); + assert_eq!(serde_json::to_value(&saved.graphs[0].attributes).unwrap(), expected, "{kind} save"); + let xml = String::from_utf8(bytes).unwrap(); + assert!(xml.contains(" NodeDefinition { - node("directional_blur", "Directional Blur", ATOMIC) + node("directional_blur", "Directional blur", ATOMIC) .desc("Blurs along one direction.") .atomic() .any_in("input", "Input") diff --git a/crates/nodes/src/atomic/directional_warp.rs b/crates/nodes/src/atomic/directional_warp.rs index 821c481d..9489b617 100644 --- a/crates/nodes/src/atomic/directional_warp.rs +++ b/crates/nodes/src/atomic/directional_warp.rs @@ -3,7 +3,7 @@ use crate::{CookContext, CookResult, NodeDefinition, node}; use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { - node("directional_warp", "Directional Warp", ATOMIC) + node("directional_warp", "Directional warp", ATOMIC) .desc("Offsets the input along a direction, by an intensity map.") .atomic() .any_in("input", "Input") diff --git a/crates/nodes/src/atomic/gradient_map.rs b/crates/nodes/src/atomic/gradient_map.rs index 033b3054..38677f5d 100644 --- a/crates/nodes/src/atomic/gradient_map.rs +++ b/crates/nodes/src/atomic/gradient_map.rs @@ -4,7 +4,7 @@ use materialcraft_core::Gradient; use materialcraft_image::{Kind, luminance}; pub(super) fn definition() -> NodeDefinition { - node("gradient_map", "Gradient Map", ATOMIC) + node("gradient_map", "Gradient map", ATOMIC) .desc("Maps grayscale values to colors along a gradient.") .atomic() .gray_in("input", "Input") diff --git a/crates/nodes/src/atomic/grayscale_conversion.rs b/crates/nodes/src/atomic/grayscale_conversion.rs index 8f14943c..f4b9fa1b 100644 --- a/crates/nodes/src/atomic/grayscale_conversion.rs +++ b/crates/nodes/src/atomic/grayscale_conversion.rs @@ -3,7 +3,7 @@ use crate::{CookContext, CookResult, NodeDefinition, node}; use materialcraft_image::Kind; pub(super) fn definition() -> NodeDefinition { - node("grayscale_conversion", "Grayscale Conversion", ATOMIC) + node("grayscale_conversion", "Grayscale conversion", ATOMIC) .desc("Weighted sum of the RGBA channels.") .atomic() .color_in("input", "Input") diff --git a/crates/nodes/src/atomic/input_color.rs b/crates/nodes/src/atomic/input_color.rs index fa94be9b..b3dc487b 100644 --- a/crates/nodes/src/atomic/input_color.rs +++ b/crates/nodes/src/atomic/input_color.rs @@ -4,7 +4,7 @@ use materialcraft_core::ComponentUsage; use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { - node("input_color", "Input Color", GRAPH_ITEMS) + node("input_color", "Input color", GRAPH_ITEMS) .desc("A color image input of the graph.") .atomic() .generator() diff --git a/crates/nodes/src/atomic/input_grayscale.rs b/crates/nodes/src/atomic/input_grayscale.rs index 80900df7..202263a6 100644 --- a/crates/nodes/src/atomic/input_grayscale.rs +++ b/crates/nodes/src/atomic/input_grayscale.rs @@ -4,7 +4,7 @@ use materialcraft_core::ComponentUsage; use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { - node("input_grayscale", "Input Grayscale", GRAPH_ITEMS) + node("input_grayscale", "Input grayscale", GRAPH_ITEMS) .desc("A grayscale image input of the graph.") .atomic() .generator() diff --git a/crates/nodes/src/atomic/input_value.rs b/crates/nodes/src/atomic/input_value.rs index 4178e2ce..5aaa5440 100644 --- a/crates/nodes/src/atomic/input_value.rs +++ b/crates/nodes/src/atomic/input_value.rs @@ -3,7 +3,7 @@ use crate::{NodeDefinition, PortKind, node}; use materialcraft_core::ComponentUsage; pub(super) fn definition() -> NodeDefinition { - node("input_value", "Input Value", GRAPH_ITEMS) + node("input_value", "Input value", GRAPH_ITEMS) .desc("A typed value input of the graph.") .atomic() .text("identifier", "Identifier", "value") diff --git a/crates/nodes/src/atomic/mod.rs b/crates/nodes/src/atomic/mod.rs index 33a2a17b..aeb31097 100644 --- a/crates/nodes/src/atomic/mod.rs +++ b/crates/nodes/src/atomic/mod.rs @@ -16,7 +16,6 @@ mod input_color; mod input_grayscale; mod input_value; mod levels; -mod motion_blur; mod normal; mod output; mod pattern_map; diff --git a/crates/nodes/src/atomic/motion_blur.rs b/crates/nodes/src/atomic/motion_blur.rs deleted file mode 100644 index 69da3bd0..00000000 --- a/crates/nodes/src/atomic/motion_blur.rs +++ /dev/null @@ -1,17 +0,0 @@ -use super::{ATOMIC, directional_blur}; -use crate::{CookContext, CookResult, NodeDefinition, node}; - -pub(super) fn definition() -> NodeDefinition { - node("motion_blur", "Motion Blur", ATOMIC) - .desc("Blurs the input along a motion direction.") - .atomic() - .any_in("input", "Input") - .float("intensity", "Intensity", 10.0, 0.0, 64.0) - .angle("shiftangle", "Angle", 0.0) - .any_out() - .cook(cook) -} - -fn cook(context: &CookContext) -> CookResult { - directional_blur::blur(context, context.f("shiftangle")) -} diff --git a/crates/nodes/src/atomic/pixel_processor.rs b/crates/nodes/src/atomic/pixel_processor.rs index 07ba8a0a..a0a34d43 100644 --- a/crates/nodes/src/atomic/pixel_processor.rs +++ b/crates/nodes/src/atomic/pixel_processor.rs @@ -2,11 +2,11 @@ use super::ATOMIC; use crate::{NodeDefinition, node}; pub(super) fn definition() -> NodeDefinition { - node("pixel_processor", "Pixel Processor", ATOMIC) + node("pixel_processor", "Pixel processor", ATOMIC) .desc("Computes every pixel with a function graph ($pos, $size; sample the inputs).") .atomic() .any_in("input0", "Input image 0") - .function("function", "Per pixel function", crate::function::default_pixel_function()) + .function("function", "Per pixel function", materialcraft_core::FunctionGraph::default()) .boolean("color_mode", "Color output", true) .any_out() .cook(crate::function::pixel_processor) diff --git a/crates/nodes/src/atomic/uniform.rs b/crates/nodes/src/atomic/uniform.rs index 36f230e0..fedde70a 100644 --- a/crates/nodes/src/atomic/uniform.rs +++ b/crates/nodes/src/atomic/uniform.rs @@ -3,7 +3,7 @@ use crate::{CookContext, CookResult, NodeDefinition, node}; use materialcraft_image::{Image, Kind, luminance}; pub(super) fn definition() -> NodeDefinition { - node("uniform", "Uniform Color", ATOMIC) + node("uniform", "Uniform color", ATOMIC) .desc("A single color or gray value.") .atomic() .generator() diff --git a/crates/nodes/src/atomic/value_processor.rs b/crates/nodes/src/atomic/value_processor.rs index 554a5bc0..583c51ac 100644 --- a/crates/nodes/src/atomic/value_processor.rs +++ b/crates/nodes/src/atomic/value_processor.rs @@ -2,11 +2,11 @@ use super::ATOMIC; use crate::{NodeDefinition, node}; pub(super) fn definition() -> NodeDefinition { - node("value_processor", "Value Processor", ATOMIC) + node("value_processor", "Value processor", ATOMIC) .desc("Computes a typed value with a function graph.") .atomic() .any_in("input0", "Input image 0") - .function("function", "Function", materialcraft_core::FunctionGraph::constant(materialcraft_core::Value::Float(0.5))) + .function("function", "Function", materialcraft_core::FunctionGraph::default()) .output("output", "Value", crate::PortKind::Value) .cook(crate::node_definition_builder::no_cook) } diff --git a/crates/nodes/src/function/catalog.rs b/crates/nodes/src/function/catalog.rs index d8f0dacf..a798180d 100644 --- a/crates/nodes/src/function/catalog.rs +++ b/crates/nodes/src/function/catalog.rs @@ -2,33 +2,59 @@ use super::FunctionDefinition; use materialcraft_core::Value; pub const FUNCTIONS: &[FunctionDefinition] = &[ - FunctionDefinition { id: "const_bool", label: "Boolean", inputs: &[], category: "Constant" }, - FunctionDefinition { id: "get_bool", label: "Get Boolean", inputs: &[], category: "Variables" }, FunctionDefinition { id: "const_float1", label: "Float", inputs: &[], category: "Constant" }, - FunctionDefinition { id: "get_float1", label: "Get Float", inputs: &[], category: "Variables" }, FunctionDefinition { id: "const_float2", label: "Float2", inputs: &[], category: "Constant" }, - FunctionDefinition { id: "get_float2", label: "Get Float2", inputs: &[], category: "Variables" }, FunctionDefinition { id: "const_float3", label: "Float3", inputs: &[], category: "Constant" }, - FunctionDefinition { id: "get_float3", label: "Get Float3", inputs: &[], category: "Variables" }, FunctionDefinition { id: "const_float4", label: "Float4", inputs: &[], category: "Constant" }, - FunctionDefinition { id: "get_float4", label: "Get Float4", inputs: &[], category: "Variables" }, FunctionDefinition { id: "const_int1", label: "Integer", inputs: &[], category: "Constant" }, - FunctionDefinition { id: "get_integer1", label: "Get Integer", inputs: &[], category: "Variables" }, FunctionDefinition { id: "const_int2", label: "Integer2", inputs: &[], category: "Constant" }, - FunctionDefinition { id: "get_integer2", label: "Get Integer2", inputs: &[], category: "Variables" }, FunctionDefinition { id: "const_int3", label: "Integer3", inputs: &[], category: "Constant" }, - FunctionDefinition { id: "get_integer3", label: "Get Integer3", inputs: &[], category: "Variables" }, FunctionDefinition { id: "const_int4", label: "Integer4", inputs: &[], category: "Constant" }, - FunctionDefinition { id: "get_integer4", label: "Get Integer4", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "const_bool", label: "Boolean", inputs: &[], category: "Constant" }, FunctionDefinition { id: "const_string", label: "String", inputs: &[], category: "Constant" }, + FunctionDefinition { id: "vector2", label: "Vector Float2", inputs: &["componentsin", "componentslast"], category: "Vector" }, + FunctionDefinition { id: "vector3", label: "Vector Float3", inputs: &["componentsin", "componentslast"], category: "Vector" }, + FunctionDefinition { id: "vector4", label: "Vector Float4", inputs: &["componentsin", "componentslast"], category: "Vector" }, + FunctionDefinition { id: "swizzle1", label: "Swizzle Float1", inputs: &["vector"], category: "Vector" }, + FunctionDefinition { id: "swizzle2", label: "Swizzle Float2", inputs: &["vector"], category: "Vector" }, + FunctionDefinition { id: "swizzle3", label: "Swizzle Float3", inputs: &["vector"], category: "Vector" }, + FunctionDefinition { id: "swizzle4", label: "Swizzle Float4", inputs: &["vector"], category: "Vector" }, + FunctionDefinition { id: "ivector2", label: "Vector Integer2", inputs: &["componentsin", "componentslast"], category: "Vector" }, + FunctionDefinition { id: "ivector3", label: "Vector Integer3", inputs: &["componentsin", "componentslast"], category: "Vector" }, + FunctionDefinition { id: "ivector4", label: "Vector Integer4", inputs: &["componentsin", "componentslast"], category: "Vector" }, + FunctionDefinition { id: "iswizzle1", label: "Swizzle Integer1", inputs: &["vector"], category: "Vector" }, + FunctionDefinition { id: "iswizzle2", label: "Swizzle Integer2", inputs: &["vector"], category: "Vector" }, + FunctionDefinition { id: "iswizzle3", label: "Swizzle Integer3", inputs: &["vector"], category: "Vector" }, + FunctionDefinition { id: "iswizzle4", label: "Swizzle Integer4", inputs: &["vector"], category: "Vector" }, + FunctionDefinition { id: "set", label: "Set", inputs: &["value"], category: "Variables" }, + FunctionDefinition { id: "get_float1", label: "Get Float", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "get_float2", label: "Get Float2", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "get_float3", label: "Get Float3", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "get_float4", label: "Get Float4", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "get_integer1", label: "Get Integer", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "get_integer2", label: "Get Integer2", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "get_integer3", label: "Get Integer3", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "get_integer4", label: "Get Integer4", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "get_bool", label: "Get Boolean", inputs: &[], category: "Variables" }, FunctionDefinition { id: "get_string", label: "Get String", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "isdefined", label: "Is defined", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "samplelum", label: "Sample gray", inputs: &["pos"], category: "Samplers" }, + FunctionDefinition { id: "samplecol", label: "Sample color", inputs: &["pos"], category: "Samplers" }, + FunctionDefinition { id: "tofloat", label: "To Float", inputs: &["value"], category: "Cast" }, + FunctionDefinition { id: "tofloat2", label: "To Float2", inputs: &["value"], category: "Cast" }, + FunctionDefinition { id: "tofloat3", label: "To Float3", inputs: &["value"], category: "Cast" }, + FunctionDefinition { id: "tofloat4", label: "To Float4", inputs: &["value"], category: "Cast" }, + FunctionDefinition { id: "toint1", label: "To Integer", inputs: &["value"], category: "Cast" }, + FunctionDefinition { id: "toint2", label: "To Integer2", inputs: &["value"], category: "Cast" }, + FunctionDefinition { id: "toint3", label: "To Integer3", inputs: &["value"], category: "Cast" }, + FunctionDefinition { id: "toint4", label: "To Integer4", inputs: &["value"], category: "Cast" }, FunctionDefinition { id: "add", label: "Add", inputs: &["a", "b"], category: "Operator" }, - FunctionDefinition { id: "sub", label: "Subtract", inputs: &["a", "b"], category: "Operator" }, - FunctionDefinition { id: "mul", label: "Multiply", inputs: &["a", "b"], category: "Operator" }, - FunctionDefinition { id: "div", label: "Divide", inputs: &["a", "b"], category: "Operator" }, + FunctionDefinition { id: "sub", label: "Subtraction", inputs: &["a", "b"], category: "Operator" }, + FunctionDefinition { id: "mul", label: "Multiplication", inputs: &["a", "b"], category: "Operator" }, + FunctionDefinition { id: "mulscalar", label: "Scalar multiplication", inputs: &["a", "scalar"], category: "Operator" }, + FunctionDefinition { id: "div", label: "Division", inputs: &["a", "b"], category: "Operator" }, + FunctionDefinition { id: "neg", label: "Negation", inputs: &["a"], category: "Operator" }, FunctionDefinition { id: "mod", label: "Modulo", inputs: &["a", "b"], category: "Operator" }, - FunctionDefinition { id: "neg", label: "Negate", inputs: &["a"], category: "Operator" }, - FunctionDefinition { id: "mulscalar", label: "Multiply by scalar", inputs: &["a", "scalar"], category: "Operator" }, FunctionDefinition { id: "dot", label: "Dot product", inputs: &["a", "b"], category: "Operator" }, FunctionDefinition { id: "and", label: "And", inputs: &["a", "b"], category: "Logical" }, FunctionDefinition { id: "or", label: "Or", inputs: &["a", "b"], category: "Logical" }, @@ -37,54 +63,28 @@ pub const FUNCTIONS: &[FunctionDefinition] = &[ FunctionDefinition { id: "noteq", label: "Not equal", inputs: &["a", "b"], category: "Comparison" }, FunctionDefinition { id: "gt", label: "Greater", inputs: &["a", "b"], category: "Comparison" }, FunctionDefinition { id: "gteq", label: "Greater or equal", inputs: &["a", "b"], category: "Comparison" }, - FunctionDefinition { id: "lr", label: "Less", inputs: &["a", "b"], category: "Comparison" }, - FunctionDefinition { id: "lreq", label: "Less or equal", inputs: &["a", "b"], category: "Comparison" }, + FunctionDefinition { id: "lr", label: "Lower", inputs: &["a", "b"], category: "Comparison" }, + FunctionDefinition { id: "lreq", label: "Lower or equal", inputs: &["a", "b"], category: "Comparison" }, FunctionDefinition { id: "abs", label: "Absolute", inputs: &["a"], category: "Function" }, FunctionDefinition { id: "floor", label: "Floor", inputs: &["a"], category: "Function" }, - FunctionDefinition { id: "ceil", label: "Ceiling", inputs: &["a"], category: "Function" }, - FunctionDefinition { id: "sqrt", label: "Square root", inputs: &["a"], category: "Function" }, - FunctionDefinition { id: "exp", label: "Exponential", inputs: &["a"], category: "Function" }, - FunctionDefinition { id: "log", label: "Natural logarithm", inputs: &["a"], category: "Function" }, - FunctionDefinition { id: "log2", label: "Logarithm base 2", inputs: &["a"], category: "Function" }, - FunctionDefinition { id: "pow2", label: "Power of 2", inputs: &["a"], category: "Function" }, - FunctionDefinition { id: "sin", label: "Sine", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "ceil", label: "Ceil", inputs: &["a"], category: "Function" }, FunctionDefinition { id: "cos", label: "Cosine", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "sin", label: "Sine", inputs: &["a"], category: "Function" }, FunctionDefinition { id: "tan", label: "Tangent", inputs: &["a"], category: "Function" }, - FunctionDefinition { id: "atan2", label: "Arc tangent", inputs: &["a"], category: "Function" }, - FunctionDefinition { id: "rand", label: "Random", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "atan2", label: "Arc tangent 2", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "cartesian", label: "Cartesian", inputs: &["rho", "theta"], category: "Function" }, + FunctionDefinition { id: "sqrt", label: "Square root", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "log", label: "Logarithm", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "exp", label: "Exponential", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "log2", label: "Logarithm base 2", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "pow2", label: "2Pow", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "pow", label: "Pow", inputs: &["a", "b"], category: "Function" }, + FunctionDefinition { id: "lerp", label: "Linear interpolation", inputs: &["a", "b", "x"], category: "Function" }, FunctionDefinition { id: "min", label: "Minimum", inputs: &["a", "b"], category: "Function" }, FunctionDefinition { id: "max", label: "Maximum", inputs: &["a", "b"], category: "Function" }, - FunctionDefinition { id: "pow", label: "Power", inputs: &["a", "b"], category: "Function" }, - FunctionDefinition { id: "lerp", label: "Linear interpolation", inputs: &["a", "b", "x"], category: "Function" }, - FunctionDefinition { id: "cartesian", label: "Cartesian", inputs: &["rho", "theta"], category: "Function" }, - FunctionDefinition { id: "vector2", label: "Float vector 2", inputs: &["componentsin", "componentslast"], category: "Vector" }, - FunctionDefinition { id: "vector3", label: "Float vector 3", inputs: &["componentsin", "componentslast"], category: "Vector" }, - FunctionDefinition { id: "vector4", label: "Float vector 4", inputs: &["componentsin", "componentslast"], category: "Vector" }, - FunctionDefinition { id: "swizzle1", label: "Float swizzle 1", inputs: &["vector"], category: "Vector" }, - FunctionDefinition { id: "swizzle2", label: "Float swizzle 2", inputs: &["vector"], category: "Vector" }, - FunctionDefinition { id: "swizzle3", label: "Float swizzle 3", inputs: &["vector"], category: "Vector" }, - FunctionDefinition { id: "swizzle4", label: "Float swizzle 4", inputs: &["vector"], category: "Vector" }, - FunctionDefinition { id: "ivector2", label: "Integer vector 2", inputs: &["componentsin", "componentslast"], category: "Vector" }, - FunctionDefinition { id: "ivector3", label: "Integer vector 3", inputs: &["componentsin", "componentslast"], category: "Vector" }, - FunctionDefinition { id: "ivector4", label: "Integer vector 4", inputs: &["componentsin", "componentslast"], category: "Vector" }, - FunctionDefinition { id: "iswizzle1", label: "Integer swizzle 1", inputs: &["vector"], category: "Vector" }, - FunctionDefinition { id: "iswizzle2", label: "Integer swizzle 2", inputs: &["vector"], category: "Vector" }, - FunctionDefinition { id: "iswizzle3", label: "Integer swizzle 3", inputs: &["vector"], category: "Vector" }, - FunctionDefinition { id: "iswizzle4", label: "Integer swizzle 4", inputs: &["vector"], category: "Vector" }, - FunctionDefinition { id: "tofloat", label: "To Float1", inputs: &["value"], category: "Cast" }, - FunctionDefinition { id: "toint1", label: "To Integer1", inputs: &["value"], category: "Cast" }, - FunctionDefinition { id: "tofloat2", label: "To Float2", inputs: &["value"], category: "Cast" }, - FunctionDefinition { id: "toint2", label: "To Integer2", inputs: &["value"], category: "Cast" }, - FunctionDefinition { id: "tofloat3", label: "To Float3", inputs: &["value"], category: "Cast" }, - FunctionDefinition { id: "toint3", label: "To Integer3", inputs: &["value"], category: "Cast" }, - FunctionDefinition { id: "tofloat4", label: "To Float4", inputs: &["value"], category: "Cast" }, - FunctionDefinition { id: "toint4", label: "To Integer4", inputs: &["value"], category: "Cast" }, - FunctionDefinition { id: "samplecol", label: "Sample color", inputs: &["pos"], category: "Samplers" }, - FunctionDefinition { id: "samplelum", label: "Sample grayscale", inputs: &["pos"], category: "Samplers" }, - FunctionDefinition { id: "set", label: "Set variable", inputs: &["value"], category: "Variables" }, - FunctionDefinition { id: "isdefined", label: "Is defined", inputs: &[], category: "Variables" }, - FunctionDefinition { id: "ifelse", label: "If…Else", inputs: &["condition", "ifpath", "elsepath"], category: "Control" }, + FunctionDefinition { id: "rand", label: "Random", inputs: &["a"], category: "Function" }, FunctionDefinition { id: "sequence", label: "Sequence", inputs: &["seqin", "seqlast"], category: "Control" }, + FunctionDefinition { id: "ifelse", label: "If...Else", inputs: &["condition", "ifpath", "elsepath"], category: "Control" }, FunctionDefinition { id: "while", label: "While loop", inputs: &["init", "cond", "loop"], category: "Control" }, FunctionDefinition { id: "passthrough", label: "Dot", inputs: &["input"], category: "Control" }, ]; diff --git a/crates/nodes/src/function/compile.rs b/crates/nodes/src/function/compile.rs index 58028516..aa7ac5a6 100644 --- a/crates/nodes/src/function/compile.rs +++ b/crates/nodes/src/function/compile.rs @@ -29,38 +29,60 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu } let node = nodes.get(&id).ok_or_else(|| format!("missing function node {id}"))?; + if node.missing.is_some() { + return Err(format!("Missing function operation `{}`", node.op)); + } let definition = if node.instance.is_some() { &super::function_call::DEFINITION } else { catalog::definition(&node.op).ok_or_else(|| format!("unknown function `{}`", node.op))? }; let names: Vec<_> = super::input_identifiers(node).collect(); - if node.inputs.len() != names.len() || node.inputs.iter().any(Option::is_none) { + 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))); + if node.inputs.len() != names.len() || missing_input { return Err(format!("{} ({id}) requires connected inputs: {}", super::node_label(node), names.join(", "))); } + // Preserved legacy connectors must not evaluate a duplicate random or stateful input twice + let ports: Vec<_> = names + .into_iter() + .zip(&node.inputs) + .filter(|(name, _)| node.instance.as_ref().is_none_or(|instance| instance.defaults.contains_key(*name))) + .collect(); + let sources: Vec<_> = ports.iter().filter_map(|(_, input)| **input).collect(); if !visited { if !active.insert(id) { return Err(format!("function cycle at node {id}")); } pending.push((id, true)); - pending.extend(node.inputs.iter().rev().flatten().map(|input| (*input, false))); + pending.extend(sources.iter().rev().map(|input| (*input, false))); continue; } active.remove(&id); let inputs: Vec = - node.inputs.iter().flatten().map(|input| indices.get(input).copied().ok_or("unresolved function input".to_string())).collect::>()?; + sources.iter().map(|input| indices.get(input).copied().ok_or("unresolved function input".to_string())).collect::>()?; 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)?; - for (port, index) in instance.inputs.iter().zip(&inputs) { + for (port, index) in instance + .inputs + .iter() + .zip(&node.inputs) + .filter(|(port, input)| input.is_some() && instance.defaults.contains_key(&port.identifier)) + .map(|(port, _)| port) + .zip(&inputs) + { if instructions.get(*index).is_some_and(|instruction| instruction.type_code != port.type_code) { return Err(format!("{}: input `{}` has the wrong type", instance.graph, port.identifier)); } } - Some(super::function_call::FunctionCall { program, inputs: names.iter().map(|name| (*name).to_string()).collect() }) + 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() }) } else { None }; diff --git a/crates/nodes/src/function/evaluation_context.rs b/crates/nodes/src/function/evaluation_context.rs index 94a2c5c1..449b685e 100644 --- a/crates/nodes/src/function/evaluation_context.rs +++ b/crates/nodes/src/function/evaluation_context.rs @@ -4,9 +4,21 @@ use std::collections::BTreeMap; /// Inputs shared by one function evaluation pub struct EvaluationContext<'a> { + pub scope: super::FunctionScope, pub position: [f32; 2], pub size: [f32; 2], pub images: &'a [Option], pub tile: bool, pub variables: &'a BTreeMap, } + +impl EvaluationContext<'_> { + pub(super) fn variable(&self, name: &str, local: &BTreeMap) -> Result, String> { + if let Some(variable) = super::SystemVariable::named(name) { + // A local name must never make a system variable available outside its caller's scope + return variable.resolve(self); + } + + Ok(local.get(name).or_else(|| self.variables.get(name)).cloned()) + } +} diff --git a/crates/nodes/src/function/function_call.rs b/crates/nodes/src/function/function_call.rs index 02d7f562..121b95b8 100644 --- a/crates/nodes/src/function/function_call.rs +++ b/crates/nodes/src/function/function_call.rs @@ -5,4 +5,5 @@ pub(crate) const DEFINITION: FunctionDefinition = FunctionDefinition { id: "inst pub(crate) struct FunctionCall { pub program: Program, pub inputs: Vec, + pub defaults: std::collections::BTreeMap, } diff --git a/crates/nodes/src/function/function_scope.rs b/crates/nodes/src/function/function_scope.rs new file mode 100644 index 00000000..f0210861 --- /dev/null +++ b/crates/nodes/src/function/function_scope.rs @@ -0,0 +1,8 @@ +/// The caller determines which context-dependent variables a function can read. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum FunctionScope { + #[default] + Node, + PixelProcessor, + FxMap, +} diff --git a/crates/nodes/src/function/mod.rs b/crates/nodes/src/function/mod.rs index 46848628..6e6acde3 100644 --- a/crates/nodes/src/function/mod.rs +++ b/crates/nodes/src/function/mod.rs @@ -8,6 +8,7 @@ mod evaluation_state; mod evaluation_step; mod function_call; mod function_definition; +mod function_scope; mod inferred_type; mod instruction; mod node_interface; @@ -17,6 +18,7 @@ mod output; mod processor; mod program; mod resolve_instances; +mod system_variable; pub mod value_type; mod vector; mod warnings; @@ -26,14 +28,19 @@ pub use compile::compile; pub use evaluation_context::EvaluationContext; pub use evaluation_state::EvaluationState; pub use function_definition::FunctionDefinition; +pub use function_scope::FunctionScope; pub use node_interface::{graph_ports, input_identifiers, node_label}; pub use node_types::node_types; pub use output::{can_be_output, output_node}; -pub use processor::default_pixel_function; pub(crate) use processor::pixel_processor; pub use program::Program; pub use resolve_instances::resolve_instances; +pub use system_variable::SystemVariable; pub use warnings::warnings; #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "system_variable.test.rs"] +mod system_variable_tests; diff --git a/crates/nodes/src/function/node_interface.rs b/crates/nodes/src/function/node_interface.rs index 4441f116..d30d8d23 100644 --- a/crates/nodes/src/function/node_interface.rs +++ b/crates/nodes/src/function/node_interface.rs @@ -4,20 +4,30 @@ pub fn input_identifiers(node: &FunctionNode) -> impl Iterator { node.instance .iter() .flat_map(|instance| instance.inputs.iter().map(|port| port.identifier.as_str())) - .chain(super::definition(&node.op).filter(|_| node.instance.is_none()).into_iter().flat_map(|definition| definition.inputs.iter().copied())) + .chain(node.missing.iter().flatten().map(String::as_str)) + .chain( + super::definition(&node.op) + .filter(|_| node.instance.is_none() && node.missing.is_none()) + .into_iter() + .flat_map(|definition| definition.inputs.iter().copied()), + ) } pub fn node_label(node: &FunctionNode) -> &str { node.instance .as_ref() - .map(|instance| instance.graph.as_str()) - .unwrap_or_else(|| super::definition(&node.op).map_or("Unknown function", |definition| definition.label)) + .map(|instance| if instance.label.is_empty() { instance.graph.rsplit('/').next().unwrap_or(&instance.graph) } else { &instance.label }) + .unwrap_or_else(|| super::definition(&node.op).map_or(node.op.as_str(), |definition| definition.label)) } pub fn graph_ports(graph: &Graph) -> Result<(Vec, Vec), String> { let function = graph.function.as_ref().ok_or("the source must be a Function Graph")?; - let output = super::output_node(function).ok_or("the source graph needs an output before it can be instanced")?; let types = super::node_types(function)?; + let result_type = super::output_node(function).and_then(|output| types.get(&output.id)).copied().unwrap_or(graph.function_type); + if materialcraft_core::ValueType::from_code(result_type).is_none() { + return Err("the source graph needs an output before it can be instanced".into()); + } + if graph.exposed.len() > 4096 { return Err("Function instance exceeds the 4096-input limit".into()); } @@ -29,5 +39,5 @@ pub fn graph_ports(graph: &Graph) -> Result<(Vec, Vec), St if inputs.iter().any(|port| port.type_code == 0) { return Err("Function inputs must be scalar or vector values".into()); } - Ok((inputs, vec![GraphPort { identifier: "output".into(), type_code: types.get(&output.id).copied().unwrap_or(256) }])) + Ok((inputs, vec![GraphPort { identifier: "output".into(), type_code: result_type }])) } diff --git a/crates/nodes/src/function/node_types.rs b/crates/nodes/src/function/node_types.rs index 72a3535e..02d3959a 100644 --- a/crates/nodes/src/function/node_types.rs +++ b/crates/nodes/src/function/node_types.rs @@ -26,7 +26,7 @@ pub fn node_types(graph: &FunctionGraph) -> Result, String> { if node.instance.is_some() && node.op != "instance" { return Err("graph references require the instance operation".into()); } - if node.instance.is_none() && catalog::definition(&node.op).is_none() { + if node.instance.is_none() && node.missing.is_none() && catalog::definition(&node.op).is_none() { return Err(format!("unknown function `{}`", node.op)); } if node.inputs.len() > super::input_identifiers(node).count() { diff --git a/crates/nodes/src/function/operation.rs b/crates/nodes/src/function/operation.rs index b206d621..f83052de 100644 --- a/crates/nodes/src/function/operation.rs +++ b/crates/nodes/src/function/operation.rs @@ -32,12 +32,7 @@ pub(crate) fn evaluate( if op.starts_with("get_") { let name = name()?; - let value = match name { - "$pos" => Value::Float2(context.position), - "$size" => Value::Float2(context.size), - "$sizelog2" => Value::Float2(context.size.map(f32::log2)), - _ => variables.get(name).or_else(|| context.variables.get(name)).cloned().ok_or_else(|| format!("undefined variable `{name}`"))?, - }; + let value = context.variable(name, variables)?.ok_or_else(|| format!("undefined variable `{name}` in this context"))?; if value_type::type_code(&value) != instruction.type_code { return Err(format!("variable `{name}` has the wrong type for {op}")); @@ -64,7 +59,7 @@ pub(crate) fn evaluate( } "isdefined" => { let name = name()?; - Value::Bool(variables.contains_key(name) || context.variables.contains_key(name) || matches!(name, "$pos" | "$size" | "$sizelog2")) + Value::Bool(context.variable(name, variables)?.is_some()) } "and" => Value::Bool(boolean(first()?)? && boolean(second()?)?), "or" => Value::Bool(boolean(first()?)? || boolean(second()?)?), diff --git a/crates/nodes/src/function/output.rs b/crates/nodes/src/function/output.rs index 69cfd05b..99caf3fc 100644 --- a/crates/nodes/src/function/output.rs +++ b/crates/nodes/src/function/output.rs @@ -5,5 +5,5 @@ pub fn can_be_output(operation: &str) -> bool { } pub fn output_node(graph: &FunctionGraph) -> Option<&FunctionNode> { - graph.output.and_then(|id| graph.node(id)).filter(|node| can_be_output(&node.op)) + graph.output.and_then(|id| graph.node(id)).filter(|node| node.missing.is_some() || can_be_output(&node.op)) } diff --git a/crates/nodes/src/function/processor.rs b/crates/nodes/src/function/processor.rs index ee07720c..801bd2bd 100644 --- a/crates/nodes/src/function/processor.rs +++ b/crates/nodes/src/function/processor.rs @@ -1,17 +1,10 @@ use super::{EvaluationContext, EvaluationState, compile}; use crate::{CookContext, CookResult}; -use materialcraft_core::{FunctionGraph, Value}; +use materialcraft_core::Value; use materialcraft_image::{Image, Kind}; use rayon::prelude::*; use std::sync::Arc; -pub fn default_pixel_function() -> FunctionGraph { - let mut graph = FunctionGraph::default(); - let position = graph.add("get_float2", &[], Some(Value::Text("$pos".into()))); - graph.output = Some(graph.add("samplecol", &[position], Some(Value::Int2([0, 1])))); - graph -} - fn pixel(value: Value, gray: bool) -> Result<[f32; 4], String> { let values = super::value_type::floats(&value)?; Ok(if gray { @@ -38,6 +31,7 @@ pub(crate) fn pixel_processor(context: &CookContext) -> CookResult { data.par_chunks_mut(width as usize * channels).enumerate().try_for_each_init(EvaluationState::default, |state, (y, row)| -> Result<(), String> { for (x, target) in row.chunks_exact_mut(channels).enumerate() { let evaluation = EvaluationContext { + scope: super::FunctionScope::PixelProcessor, position: [(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32], size: [width as f32, height as f32], images: context.inputs, diff --git a/crates/nodes/src/function/program.rs b/crates/nodes/src/function/program.rs index cf16af45..16b2d50b 100644 --- a/crates/nodes/src/function/program.rs +++ b/crates/nodes/src/function/program.rs @@ -85,6 +85,7 @@ impl Program { let result = if let Some(call) = &instruction.call { let storage = state.calls.entry(index).or_default(); 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()); } diff --git a/crates/nodes/src/function/resolve_instances.rs b/crates/nodes/src/function/resolve_instances.rs index 6f1ec2c8..9816bfc6 100644 --- a/crates/nodes/src/function/resolve_instances.rs +++ b/crates/nodes/src/function/resolve_instances.rs @@ -18,8 +18,9 @@ fn resolve(function: &mut FunctionGraph, local: &Package, sources: &BTreeMap = instance.inputs.iter().zip(&node.inputs).map(|(port, value)| (port.identifier.clone(), *value)).collect(); + instance.defaults = graph.exposed.iter().map(|parameter| (parameter.id.clone(), parameter.default.clone())).collect(); instance.inputs = graph .exposed .iter() .map(|parameter| GraphPort { identifier: parameter.id.clone(), type_code: super::value_type::type_code(¶meter.default) }) .collect(); + let declared_sources: std::collections::BTreeSet<_> = + instance.inputs.iter().filter_map(|port| previous.get(&port.identifier).copied().flatten()).collect(); + let mut conflicting_input = false; + // Keep connected removed inputs visible so saving never discards a wire for (name, value) in &previous { if value.is_some() && !instance.inputs.iter().any(|port| port.identifier == *name) { instance.inputs.push(GraphPort { identifier: name.clone(), type_code: 0 }); + // A legacy connector may repeat a declared wire without supplying another argument + conflicting_input |= value.is_some_and(|source| !declared_sources.contains(&source)); } } node.inputs = instance.inputs.iter().map(|port| previous.get(&port.identifier).copied().flatten()).collect(); @@ -53,7 +61,7 @@ fn resolve(function: &mut FunctionGraph, local: &Package, sources: &BTreeMap Option { + Self::ALL.into_iter().find(|variable| variable.name() == name) + } + + pub fn name(self) -> &'static str { + match self { + Self::NormalFormat => "$normalformat", + Self::Tiling => "$tiling", + Self::PixelRatio => "$pixelratio", + Self::UvTile => "$uvtile", + Self::PhysicalSize => "$physicalsize", + Self::Size => "$size", + Self::SizeLog2 => "$sizelog2", + Self::Time => "$time", + Self::Position => "$pos", + Self::Depth => "$depth", + Self::DepthPow2 => "$depthpow2", + Self::Number => "$number", + } + } + + pub fn value_type(self) -> ValueType { + match self { + Self::NormalFormat | Self::Tiling | Self::PixelRatio => ValueType::Integer, + Self::UvTile => ValueType::Integer2, + Self::PhysicalSize => ValueType::Float3, + Self::Size | Self::SizeLog2 | Self::Position => ValueType::Float2, + Self::Time | Self::Depth | Self::DepthPow2 | Self::Number => ValueType::Float, + } + } + + pub fn available_in(self, scope: FunctionScope) -> bool { + match self { + Self::Position => matches!(scope, FunctionScope::PixelProcessor | FunctionScope::FxMap), + Self::Depth | Self::DepthPow2 | Self::Number => scope == FunctionScope::FxMap, + _ => true, + } + } + + pub(super) fn resolve(self, context: &EvaluationContext<'_>) -> Result, String> { + if !self.available_in(context.scope) { + return Ok(None); + } + + let value = match self { + Self::Position => Value::Float2(context.position), + Self::Size => Value::Float2(context.size), + Self::SizeLog2 => Value::Float2(context.size.map(f32::log2)), + _ => context.variables.get(self.name()).cloned().unwrap_or_else(|| match self { + Self::Tiling => Value::Int(if context.tile { 3 } else { 0 }), + Self::DepthPow2 => Value::Float(1.0), + _ => self.value_type().default_value(), + }), + }; + + if ValueType::of(&value) != Some(self.value_type()) { + return Err(format!("system variable `{}` has the wrong type; expected {}", self.name(), self.value_type().label())); + } + + if matches!(self.value_type(), ValueType::Float | ValueType::Float2 | ValueType::Float3) + && super::value_type::floats(&value)?.iter().any(|component| !component.is_finite()) + { + return Err(format!("system variable `{}` must be finite", self.name())); + } + + match (&self, &value) { + (Self::Tiling, Value::Int(value)) if !(0..=3).contains(value) => return Err("$tiling must be between 0 and 3".into()), + (Self::PixelRatio, Value::Int(value)) if !(0..=1).contains(value) => return Err("$pixelratio must be 0 or 1".into()), + _ => {} + } + + Ok(Some(value)) + } +} diff --git a/crates/nodes/src/function/system_variable.test.rs b/crates/nodes/src/function/system_variable.test.rs new file mode 100644 index 00000000..3b64d7b8 --- /dev/null +++ b/crates/nodes/src/function/system_variable.test.rs @@ -0,0 +1,68 @@ +use std::collections::BTreeMap; + +use materialcraft_core::{FunctionGraph, Value}; + +use super::{EvaluationContext, EvaluationState, FunctionScope, compile}; + +fn evaluate(operation: &str, name: &str, context: &EvaluationContext<'_>) -> Result { + let mut graph = FunctionGraph::default(); + graph.output = Some(graph.add(operation, &[], Some(Value::Text(name.into())))); + compile(&graph, 0)?.evaluate(context, &mut EvaluationState::default()) +} + +#[test] +fn system_variables_use_caller_scope_even_when_a_local_name_exists() { + let variables = BTreeMap::from([ + ("$pos".into(), Value::Float2([0.9; 2])), + ("$depth".into(), Value::Float(3.0)), + ("$depthpow2".into(), Value::Float(0.125)), + ("$number".into(), Value::Float(7.0)), + ]); + let mut context = + EvaluationContext { scope: FunctionScope::Node, position: [0.25, 0.75], size: [256.0, 128.0], images: &[], tile: true, variables: &variables }; + + for scope in [FunctionScope::Node, FunctionScope::PixelProcessor, FunctionScope::FxMap] { + context.scope = scope; + for (name, operation, expected, available) in [ + ("$pos", "get_float2", Value::Float2([0.25, 0.75]), scope != FunctionScope::Node), + ("$depth", "get_float1", Value::Float(3.0), scope == FunctionScope::FxMap), + ("$depthpow2", "get_float1", Value::Float(0.125), scope == FunctionScope::FxMap), + ("$number", "get_float1", Value::Float(7.0), scope == FunctionScope::FxMap), + ] { + assert_eq!(evaluate("isdefined", name, &context).unwrap(), Value::Bool(available), "{scope:?}: {name}"); + if available { + assert_eq!(evaluate(operation, name, &context).unwrap(), expected, "{scope:?}: {name}"); + } else { + assert!(evaluate(operation, name, &context).unwrap_err().contains("undefined variable")); + } + } + + assert_eq!(evaluate("get_float2", "$size", &context).unwrap(), Value::Float2([256.0, 128.0])); + assert_eq!(evaluate("get_float2", "$sizelog2", &context).unwrap(), Value::Float2([8.0, 7.0])); + } +} + +#[test] +fn system_values_are_typed_finite_and_read_only() { + for (name, operation, value) in [ + ("$time", "get_float1", Value::Float(f32::NAN)), + ("$physicalsize", "get_float3", Value::Float3([1.0, f32::INFINITY, 2.0])), + ("$uvtile", "get_integer2", Value::Float2([0.0; 2])), + ("$pixelratio", "get_integer1", Value::Int(2)), + ("$tiling", "get_integer1", Value::Int(4)), + ] { + let variables = BTreeMap::from([(name.into(), value)]); + let context = EvaluationContext { scope: FunctionScope::Node, position: [0.0; 2], size: [16.0; 2], images: &[], tile: true, variables: &variables }; + + assert!(evaluate(operation, name, &context).is_err(), "{name}"); + } + + let variables = BTreeMap::new(); + let context = EvaluationContext { scope: FunctionScope::Node, position: [0.0; 2], size: [16.0; 2], images: &[], tile: true, variables: &variables }; + let mut graph = FunctionGraph::default(); + let value = graph.add_constant(Value::Float(9.0)); + graph.output = Some(graph.add("set", &[value], Some(Value::Text("$time".into())))); + + assert!(compile(&graph, 0).unwrap().evaluate(&context, &mut EvaluationState::default()).unwrap_err().contains("user variable name")); + assert!(evaluate("get_integer1", "$time", &context).unwrap_err().contains("wrong type")); +} diff --git a/crates/nodes/src/function/tests.rs b/crates/nodes/src/function/tests.rs index a0c627e9..244a36ea 100644 --- a/crates/nodes/src/function/tests.rs +++ b/crates/nodes/src/function/tests.rs @@ -6,7 +6,7 @@ use super::{EvaluationContext, EvaluationState, FUNCTIONS, compile, default_valu fn evaluate(graph: &FunctionGraph, variables: &BTreeMap) -> Result { let image = Image::filled(3, 5, Kind::Color, [0.25, 0.5, 0.75, 1.0]); - let context = EvaluationContext { position: [0.5; 2], size: [3.0, 5.0], images: &[Some(image)], tile: true, variables }; + let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [3.0, 5.0], images: &[Some(image)], tile: true, variables }; compile(graph, 7)?.evaluate(&context, &mut EvaluationState::default()) } @@ -17,6 +17,21 @@ fn operation(name: &str, arguments: &[Value], setting: Option) -> Result< evaluate(&graph, &BTreeMap::new()) } +#[test] +fn system_variables_resolve_with_their_declared_types() { + for (operation, name, expected) in [ + ("get_integer1", "$pixelratio", Value::Int(0)), + ("get_float3", "$physicalsize", Value::Float3([0.0; 3])), + ("get_integer2", "$uvtile", Value::Int2([0; 2])), + ("get_integer1", "$normalformat", Value::Int(0)), + ] { + let mut graph = FunctionGraph::default(); + graph.output = Some(graph.add(operation, &[], Some(Value::Text(name.into())))); + + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), expected, "{name}"); + } +} + #[test] fn every_native_function_executes_with_its_declared_ports() { let mut covered = BTreeSet::new(); @@ -123,6 +138,35 @@ fn branches_are_lazy_and_sequence_orders_side_effects() { assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(17)); } +#[test] +fn time_and_tiling_variables_have_typed_defaults_and_host_overrides() { + for (name, operation, default, supplied) in + [("$time", "get_float1", Value::Float(0.0), Value::Float(2.5)), ("$tiling", "get_integer1", Value::Int(3), Value::Int(2))] + { + let mut graph = FunctionGraph::default(); + let get = graph.add(operation, &[], Some(Value::Text(name.into()))); + let defined = graph.add("isdefined", &[], Some(Value::Text(name.into()))); + graph.output = Some(get); + + for variables in [BTreeMap::new(), BTreeMap::from([(name.into(), supplied.clone())])] { + let expected = variables.get(name).unwrap_or(&default); + 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!(evaluate(&graph, &BTreeMap::from([(name.into(), Value::Bool(false))])).unwrap_err().contains("wrong type")); + graph.output = Some(defined); + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Bool(true)); + } + + let mut graph = FunctionGraph::default(); + graph.output = Some(graph.add("get_integer1", &[], Some(Value::Text("$tiling".into())))); + let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: false, variables: &BTreeMap::new() }; + assert_eq!(compile(&graph, 0).unwrap().evaluate(&context, &mut EvaluationState::default()).unwrap(), Value::Int(0)); +} + #[test] fn loops_recompute_state_and_have_a_budget() { let mut graph = FunctionGraph::default(); @@ -177,7 +221,7 @@ fn pixel_assignments_are_local_and_match_exported_evaluation() { let mut pixel_state = EvaluationState::default(); for initial in [3.0, 10.0, -2.0] { let variables = BTreeMap::from([("counter".into(), Value::Float(initial)), ("untouched".into(), Value::Text("keep".into()))]); - let context = EvaluationContext { position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables }; + let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables }; let mut exported = EvaluationState::default(); let expected = program.evaluate(&context, &mut exported).unwrap(); for _ in 0..2 { @@ -190,7 +234,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 { position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &BTreeMap::new() }; + 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!(pixel_state.variables().is_empty()); } @@ -206,7 +250,7 @@ fn pixel_random_seed_and_defined_variables_match_general_evaluation() { let program = compile(&graph, 7).unwrap(); let mut state = EvaluationState::default(); for variables in [BTreeMap::from([("$randomseed".into(), Value::Int(42)), ("known".into(), Value::Bool(true))]), BTreeMap::new()] { - let context = EvaluationContext { position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables }; + 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); } diff --git a/crates/nodes/src/function/warnings.rs b/crates/nodes/src/function/warnings.rs index 53922519..022e3a49 100644 --- a/crates/nodes/src/function/warnings.rs +++ b/crates/nodes/src/function/warnings.rs @@ -13,11 +13,17 @@ pub fn warnings(graph: &FunctionGraph) -> Vec { let mut has_value_source = false; while let Some(id) = pending.pop() { let Some(node) = remaining.remove(&id) else { continue }; + if node.missing.is_some() { + return vec![format!("Missing function operation `{}`", node.op)]; + } if let Some(instance) = &node.instance { - if node.inputs.len() != instance.inputs.len() || node.inputs.iter().any(Option::is_none) { + if node.inputs.len() != instance.inputs.len() + || instance.inputs.iter().zip(&node.inputs).any(|(port, input)| input.is_none() && !instance.defaults.contains_key(&port.identifier)) + { return vec![format!("{}: missing input connection", instance.graph)]; } + has_value_source |= !instance.defaults.is_empty(); match &node.source { Some(Err(error)) => return vec![error.clone()], None => return vec![format!("{}: source is unavailable", instance.graph)], diff --git a/crates/nodes/src/pattern/evaluation.rs b/crates/nodes/src/pattern/evaluation.rs index d8d9aade..1195ae05 100644 --- a/crates/nodes/src/pattern/evaluation.rs +++ b/crates/nodes/src/pattern/evaluation.rs @@ -50,13 +50,13 @@ pub(crate) fn cook(context: &CookContext) -> CookResult { 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)); - visit.variables.insert("$time".into(), Value::Float(0.0)); let mut parameters = BTreeMap::new(); for parameter in &definition.params { let value = match functions.get(&(node.id, parameter.id)) { Some(program) => { let evaluation = EvaluationContext { + scope: crate::function::FunctionScope::FxMap, position: visit.center, size: [context.w as f32, context.h as f32], images: context.inputs.get(1..).unwrap_or(&[]), diff --git a/crates/nodes/src/pattern/tests.rs b/crates/nodes/src/pattern/tests.rs index 69dc8867..cd27f87a 100644 --- a/crates/nodes/src/pattern/tests.rs +++ b/crates/nodes/src/pattern/tests.rs @@ -3,13 +3,35 @@ use materialcraft_core::{FunctionGraph, PatternGraph, PatternNodeKind, Value}; use std::collections::BTreeMap; fn cook(graph: PatternGraph) -> crate::CookResult { + cook_with_variables(graph, &BTreeMap::new()) +} + +fn cook_with_variables(graph: PatternGraph, variables: &BTreeMap) -> crate::CookResult { let definition = find("fx_map").unwrap(); let parameters = resolve_params(definition, &BTreeMap::from([("pattern".into(), Value::PatternGraph(Box::new(graph)))])); - let variables = BTreeMap::new(); - let context = CookContext { w: 16, h: 16, seed: 7, tile: true, inputs: &[], params: ¶meters, resource: &|_| None, vars: &variables }; + let context = CookContext { w: 16, h: 16, seed: 7, tile: true, inputs: &[], params: ¶meters, resource: &|_| None, vars: variables }; (definition.cook)(&context) } +#[test] +fn pattern_functions_keep_host_time_and_quadrant_depth() { + for (name, expected) in [("$time", 0.75), ("$depth", 1.0), ("$depthpow2", 0.5)] { + let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); + let child = graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes[0].parameters.insert("patterntype".into(), Value::Int(0)); + graph.nodes[0].children[0] = Some(child); + graph.nodes[1].parameters.insert("patterntype".into(), Value::Int(2)); + graph.nodes[1].parameters.insert("patternsize".into(), Value::Float2([2.0; 2])); + let mut function = FunctionGraph::default(); + function.output = Some(function.add("get_float1", &[], Some(Value::Text(name.into())))); + graph.nodes[1].parameters.insert("opacity".into(), Value::Function(Box::new(function))); + + let image = cook_with_variables(graph, &BTreeMap::from([("$time".into(), Value::Float(0.75))])).unwrap().remove(0); + + assert!((image.mean()[0] - expected).abs() < 1e-6, "{name}: {}", image.mean()[0]); + } +} + #[test] fn iterate_sets_number_and_switch_selects_one_child() { let mut graph = PatternGraph::default(); diff --git a/crates/nodes/src/tests.rs b/crates/nodes/src/tests.rs index 9c77e463..7e2ddbf3 100644 --- a/crates/nodes/src/tests.rs +++ b/crates/nodes/src/tests.rs @@ -13,29 +13,38 @@ fn cook(def: &NodeDefinition, inputs: &[Option], size: u32) -> CookResult (def.cook)(&ctx) } -/// Every node cooks with no inputs and with hostile-sized inputs, returns as many images as it has outputs, at the requested size, with finite values +/// Image nodes cook finite outputs at the requested size; an empty processor reports its missing result #[test] fn every_node_cooks() { - let ids: Vec<&str> = catalog().iter().map(|d| d.id).collect(); + let ids: Vec<&str> = catalog().iter().map(|definition| definition.id).collect(); let mut seen = std::collections::BTreeSet::new(); for id in &ids { assert!(seen.insert(*id), "duplicate node id {id}"); } - let odd = Image::generate(5, 3, Kind::Color, |x, y| [x as f32 / 4.0, y as f32 / 2.0, 0.5, 1.0]); - for def in catalog() { - if matches!(def.id, "graph_instance" | "value_processor" | "input_value") { + + let odd_size_image = Image::generate(5, 3, Kind::Color, |x, y| [x as f32 / 4.0, y as f32 / 2.0, 0.5, 1.0]); + for definition in catalog() { + if matches!(definition.id, "graph_instance" | "value_processor" | "input_value") { continue; } - for inputs in [vec![None; def.inputs.len()], vec![Some(odd.clone()); def.inputs.len()]] { - let out = cook(def, &inputs, 32).unwrap_or_else(|e| panic!("{}: {e}", def.id)); - assert_eq!(out.len(), def.outputs.len().max(1), "{}", def.id); - for img in &out { - assert_eq!((img.w, img.h), (32, 32), "{}", def.id); - assert!(img.data.iter().all(|v| v.is_finite()), "{} produced a non-finite value", def.id); + + for inputs in [vec![None; definition.inputs.len()], vec![Some(odd_size_image.clone()); definition.inputs.len()]] { + let result = cook(definition, &inputs, 32); + if definition.id == "pixel_processor" { + assert_eq!(result.unwrap_err(), "function has no result node"); + continue; + } + + let outputs = result.unwrap_or_else(|error| panic!("{}: {error}", definition.id)); + assert_eq!(outputs.len(), definition.outputs.len().max(1), "{}", definition.id); + for image in &outputs { + assert_eq!((image.w, image.h), (32, 32), "{}", definition.id); + assert!(image.data.iter().all(|value| value.is_finite()), "{} produced a non-finite value", definition.id); } } } - assert_eq!(catalog().len(), 30); + + assert_eq!(catalog().len(), 29); } /// Every node cooks with each numeric parameter at a hostile value (huge, negative huge, NaN): the hard limits keep the cook bounded, finite and the right size diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index d145aac5..6cb62b06 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -294,6 +294,7 @@ fn handle_inner(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p "graphView": rect(view), "selection": app.session.selection, "inspectedNode": app.graph.inspected_node, + "inspectedGraph": app.inspected_graph.map(|target| json!({"document": target.document, "graph": target.graph})), "subgraph": match target { crate::graph::editor_target::EditorTarget::Function => app.function_editor.as_ref() .map(|editor| json!({"kind": "function", "graph": app.session.graph, "node": editor.node, "target": editor.command_target(), "selection": editor.selection, "selectedWires": editor.selected_wires, "inspectedNode": editor.inspected_node})), diff --git a/crates/ui-egui/src/cook.rs b/crates/ui-egui/src/cook.rs index 07f8908d..fefb1e83 100644 --- a/crates/ui-egui/src/cook.rs +++ b/crates/ui-egui/src/cook.rs @@ -124,6 +124,7 @@ fn start(app: &mut MaterialCraftApp, now: f64) { s.dirty = false; let pkg = s.pkg.clone(); let (gi, max) = (s.graph, s.preview_size); + let environment = s.environment; let materials = s.material_preview.graphs(); let cache = s.cache.clone(); let epoch = s.cook_epoch; @@ -134,6 +135,7 @@ fn start(app: &mut MaterialCraftApp, now: f64) { use materialcraft_engine::eval::Options; let spawned = std::thread::Builder::new().name("materialcraft-cook".into()).spawn(move || { let mut opts = Options::new(&dec); + opts.environment = environment; opts.max_size = max; opts.cancel = Some(&thread_flag); let cooked = guard("cook", || Ok(PreviewCook::run(&pkg, gi, &materials, &opts, &cache))); diff --git a/crates/ui-egui/src/explorer.rs b/crates/ui-egui/src/explorer.rs index f40555e6..8c071570 100644 --- a/crates/ui-egui/src/explorer.rs +++ b/crates/ui-egui/src/explorer.rs @@ -1,21 +1,26 @@ //! The package tree, its graphs, inputs, outputs and resources -use egui::{RichText, Ui}; +use egui::Ui; +mod actions; +mod context_menu; +mod explorer_state; +mod explorer_target; +mod explorer_tree; mod tree_row; use egui_phosphor::regular as icon; +pub use explorer_state::ExplorerState; +pub use explorer_target::ExplorerTarget; use serde_json::json; use crate::MaterialCraftApp; use crate::i18n::tr; -use crate::theme::Tokens; pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 2.0; if crate::widgets::icon_button(ui, icon::FILE_PLUS, tr("New graph..."), false, 22.0).clicked() { - app.ui.windows.new_graph = true; + crate::menus::invoke(app, ui.ctx(), "ui.newGraph"); } if crate::widgets::icon_button(ui, icon::FOLDER_OPEN, tr("Open package..."), false, 22.0).clicked() { crate::menus::invoke(app, ui.ctx(), "file.open"); @@ -31,172 +36,68 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } }); ui.add_space(2.0); + let context = ui.ctx().clone(); + let mut tree = explorer_tree::ExplorerTree { + session: &app.session, + state: &mut app.ui.explorer, + action: None, + opened_node: None, + assignment: None, + movement: None, + inspected_graph: None, + }; egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - let mut open = None; - let mut action = None; - let mut selected_node = None; - let mut assignment = None; - for (document, package, path, modified) in app.session.open_packages() { - ui.push_id(document, |ui| { - let graph_warnings: Vec = package - .graphs - .iter() - .map(|graph| { - materialcraft_engine::function_inspection::warnings(graph).into_iter().flat_map(|(_, messages)| messages).collect::>().join("\n") - }) - .collect(); - let package_warnings = package - .graphs - .iter() - .zip(&graph_warnings) - .filter(|(_, warning)| !warning.is_empty()) - .map(|(graph, warning)| format!("{}: {warning}", graph.name)) - .collect::>() - .join("\n"); - let name = format!("{}{}", package.name, if modified { "*" } else { "" }); - let package_row = tree_row::show(ui, &name, icon::PACKAGE, false, (!package_warnings.is_empty()).then_some(package_warnings.as_str())); - if package_row.clicked() { - action = Some(("package", document, 0)); - } - if let Some(path) = path { - package_row.on_hover_text(path); - } - for (index, graph) in package.graphs.iter().enumerate() { - let active = document == app.session.document_id && index == app.session.graph; - let function = graph.function.is_some(); - let mut header = |ui: &mut Ui| { - let symbol = if function { icon::FUNCTION } else { icon::TREE_STRUCTURE }; - let warning = graph_warnings.get(index).map(String::as_str).unwrap_or(""); - let response = tree_row::show(ui, &graph.name, symbol, active, (!warning.is_empty()).then_some(warning)); - if graph.function.as_ref().map_or_else( - || graph.nodes.iter().any(|node| node.def == "output"), - |function| materialcraft_engine::nodes::function::output_node(function).is_some(), - ) { - response - .interact(egui::Sense::drag()) - .dnd_set_drag_payload(crate::graph_drag_payload::GraphDragPayload { document, name: graph.name.clone() }); - } - if response.clicked() { - open = Some((document, index)); - } - response.context_menu(|ui| { - if !function { - for (label, command) in [("View outputs in 3D view", "view3d"), ("Reset and view outputs in 3D view", "reset3d")] { - if ui.button(tr(label)).clicked() { - action = Some((command, document, index)); - ui.close(); - } - } - } - for (label, command) in [("Open", "open"), ("Export outputs...", "export"), ("Duplicate", "duplicate"), ("Delete", "delete")] { - if ui.button(tr(label)).clicked() { - action = Some((command, document, index)); - ui.close(); - } - } - }); - }; - - let mut ports = - graph.nodes.iter().filter(|node| matches!(node.def.as_str(), "output" | "input_color" | "input_grayscale" | "input_value")).peekable(); - if function || ports.peek().is_none() { - ui.horizontal(|ui| { - ui.add_space(ui.spacing().indent); - header(ui); - }); - continue; - } - - let id = ui.make_persistent_id(("graph", index, &graph.name)); - egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true).show_header(ui, header).body(|ui| { - ui.indent("graph-ports", |ui| { - for node in ports { - ui.push_id(node.id, |ui| { - let name = crate::graph::node_label(node); - let selected = active && app.session.selection.contains(&node.id); - let symbol = if node.def == "input_value" { icon::FUNCTION } else { icon::IMAGE }; - let response = tree_row::show(ui, &name, symbol, selected, None); - - response.context_menu(|ui| { - if document == app.session.document_id - && let Some(parameters) = crate::material_preview_menu::show(ui, &app.session, index, node.id) - { - assignment = Some(parameters); - } - }); - if response.clicked() || response.double_clicked() { - selected_node = Some((document, index, node.id, response.double_clicked())); - } - }); - } - }); - }); - } - if !package.resources.is_empty() { - ui.add_space(6.0); - ui.label(RichText::new(tr("Resources")).color(tk.text_dim).size(11.0)); - for resource in &package.resources { - ui.label(format!("{} {} ({} KB)", icon::IMAGE, resource.name, resource.bytes.len() / 1024)); - } - } - }); - } - if let Some((document, index)) = open - && activate(app, document) - { - app.run("graph.open", json!({"graph": index})); - } - if let Some((document, index, node, preview)) = selected_node { - if !activate(app, document) { - return; - } - if index != app.session.graph && app.run("graph.open", json!({"graph": index})).is_none() { - return; - } - - app.pattern_editor = None; - app.function_editor = None; - app.run("graph.annotation.select", json!({})); - app.run("graph.select", json!({"ids": [node.0]})); - app.graph.inspected_node = Some(node); - app.ui.dock.focus(crate::docking::Panel::Properties); - if preview { - app.run("view.2d", json!({"node": node.0})); - app.ui.dock.focus(crate::docking::Panel::View2d); - } - } - - if let Some(parameters) = assignment { - app.run("view.3d.assign", parameters); - } - let Some((command, document, index)) = action else { return }; - if !activate(app, document) { - return; - } - match (command, index) { - (command @ ("view3d" | "reset3d"), graph) => { - app.run("view.3d.outputs", json!({"graph": graph, "reset": command == "reset3d"})); - } - ("open", i) => { - app.run("graph.open", json!({"graph": i})); - } - ("export", i) => { - // The export window works on the open graph - if app.run("graph.open", json!({"graph": i})).is_some() { - app.ui.windows.export = true; - } - } - ("duplicate", i) => { - app.run("graph.duplicate", json!({"graph": i})); - } - ("delete", i) => { - app.run("graph.delete", json!({"graph": i})); - } - _ => {} + for (document, package, path, modified) in tree.session.open_packages() { + ui.push_id(document, |ui| tree.package(ui, document, package, path, modified)); } }); + let action = tree.action; + let opened_node = tree.opened_node; + let assignment = tree.assignment; + let movement = tree.movement; + if let Some(target) = tree.inspected_graph { + crate::properties::GraphPropertyDraft::commit(app); + app.inspected_graph = Some(target); + app.ui.dock.focus(crate::docking::Panel::Properties); + } + if let Some((document, index, node)) = opened_node { + if !actions::activate(app, document) { + return; + } + if index != app.session.graph && app.run("graph.open", json!({"graph": index})).is_none() { + return; + } + + app.pattern_editor = None; + crate::properties::GraphPropertyDraft::commit(app); + app.inspected_graph = None; + app.function_editor = None; + app.run("graph.annotation.select", json!({})); + app.run("graph.select", json!({"ids": [node.0]})); + app.graph.inspected_node = Some(node); + app.ui.dock.focus(crate::docking::Panel::Properties); + app.run("view.2d", json!({"node": node.0})); + app.ui.dock.focus(crate::docking::Panel::View2d); + } + if let Some(parameters) = assignment { + app.run("view.3d.assign", parameters); + } + if let Some((target, parent)) = movement + && actions::activate(app, target.document()) + { + let mut parameters = target.parameters(); + parameters["parent"] = json!(parent); + app.run("explorer.move", parameters); + } + if let Some((target, command)) = action { + if command == "activate" { + actions::activate(app, target.document()); + } else { + actions::invoke(app, &context, target, command); + } + } } -fn activate(app: &mut MaterialCraftApp, document: u64) -> bool { - document == app.session.document_id || app.run("package.activate", json!({"document": document})).is_some() +pub(crate) fn dialogs(app: &mut MaterialCraftApp, ctx: &egui::Context) { + actions::rename_dialog(app, ctx); } diff --git a/crates/ui-egui/src/explorer/actions.rs b/crates/ui-egui/src/explorer/actions.rs new file mode 100644 index 00000000..adce19a7 --- /dev/null +++ b/crates/ui-egui/src/explorer/actions.rs @@ -0,0 +1,87 @@ +use super::ExplorerTarget; +use crate::{MaterialCraftApp, i18n::tr}; +use serde_json::json; + +pub(super) fn activate(app: &mut MaterialCraftApp, document: u64) -> bool { + document == app.session.document_id || app.run("package.activate", json!({"document": document})).is_some() +} + +pub(super) fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, target: ExplorerTarget, command: &str) { + if !activate(app, target.document()) { + return; + } + let Some(folder) = target.folder(&app.session.pkg) else { return }; + match command { + "ui.newGraph" | "ui.newFunctionGraph" => { + let (kind, name) = if command == "ui.newFunctionGraph" { ("function", "Untitled_Function_Graph_1") } else { ("material", "Untitled_Graph_1") }; + if app.run("file.new", json!({"folder": folder, "kind": kind, "name": name, "template": "empty"})).is_some() { + app.ui.explorer.selected = Some(ExplorerTarget::Graph { document: target.document(), index: app.session.graph }); + } + } + "folder.create" => { + if let Some(path) = app + .run(command, json!({"parent": folder, "name": "Untitled_Folder_1"})) + .and_then(|result| result.get("folder").and_then(|path| path.as_str()).map(str::to_string)) + { + app.ui.explorer.selected = Some(ExplorerTarget::Folder { document: target.document(), path }); + } + } + "graph.rename" | "folder.rename" => { + if let Some(name) = target.name(&app.session.pkg) { + app.ui.explorer.rename = Some((target, name)); + } + } + "explorer.paste" => { + app.run(command, json!({"folder": folder})); + } + "package.close" | "file.reload" => { + crate::unsaved::guard(app, crate::unsaved::Guarded::Package { document: target.document(), reload: command == "file.reload" }) + } + "file.save" | "file.saveAs" | "file.saveCopyAs" => { + crate::windows::file_action(app, ctx, command); + } + _ => { + app.run(command, target.parameters()); + } + } +} + +pub(super) fn rename_dialog(app: &mut MaterialCraftApp, ctx: &egui::Context) { + let Some((target, mut name)) = app.ui.explorer.rename.clone() else { return }; + let mut open = true; + let mut accept = false; + let mut cancel = false; + egui::Window::new(tr("Rename")) + .id(egui::Id::unique("explorer-rename")) + .collapsible(false) + .resizable(false) + .open(&mut open) + .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO) + .show(ctx, |ui| { + let response = ui.text_edit_singleline(&mut name); + crate::widgets::name(&response, egui::Role::TextInput, "Name"); + if !ctx.memory(|memory| memory.has_focus(response.id)) && !ctx.egui_wants_keyboard_input() { + response.request_focus(); + } + accept |= response.lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)); + ui.horizontal(|ui| { + accept |= ui.button(tr("Rename")).clicked(); + cancel |= ui.button(tr("Cancel")).clicked(); + }); + }); + cancel |= ctx.input(|input| input.key_pressed(egui::Key::Escape)); + app.ui.explorer.rename = if open && !cancel { Some((target.clone(), name.clone())) } else { None }; + if accept && activate(app, target.document()) { + let mut parameters = target.parameters(); + parameters["name"] = json!(name); + let command = if matches!(target, ExplorerTarget::Folder { .. }) { "folder.rename" } else { "graph.rename" }; + if let Some(result) = app.run(command, parameters) { + app.ui.explorer.rename = None; + app.ui.explorer.selected = if let Some(path) = result.get("folder").and_then(|path| path.as_str()) { + Some(ExplorerTarget::Folder { document: target.document(), path: path.into() }) + } else { + Some(target) + }; + } + } +} diff --git a/crates/ui-egui/src/explorer/context_menu.rs b/crates/ui-egui/src/explorer/context_menu.rs new file mode 100644 index 00000000..05ddd04e --- /dev/null +++ b/crates/ui-egui/src/explorer/context_menu.rs @@ -0,0 +1,36 @@ +use super::ExplorerTarget; +use crate::{i18n::tr, menus}; + +pub(super) fn show(ui: &mut egui::Ui, target: &ExplorerTarget, paste: bool, reload: bool) -> Option<&'static str> { + ui.set_min_width(190.0); + let mut action = None; + if matches!(target, ExplorerTarget::Package { .. } | ExplorerTarget::Folder { .. }) { + ui.menu_button(tr("New"), |ui| { + for (label, command) in menus::EXPLORER_NEW { + if ui.button(tr(label)).clicked() { + action = Some(*command); + ui.close(); + } + } + }); + ui.separator(); + } + let entries = match target { + ExplorerTarget::Package { .. } => menus::EXPLORER_PACKAGE, + ExplorerTarget::Folder { .. } => menus::EXPLORER_FOLDER, + ExplorerTarget::Graph { .. } => menus::EXPLORER_GRAPH, + ExplorerTarget::Node { .. } => return None, + }; + for (label, command) in entries { + let enabled = match *command { + "explorer.paste" => paste, + "file.reload" => reload, + _ => true, + }; + if ui.add_enabled(enabled, egui::Button::new(tr(label))).clicked() { + action = Some(*command); + ui.close(); + } + } + action +} diff --git a/crates/ui-egui/src/explorer/explorer_state.rs b/crates/ui-egui/src/explorer/explorer_state.rs new file mode 100644 index 00000000..57ccb897 --- /dev/null +++ b/crates/ui-egui/src/explorer/explorer_state.rs @@ -0,0 +1,9 @@ +use super::ExplorerTarget; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct ExplorerState { + pub selected: Option, + pub rename: Option<(ExplorerTarget, String)>, +} diff --git a/crates/ui-egui/src/explorer/explorer_target.rs b/crates/ui-egui/src/explorer/explorer_target.rs new file mode 100644 index 00000000..0434857e --- /dev/null +++ b/crates/ui-egui/src/explorer/explorer_target.rs @@ -0,0 +1,47 @@ +use materialcraft_engine::core::{NodeId, Package}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum ExplorerTarget { + Package { document: u64 }, + Folder { document: u64, path: String }, + Graph { document: u64, index: usize }, + Node { document: u64, graph: usize, node: NodeId }, +} + +impl ExplorerTarget { + pub fn document(&self) -> u64 { + match self { + Self::Package { document } | Self::Folder { document, .. } | Self::Graph { document, .. } | Self::Node { document, .. } => *document, + } + } + + pub fn parameters(&self) -> Value { + match self { + Self::Package { .. } => json!({}), + Self::Folder { path, .. } => json!({"folder": path}), + Self::Graph { index, .. } => json!({"graph": index}), + Self::Node { graph, node, .. } => json!({"graph": graph, "id": node.0}), + } + } + + pub fn folder(&self, package: &Package) -> Option { + match self { + Self::Package { .. } => Some(String::new()), + Self::Folder { path, .. } => package.folder_paths().contains(path).then(|| path.clone()), + Self::Graph { index, .. } => package.graphs.get(*index).map(|graph| graph.folder.clone()), + Self::Node { graph, .. } => package.graphs.get(*graph).map(|graph| graph.folder.clone()), + } + } + + pub fn name(&self, package: &Package) -> Option { + match self { + Self::Package { .. } => Some(package.name.clone()), + Self::Folder { path, .. } => Some(path.rsplit('/').next().unwrap_or(path).into()), + Self::Graph { index, .. } => package.graphs.get(*index).map(|graph| graph.name.clone()), + Self::Node { graph, node, .. } => package.graphs.get(*graph).and_then(|graph| graph.node(*node).ok()).map(crate::graph::node_label), + } + } +} diff --git a/crates/ui-egui/src/explorer/explorer_tree.rs b/crates/ui-egui/src/explorer/explorer_tree.rs new file mode 100644 index 00000000..7583fbe5 --- /dev/null +++ b/crates/ui-egui/src/explorer/explorer_tree.rs @@ -0,0 +1,166 @@ +use super::{ExplorerState, ExplorerTarget, context_menu, tree_row}; +use crate::graph_drag_payload::GraphDragPayload; +use egui::Ui; +use egui_phosphor::regular as icon; +use materialcraft_engine::{ + Session, + core::{NodeId, Package}, +}; +use serde_json::Value; +use std::collections::BTreeSet; + +pub(super) struct ExplorerTree<'a> { + pub session: &'a Session, + pub state: &'a mut ExplorerState, + pub action: Option<(ExplorerTarget, &'static str)>, + pub opened_node: Option<(u64, usize, NodeId)>, + pub assignment: Option, + pub movement: Option<(ExplorerTarget, String)>, + pub inspected_graph: Option, +} + +impl ExplorerTree<'_> { + pub fn package(&mut self, ui: &mut Ui, document: u64, package: &Package, path: Option<&str>, modified: bool) { + let warnings: Vec<_> = package + .graphs + .iter() + .map(|graph| { + materialcraft_engine::function_inspection::warnings(graph).into_iter().flat_map(|(_, messages)| messages).collect::>().join("\n") + }) + .collect(); + let package_warning = warnings.iter().filter(|warning| !warning.is_empty()).cloned().collect::>().join("\n"); + let target = ExplorerTarget::Package { document }; + let name = format!("{}{}", package.name, if modified { "*" } else { "" }); + let id = ui.make_persistent_id((document, "package")); + egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true) + .show_header(ui, |ui| { + let response = self.row(ui, &target, package, &name, icon::PACKAGE, &package_warning, path.is_some()); + if let Some(path) = path { + response.on_hover_text(path); + } + }) + .body(|ui| { + self.level(ui, document, package, &package.folder_paths(), "", &warnings, 0); + }); + } + + fn level(&mut self, ui: &mut Ui, document: u64, package: &Package, folders: &BTreeSet, parent: &str, warnings: &[String], depth: usize) { + // Imported paths are bounded too, but UI inspection can supply arbitrary state + if depth > 64 { + return; + } + + for folder in folders.iter().filter(|path| path.rsplit_once('/').map_or("", |(parent, _)| parent) == parent) { + let target = ExplorerTarget::Folder { document, path: folder.clone() }; + let name = folder.rsplit('/').next().unwrap_or(folder); + let id = ui.make_persistent_id((document, "folder", folder)); + egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true) + .show_header(ui, |ui| { + self.row(ui, &target, package, name, icon::FOLDER, "", false); + }) + .body(|ui| self.level(ui, document, package, folders, folder, warnings, depth + 1)); + } + for resource in package.resources.iter().filter(|resource| resource.folder == parent) { + ui.horizontal(|ui| { + ui.add_space(ui.spacing().indent); + tree_row::show(ui, &resource.name, icon::IMAGE, false, resource.bytes.is_empty().then_some("Missing resource")); + }); + } + for (index, graph) in package.graphs.iter().enumerate().filter(|(_, graph)| graph.folder == parent) { + let target = ExplorerTarget::Graph { document, index }; + let symbol = if graph.function.is_some() { icon::FUNCTION } else { icon::TREE_STRUCTURE }; + let warning = warnings.get(index).map(String::as_str).unwrap_or(""); + let mut ports = + graph.nodes.iter().filter(|node| matches!(node.def.as_str(), "output" | "input_color" | "input_grayscale" | "input_value")).peekable(); + if graph.function.is_some() || ports.peek().is_none() { + ui.horizontal(|ui| { + ui.add_space(ui.spacing().indent); + self.row(ui, &target, package, &graph.name, symbol, warning, false); + }); + continue; + } + + let id = ui.make_persistent_id((document, "graph", index)); + egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true) + .show_header(ui, |ui| { + self.row(ui, &target, package, &graph.name, symbol, warning, false); + }) + .body(|ui| { + ui.indent("graph-ports", |ui| { + for node in ports { + ui.push_id(node.id, |ui| { + let name = crate::graph::node_label(node); + let target = ExplorerTarget::Node { document, graph: index, node: node.id }; + let selected = self.state.selected.as_ref() == Some(&target); + let symbol = if node.def == "input_value" { icon::FUNCTION } else { icon::IMAGE }; + let response = tree_row::show(ui, &name, symbol, selected, None); + response.context_menu(|ui| { + if document == self.session.document_id + && let Some(parameters) = crate::material_preview_menu::show(ui, self.session, index, node.id) + { + self.assignment = Some(parameters); + } + }); + if response.clicked() || response.secondary_clicked() { + self.state.selected = Some(target); + } + if response.double_clicked() { + self.opened_node = Some((document, index, node.id)); + } + }); + } + }); + }); + } + } + + fn row(&mut self, ui: &mut Ui, target: &ExplorerTarget, package: &Package, name: &str, symbol: &str, warning: &str, reload: bool) -> egui::Response { + let selected = self.state.selected.as_ref().map_or_else( + || matches!(target, ExplorerTarget::Graph { document, index } if *document == self.session.document_id && *index == self.session.graph), + |selected| selected == target, + ); + let response = tree_row::show(ui, name, symbol, selected, (!warning.is_empty()).then_some(warning)); + if response.clicked() || response.secondary_clicked() { + self.state.selected = Some(target.clone()); + if let ExplorerTarget::Graph { document, index } = target { + self.inspected_graph = Some(materialcraft_engine::GraphTarget { document: *document, graph: *index }); + } + } + if response.double_clicked() && matches!(target, ExplorerTarget::Graph { .. }) { + self.action = Some((target.clone(), "graph.open")); + } + if response.double_clicked() && matches!(target, ExplorerTarget::Package { .. } | ExplorerTarget::Folder { .. }) { + self.action = Some((target.clone(), "activate")); + } + response.context_menu(|ui| { + if let Some(command) = context_menu::show(ui, target, self.session.explorer_clipboard.is_some(), reload) { + self.action = Some((target.clone(), command)); + } + }); + if response.drag_started() { + match target { + ExplorerTarget::Graph { document, index } => { + if let Some(graph) = package.graphs.get(*index) { + egui::DragAndDrop::set_payload(ui.ctx(), GraphDragPayload { document: *document, name: graph.sbs_path() }); + } + } + ExplorerTarget::Folder { .. } => egui::DragAndDrop::set_payload(ui.ctx(), target.clone()), + ExplorerTarget::Package { .. } | ExplorerTarget::Node { .. } => {} + } + } + if let Some(parent) = target.folder(package) { + if let Some(payload) = response.dnd_release_payload::() + && payload.document == target.document() + && let Some((index, _)) = package.graph_by_name(&payload.name) + { + self.movement = Some((ExplorerTarget::Graph { document: payload.document, index }, parent.clone())); + } + if let Some(payload) = response.dnd_release_payload::() + && payload.document() == target.document() + { + self.movement = Some((payload.as_ref().clone(), parent)); + } + } + response + } +} diff --git a/crates/ui-egui/src/explorer/tree_row.rs b/crates/ui-egui/src/explorer/tree_row.rs index c6d701be..3b175cc9 100644 --- a/crates/ui-egui/src/explorer/tree_row.rs +++ b/crates/ui-egui/src/explorer/tree_row.rs @@ -4,7 +4,7 @@ use crate::{theme::Tokens, widgets}; pub(super) fn show(ui: &mut Ui, name: &str, icon: &str, selected: bool, warning: Option<&str>) -> Response { let theme = Tokens::get(ui.ctx()); - let (bounds, response) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); + let (bounds, response) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag()); widgets::name(&response, egui::Role::TreeItem, name); if selected { ui.painter().rect_filled(bounds, 4.0, theme.row_selected); diff --git a/crates/ui-egui/src/function/context_menu.rs b/crates/ui-egui/src/function/context_menu.rs index 4d66a50f..541d97ef 100644 --- a/crates/ui-egui/src/function/context_menu.rs +++ b/crates/ui-egui/src/function/context_menu.rs @@ -56,10 +56,8 @@ fn background_actions(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, u let mut add = None; let standalone = matches!(editor.target, FunctionTarget::Graph); ui.menu_button(tr("Add node"), |ui| { - let entries = target - .available_operations(&app.session) - .filter(|operation| operation.id != "passthrough") - .map(|operation| (operation.id, operation.label, operation.category)); + let entries = + target.available_operations(&app.session).filter(|operation| operation.id != "passthrough").map(|operation| (operation.id, operation.label, "")); add = crate::graph::add_node_menu::show(ui, entries); }); annotations(app, editor, ui); diff --git a/crates/ui-egui/src/function/function_library_drag.rs b/crates/ui-egui/src/function/function_library_drag.rs new file mode 100644 index 00000000..c16f4cf6 --- /dev/null +++ b/crates/ui-egui/src/function/function_library_drag.rs @@ -0,0 +1,4 @@ +pub(super) enum FunctionLibraryDrag { + Operation(String), + Instance { package: String, graph: String }, +} diff --git a/crates/ui-egui/src/function/input.rs b/crates/ui-egui/src/function/input.rs index 419c85d5..e0a805e6 100644 --- a/crates/ui-egui/src/function/input.rs +++ b/crates/ui-egui/src/function/input.rs @@ -124,6 +124,13 @@ pub(super) fn handle( let camera = GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom }; + if let Some(payload) = crate::widgets::dnd_release::(response) + && let Some(pointer) = pointer + { + let position = camera.to_graph(pointer); + super::library::insert(app, editor, &payload, [position.x - crate::graph::NODE_W * 0.5, position.y - 20.0]); + } + if let Some(payload) = crate::widgets::dnd_release::(response) && let Some(pointer) = pointer && let Some(target) = editor.command_target() diff --git a/crates/ui-egui/src/function/library.rs b/crates/ui-egui/src/function/library.rs index 56ea6a75..2bc4ab2a 100644 --- a/crates/ui-egui/src/function/library.rs +++ b/crates/ui-egui/src/function/library.rs @@ -1,5 +1,6 @@ +use super::function_library_drag::FunctionLibraryDrag; use crate::{MaterialCraftApp, i18n::tr}; -use egui::Ui; +use egui::{Sense, Ui}; use materialcraft_engine::FunctionEdit; pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { @@ -8,15 +9,88 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let operations = target.available_operations(&app.session); ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search functions"))); let search = app.ui.library_search.to_ascii_lowercase(); + let functions: Vec<_> = app + .session + .pkg + .dependencies + .iter() + .filter(|(path, _)| path.starts_with("sbs://")) + .flat_map(|(path, package)| { + package.graphs.iter().filter(|graph| graph.function.is_some()).map(move |graph| { + ( + path.clone(), + graph.sbs_path(), + graph.display_name().to_string(), + graph.attributes.description.clone(), + graph.function.as_ref().is_some_and(|function| function.output.is_none() || function.nodes.iter().any(|node| node.missing.is_some())), + ) + }) + }) + .filter(|(_, path, label, _, _)| path.to_ascii_lowercase().contains(&search) || label.to_ascii_lowercase().contains(&search)) + .collect(); + let mut add = None; egui::ScrollArea::vertical().show(ui, |ui| { + ui.strong(tr("SBS functions")); + if !app.session.pkg.dependencies.keys().any(|path| path.starts_with("sbs://")) { + ui.colored_label(egui::Color32::from_rgb(255, 90, 180), tr("Missing SBS function library")); + } + + for (package, graph, label, description, missing) in functions { + let text = if missing { + egui::RichText::new(format!("{}: {label}", tr("Missing"))).color(egui::Color32::from_rgb(255, 90, 180)) + } else { + egui::RichText::new(&label) + }; + let response = ui.add(egui::Label::new(text).selectable(false).sense(Sense::click_and_drag())); + crate::widgets::name(&response, egui::Role::ListItem, &label); + if response.drag_started() { + egui::DragAndDrop::set_payload(ui.ctx(), FunctionLibraryDrag::Instance { package: package.clone(), graph: graph.clone() }); + } + if response.double_clicked() { + add = Some(FunctionLibraryDrag::Instance { package: package.clone(), graph: graph.clone() }); + } + response.on_hover_text(format!("{description}\n{package}/{graph}")); + } + ui.separator(); + ui.strong(tr("Native operations")); for definition in operations.filter(|definition| definition.label.to_ascii_lowercase().contains(&search)) { - if ui.selectable_label(false, tr(definition.label)).double_clicked() - && let Some(mut editor) = app.function_editor.take() - { - let at = editor.current(app).map_or([0.0; 2], |graph| [graph.nodes.len() as f32 * 140.0, 0.0]); - editor.edit(app, FunctionEdit::Add { operation: definition.id.into(), at, snap: app.ui.prefs.snap_to_grid }, false); - app.function_editor = Some(editor); + let response = ui.add(egui::Label::new(tr(definition.label)).selectable(false).sense(Sense::click_and_drag())); + crate::widgets::name(&response, egui::Role::ListItem, definition.label); + if response.drag_started() { + egui::DragAndDrop::set_payload(ui.ctx(), FunctionLibraryDrag::Operation(definition.id.into())); + } + if response.double_clicked() { + add = Some(FunctionLibraryDrag::Operation(definition.id.into())); } } }); + if let Some(add) = add + && let Some(mut editor) = app.function_editor.take() + { + let at = editor.current(app).map_or([0.0; 2], |graph| [graph.nodes.len() as f32 * 140.0, 0.0]); + insert(app, &mut editor, &add, at); + app.function_editor = Some(editor); + } +} + +pub(super) fn insert(app: &mut MaterialCraftApp, editor: &mut super::FunctionEditor, entry: &FunctionLibraryDrag, at: [f32; 2]) { + match entry { + FunctionLibraryDrag::Operation(operation) => { + editor.edit(app, FunctionEdit::Add { operation: operation.clone(), at, snap: app.ui.prefs.snap_to_grid }, false) + } + FunctionLibraryDrag::Instance { package, graph } => { + let Some(target) = editor.command_target() else { return }; + if let Some(result) = app.run( + "library.function.add", + serde_json::json!({ + "package": package, "graph": graph, "function": target, "at": at, "snapToGrid": app.ui.prefs.snap_to_grid, + }), + ) && let Some(id) = result.get("id").and_then(serde_json::Value::as_u64).and_then(|id| u32::try_from(id).ok()) + { + editor.selection = vec![id]; + editor.selected_wires.clear(); + editor.inspected_node = Some(id); + } + } + } } diff --git a/crates/ui-egui/src/function/mod.rs b/crates/ui-egui/src/function/mod.rs index b7b5c4e5..bfa47d91 100644 --- a/crates/ui-egui/src/function/mod.rs +++ b/crates/ui-egui/src/function/mod.rs @@ -2,6 +2,7 @@ mod canvas; mod context_menu; mod function_drag; mod function_editor; +mod function_library_drag; mod function_target; pub(crate) mod library; mod port_label; @@ -22,4 +23,5 @@ mod panel; mod function_canvas; mod function_port; mod render; +mod variable_picker; mod warning_banner; diff --git a/crates/ui-egui/src/function/node_canvas.rs b/crates/ui-egui/src/function/node_canvas.rs index ebcf24db..aeff7058 100644 --- a/crates/ui-egui/src/function/node_canvas.rs +++ b/crates/ui-egui/src/function/node_canvas.rs @@ -31,7 +31,14 @@ pub(super) fn paint( let label = materialcraft_engine::nodes::function::node_label(node); let category = definition.map_or("", |definition| definition.category); - let color = if node.instance.is_some() { crate::graph::header_color("graph_instance") } else { category_color(category) }; + let missing = node.missing.is_some() || (node.instance.is_some() && !matches!(node.source, Some(Ok(_)))); + let color = if missing { + Color32::from_rgb(210, 35, 125) + } else if node.instance.is_some() { + crate::graph::header_color("graph_instance") + } else { + category_color(category) + }; node_card::paint(painter, bounds, zoom, label, color); let body = node_card::body(bounds, zoom); if output { @@ -39,7 +46,9 @@ pub(super) fn paint( } node_card::outline(painter, bounds, zoom, Stroke::new(if selected { 2.0 } else { 1.0 }, outline)); - if node.value.is_none() { + 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); } diff --git a/crates/ui-egui/src/function/properties.rs b/crates/ui-egui/src/function/properties.rs index 6792e262..eb242c7d 100644 --- a/crates/ui-egui/src/function/properties.rs +++ b/crates/ui-egui/src/function/properties.rs @@ -31,9 +31,30 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) -> bool { if let Some(instance) = &node.instance { ui.label(format!("Source: {}", if instance.package.is_empty() { "This package" } else { &instance.package })); + ui.label(&instance.graph); + if let Some(Err(error)) = &node.source { + ui.colored_label(egui::Color32::from_rgb(255, 90, 180), error); + } } + if node.missing.is_some() { + ui.colored_label(egui::Color32::from_rgb(255, 90, 180), tr("Missing function operation")); + return true; + } + let mut value = node.value.clone(); - let changed = value.as_mut().is_some_and(|value| crate::value_editor::show(ui, value)); + let changed = if (node.op.starts_with("get_") || node.op == "isdefined") + && let Some(materialcraft_engine::core::Value::Text(name)) = &mut value + { + let variables = app + .function_editor + .as_ref() + .and_then(|editor| editor.command_target()) + .and_then(|target| target.variables(&app.session, id).ok()) + .unwrap_or_default(); + super::variable_picker::show(ui, id, name, &variables) + } else { + value.as_mut().is_some_and(|value| crate::value_editor::show(ui, value)) + }; if changed && let Some(value) = value && let Some(mut editor) = app.function_editor.take() diff --git a/crates/ui-egui/src/function/render.rs b/crates/ui-egui/src/function/render.rs index 5b201801..a873cb25 100644 --- a/crates/ui-egui/src/function/render.rs +++ b/crates/ui-egui/src/function/render.rs @@ -148,7 +148,7 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu 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.value.is_some() { + 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)); diff --git a/crates/ui-egui/src/function/variable_picker.rs b/crates/ui-egui/src/function/variable_picker.rs new file mode 100644 index 00000000..67f1278b --- /dev/null +++ b/crates/ui-egui/src/function/variable_picker.rs @@ -0,0 +1,37 @@ +use egui::{TextEdit, Ui}; +use materialcraft_engine::FunctionVariable; + +use crate::i18n::tr; + +pub(super) fn show(ui: &mut Ui, id: u32, name: &mut String, variables: &[FunctionVariable]) -> bool { + let mut changed = false; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + let width = (ui.available_width() - ui.spacing().interact_size.y).max(40.0); + let field = ui.add(TextEdit::singleline(name).id_salt(("function_variable", id)).hint_text(tr("Variable name")).desired_width(width)); + crate::widgets::name(&field, egui::Role::TextInput, tr("Variable name")); + changed |= field.changed(); + + let button = ui.button(egui_phosphor::regular::CARET_DOWN); + crate::widgets::name(&button, egui::Role::Button, tr("Choose variable")); + let bounds = field.rect.union(button.rect); + egui::Popup::menu(&button).anchor(bounds).width(bounds.width()).show(|ui| { + ui.set_min_width(ui.available_width()); + egui::ScrollArea::vertical().max_height(240.0).auto_shrink([false, true]).show(ui, |ui| { + if variables.is_empty() { + ui.label(tr("No suggested variables")); + } + + for variable in variables { + if ui.selectable_label(*name == variable.name, &variable.name).clicked() { + changed |= *name != variable.name; + name.clone_from(&variable.name); + ui.close(); + } + } + }); + }); + button.on_hover_text(tr("Choose variable")); + }); + changed +} diff --git a/crates/ui-egui/src/graph/add_node_menu.rs b/crates/ui-egui/src/graph/add_node_menu.rs index e1f783e0..3090be32 100644 --- a/crates/ui-egui/src/graph/add_node_menu.rs +++ b/crates/ui-egui/src/graph/add_node_menu.rs @@ -23,8 +23,6 @@ pub(crate) fn show(ui: &mut Ui, entries: impl IntoIterator = entries.into_iter().collect(); - entries.sort_by_key(|(_, label, category)| (*category, *label)); let mut selected = None; let enter = filter.is_some() && ui.input(|input| input.key_pressed(Key::Enter)); ui.set_min_width(220.0); @@ -64,6 +62,20 @@ mod tests { kittest::{By, NodeT, Queryable}, }; + #[test] + fn ordered_entries_keep_the_catalog_sequence() { + let mut harness = Harness::builder().build_ui(|ui| { + super::show(ui, [("second", "Second", "Native"), ("first", "First", "Native"), ("third", "Third", "Native")]); + }); + harness.run_steps(3); + let rows: Vec<_> = ["Second", "First", "Third"] + .iter() + .map(|label| harness.get(By::new().role(egui::accesskit::Role::Button).label(label)).rect().center().y) + .collect(); + + assert!(rows.windows(2).all(|pair| pair[0] < pair[1]), "catalog order must survive rendering: {rows:?}"); + } + #[test] fn letters_disable_other_initials_without_removing_entries() { let mut harness = Harness::builder().build_ui_state( diff --git a/crates/ui-egui/src/graph/canvas.rs b/crates/ui-egui/src/graph/canvas.rs index 03ff3fb9..19966e9a 100644 --- a/crates/ui-egui/src/graph/canvas.rs +++ b/crates/ui-egui/src/graph/canvas.rs @@ -14,6 +14,11 @@ use materialcraft_engine::core::NodeId; /// The graph panel: toolbar row and canvas pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + if ui.rect_contains_pointer(ui.available_rect_before_wrap()) && ui.input(|input| input.pointer.primary_pressed() || input.pointer.secondary_pressed()) { + crate::properties::GraphPropertyDraft::commit(app); + app.inspected_graph = None; + } + app.reconcile_editors(); if !crate::pattern::active(app) { app.pattern_editor = None; diff --git a/crates/ui-egui/src/graph/context_menu.rs b/crates/ui-egui/src/graph/context_menu.rs index 1f37b811..c809a0a0 100644 --- a/crates/ui-egui/src/graph/context_menu.rs +++ b/crates/ui-egui/src/graph/context_menu.rs @@ -63,7 +63,7 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2, node: Opti pub(super) fn add_nodes(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2) { let definitions = materialcraft_engine::nodes::catalog().iter().filter(|definition| definition.id != "dot"); - let entries = definitions.map(|definition| (definition.id, definition.label, definition.category)); + let entries = definitions.map(|definition| (definition.id, definition.label, if definition.id == "output" { "Output" } else { definition.category })); if let Some(definition) = super::add_node_menu::show(ui, entries) { app.run("graph.node.add", json!({"def": definition, "at": [at.x, at.y], "snapToGrid": app.ui.prefs.snap_to_grid})); } diff --git a/crates/ui-egui/src/graph/input.rs b/crates/ui-egui/src/graph/input.rs index 6a9e6014..c2a96878 100644 --- a/crates/ui-egui/src/graph/input.rs +++ b/crates/ui-egui/src/graph/input.rs @@ -11,26 +11,27 @@ pub(super) fn handle( ui: &mut Ui, canvas: &egui::Response, rect: Rect, - cam: &GraphCamera, + camera: &GraphCamera, nodes: &[(NodeId, egui::Response)], frames: &[super::frame_hit::FrameHit], comments: &[(u64, Rect)], port_hover: Option, wire_hover: Option, ) { - let ctx = ui.ctx().clone(); + let context = ui.ctx().clone(); if super::gesture::cancelled(ui) { app.graph.drag = None; return; } - let (pointer, mods, primary_pressed) = ctx.input(|input| (input.pointer.interact_pos(), input.modifiers, input.pointer.primary_pressed())); - let zoom = cam.zoom; - let motion = ctx.input(|i| i.pointer.delta()) / zoom; + + let (pointer, modifiers, primary_pressed) = context.input(|input| (input.pointer.interact_pos(), input.modifiers, input.pointer.primary_pressed())); + let zoom = camera.zoom; + let motion = context.input(|input| input.pointer.delta()) / zoom; // Starting gestures (only on a press inside the canvas, with no gesture running) if app.graph.drag.is_none() - && let Some(p) = pointer - && rect.contains(p) + && let Some(position) = pointer + && rect.contains(position) && ui.rect_contains_pointer(rect) && app.graph.search.is_none() { @@ -41,28 +42,30 @@ pub(super) fn handle( app.run("graph.annotation.select", json!({})); } - let on_card = nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p)); + let on_card = nodes.iter().any(|(_, response)| response.rect.contains(position)) || comments.iter().any(|(_, bounds)| bounds.contains(position)); let wire = wire_hover.as_ref().filter(|_| port_hover.is_none() && !on_card); if wire.is_none() { - super::node_selection::select(&mut app.graph.selected_wires, None, mods); + super::node_selection::select(&mut app.graph.selected_wires, None, modifiers); } - if let Some(w) = wire { - app.graph.drag = Some(GraphDrag::WirePress { wire: w.clone(), start: p }); - } else if let Some(h) = &port_hover { - if h.output { - app.graph.drag = Some(GraphDrag::Wire { from: (h.node, h.port.clone()), detached: None }); - } else if let Some(c) = app.session.graph().ok().and_then(|g| g.input_of(h.node, &h.port).cloned()) { - app.graph.drag = Some(GraphDrag::Wire { from: (c.from, c.from_port.clone()), detached: Some((h.node, h.port.clone())) }); + + if let Some(wire) = wire { + app.graph.drag = Some(GraphDrag::WirePress { wire: wire.clone(), start: position }); + } else if let Some(port) = &port_hover { + if port.output { + app.graph.drag = Some(GraphDrag::Wire { from: (port.node, port.port.clone()), detached: None }); + } else if let Some(connection) = app.session.graph().ok().and_then(|graph| graph.input_of(port.node, &port.port).cloned()) { + app.graph.drag = + Some(GraphDrag::Wire { from: (connection.from, connection.from_port.clone()), detached: Some((port.node, port.port.clone())) }); } - } else if let Some((id, _)) = comments.iter().rev().find(|(_, r)| r.contains(p)) { + } else if let Some((id, _)) = comments.iter().rev().find(|(_, bounds)| bounds.contains(position)) { super::annotation_input::begin_comment(app, *id); - } else if let Some((id, _)) = nodes.iter().rev().find(|(_, r)| r.rect.contains(p)) { - super::node_selection::select(&mut app.session.selection, Some(*id), mods); + } else if let Some((id, _)) = nodes.iter().rev().find(|(_, response)| response.rect.contains(position)) { + super::node_selection::select(&mut app.session.selection, Some(*id), modifiers); app.graph.drag = Some(GraphDrag::Nodes { delta: Vec2::ZERO }); - } else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(p)) { - super::annotation_input::begin_frame(app, hit.id, hit.grip.contains(p)); + } else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(position)) { + super::annotation_input::begin_frame(app, hit.id, hit.grip.contains(position)); } else { - app.graph.drag = Some(GraphDrag::Box { start: p }); + app.graph.drag = Some(GraphDrag::Box { start: position }); } } } @@ -70,20 +73,20 @@ pub(super) fn handle( // Continuing gestures match &mut app.graph.drag { Some(GraphDrag::Pan(_)) => { - let d = ctx.input(|i| i.pointer.delta()) / zoom; - app.ui.graph_camera.pan = [app.ui.graph_camera.pan[0] - d.x, app.ui.graph_camera.pan[1] - d.y]; + let delta = context.input(|input| input.pointer.delta()) / zoom; + app.ui.graph_camera.pan = [app.ui.graph_camera.pan[0] - delta.x, app.ui.graph_camera.pan[1] - delta.y]; } Some(GraphDrag::Nodes { delta }) | Some(GraphDrag::Frame { delta, .. }) | Some(GraphDrag::Comment { delta, .. }) => *delta += motion, Some(GraphDrag::WirePress { wire, start }) => { // Dragged far enough: a reroute dot where the press was, carried by the pointer - if let Some(p) = pointer - && p.distance(*start) > 4.0 + if let Some(position) = pointer + && position.distance(*start) > 4.0 { let (wire, start) = (wire.clone(), *start); - let at = cam.to_graph(start); + let at = camera.to_graph(start); app.graph.drag = None; if app.run("graph.wire.insertDot", json!({"to": wire.0.0, "toPort": wire.1, "at": [at.x, at.y]})).is_some() { - app.graph.drag = Some(GraphDrag::Nodes { delta: (p - start) / zoom }); + app.graph.drag = Some(GraphDrag::Nodes { delta: (position - start) / zoom }); } } } @@ -100,7 +103,7 @@ pub(super) fn handle( match drag { GraphDrag::Pan(_) => {} GraphDrag::WirePress { wire, .. } => { - super::wire_selection::select(&mut app.graph.selected_wires, &mut app.session.selection, wire, mods, false); + super::wire_selection::select(&mut app.graph.selected_wires, &mut app.session.selection, wire, modifiers, false); } GraphDrag::Nodes { delta } => { if delta.length() > 0.5 { @@ -108,15 +111,15 @@ pub(super) fn handle( } } GraphDrag::Box { start } => { - if let Some(p) = pointer { - super::node_selection::select_box(&mut app.session.selection, app.graph.rects.iter().copied(), start, p, mods); + if let Some(position) = pointer { + super::node_selection::select_box(&mut app.session.selection, app.graph.rects.iter().copied(), start, position, modifiers); } } GraphDrag::Wire { from, detached } => { - let target = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 12.0)).filter(|h| !h.output).cloned(); + let target = pointer.and_then(|position| nearest_port(&app.graph.ports, position, 12.0)).filter(|port| !port.output).cloned(); match target { - Some(t) => { - let mut parameters = json!({"from": from.0.0, "fromPort": from.1, "to": t.node.0, "toPort": t.port}); + Some(target) => { + let mut parameters = json!({"from": from.0.0, "fromPort": from.1, "to": target.node.0, "toPort": target.port}); if let Some((node, port)) = detached { parameters["detach"] = json!({"to": node.0, "toPort": port}); } @@ -124,12 +127,12 @@ pub(super) fn handle( app.run("graph.connect", parameters); } None => { - if let Some((n, p)) = &detached { - app.run("graph.disconnect", json!({"to": n.0, "toPort": p})); - } else if let Some(p) = pointer - && rect.contains(p) + if let Some((node, port)) = &detached { + app.run("graph.disconnect", json!({"to": node.0, "toPort": port})); + } else if let Some(position) = pointer + && rect.contains(position) { - open_search(app, cam.to_graph(p), Some(from)); + open_search(app, camera.to_graph(position), Some(from)); } } } @@ -139,60 +142,63 @@ pub(super) fn handle( } // Clicks - for (id, r) in nodes { - if r.double_clicked() { - // Instances open their sources only through Open reference + for (id, response) in nodes { + if response.double_clicked() { + // Double-click previews outputs; embedded graphs require an explicit edit action + // Linked instances open their sources through Open reference if app.session.graph().ok().and_then(|graph| graph.node(*id).ok()).is_some_and(|node| node.def != "graph_instance") { app.run("view.2d", json!({"node": id.0, "port": 0})); - if crate::menus::enabled(app, "graph.node.edit") { - crate::menus::invoke(app, ui.ctx(), "graph.node.edit"); - } } - } else if r.clicked() && app.session.selection.contains(id) && app.session.view2d.node != Some(*id) { + } else if response.clicked() && app.session.selection.contains(id) && app.session.view2d.node != Some(*id) { // Keep the current output when deselecting or clicking the node already shown app.run("view.2d", json!({"node": id.0})); } - if r.secondary_clicked() + if response.secondary_clicked() && let Some(pointer) = pointer { - app.graph.menu_at = cam.to_graph(pointer); + app.graph.menu_at = camera.to_graph(pointer); } let at = app.graph.menu_at; - r.context_menu(|ui| super::context_menu::show(app, ui, at, Some(*id))); + response.context_menu(|ui| super::context_menu::show(app, ui, at, Some(*id))); } - if let Some(h) = &port_hover - && h.output + + if let Some(port) = &port_hover + && port.output && ui.rect_contains_pointer(rect) - && ctx.input(|i| i.pointer.primary_clicked()) + && context.input(|input| input.pointer.primary_clicked()) { - let idx = app.session.output_ports(h.node).iter().position(|p| *p == h.port).unwrap_or(0); - app.run("view.2d", json!({"node": h.node.0, "port": idx})); + let port_index = app.session.output_ports(port.node).iter().position(|identifier| *identifier == port.port).unwrap_or(0); + app.run("view.2d", json!({"node": port.node.0, "port": port_index})); } - let on_node = pointer.is_some_and(|p| { - nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p)) || frames.iter().any(|frame| frame.contains(p)) + + let on_node = pointer.is_some_and(|position| { + nodes.iter().any(|(_, response)| response.rect.contains(position)) + || comments.iter().any(|(_, bounds)| bounds.contains(position)) + || frames.iter().any(|frame| frame.contains(position)) }); if canvas.double_clicked() && !on_node - && let Some(p) = pointer + && let Some(position) = pointer { match &wire_hover { // Double-click a wire: a reroute dot there - Some(w) => { - let at = cam.to_graph(p); - app.run("graph.wire.insertDot", json!({"to": w.0.0, "toPort": w.1, "at": [at.x, at.y]})); + Some(wire) => { + let at = camera.to_graph(position); + app.run("graph.wire.insertDot", json!({"to": wire.0.0, "toPort": wire.1, "at": [at.x, at.y]})); app.graph.selected_wires.clear(); } - None => open_search(app, cam.to_graph(p), None), + None => open_search(app, camera.to_graph(position), None), } } + if canvas.secondary_clicked() - && let Some(p) = pointer + && let Some(position) = pointer { - app.graph.menu_at = cam.to_graph(p); - if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(p)) { + app.graph.menu_at = camera.to_graph(position); + if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(position)) { app.run("graph.annotation.select", json!({"kind": "comment", "id": id})); - } else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(p)) { + } else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(position)) { app.run("graph.annotation.select", json!({"kind": "frame", "id": hit.id})); } app.graph.menu_wire = wire_hover.clone().filter(|_| !on_node); @@ -200,41 +206,42 @@ pub(super) fn handle( super::wire_selection::select(&mut app.graph.selected_wires, &mut app.session.selection, wire, egui::Modifiers::NONE, true); } } + let at = app.graph.menu_at; canvas.context_menu(|ui| match app.graph.menu_wire.clone() { - Some(w) => wire_menu(app, ui, w, at), + Some(wire) => wire_menu(app, ui, wire, at), None => super::context_menu::show(app, ui, at, None), }); if let Some(payload) = crate::widgets::dnd_release::(canvas) && let Some(pointer) = pointer { - let at = cam.to_graph(pointer); + let at = camera.to_graph(pointer); app.run("graph.instance.add", json!({"document": payload.document, "graph": payload.name, "at": [at.x - NODE_W * 0.5, at.y - 20.0]})); } // Library drops if let Some(payload) = crate::widgets::dnd_release::(canvas) - && let Some(p) = pointer + && let Some(position) = pointer { - let gp = cam.to_graph(p); - let at = [gp.x - NODE_W * 0.5, gp.y - 20.0]; + let graph_position = camera.to_graph(position); + let at = [graph_position.x - NODE_W * 0.5, graph_position.y - 20.0]; app.run("graph.node.add", json!({"def": payload.0, "at": at})); } // Keys over the canvas - let hovered = pointer.is_some_and(|p| rect.contains(p)); + let hovered = pointer.is_some_and(|position| rect.contains(position)); if hovered && app.graph.search.is_none() { - let space = !ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::Space)); - let tab = !app.graph.keyboard_was_focused && !ctx.text_edit_focused() && ctx.input(|i| i.key_pressed(egui::Key::Tab)); + let space = !context.egui_wants_keyboard_input() && context.input(|input| input.key_pressed(egui::Key::Space)); + let tab = !app.graph.keyboard_was_focused && !context.text_edit_focused() && context.input(|input| input.key_pressed(egui::Key::Tab)); if (space || tab) - && let Some(p) = pointer + && let Some(position) = pointer { - open_search(app, cam.to_graph(p), None); + open_search(app, camera.to_graph(position), None); } if GraphCamera::frame_key(ui, rect) { - let sel = !app.session.selection.is_empty(); - frame(app, rect, sel); + let selected = !app.session.selection.is_empty(); + frame(app, rect, selected); } } } diff --git a/crates/ui-egui/src/graph/interaction_tests.rs b/crates/ui-egui/src/graph/interaction_tests.rs index a08bd522..85883285 100644 --- a/crates/ui-egui/src/graph/interaction_tests.rs +++ b/crates/ui-egui/src/graph/interaction_tests.rs @@ -133,6 +133,45 @@ fn standalone_function_canvas_wires_constants_and_marks_an_output() { assert_eq!(function.output, Some(multiply)); } +#[test] +fn embedded_graphs_open_with_control_e_but_not_double_click() { + for definition in ["fx_map", "pixel_processor", "value_processor"] { + let mut frames = Frames::new(new_session()); + let node = NodeId(frames.app.run("graph.node.add", json!({"def": definition})).unwrap()["id"].as_u64().unwrap()); + frames.app.ui.frame_all = true; + frames.run(Vec::new(), Modifiers::NONE); + let original = frames.app.session.pkg.clone(); + let history = frames.app.session.history(); + let position = frames.center(node); + + frames.time += 1.0; + frames.run(vec![Event::PointerMoved(position)], Modifiers::NONE); + for pressed in [true, false, true, false] { + frames.run(vec![Event::PointerButton { pos: position, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }], Modifiers::NONE); + } + + assert!(frames.app.function_editor.is_none(), "{definition} double-click opened a function"); + assert!(frames.app.pattern_editor.is_none(), "{definition} double-click opened a pattern"); + assert_eq!(frames.app.session.selection, vec![node]); + assert_eq!(frames.app.session.view2d.node, Some(node)); + + let control = Modifiers::CTRL | Modifiers::COMMAND; + for pressed in [true, false] { + frames.run(vec![Event::Key { key: egui::Key::E, physical_key: Some(egui::Key::E), pressed, repeat: false, modifiers: control }], control); + } + + if definition == "fx_map" { + assert_eq!(frames.app.pattern_editor.as_ref().map(|editor| editor.node), Some(node)); + assert!(frames.app.function_editor.is_none()); + } else { + assert_eq!(frames.app.function_editor.as_ref().and_then(|editor| editor.node), Some(node)); + assert!(frames.app.pattern_editor.is_none()); + } + assert_eq!(frames.app.session.pkg, original); + assert_eq!(frames.app.session.history(), history); + } +} + #[test] fn selected_pattern_subgraph_opens_with_control_e() { let mut frames = Frames::new(new_session()); @@ -465,7 +504,7 @@ fn every_canvas_keeps_properties_after_deselection() { graph.nodes[1].pos = [256.0, 0.0]; graph.output = Some(id); frames.app.run("graph.function.set", json!({"function": graph})).unwrap(); - (NodeId(u64::from(id)), "Multiply - Properties") + (NodeId(u64::from(id)), "Multiplication - Properties") } "pattern" => { let owner = NodeId(frames.app.run("graph.node.add", json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); @@ -478,7 +517,7 @@ fn every_canvas_keeps_properties_after_deselection() { } _ => { let id = NodeId(frames.app.run("graph.node.add", json!({"def": "uniform"})).unwrap()["id"].as_u64().unwrap()); - (id, "Uniform Color - Properties") + (id, "Uniform color - Properties") } }; frames.app.ui.frame_all = true; diff --git a/crates/ui-egui/src/graph/node_style.rs b/crates/ui-egui/src/graph/node_style.rs index 5a35949e..51da3612 100644 --- a/crates/ui-egui/src/graph/node_style.rs +++ b/crates/ui-egui/src/graph/node_style.rs @@ -39,7 +39,7 @@ pub fn node_label(n: &Node) -> String { return n.label.clone(); } if let Some(instance) = &n.instance { - return instance.graph.clone(); + return if instance.label.is_empty() { instance.graph.clone() } else { instance.label.clone() }; } let label = match n.def.as_str() { "graph_instance" => match n.params.get("graph") { @@ -47,7 +47,13 @@ pub fn node_label(n: &Node) -> String { _ => tr("Graph instance").into(), }, "output" | "input_color" | "input_grayscale" | "input_value" => materialcraft_engine::eval::identifier(n), - d => materialcraft_engine::nodes::find(d).map_or(d, |d| d.label).to_string(), + d => { + if let Some(definition) = materialcraft_engine::nodes::find(d) { + return tr(definition.label).into(); + } + + d.to_string() + } }; label.split(['_', ' ']).filter(|word| !word.is_empty()).fold(String::with_capacity(label.len()), |mut display, word| { if !display.is_empty() { diff --git a/crates/ui-egui/src/graph/review_tests.rs b/crates/ui-egui/src/graph/review_tests.rs index a327668a..b00921cb 100644 --- a/crates/ui-egui/src/graph/review_tests.rs +++ b/crates/ui-egui/src/graph/review_tests.rs @@ -13,11 +13,15 @@ use serde_json::json; fn embedded_function_commands_do_not_edit_the_parent_selection() { let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); let owner = NodeId(app.run("graph.node.add", json!({"def": "pixel_processor"})).unwrap()["id"].as_u64().unwrap()); + let target = materialcraft_engine::FunctionGraphTarget::Parameter { node: owner, parameter: "function".into() }; + app.run("graph.function.set", json!({"target": target, "function": FunctionGraph::constant(Value::Float(0.5))})).unwrap(); app.function_editor = Some(FunctionEditor::new(app.session.graph, owner, FunctionTarget::Parameter("function".into()))); app.session.selection = vec![owner]; let context = egui::Context::default(); + menus::invoke(&mut app, &context, "edit.selectAll"); menus::invoke(&mut app, &context, "edit.delete"); + let node = app.session.graph().unwrap().node(owner).expect("Delete must stay in the Function editor"); let Value::Function(function) = &node.params["function"] else { panic!("missing function") }; assert!(function.nodes.is_empty()); @@ -323,7 +327,7 @@ fn properties_and_library_follow_the_active_embedded_function() { assert!(output.shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.job.text.contains("Search functions")))); menus::invoke(&mut frames.app, &frames.ctx, "ui.graph.parent"); assert_eq!(EditorTarget::resolve(&frames.app), EditorTarget::Material); - assert!(crate::properties::title(&frames.app).starts_with("Pixel Processor")); + assert!(crate::properties::title(&frames.app).starts_with("Pixel processor")); } #[test] diff --git a/crates/ui-egui/src/material_craft_app.rs b/crates/ui-egui/src/material_craft_app.rs index 8fa24225..813820c2 100644 --- a/crates/ui-egui/src/material_craft_app.rs +++ b/crates/ui-egui/src/material_craft_app.rs @@ -22,6 +22,8 @@ pub struct MaterialCraftApp { /// Embedded graph editors in the main graph panel pub pattern_editor: Option, pub function_editor: Option, + pub(crate) inspected_graph: Option, + pub(crate) graph_property_draft: Option, pub(crate) graph_parents: Vec, /// Synthetic input from the control channel, fed to egui on the next frames pub input_queue: VecDeque, @@ -72,6 +74,8 @@ impl MaterialCraftApp { view3d: view3d::View3dState::default(), view2d: view2d::View2dState::default(), function_editor: None, + inspected_graph: None, + graph_property_draft: None, graph_parents: Vec::new(), pattern_editor: None, input_queue: VecDeque::new(), @@ -106,6 +110,13 @@ impl MaterialCraftApp { /// Run an engine command, reporting errors as toasts. Returns the result on success pub fn run(&mut self, id: &str, mut params: Value) -> Option { + if id.starts_with("file.") + || id.starts_with("package.") + || matches!(id, "graph.open" | "graph.delete" | "graph.duplicate" | "folder.remove" | "explorer.paste" | "edit.undo" | "edit.redo") + { + crate::properties::GraphPropertyDraft::commit(self); + } + if matches!( id, "graph.node.add" @@ -148,9 +159,11 @@ impl MaterialCraftApp { pub(crate) fn close_subgraph_after(&mut self, command: &str) { if command.starts_with("file.new") || command.starts_with("package.") - || matches!(command, "file.open" | "graph.open" | "graph.delete" | "graph.duplicate") + || matches!(command, "file.open" | "file.reload" | "graph.open" | "graph.delete" | "graph.duplicate" | "folder.remove" | "explorer.paste") { self.graph.inspected_node = None; + self.inspected_graph = None; + self.graph_property_draft = None; self.graph_parents.clear(); self.pattern_editor = None; self.function_editor = None; @@ -167,6 +180,9 @@ impl MaterialCraftApp { } pub(crate) fn reconcile_editors(&mut self) { + if self.inspected_graph.is_some_and(|target| target.get(&self.session).is_err()) { + self.inspected_graph = None; + } if self.function_editor.as_ref().is_some_and(|editor| editor.current(self).is_none()) { self.function_editor = None; } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index ce43ef0d..908865d3 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -23,6 +23,21 @@ const fn sep(menu: &'static str) -> MenuItem { pub const TOP: [&str; 5] = ["File", "Edit", "Tools", "Windows", "Help"]; +pub(crate) const EXPLORER_NEW: &[(&str, &str)] = &[("Graph", "ui.newGraph"), ("Function Graph", "ui.newFunctionGraph"), ("Folder", "folder.create")]; +pub(crate) const EXPLORER_PACKAGE: &[(&str, &str)] = &[ + ("Reload", "file.reload"), + ("Save", "file.save"), + ("Save As", "file.saveAs"), + ("Save A Copy As", "file.saveCopyAs"), + ("Copy", "explorer.copy"), + ("Paste", "explorer.paste"), + ("Close", "package.close"), +]; +pub(crate) const EXPLORER_FOLDER: &[(&str, &str)] = + &[("Copy", "explorer.copy"), ("Paste", "explorer.paste"), ("Rename", "folder.rename"), ("Remove", "folder.remove")]; +pub(crate) const EXPLORER_GRAPH: &[(&str, &str)] = + &[("Open", "graph.open"), ("Copy", "explorer.copy"), ("Paste", "explorer.paste"), ("Remove", "graph.delete"), ("Rename", "graph.rename")]; + /// The menu catalog (the target menu tree with our ids) pub const CATALOG: &[MenuItem] = &[ sub("File", "New", "Graph...", "ui.newGraph", Some("Ctrl+N")), diff --git a/crates/ui-egui/src/property/graph.rs b/crates/ui-egui/src/property/graph.rs index 8613cdb5..89685a8d 100644 --- a/crates/ui-egui/src/property/graph.rs +++ b/crates/ui-egui/src/property/graph.rs @@ -5,44 +5,29 @@ use egui_phosphor::regular as icon; use materialcraft_engine::core::{Graph, OutputFormat, Resource, Value}; use serde_json::{Value as JsonValue, json}; -/// A one-line field for a value the engine holds: what is typed stays between frames, and the text -/// comes back when the field loses focus with something new in it. A change to the value from -/// elsewhere (undo) drops the draft. -fn draft_field(ui: &mut Ui, salt: String, current: &str, label: &str) -> Option { - let id = ui.make_persistent_id(salt); - let draft: Option<(String, String)> = ui.data(|data| data.get_temp(id)); - let mut text = draft.filter(|(seen, _)| seen == current).map_or_else(|| current.to_string(), |(_, text)| text); - let response = ui.add(egui::TextEdit::singleline(&mut text).desired_width(ui.available_width())); - crate::widgets::name(&response, egui::Role::TextInput, label); - if response.has_focus() { - ui.data_mut(|data| data.insert_temp(id, (current.to_string(), text.clone()))); - } else { - ui.data_mut(|data| data.remove_temp::<(String, String)>(id)); - } - (response.lost_focus() && text != current).then_some(text) +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, target: materialcraft_engine::GraphTarget) { + ui.push_id(target, |ui| show_target(app, ui, target)); } -pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { +fn show_target(app: &mut MaterialCraftApp, ui: &mut Ui, target: materialcraft_engine::GraphTarget) { + super::graph_attributes::show(app, ui, target); let tokens = Tokens::get(ui.ctx()); - let graph_index = app.session.graph; - let Ok(graph) = app.session.graph() else { + let Ok(graph) = target.get(&app.session) else { ui.label(tr("No graph is open")); return; }; let mut commands = Vec::new(); - let mut emit = |id: &'static str, parameters| commands.push((id, parameters)); - section(ui, "graph-base", tr("Base parameters"), |ui| { - ui.horizontal(|ui| { - ui.label(tr("Name")); - if let Some(name) = draft_field(ui, format!("graph-name-{graph_index}"), &graph.name, "Graph name") { - emit("graph.rename", json!({"name": name})); - } - }); - if graph.function.is_some() { - return; - } + let mut emit = |id: &'static str, mut parameters: JsonValue| { + parameters["document"] = serde_json::json!(target.document); + parameters["graph"] = serde_json::json!(target.graph); + commands.push((id, parameters)); + }; + if graph.function.is_some() { + return; + } + section(ui, "graph-base", tr("Base parameters"), |ui| { for (axis, label) in [(0usize, "Width"), (1, "Height")] { let mut value = graph.size[axis] as f32; if crate::widgets::slider(ui, &format!("{} {} px", tr(label), 1u32 << graph.size[axis]), &mut value, 4.0..=13.0, 0).changed() { @@ -63,21 +48,13 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { emit("graph.seed", json!({"seed": seed.round() as i64})); } }); - section(ui, "graph-attr", tr("Attributes"), |ui| { - for (key, label, current) in [ - ("category", "Category", &graph.attributes.category), - ("description", "Description", &graph.attributes.description), - ("author", "Author", &graph.attributes.author), - ("tags", "Tags", &graph.attributes.tags), - ] { - ui.horizontal(|ui| { - ui.label(tr(label)); - if let Some(edited) = draft_field(ui, format!("graph-attribute-{graph_index}-{key}"), current, label) { - emit("graph.attributes", json!({key: edited})); - } - }); + if target != materialcraft_engine::GraphTarget::active(&app.session) { + for (id, parameters) in commands { + app.run(id, parameters); } - }); + return; + } + section(ui, "graph-inputs", tr("Input parameters"), |ui| { if graph.exposed.is_empty() { ui.label(RichText::new(tr("Right-click a node parameter > Expose as graph input")).size(11.0).color(tokens.text_dim)); diff --git a/crates/ui-egui/src/property/graph_attributes.rs b/crates/ui-egui/src/property/graph_attributes.rs new file mode 100644 index 00000000..2203aa0b --- /dev/null +++ b/crates/ui-egui/src/property/graph_attributes.rs @@ -0,0 +1,48 @@ +use super::{graph_property_draft::GraphPropertyDraft, section}; +use crate::{MaterialCraftApp, i18n::tr}; +use materialcraft_engine::GraphTarget; + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut egui::Ui, target: GraphTarget) { + if app.graph_property_draft.as_ref().is_some_and(|draft| draft.target != target) { + GraphPropertyDraft::commit(app); + } + + let Ok(graph) = target.get(&app.session) else { return }; + let draft = &mut app.graph_property_draft; + section(ui, "graph-attributes", tr("Attributes"), |ui| { + for (key, label, current) in [ + ("name", "Identifier", &graph.name), + ("description", "Description", &graph.attributes.description), + ("category", "Category", &graph.attributes.category), + ("label", "Label", &graph.attributes.label), + ("author", "Author", &graph.attributes.author), + ("authorUrl", "Author URL", &graph.attributes.author_url), + ("tags", "Tags", &graph.attributes.tags), + ("group", "Group", &graph.attributes.group), + ("userData", "User Data", &graph.attributes.user_data), + ] { + if graph.function.is_none() && !matches!(key, "name" | "label") { + continue; + } + + let widget = ui.make_persistent_id((target, key)); + if draft.as_ref().is_some_and(|draft| draft.widget == widget && draft.original != *current) { + *draft = None; + } + + let pending = draft.as_ref().filter(|draft| draft.widget == widget && draft.original == *current); + let mut text = pending.map_or_else(|| current.clone(), |draft| draft.text.clone()); + ui.label(tr(label)); + let editor = if key == "description" { egui::TextEdit::multiline(&mut text).desired_rows(6) } else { egui::TextEdit::singleline(&mut text) }; + let response = ui.add(editor.id(widget).desired_width(ui.available_width())); + crate::widgets::name(&response, egui::Role::TextInput, label); + if response.changed() { + *draft = Some(GraphPropertyDraft { target, key, original: current.clone(), text, widget }); + } + ui.add_space(5.0); + } + }); + if app.graph_property_draft.as_ref().is_some_and(|draft| !ui.memory(|memory| memory.has_focus(draft.widget))) { + GraphPropertyDraft::commit(app); + } +} diff --git a/crates/ui-egui/src/property/graph_property_draft.rs b/crates/ui-egui/src/property/graph_property_draft.rs new file mode 100644 index 00000000..6ee426e3 --- /dev/null +++ b/crates/ui-egui/src/property/graph_property_draft.rs @@ -0,0 +1,24 @@ +use crate::MaterialCraftApp; +use materialcraft_engine::GraphTarget; +use serde_json::json; + +/// Text retained until focus leaves the field or the inspector changes target +pub(crate) struct GraphPropertyDraft { + pub target: GraphTarget, + pub key: &'static str, + pub original: String, + pub text: String, + pub widget: egui::Id, +} + +impl GraphPropertyDraft { + pub fn commit(app: &mut MaterialCraftApp) { + let Some(draft) = app.graph_property_draft.take() else { return }; + if draft.text == draft.original || draft.target.get(&app.session).is_err() { + return; + } + + let command = if draft.key == "name" { "graph.rename" } else { "graph.attributes" }; + app.run(command, json!({"document": draft.target.document, "graph": draft.target.graph, draft.key: draft.text})); + } +} diff --git a/crates/ui-egui/src/property/mod.rs b/crates/ui-egui/src/property/mod.rs index 89e6720f..a6bee45a 100644 --- a/crates/ui-egui/src/property/mod.rs +++ b/crates/ui-egui/src/property/mod.rs @@ -1,6 +1,8 @@ mod curve; mod gradient; mod graph; +mod graph_attributes; +mod graph_property_draft; mod input; mod node; mod parameter; @@ -8,6 +10,7 @@ mod section; pub use curve::curve_editor; pub use gradient::gradient_editor; +pub(crate) use graph_property_draft::GraphPropertyDraft; pub(crate) use section::section; use crate::{MaterialCraftApp, graph::editor_target::EditorTarget, i18n::tr}; @@ -15,10 +18,19 @@ use egui::Ui; /// The panel title: " - Properties" or " - Properties" pub fn title(app: &MaterialCraftApp) -> String { + if let Some(target) = app.inspected_graph + && let Ok(graph) = target.get(&app.session) + { + return format!("{} - {}", graph.name, tr("Properties")); + } + match EditorTarget::resolve(app) { EditorTarget::Pattern => return crate::pattern::properties::title(app), EditorTarget::Function if !EditorTarget::annotation_active(app) => { - return crate::function::properties::title(app).unwrap_or_else(|| format!("{} - {}", tr("Function Graph"), tr("Properties"))); + return crate::function::properties::title(app).unwrap_or_else(|| { + let name = app.session.graph().ok().filter(|graph| graph.function.is_some()).map_or(tr("Function Graph"), |graph| graph.name.as_str()); + format!("{name} - {}", tr("Properties")) + }); } _ => {} } @@ -40,6 +52,15 @@ pub fn title(app: &MaterialCraftApp) -> String { pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { ui.set_width(ui.available_width()); + if let Some(target) = app.inspected_graph { + if target.get(&app.session).is_ok() { + graph::show(app, ui, target); + return; + } + + app.inspected_graph = None; + } + match EditorTarget::resolve(app) { EditorTarget::Pattern => { crate::pattern::properties::show(app, ui); @@ -47,7 +68,11 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } EditorTarget::Function if !EditorTarget::annotation_active(app) => { if !crate::function::properties::show(app, ui) { - ui.label(tr("Select a node")); + if app.function_editor.as_ref().is_some_and(|editor| matches!(editor.target, crate::function::FunctionTarget::Graph)) { + graph::show(app, ui, materialcraft_engine::GraphTarget::active(&app.session)); + } else { + ui.label(tr("Select a node")); + } } return; } @@ -63,7 +88,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { .and_then(|id| app.session.graph().ok()?.node(id).ok().cloned()); ui.push_id((app.session.graph, node.as_ref().map(|n| n.id)), |ui| match node { Some(n) => node::show(app, ui, &n), - None => graph::show(app, ui), + None => graph::show(app, ui, materialcraft_engine::GraphTarget::active(&app.session)), }); }); } diff --git a/crates/ui-egui/src/state/ui_state.rs b/crates/ui-egui/src/state/ui_state.rs index a124b356..93ffb92f 100644 --- a/crates/ui-egui/src/state/ui_state.rs +++ b/crates/ui-egui/src/state/ui_state.rs @@ -9,6 +9,8 @@ pub struct UiState { pub dock: Dock, pub prefs: Prefs, pub windows: Windows, + #[serde(skip)] + pub explorer: crate::explorer::ExplorerState, pub graph_camera: GraphCamera, pub image_camera: ImageCamera, /// Library: the selected category path ("" = all) and the search text @@ -39,6 +41,7 @@ impl Default for UiState { dock: Dock::default(), prefs: Prefs::default(), windows: Windows::default(), + explorer: Default::default(), graph_camera: GraphCamera::default(), image_camera: ImageCamera::default(), library_category: String::new(), diff --git a/crates/ui-egui/src/unsaved.rs b/crates/ui-egui/src/unsaved.rs index b240d0a8..31967c80 100644 --- a/crates/ui-egui/src/unsaved.rs +++ b/crates/ui-egui/src/unsaved.rs @@ -60,6 +60,20 @@ pub fn holds_close(modified: bool, confirmed: bool) -> bool { /// Run `action`, asking first when the package has unsaved changes pub fn guard(app: &mut MaterialCraftApp, action: Guarded) { + if app.ui.windows.unsaved.is_some() { + return; + } + + if let Guarded::Package { document, .. } = &action { + if app.run("package.activate", serde_json::json!({"document": document})).is_none() { + return; + } + if let Some(action) = request(&mut app.ui.windows.unsaved, app.session.modified, action) { + perform(app, action); + } + return; + } + if app.ui.windows.unsaved.is_none() && let Some((document, ..)) = app.session.open_packages().into_iter().find(|entry| entry.3) { @@ -74,6 +88,11 @@ pub fn guard(app: &mut MaterialCraftApp, action: Guarded) { /// Run an allowed action fn perform(app: &mut MaterialCraftApp, action: Guarded) { match action { + Guarded::Package { document, reload } => { + if app.run("package.activate", serde_json::json!({"document": document})).is_some() { + app.run(if reload { "file.reload" } else { "package.close" }, serde_json::json!({"discard": true})); + } + } action @ (Guarded::Menu { .. } | Guarded::Quit) => { if app.session.modified { app.run("package.close", serde_json::json!({"discard": true})); @@ -114,6 +133,13 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &Context) { if app.ui.windows.unsaved.is_none() { return; } + if let Some(Guarded::Package { document, .. }) = &app.ui.windows.unsaved { + let document = *document; + if app.run("package.activate", serde_json::json!({"document": document})).is_none() { + app.ui.windows.unsaved = None; + return; + } + } let mut choice = None; Window::new(tr("Unsaved changes")) .id(egui::Id::unique("unsaved-changes")) diff --git a/crates/ui-egui/src/unsaved.test.rs b/crates/ui-egui/src/unsaved.test.rs index 1aee73d7..1549512b 100644 --- a/crates/ui-egui/src/unsaved.test.rs +++ b/crates/ui-egui/src/unsaved.test.rs @@ -67,3 +67,25 @@ fn a_pending_action_is_kept_even_if_the_package_was_saved_elsewhere() { assert!(crate::unsaved::request(&mut pending, false, crate::unsaved::Guarded::Menu { id: "ui.closeAll".into() }).is_none()); assert_eq!(pending, Some(first)); } + +#[test] +fn closing_one_package_only_prompts_for_that_packages_edits() { + use crate::unsaved::{Guarded, guard, perform}; + let mut app = crate::MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default()); + app.session.modified = true; + app.run("file.newPackage", serde_json::json!({"name": "Second"})).unwrap(); + let second = app.session.document_id; + guard(&mut app, Guarded::Package { document: second, reload: false }); + assert!(app.ui.windows.unsaved.is_none()); + assert_eq!(app.session.document_id, 0); + assert!(app.session.modified); + + app.run("file.newPackage", serde_json::json!({"name": "Third"})).unwrap(); + let third = app.session.document_id; + guard(&mut app, Guarded::Package { document: 0, reload: false }); + assert_eq!(app.ui.windows.unsaved, Some(Guarded::Package { document: 0, reload: false })); + app.ui.windows.unsaved = None; + perform(&mut app, Guarded::Package { document: 0, reload: false }); + assert_eq!(app.session.document_id, third); + assert_eq!(app.session.open_packages().len(), 1); +} diff --git a/crates/ui-egui/src/unsaved/guarded.rs b/crates/ui-egui/src/unsaved/guarded.rs index a0a46f62..33fbffd2 100644 --- a/crates/ui-egui/src/unsaved/guarded.rs +++ b/crates/ui-egui/src/unsaved/guarded.rs @@ -4,6 +4,8 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "camelCase")] pub enum Guarded { + /// Reload or close one package without affecting other open documents + Package { document: u64, reload: bool }, /// A menu item: `ui.closeAll` or `file.newPackage` Menu { id: String }, /// Open the package at `path` (desktop) diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 73207bca..701b4d49 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -168,10 +168,20 @@ mod web { /// File ▸ Save: download the package as `.sbs` (bitmaps embedded) pub fn save(app: &mut MaterialCraftApp) { + save_download(app, false); + } + + pub fn save_copy(app: &mut MaterialCraftApp) { + save_download(app, true); + } + + fn save_download(app: &mut MaterialCraftApp, copy: bool) { let name = format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name)); match materialcraft_engine::file_cmds::save_bytes(&app.session).map_err(|e| e.to_string()).and_then(|b| download(&name, &b)) { Ok(()) => { - app.session.modified = false; + if !copy { + app.session.modified = false; + } app.toast(format!("{} {name}", tr("Downloaded")), false); } Err(e) => app.toast(format!("{} {name}: {e}", tr("Couldn't save")), true), diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 9f6b2891..50e6f43b 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -96,6 +96,7 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { home(app, ctx); } crate::unsaved::show(app, ctx); + crate::explorer::dialogs(app, ctx); } fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, size: egui::Vec2, body: impl FnOnce(&mut Ui)) { @@ -529,7 +530,7 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> } true } - "file.save" if app.session.path.is_some() => { + "file.save" if app.session.path.as_ref().is_some_and(|path| !path.contains("://")) => { if let Some(r) = app.run("file.save", json!({})) { let path = r["path"].as_str().unwrap_or_default().to_string(); app.ui.add_recent(&path); @@ -537,12 +538,14 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> } true } - "file.save" | "file.saveAs" => { + "file.save" | "file.saveAs" | "file.saveCopyAs" => { let name = format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name)); if let Some(p) = rfd::FileDialog::new().set_file_name(name).add_filter("SBS package", &["sbs"]).save_file() { let path = materialcraft_engine::file_cmds::package_path(&p.display().to_string()); - if app.run("file.save", json!({"path": path})).is_some() { - app.ui.add_recent(&path); + if app.run(if id == "file.saveCopyAs" { id } else { "file.save" }, json!({"path": path})).is_some() { + if id != "file.saveCopyAs" { + app.ui.add_recent(&path); + } app.toast(format!("{} {path}", tr("Saved")), false); } } @@ -581,6 +584,7 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> "file.open" => crate::web_files::open(ctx), "file.importBitmap" => crate::web_files::import_bitmap(ctx), "file.save" | "file.saveAs" => crate::web_files::save(app), + "file.saveCopyAs" => crate::web_files::save_copy(app), "file.exportMaterial" => crate::web_files::export_material(app), _ => return false, } diff --git a/crates/ui-egui/tests/graph_properties.rs b/crates/ui-egui/tests/graph_properties.rs new file mode 100644 index 00000000..1f623a79 --- /dev/null +++ b/crates/ui-egui/tests/graph_properties.rs @@ -0,0 +1,114 @@ +use egui::{Event, Key, Modifiers, vec2}; +use egui_kittest::{ + Harness, + kittest::{By, Queryable}, +}; +use materialcraft_engine::{ + Session, + core::{FunctionGraph, Graph, Package}, +}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; +use serde_json::json; + +fn harness(render: bool) -> Harness<'static, MaterialCraftApp> { + let mut package = Package::new("Source"); + let mut function = Graph::new("Helper"); + function.function = Some(FunctionGraph::default()); + function.attributes.description = "A reusable function.\nAnother line.".into(); + function.attributes.label = "Readable helper".into(); + function.attributes.author_url = "https://example.org".into(); + package.graphs = vec![Graph::new("Material"), function]; + let mut app = MaterialCraftApp::headless(Session::new(package), UiState::default()); + app.run("file.newPackage", json!({"name": "Canvas"})).unwrap(); + app.run("file.new", json!({"template": "empty", "name": "Open_graph"})).unwrap(); + let builder = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0); + let builder = if render { builder.wgpu() } else { builder }; + let mut harness = builder.build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + harness.run_steps(8); + harness +} + +fn select(harness: &mut Harness<'static, MaterialCraftApp>, name: &str) { + harness.get(By::new().role(egui::Role::TreeItem).label(name)).click(); + harness.run_steps(5); +} + +fn field(label: &str) -> By<'_> { + By::new().role(egui::Role::TextInput).label(label) +} + +fn type_field(harness: &mut Harness<'static, MaterialCraftApp>, label: &str, text: &str) { + harness.get(field(label)).click(); + harness.step(); + harness.key_press_modifiers(Modifiers::COMMAND, Key::A); + harness.step(); + harness.event(Event::Text(text.into())); + harness.run_steps(3); +} + +#[test] +fn explorer_inspects_unopened_graphs_and_edits_the_selected_package() { + let mut harness = harness(false); + let active = (harness.state().session.document_id, harness.state().session.graph); + + select(&mut harness, "Helper"); + + for label in ["Identifier", "Description", "Category", "Label", "Author", "Author URL", "Tags", "Group", "User Data"] { + assert!(harness.query(field(label)).is_some(), "missing {label}"); + } + assert_eq!(harness.get(field("Identifier")).value().as_deref(), Some("Helper")); + assert_eq!(harness.get(field("Label")).value().as_deref(), Some("Readable helper")); + assert_eq!(harness.get(field("Author URL")).value().as_deref(), Some("https://example.org")); + assert_eq!((harness.state().session.document_id, harness.state().session.graph), active); + + type_field(&mut harness, "Description", "First edited line\nSecond edited line"); + select(&mut harness, "Material"); + + let source = materialcraft_engine::GraphTarget { document: 0, graph: 0 }.package(&harness.state().session).unwrap(); + assert_eq!(source.graphs[1].attributes.description, "First edited line\nSecond edited line"); + assert_eq!(harness.get(field("Identifier")).value().as_deref(), Some("Material")); + assert!(harness.query(field("Label")).is_some()); + for label in ["Description", "Category", "Author", "Author URL", "Tags", "Group", "User Data"] { + assert!(harness.query(field(label)).is_none(), "unexpected regular graph attribute {label}"); + } + assert!(harness.state().session.graph().unwrap().attributes.description.is_empty()); + + type_field(&mut harness, "Label", "Surface label"); + harness.key_press(Key::Enter); + harness.run_steps(4); + assert_eq!(materialcraft_engine::GraphTarget { document: 0, graph: 0 }.get(&harness.state().session).unwrap().attributes.label, "Surface label"); + assert_eq!(materialcraft_engine::GraphTarget { document: 0, graph: 0 }.get(&harness.state().session).unwrap().name, "Material"); + assert_eq!((harness.state().session.document_id, harness.state().session.graph), active); +} + +#[test] +fn identifier_edit_commits_before_switching_the_inspector() { + let mut harness = harness(false); + select(&mut harness, "Helper"); + type_field(&mut harness, "Identifier", "Renamed_helper"); + select(&mut harness, "Material"); + + let source = materialcraft_engine::GraphTarget { document: 0, graph: 0 }.package(&harness.state().session).unwrap(); + assert_eq!(source.graphs[1].name, "Renamed_helper"); + assert_eq!(source.graphs[1].attributes.label, "Readable helper"); + assert_eq!(harness.state().session.graph().unwrap().name, "Open_graph"); +} + +#[test] +#[ignore = "requires an offscreen GPU"] +fn graph_properties_screenshot() { + let mut harness = harness(true); + select(&mut harness, "Helper"); + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + harness.render().unwrap().save(directory.join("function-graph-properties.png")).unwrap(); + + select(&mut harness, "Material"); + harness.render().unwrap().save(directory.join("material-graph-properties.png")).unwrap(); +} diff --git a/crates/ui-egui/tests/numeric_input.rs b/crates/ui-egui/tests/numeric_input.rs index df84d97e..fcc7db08 100644 --- a/crates/ui-egui/tests/numeric_input.rs +++ b/crates/ui-egui/tests/numeric_input.rs @@ -62,7 +62,7 @@ fn graph_name_typed_across_frames_commits_on_focus_loss() { h.run_steps(8); h.state_mut().run("graph.select", json!({"ids": []})).unwrap(); h.run_steps(3); - h.get_by_label("Graph name").click(); + h.get(By::new().role(egui::Role::TextInput).label("Identifier")).click(); h.step(); h.key_press_modifiers(Modifiers::COMMAND, Key::A); h.step(); diff --git a/crates/ui-egui/tests/snapshot.rs b/crates/ui-egui/tests/snapshot.rs index 44e7cebc..088f97cd 100644 --- a/crates/ui-egui/tests/snapshot.rs +++ b/crates/ui-egui/tests/snapshot.rs @@ -1,6 +1,18 @@ +#[path = "snapshot/explorer.rs"] +mod explorer; + #[path = "snapshot/function_instances.rs"] mod function_instances; +#[path = "snapshot/function_library.rs"] +mod function_library; + +#[path = "snapshot/function_variables.rs"] +mod function_variables; + +#[path = "snapshot/embedded_graphs.rs"] +mod embedded_graphs; + use std::time::Duration; use egui::vec2; @@ -35,6 +47,22 @@ fn save(h: &mut Harness<'static, MaterialCraftApp>, dir: &std::path::Path, name: println!("wrote {}", dir.join(format!("{name}.png")).display()); } +fn assert_node_menu_order(harness: &Harness<'static, MaterialCraftApp>, labels: &[&str]) { + let button = |label| By::new().role(egui::accesskit::Role::Button).label(label); + // Canvas cards share these labels; compare the buttons within the submenu's own parent + let menu = harness + .get_all(button(labels[0])) + .filter_map(|node| node.parent()) + .find(|parent| { + let actual: Vec<_> = parent.query_all(By::new().role(egui::accesskit::Role::Button)).filter_map(|node| node.accesskit_node().label()).collect(); + actual.len() == labels.len() && labels.iter().all(|label| actual.iter().any(|actual| actual == label)) + }) + .expect("the submenu must contain every available native operation exactly once"); + let actual: Vec<_> = menu.query_all(By::new().role(egui::accesskit::Role::Button)).filter_map(|node| node.accesskit_node().label()).collect(); + + assert_eq!(actual, labels, "native node menu order must match the catalog"); +} + fn double_click(harness: &mut Harness<'static, MaterialCraftApp>, position: egui::Pos2) { harness.event(egui::Event::PointerMoved(position)); harness.step(); @@ -94,12 +122,13 @@ fn explorer_drags_a_linked_graph_between_open_packages() { assert_eq!(harness.state().session.graph().unwrap().node(instance).unwrap().instance.as_ref().unwrap().graph, "Reusable tint"); assert!(harness.state().session.cooked.nodes[&instance].error.is_none()); save(&mut harness, &directory, "linked-instance-explorer-drop"); - harness.get(By::new().role(egui::accesskit::Role::TreeItem).label("Reusable tint")).click(); - settle(&mut harness, 3); + let position = harness.get(By::new().role(egui::accesskit::Role::TreeItem).label("Reusable tint")).rect().center(); + double_click(&mut harness, position); assert_eq!(harness.state().session.document_id, 0); harness.state_mut().run("graph.select", json!({"ids": [color.0]})).unwrap(); harness.state_mut().run("graph.node.param", json!({"id": color.0, "param": "color", "value": [0.9, 0.3, 0.1, 1.0]})).unwrap(); - harness.get(By::new().role(egui::accesskit::Role::TreeItem).label("Target canvas")).click(); + let position = harness.get(By::new().role(egui::accesskit::Role::TreeItem).label("Target canvas")).rect().center(); + double_click(&mut harness, position); settle(&mut harness, 8); assert_eq!(harness.state().session.document_id, target_document); assert_eq!(harness.state().session.history(), ["Add graph instance"]); @@ -162,7 +191,7 @@ fn function_output_highlight_follows_context_menu_and_undo() { assert_eq!(pixel == [255, 163, 26, 255], output, "{label}: {pixel:?}"); }; - harness.get(query("Multiply")).click_secondary(); + harness.get(query("Multiplication")).click_secondary(); settle(&mut harness, 3); let labels = [ "Add Comment", @@ -201,24 +230,24 @@ fn function_output_highlight_follows_context_menu_and_undo() { harness.get(query("Add")).click(); settle(&mut harness, 3); assert_highlight(&mut harness, "Add", false); - assert_highlight(&mut harness, "Multiply", true); + assert_highlight(&mut harness, "Multiplication", true); save(&mut harness, &directory, "function-output-separate-selection"); harness.state_mut().run("edit.undo", json!({})).unwrap(); settle(&mut harness, 3); assert_eq!(harness.state().session.graph().unwrap().function.as_ref().unwrap().output, Some(add)); assert_highlight(&mut harness, "Add", true); - assert_highlight(&mut harness, "Multiply", false); + assert_highlight(&mut harness, "Multiplication", false); harness.state_mut().run("edit.redo", json!({})).unwrap(); settle(&mut harness, 3); - assert_highlight(&mut harness, "Multiply", true); + assert_highlight(&mut harness, "Multiplication", true); harness.get(query("Dot")).click_secondary(); settle(&mut harness, 3); assert!(harness.query(query("Set as output node")).is_none()); assert_eq!(harness.state().session.graph().unwrap().function.as_ref().unwrap().output, Some(multiply)); assert_highlight(&mut harness, "Dot", false); - assert_highlight(&mut harness, "Multiply", true); + assert_highlight(&mut harness, "Multiplication", true); save(&mut harness, &directory, "function-dot-context-menu"); let history = harness.state().session.history(); harness.get(query("Copy info to clipboard")).click(); @@ -236,7 +265,7 @@ fn function_output_highlight_follows_context_menu_and_undo() { harness.state_mut().run("graph.select", json!({"ids": [add, multiply]})).unwrap(); settle(&mut harness, 2); - harness.get(query("Multiply")).click_secondary(); + harness.get(query("Multiplication")).click_secondary(); settle(&mut harness, 3); assert!(harness.get(query("Set as output node")).accesskit_node().is_disabled()); harness.get(query("Create graph from selection (2)")); @@ -488,7 +517,7 @@ fn incomplete_functions_warn_in_standalone_and_processor_canvases() { std::fs::create_dir_all(&directory).unwrap(); save(&mut harness, &directory, &format!("{definition}-warnings")); - harness.get(By::new().role(egui::accesskit::Role::Button).label("Multiply")).click_secondary(); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Multiplication")).click_secondary(); settle(&mut harness, 2); harness.get(By::new().role(egui::accesskit::Role::Button).label_contains("Set as output node")).click(); settle(&mut harness, 3); @@ -609,7 +638,7 @@ fn explorer_disclosure_tracks_input_and_output_entries() { #[test] #[ignore = "requires an offscreen GPU; run explicitly with --ignored"] -fn explorer_export_opens_the_clicked_graph() { +fn explorer_open_targets_the_clicked_graph() { let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); app.run("graph.duplicate", json!({"graph": 0})); app.session.pkg.graphs[1].name = "Export target".into(); @@ -618,13 +647,13 @@ fn explorer_export_opens_the_clicked_graph() { settle(&mut h, 5); h.get_by_label("Export target").click_secondary(); settle(&mut h, 3); - h.get_all(By::new().label("Export outputs...")).last().unwrap().click(); + h.get(By::new().role(egui::accesskit::Role::Button).label("Open")).click(); settle(&mut h, 3); assert_eq!(h.state().session.graph, 1); - assert!(h.state().ui.windows.export); + assert!(!h.state().ui.windows.export); if let Some(dir) = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from) { std::fs::create_dir_all(&dir).unwrap(); - save(&mut h, &dir, "explorer-export"); + save(&mut h, &dir, "explorer-open"); } } @@ -816,12 +845,50 @@ fn graph_context_menu_has_flat_node_list() { harness.get_by_label("Add node").click(); settle(&mut harness, 3); + let primitive_labels = [ + "Bitmap", + "Blend", + "Blur", + "Channels shuffle", + "Curve", + "Directional blur", + "Directional warp", + "Distance", + "Emboss", + "FX-Map", + "Gradient (Dynamic)", + "Gradient map", + "Grayscale conversion", + "HSL", + "Levels", + "Normal", + "Pixel processor", + "SVG", + "Sharpen", + "Text", + "Transformation 2D", + "Uniform color", + "Value processor", + "Warp", + "Input color", + "Input grayscale", + "Input value", + "Output", + ]; + if let Some(directory) = &directory { + save(&mut harness, directory, "unfiltered-add-node-menu"); + } + assert_node_menu_order(&harness, &primitive_labels); + assert_eq!( + materialcraft_engine::nodes::catalog().iter().filter(|definition| definition.id != "dot").map(|definition| definition.label).collect::>(), + primitive_labels + ); harness.key_press(egui::Key::S); settle(&mut harness, 3); let button = |label| By::new().role(egui::accesskit::Role::Button).label(label); assert!(!harness.get_all(button("SVG")).last().unwrap().accesskit_node().is_disabled()); assert!(!harness.get_all(button("Sharpen")).last().unwrap().accesskit_node().is_disabled()); - assert!(harness.get_all(button("Grayscale Conversion")).last().unwrap().accesskit_node().is_disabled()); + assert!(harness.get_all(button("Grayscale conversion")).last().unwrap().accesskit_node().is_disabled()); if let Some(directory) = &directory { save(&mut harness, directory, "flat-add-node-menu"); } @@ -829,7 +896,7 @@ fn graph_context_menu_has_flat_node_list() { let before_clear = harness.state().session.pkg.clone(); harness.key_press(egui::Key::Backspace); settle(&mut harness, 3); - assert!(!harness.get_all(button("Grayscale Conversion")).last().unwrap().accesskit_node().is_disabled()); + assert!(!harness.get_all(button("Grayscale conversion")).last().unwrap().accesskit_node().is_disabled()); assert_eq!(harness.state().session.pkg, before_clear); for _ in 0..2 { @@ -939,6 +1006,7 @@ fn graph_context_menu_has_flat_node_list() { settle(&mut harness, 3); harness.get_by_label("Add node").click(); settle(&mut harness, 3); + assert_node_menu_order(&harness, &["Quadrant", "Switch", "Iterate"]); harness.key_press(egui::Key::S); settle(&mut harness, 3); if let Some(directory) = &directory { @@ -1042,10 +1110,18 @@ fn annotations_and_function_graph_creation() { save(&mut harness, &directory, "function-context-menu"); harness.get_by_label("Add node").click(); settle(&mut harness, 3); - for label in ["Float", "Float2", "Multiply", "While loop"] { + for label in ["Float", "Float2", "Multiplication", "Division", "Ceil", "Vector Float2", "Swizzle Integer1", "To Float", "If...Else", "While loop"] { assert!(harness.query_all(By::new().label(label)).next().is_some(), "missing {label}"); } + let labels: Vec<_> = materialcraft_engine::nodes::function::FUNCTIONS + .iter() + .filter(|definition| definition.id != "passthrough") + .map(|definition| definition.label) + .collect(); + assert_eq!(labels.len(), 84); + assert!(harness.query(By::new().role(egui::accesskit::Role::Button).label("Dot")).is_none()); save(&mut harness, &directory, "flat-function-node-menu"); + assert_node_menu_order(&harness, &labels); } #[test] @@ -1070,7 +1146,7 @@ fn function_cards_and_dot_share_the_regular_graph_style() { let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); std::fs::create_dir_all(&directory).unwrap(); save(&mut harness, &directory, "function-cards-and-dot"); - harness.get_all(By::new().role(egui::accesskit::Role::Button).label("Multiply")).last().unwrap().click(); + harness.get_all(By::new().role(egui::accesskit::Role::Button).label("Multiplication")).last().unwrap().click(); settle(&mut harness, 3); let blank = harness.state().graph.view.left_bottom() + vec2(12.0, -12.0); click_canvas(&mut harness, blank); @@ -1111,7 +1187,7 @@ fn click_canvas(harness: &mut Harness<'static, MaterialCraftApp>, position: egui #[test] #[ignore = "requires an offscreen GPU; run explicitly with --ignored"] -fn named_outputs_open_properties_and_preview_only_on_double_click() { +fn named_outputs_select_without_loading_and_open_on_double_click() { let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); let source = app.run("graph.node.add", json!({"def": "uniform", "at": [0, 0]})).unwrap()["id"].as_u64().unwrap(); let output = app @@ -1125,6 +1201,7 @@ fn named_outputs_open_properties_and_preview_only_on_double_click() { .as_u64() .unwrap(); app.run("view.2d", json!({"node": source})).unwrap(); + app.run("graph.select", json!({"ids": [source]})).unwrap(); app.session.cook(); let material = app.session.material_maps().into_iter().map(|(name, image)| (name, image.data.clone())).collect::>(); let view3d = serde_json::to_value(&app.session.view3d).unwrap(); @@ -1133,14 +1210,13 @@ fn named_outputs_open_properties_and_preview_only_on_double_click() { let query = By::new().role(egui::accesskit::Role::TreeItem).label("Base Color"); let position = harness.get(query.clone()).rect().center(); click_canvas(&mut harness, position); - assert_eq!(harness.state().session.selection, vec![materialcraft_engine::core::NodeId(output)]); + assert_eq!(harness.state().session.selection, vec![materialcraft_engine::core::NodeId(source)]); assert_eq!(harness.state().session.view2d.node, Some(materialcraft_engine::core::NodeId(source))); - assert!(harness.query_all(By::new().label("Identifier")).next().is_some()); assert!(!harness.state().graph.ports.iter().any(|port| port.node.0 == output && port.output)); let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); std::fs::create_dir_all(&directory).unwrap(); - save(&mut harness, &directory, "named-output-properties"); + save(&mut harness, &directory, "named-output-selection"); let start = harness.ctx.input(|input| input.time) + 1.0; for (index, pressed) in [true, false, true, false].into_iter().enumerate() { harness.input_mut().time = Some(start + index as f64 * 0.05); @@ -1149,6 +1225,8 @@ fn named_outputs_open_properties_and_preview_only_on_double_click() { } settle(&mut harness, 3); assert_eq!(harness.state().session.view2d.node, Some(materialcraft_engine::core::NodeId(output))); + assert_eq!(harness.state().session.selection, vec![materialcraft_engine::core::NodeId(output)]); + assert!(harness.query_all(By::new().label("Identifier")).next().is_some()); assert_eq!(serde_json::to_value(&harness.state().session.view3d).unwrap(), view3d); let current = harness.state().session.material_maps().into_iter().map(|(name, image)| (name, image.data.clone())).collect::>(); assert_eq!(current, material); @@ -1296,17 +1374,22 @@ fn embedded_function_toolbar_and_panels_share_the_active_target() { save(&mut harness, &directory, &format!("{definition}-inline-function")); harness.state_mut().ui.library_search = "Sample".into(); settle(&mut harness, 2); - for label in ["Sample grayscale", "Sample color"] { + for label in ["Sample gray", "Sample color"] { assert_eq!(harness.query_all(By::new().label(label)).next().is_some(), definition == "pixel_processor"); } harness.get(By::new().role(egui::accesskit::Role::Canvas).label("Function Graph")).click_secondary(); settle(&mut harness, 2); harness.get_by_label("Add node").click(); settle(&mut harness, 2); - for label in ["Sample grayscale", "Sample color"] { + for label in ["Sample gray", "Sample color"] { assert_eq!(harness.query_all(query(label)).next().is_some(), definition == "pixel_processor"); } + let labels: Vec<_> = + target.available_operations(&harness.state().session).filter(|operation| operation.id != "passthrough").map(|operation| operation.label).collect(); + assert_eq!(labels.len(), if definition == "pixel_processor" { 84 } else { 82 }); + assert!(harness.query(query("Dot")).is_none()); save(&mut harness, &directory, &format!("{definition}-node-menu")); + assert_node_menu_order(&harness, &labels); harness.key_press(egui::Key::Escape); harness.key_press(egui::Key::Escape); settle(&mut harness, 2); @@ -1407,8 +1490,8 @@ fn explorer_inputs_and_graph_drop_share_labels_and_material_assignment() { for (id, label) in inputs { let row = harness.get(By::new().role(egui::accesskit::Role::TreeItem).label(label)); assert!(row.rect().left() > graph_row.left()); - row.click(); - settle(&mut harness, 3); + let position = row.rect().center(); + double_click(&mut harness, position); assert_eq!(harness.state().session.selection, vec![id]); assert_eq!(harness.get(By::new().role(egui::accesskit::Role::TextInput).label("Node label")).value().as_deref(), Some(label)); assert!(harness.query_all(By::new().label("Identifier")).next().is_some()); @@ -1426,8 +1509,8 @@ fn explorer_inputs_and_graph_drop_share_labels_and_material_assignment() { harness.state_mut().run("edit.undo", json!({})).unwrap(); assert_eq!(harness.state().session.graph().unwrap().node(id).unwrap(), &before); } - harness.get(By::new().role(egui::accesskit::Role::TreeItem).label("Base Color")).click(); - settle(&mut harness, 3); + let position = harness.get(By::new().role(egui::accesskit::Role::TreeItem).label("Base Color")).rect().center(); + double_click(&mut harness, position); harness.get(By::new().role(egui::accesskit::Role::ComboBox).label("Component Usage")).click(); settle(&mut harness, 3); harness.get_by_label("Glossiness").scroll_to_me(); diff --git a/crates/ui-egui/tests/snapshot/embedded_graphs.rs b/crates/ui-egui/tests/snapshot/embedded_graphs.rs new file mode 100644 index 00000000..be0d1467 --- /dev/null +++ b/crates/ui-egui/tests/snapshot/embedded_graphs.rs @@ -0,0 +1,48 @@ +use super::{double_click, harness, save, settle}; +use egui_kittest::kittest::{By, Queryable}; +use materialcraft_engine::core::NodeId; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; +use serde_json::json; + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn fresh_embedded_graphs_open_only_after_explicit_editing() { + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&directory).unwrap(); + + for (definition, label) in [("fx_map", "FX-Map"), ("pixel_processor", "Pixel processor"), ("value_processor", "Value processor")] { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + let owner = NodeId(app.run("graph.node.add", json!({"def": definition})).unwrap()["id"].as_u64().unwrap()); + app.ui.frame_all = true; + let original = app.session.pkg.clone(); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 4); + let canvas = harness.get(By::new().role(egui::accesskit::Role::Canvas).label("Node graph")).rect(); + let position = harness + .query_all(By::new().role(egui::accesskit::Role::Button).label(label)) + .map(|node| node.rect().center()) + .find(|position| canvas.contains(*position)) + .expect("the newly created node must be on the canvas"); + + double_click(&mut harness, position); + + assert!(harness.state().function_editor.is_none(), "{definition}"); + assert!(harness.state().pattern_editor.is_none(), "{definition}"); + assert_eq!(harness.state().session.selection, vec![owner]); + save(&mut harness, &directory, &format!("{definition}-after-double-click")); + + harness.key_press_modifiers(egui::Modifiers::CTRL | egui::Modifiers::COMMAND, egui::Key::E); + settle(&mut harness, 3); + + if definition == "fx_map" { + assert_eq!(harness.state().pattern_editor.as_ref().unwrap().node, owner); + let canvas = harness.get(By::new().role(egui::accesskit::Role::Canvas).label("FX-Map graph")).rect(); + assert!(harness.query_all(By::new().role(egui::accesskit::Role::Button).label("Quadrant")).any(|node| canvas.contains(node.rect().center()))); + } else { + assert_eq!(harness.state().function_editor.as_ref().unwrap().node, Some(owner)); + assert!(harness.query(By::new().label_contains("No output node defined")).is_some()); + } + assert_eq!(harness.state().session.pkg, original); + save(&mut harness, &directory, &format!("{definition}-initial-embedded-graph")); + } +} diff --git a/crates/ui-egui/tests/snapshot/explorer.rs b/crates/ui-egui/tests/snapshot/explorer.rs new file mode 100644 index 00000000..1b323b79 --- /dev/null +++ b/crates/ui-egui/tests/snapshot/explorer.rs @@ -0,0 +1,147 @@ +use super::{By, MaterialCraftApp, NodeT, Queryable, UiState, harness, json, save, settle}; +use egui::accesskit::Role; + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn explorer_selection_does_not_open_documents_or_graphs() { + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.session.pkg.name = "Source".into(); + app.run("graph.rename", json!({"name": "Material"})).unwrap(); + let output = app.run("graph.node.add", json!({"def": "output", "params": {"identifier": "result"}})).unwrap()["id"].as_u64().unwrap(); + app.run("graph.node.add", json!({"def": "input_color", "params": {"identifier": "input"}})).unwrap(); + app.run("folder.create", json!({"name": "Tools"})).unwrap(); + app.run("file.new", json!({"folder": "Tools", "kind": "function", "name": "Helper"})).unwrap(); + let source = app.session.document_id; + app.run("file.newPackage", json!({"name": "Active"})).unwrap(); + let active = (app.session.document_id, app.session.graph); + let selection = app.session.selection.clone(); + let view = app.session.view2d.node; + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 5); + + for label in ["Source*", "Tools", "Material", "Helper", "Result", "Input"] { + let position = harness.get(By::new().role(Role::TreeItem).label(label)).rect().center(); + super::click_canvas(&mut harness, position); + + assert_eq!((harness.state().session.document_id, harness.state().session.graph), active, "single click on {label}"); + assert_eq!(harness.state().session.selection, selection, "single click on {label}"); + assert_eq!(harness.state().session.view2d.node, view, "single click on {label}"); + } + save(&mut harness, &directory, "explorer-select-without-opening"); + + let position = harness.get(By::new().role(Role::TreeItem).label("Helper")).rect().center(); + super::double_click(&mut harness, position); + assert_eq!(harness.state().session.document_id, source); + assert_eq!(harness.state().session.graph().unwrap().name, "Helper"); + + let position = harness.get(By::new().role(Role::TreeItem).label("Material")).rect().center(); + super::click_canvas(&mut harness, position); + assert_eq!(harness.state().session.graph().unwrap().name, "Helper"); + super::double_click(&mut harness, position); + assert_eq!(harness.state().session.graph().unwrap().name, "Material"); + + let position = harness.get(By::new().role(Role::TreeItem).label("Result")).rect().center(); + super::double_click(&mut harness, position); + assert_eq!(harness.state().session.selection, vec![materialcraft_engine::core::NodeId(output)]); + assert_eq!(harness.state().session.view2d.node, Some(materialcraft_engine::core::NodeId(output))); + save(&mut harness, &directory, "explorer-double-click-open"); +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn explorer_folder_tree_and_context_menus() { + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.session.pkg.name = "Explorer menus".into(); + app.run("folder.create", json!({"name": "Tools"})).unwrap(); + app.run("folder.create", json!({"parent": "Tools", "name": "Math"})).unwrap(); + app.run("file.new", json!({"folder": "Tools/Math", "kind": "function", "name": "Helper"})).unwrap(); + app.run("file.new", json!({"folder": "Tools", "template": "empty", "name": "Surface"})).unwrap(); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 6); + fn tree(label: &str) -> By<'_> { + By::new().role(Role::TreeItem).label(label) + } + fn button(label: &str) -> By<'_> { + By::new().role(Role::Button).label(label) + } + let tools = harness.get(tree("Tools")).rect(); + let math = harness.get(tree("Math")).rect(); + let helper = harness.get(tree("Helper")).rect(); + assert!(tools.left() < math.left() && math.left() < helper.left()); + save(&mut harness, &directory, "explorer-folders"); + + for (label, expected, screenshot) in [ + ("Tools", vec!["New", "Copy", "Paste", "Rename", "Remove"], "explorer-folder-menu"), + ("Explorer menus*", vec!["New", "Reload", "Save", "Save As", "Save A Copy As", "Copy", "Paste", "Close"], "explorer-package-menu"), + ("Helper", vec!["Open", "Copy", "Paste", "Remove", "Rename"], "explorer-function-menu"), + ("Surface", vec!["Open", "Copy", "Paste", "Remove", "Rename"], "explorer-graph-menu"), + ] { + harness.get(tree(label)).click_secondary(); + settle(&mut harness, 3); + for label in expected { + assert!(harness.query(By::new().label(label)).is_some(), "{screenshot}: {label}"); + } + for label in ["Duplicate", "Delete", "Import", "Link"] { + assert!(harness.query(button(label)).is_none(), "{screenshot}: unexpected {label}"); + } + assert!(harness.get(button("Paste")).accesskit_node().is_disabled()); + save(&mut harness, &directory, screenshot); + harness.key_press(egui::Key::Escape); + settle(&mut harness, 2); + } + + harness.get(tree("Helper")).click_secondary(); + settle(&mut harness, 2); + harness.get(button("Copy")).click(); + settle(&mut harness, 2); + harness.get(tree("Tools")).click_secondary(); + settle(&mut harness, 2); + harness.get(button("Paste")).click(); + settle(&mut harness, 3); + assert!(harness.state().session.pkg.graph_by_name("Tools/Helper").is_some()); + + harness.get(tree("Math")).click_secondary(); + settle(&mut harness, 2); + harness.get(By::new().label("New")).click(); + settle(&mut harness, 3); + for label in ["Graph", "Function Graph", "Folder"] { + assert!(harness.query(button(label)).is_some()); + } + save(&mut harness, &directory, "explorer-new-submenu"); + harness.get(button("Function Graph")).click(); + settle(&mut harness, 3); + assert!(!harness.state().ui.windows.new_graph); + assert!(harness.state().ui.explorer.rename.is_none()); + assert_eq!(harness.state().session.graph().unwrap().folder, "Tools/Math"); + assert_eq!(harness.state().session.graph().unwrap().name, "Untitled_Function_Graph_1"); + assert!(harness.state().session.graph().unwrap().function.is_some()); + + for (label, expected) in [ + ("Function Graph", "Untitled_Function_Graph_2"), + ("Graph", "Untitled_Graph_1"), + ("Graph", "Untitled_Graph_2"), + ("Folder", "Untitled_Folder_1"), + ("Folder", "Untitled_Folder_2"), + ] { + harness.get(tree("Math")).click_secondary(); + settle(&mut harness, 2); + harness.get(By::new().label("New")).click(); + settle(&mut harness, 2); + harness.get(button(label)).click(); + settle(&mut harness, 3); + + assert!(!harness.state().ui.windows.new_graph); + assert!(harness.state().ui.explorer.rename.is_none()); + let path = format!("Tools/Math/{expected}"); + if label == "Folder" { + assert!(harness.state().session.pkg.folder_paths().contains(&path)); + } else { + assert!(harness.state().session.pkg.graph_by_name(&path).is_some()); + } + } + save(&mut harness, &directory, "explorer-create-without-prompts"); +} diff --git a/crates/ui-egui/tests/snapshot/function_library.rs b/crates/ui-egui/tests/snapshot/function_library.rs new file mode 100644 index 00000000..b661ed5d --- /dev/null +++ b/crates/ui-egui/tests/snapshot/function_library.rs @@ -0,0 +1,146 @@ +use super::{By, Harness, MaterialCraftApp, Queryable, UiState, harness, json, save, settle, vec2}; +use materialcraft_engine::{FunctionGraphTarget, core::NodeId}; + +fn drag(harness: &mut Harness<'static, MaterialCraftApp>, label: &str, offset: egui::Vec2) { + let start = harness.get(By::new().role(egui::accesskit::Role::ListItem).label(label)).rect().center(); + let end = harness.state().graph.view.center() + offset; + harness.event(egui::Event::PointerMoved(start)); + harness.step(); + harness.event(egui::Event::PointerButton { pos: start, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + harness.step(); + for position in [start + vec2(12.0, 0.0), end] { + harness.event(egui::Event::PointerMoved(position)); + harness.step(); + } + harness.event(egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + settle(harness, 5); +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn bottom_library_drags_functions_into_function_and_processor_canvases() { + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + for kind in ["function", "pixel_processor", "value_processor"] { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.run("file.new", json!({"kind": if kind == "function" { "function" } else { "material" }, "name": "Library instance"})).unwrap(); + let owner = if kind == "function" { None } else { Some(NodeId(app.run("graph.node.add", json!({"def": kind})).unwrap()["id"].as_u64().unwrap())) }; + app.ui.library_search = "Pi".into(); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 5); + if owner.is_some() { + harness.key_press_modifiers(egui::Modifiers::CTRL | egui::Modifiers::COMMAND, egui::Key::E); + settle(&mut harness, 4); + } + let target = owner.map_or(FunctionGraphTarget::Graph, |node| FunctionGraphTarget::Parameter { node, parameter: "function".into() }); + let previous = target.current(&harness.state().session).unwrap().nodes.len(); + + drag(&mut harness, "Pi", vec2(-140.0, 0.0)); + + let function = target.current(&harness.state().session).unwrap(); + assert_eq!(function.nodes.len(), previous + 1, "{kind}"); + let node = function.nodes.iter().find(|node| node.instance.is_some()).unwrap(); + assert_eq!(node.instance.as_ref().unwrap().package, "sbs://functions.sbs"); + assert_eq!(node.instance.as_ref().unwrap().graph, "Functions/Math/Pi"); + assert!(matches!(node.source, Some(Ok(_)))); + save(&mut harness, &directory, &format!("library-drag-{kind}")); + + harness.state_mut().ui.library_search = "Division".into(); + settle(&mut harness, 3); + drag(&mut harness, "Division", vec2(20.0, 120.0)); + + let function = target.current(&harness.state().session).unwrap(); + let division = function.nodes.iter().find(|node| node.op == "div").unwrap(); + assert!(division.instance.is_none(), "native operations must not become SBS instances"); + assert_eq!(division.inputs.len(), 2); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Division")); + save(&mut harness, &directory, &format!("library-native-{kind}")); + + harness.state_mut().ui.library_search = "GlobalRandom".into(); + settle(&mut harness, 3); + drag(&mut harness, "GlobalRandom", vec2(160.0, 0.0)); + + let random = target + .current(&harness.state().session) + .unwrap() + .nodes + .iter() + .find(|node| node.instance.as_ref().is_some_and(|instance| instance.graph.ends_with("GlobalRandom"))) + .unwrap(); + assert!(matches!(random.source, Some(Ok(_)))); + save(&mut harness, &directory, &format!("library-random-{kind}")); + + let mut missing = harness.state().session.pkg.dependencies["sbs://functions.sbs"].graph_by_name("Functions/Random/GlobalRandom").unwrap().1.clone(); + missing.name = "MissingFunction".into(); + missing.folder = "Functions/Test".into(); + missing.function = Some(Default::default()); + let mut package = materialcraft_engine::core::Package::new("Missing library"); + package.graphs.push(missing); + harness.state_mut().session.pkg.dependencies.insert("sbs://missing-functions.sbs".into(), std::sync::Arc::new(package)); + + harness.state_mut().ui.library_search = "MissingFunction".into(); + settle(&mut harness, 3); + drag(&mut harness, "MissingFunction", vec2(160.0, 180.0)); + + let missing = target + .current(&harness.state().session) + .unwrap() + .nodes + .iter() + .find(|node| node.instance.as_ref().is_some_and(|instance| instance.graph.ends_with("MissingFunction"))) + .unwrap(); + assert!(matches!(missing.source, Some(Err(_)))); + let bounds = harness.get(By::new().role(egui::accesskit::Role::Button).label("MissingFunction")).rect(); + let image = harness.render().unwrap(); + let magenta = (2..12).any(|y| { + (2..60).any(|x| { + let pixel = image.get_pixel((bounds.min.x + x as f32) as u32, (bounds.min.y + y as f32) as u32).0; + pixel[0] > 150 && pixel[1] < 80 && pixel[2] > 80 + }) + }); + assert!(magenta, "missing header must be magenta"); + save(&mut harness, &directory, &format!("library-missing-{kind}")); + } +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn bundled_even_count_opens_as_an_editable_arithmetic_tree() { + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.run("file.open", json!({"path": "sbs://functions.sbs"})).unwrap(); + app.run("graph.open", json!({"graph": "Functions/Math/Parity/EvenCount"})).unwrap(); + app.ui.library_search = "EvenCount".into(); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 5); + + for label in ["Get Float", "Floor", "Float", "Division", "Ceil"] { + harness.get(By::new().role(egui::accesskit::Role::Button).label(label)); + } + let function = harness.state().session.graph().unwrap().function.as_ref().unwrap(); + assert_eq!(function.nodes.len(), 5); + assert_eq!(function.nodes.iter().flat_map(|node| node.inputs.iter().flatten()).count(), 4); + assert_eq!(function.node(function.output.unwrap()).unwrap().op, "ceil"); + save(&mut harness, &directory, "even-count-arithmetic-tree"); +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn converted_wave_opens_with_its_complete_function_body() { + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.run("file.open", json!({"path": "sbs://functions.sbs"})).unwrap(); + app.run("graph.open", json!({"graph": "Functions/Cycles/Wave"})).unwrap(); + app.ui.library_search = "Wave".into(); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 5); + + let function = harness.state().session.graph().unwrap().function.as_ref().unwrap(); + assert_eq!(function.nodes.len(), 9); + assert!(function.output.is_some()); + assert!(function.nodes.iter().all(|node| node.missing.is_none())); + materialcraft_engine::nodes::function::compile(function, 0).unwrap(); + save(&mut harness, &directory, "wave-converted-function-tree"); +} diff --git a/crates/ui-egui/tests/snapshot/function_variables.rs b/crates/ui-egui/tests/snapshot/function_variables.rs new file mode 100644 index 00000000..d2875a45 --- /dev/null +++ b/crates/ui-egui/tests/snapshot/function_variables.rs @@ -0,0 +1,55 @@ +use super::{By, MaterialCraftApp, Queryable, UiState, harness, json, save, settle}; +use materialcraft_engine::core::{FunctionGraph, Value}; + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn get_properties_offer_typed_choices_and_accept_custom_names() { + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.run("file.new", json!({"kind": "function", "name": "Variable choices"})).unwrap(); + let mut function = FunctionGraph::default(); + let float = function.add("get_float1", &[], Some(Value::Text("ITypedThis".into()))); + let integer = function.add("get_integer1", &[], Some(Value::Text("".into()))); + function.nodes[1].pos = [240.0, 0.0]; + function.output = Some(float); + app.run("graph.function.set", json!({"function": function})).unwrap(); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 5); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Get Float")).click(); + settle(&mut harness, 2); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Choose variable")).click(); + settle(&mut harness, 2); + + harness.get_by_label("$time"); + harness.get_by_label("ITypedThis"); + let field = harness.get(By::new().role(egui::accesskit::Role::TextInput).label("Variable name")).rect(); + let choice = harness.get_by_label("$time").rect(); + assert!((choice.left() - field.left()).abs() < 16.0, "the dropdown must align with the editable field"); + assert!(choice.width() >= field.width() - 16.0, "the dropdown must span the editable field"); + assert!(harness.query_all(By::new().label("$depth")).next().is_none()); + assert!(harness.query_all(By::new().label("$tiling")).next().is_none()); + save(&mut harness, &directory, "get-float-variable-dropdown"); + harness.get_by_label("$time").click(); + settle(&mut harness, 2); + assert_eq!(harness.state().session.graph().unwrap().function.as_ref().unwrap().node(float).unwrap().value, Some(Value::Text("$time".into()))); + + harness.get(By::new().role(egui::accesskit::Role::Button).label("Get Integer")).click(); + settle(&mut harness, 2); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Choose variable")).click(); + settle(&mut harness, 2); + let choices = ["$normalformat", "$tiling", "$pixelratio"].map(|name| harness.get_by_label(name).rect()); + assert!(choices[0].top() < choices[1].top() && choices[1].top() < choices[2].top()); + save(&mut harness, &directory, "get-integer-variable-dropdown"); + harness.get_by_label("$tiling").click(); + settle(&mut harness, 2); + assert_eq!(harness.state().session.graph().unwrap().function.as_ref().unwrap().node(integer).unwrap().value, Some(Value::Text("$tiling".into()))); + + let field = harness.get(By::new().role(egui::accesskit::Role::TextInput).label("Variable name")); + field.click(); + harness.key_press_modifiers(egui::Modifiers::CTRL | egui::Modifiers::COMMAND, egui::Key::A); + harness.event(egui::Event::Text("MyInteger".into())); + settle(&mut harness, 2); + assert_eq!(harness.state().session.graph().unwrap().function.as_ref().unwrap().node(integer).unwrap().value, Some(Value::Text("MyInteger".into()))); + save(&mut harness, &directory, "get-integer-typed-variable"); +} diff --git a/docs/architecture.md b/docs/architecture.md index d06e173d..dd50efd9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -80,6 +80,59 @@ per pixel. Calls share the execution-step budget and are capped at eight levels SBS Function nodes store the source URI in their instance data; a `materialcraftInterface` cache preserves unconnected input pins when a source file is unavailable. +Package folders are part of each graph's SBS identity. Exact paths take priority over leaf names; +a leaf name is accepted only when it is unambiguous. Unconnected function-instance inputs use +the source's declared defaults. Unknown function operations retain their connector names, data +and output designation so an unavailable implementation does not erase the containing graph. +Missing external resources retain their paths for repair on a later load. + +Empty folders also persist as native SBS groups. Explorer renders these groups as a collapsible +tree, including resources in their original folders. Folder creation, rename, removal, copying +and moving use engine commands with snapshot undo. Renames and moves update local instance paths; +copies retarget references between copied graphs. The Explorer clipboard survives document changes. +Single clicks select Explorer rows; double clicks open their graph or input/output preview. +The Explorer New submenu creates items immediately with numbered default names, advancing past +name conflicts in the destination folder. Rename remains an explicit context-menu action. + +`sbs://` resolves beneath `assets/sbs/`. Native installations can place that directory beside the +executable or set `MATERIALCRAFT_SBS_DIR`; packaged and browser builds also embed the standard +library. Alias paths cannot escape that root, and saved packages retain the alias. The Function +Library lists these source graphs and inserts references into Function and processor canvases. +Library aliases are read-only save destinations; an edited library can be saved to a local path. +Resource paths resolve beside their owning package: `resources/tile.png` in +`sbs://functions.sbs` reads `assets/sbs/resources/tile.png`, also addressable as +`sbs://resources/tile.png`. Nested packages use their own adjacent `resources/` directory. +Loaded resource bytes are embedded on save; unavailable files keep their reference and missing state. + +Importing a user-supplied function package preserves its graph bodies, connections and positions; +it does not replace them with the bundled library. Redundant legacy instance connectors are retained +on save and evaluated only through the declared inputs. Conflicting obsolete connections remain +visible errors. A shared typed system-variable catalog drives Get-node suggestions and execution. +Ordinary functions expose size, log2 size, pixel ratio, tiling, physical size, UV tile, time and +normal-format variables. Pixel Processor adds `$pos`; FX-Map adds `$pos`, `$depth`, `$depthpow2` +and `$number`. Reusable function instances inherit their caller's scope. Out-of-scope variables +remain undefined even if a user input has the same name, and Set cannot overwrite system variables. +Get properties offer a type-filtered dropdown and accept typed custom names. + +Node tiling and pixel ratio resolve from absolute values, the first connected image input or the +parent graph. SBS preserves these inheritance modes and the graph's `physicalSize` attribute. +The host supplies time, UV tile and a raw normal-format integer through `EvaluationEnvironment`; +the static authoring defaults are zero. These values propagate through nested graph instances +without becoming constants in saved functions. Relevant variable changes invalidate cached cooks. +The normal-format integer is passed through without assigning a convention label to an unverified code. + +The local `assets/sbs/functions.sbs` is converted from a user-supplied package with +`cargo run -p materialcraft-formats --release --example standard_function_library -- assets/sbs/functions.sbs`. +The converter preserves all 171 function bodies (2,334 nodes), folder paths, identifiers, inputs, +defaults and internal references. It writes new interface-based descriptions, generates node +positions and omits source annotations and icons. It rejects import warnings and functions that +cannot compile instead of substituting empty graphs. The source graph bodies are retained; +rewritten metadata does not establish redistribution rights. +Local tests compare every converted body and evaluate all 171 functions against the supplied +package with valid inputs and caller context. External runtime import and numerical compatibility +still require validation. SBS's `updaterVersion` derives from the workspace's Cargo version; +its format schema version is a separate constant. + Every user-visible action is a `CommandSpec` (`engine/src/*_cmds.rs`): id, label, menu, shortcut, params doc, `enabled`, `run`. The UI calls them through `MaterialCraftApp::run`; the CLI, the JSON control channel and MCP dispatch the same ids. `Session::edit` snapshots the package before running @@ -117,6 +170,10 @@ Shared modules own node cards, selection and annotation gestures. The regular ca document while drawing, then dispatches edits. Graph Properties follows the same pattern; its `property/` modules separate panel routing, node and graph settings, parameter controls, curves and gradients. Function and pattern Properties dispatch value edits without cloning graphs in the UI. +Explorer inspection uses a document-and-graph target independent of the canvas. Shared graph +attribute controls retain text drafts until focus changes, then dispatch targeted engine commands. +Inactive packages record those edits in their own snapshot history. Both graph kinds share the SBS +attribute codec; display labels are resolved separately from reference identifiers. The properties panel builds every parameter editor from the node catalog; the Levels node adds a histogram editor with range handles on top of its sliders ([levels-editor.md](levels-editor.md)). diff --git a/docs/atomic-workflow.md b/docs/atomic-workflow.md index 77fa4e3d..9ef2c15c 100644 --- a/docs/atomic-workflow.md +++ b/docs/atomic-workflow.md @@ -121,6 +121,9 @@ function graphs remains outside this change. The reference application's ability saved files still needs external verification. Function Graphs share the main canvas card geometry and styling, including compact Dot nodes. -The Graph, Function Graph and FX-Map Add node menus remain flat, with dividers between groups -and room to use the window height. Type a letter to enable names starting with it while keeping the full list visible; -Backspace clears the filter. +The Graph, Function Graph and FX-Map Add node menus remain flat and preserve their native catalog +order, also used by the Library. The regular graph menu separates primitives, inputs and output; +Dot is excluded from every Add node list and is added through its separate action. The function +and Pixel Processor menus list 84 operations; Value Processor omits the two samplers. FX-Map lists +Quadrant, Switch, Iterate in that order. Type a letter to enable names starting +with it while keeping the full list visible; Backspace clears the filter. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1cc4ae0e..218c49b8 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -72,12 +72,20 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg | Command | Params | |---|---| +| `graph.function.variables` | `{id, target?: FunctionGraphTarget}` returns ordered suggestions matching a Get node's type and caller scope; typed custom names remain supported | +| `session.environment` | `{timeSeconds?, uvTile?: [int, int], normalFormat?: int}` updates host evaluation values without modifying the package; `{}` reads them; defaults are zero and the normal-format code is passed through | +| `graph.context` | `{physicalSize?: [x, y, z], pixelRatio?: 0\|1, tiling?: [horizontal, vertical]}` edits material-graph metadata with undo; `{}` reads it; reusable functions receive their caller's context | | `file.new` | `{template?, name?, size?}`; templates from `graph.templates` (`empty`, `pbr`, `bricks`, `stone_tiles`, `wood`, `rusty_metal`, `fabric`, `ground`) | | `graph.node.edit` | `{}` resolves the selected FX-Map, processor or graph instance to `{kind, node, parameter?, graph?, document?, path?}`; use `ui.menu.invoke` to open its reference in the graph panel | | `graph.node.info` | `{id}` returns `{text}` describing a main-graph node without changing the document or node clipboard | | `graph.instance.add` | `{document, graph, function?: FunctionGraphTarget, at?, snapToGrid?}` adds a linked graph instance from an open package; requires a source output and rejects dependency cycles | | `package.activate` | `{document}` activates an open package while retaining each package's selection, views and undo history | | `package.close` / `package.closeAll` | `{document?, discard?}` / `{discard?}` closes one/all packages; modified packages require explicit discard | +| `folder.create` / `folder.rename` / `folder.remove` | `{parent?, name?}` / `{folder, name}` / `{folder}` edits SBS folders, including empty folders; removal includes descendants and supports undo | +| `explorer.copy` / `explorer.paste` | `{graph? index, folder?}` / `{folder?}` copies a graph, folder subtree, or package contents and pastes into a folder or the package root; internal references follow the copies | +| `explorer.move` | `{graph? index, folder?, parent?}` moves a graph or folder within the active package and updates local graph references | +| `file.reload` | `{discard?}` reloads the active document in place; unsaved changes require explicit discard | +| `file.saveCopyAs` | `{path}` writes a copy without changing the active document's path, modified flag, or history | | `graph.pattern.set` | `{id, pattern}` replaces an FX-Map subgraph with cycle validation and undo | | `graph.node.add` | `{def, at?, params?, connectFrom?: {node, port?}, label?}` | | `graph.connect` / `graph.disconnect` | `{from, fromPort?, to, toPort?}` / `{to, toPort}` | @@ -99,6 +107,17 @@ Opening an SBS file or creating a package retains the other open packages. `sess includes `documents` with each package's document id, path, active state, modified state and graphs. Explorer graph drags use that document id and graph name with `graph.instance.add`. +A single click on an Explorer graph inspects its properties without changing the open canvas. +Regular graphs currently show Identifier and Label in Attributes; function graphs show the full +attribute form. +`graph.properties`, `graph.attributes`, and `graph.rename` accept optional `document` and `graph` +targets, including graphs in inactive packages. Attribute edits use `label`, `description`, +`category`, `author`, `authorUrl`, `tags`, `group`, and `userData`; the identifier uses +`graph.rename` with `name`. Labels are display text, while identifiers remain the SBS reference +names. Graph metadata is saved in native SBS attributes for both material and function graphs. +Edits belong to the target package's undo history. Size, format, and seed commands accept the same +optional targets. + Main graphs with outputs can be instanced in other main graphs. Cross-file sources must be saved first; the target stores a file reference and connector metadata, not a copy of the source nodes. Unsaved source edits update open instances and mark dependent packages modified, including @@ -119,7 +138,7 @@ and retains the parent Function/processor canvas for return navigation. Double-c has no additional action, and Ctrl+E does not open its source. Ctrl+E still opens the embedded canvas of a Pixel Processor, Value Processor or FX-Map node. -Source-file watching and global Library SBS assets are not implemented yet. +Source-file watching is not implemented yet. The global Function Library reads `sbs://functions.sbs`. References currently identify graphs by name; renaming an external source graph requires recreating its instances. Save As creates a separate file and does not redirect references to the original. @@ -268,6 +287,8 @@ each has its own reader and writer (`crates/formats/src/material.rs` here), so k | `graph.input.bind` / `graph.input.unbind` | `{identifier, resource? \| path?, linear?}` / `{identifier}`: a preview image for an input node (a mesh map exported from TextureCraft), saved in the package | | `file.open` | opens native `.sbs` packages, and a `.mcmat`'s source package, on its graph, with no file name. Returns `warnings`: what an SBS file holds that MaterialCraft can't read yet (missing nodes are kept as placeholders); also in `session.inspect` as `package.warnings` | | `file.save` | `{path?}`: native SBS; `.sbs` is appended when the path does not end in `.sbs` | +| `library.functions` | `{filter?}`: list reusable SBS functions with package URI, full graph path, typed ports and missing status | +| `library.function.add` | `{graph, package? (default: sbs://functions.sbs), function?: FunctionGraphTarget, at?, snapToGrid?}`: insert a reference into the active Function or processor canvas | ## MCP tools diff --git a/docs/gaps.md b/docs/gaps.md index 7c322033..61dfd610 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -8,6 +8,16 @@ Current integration also provides workspace-scoped `material_export`, real Heigh from the assigned material, explicit normal-map convention, and linear bitmap/input previews. The native SBS and primitive-library limitations in [atomic-workflow.md](atomic-workflow.md) remain. +Reusable SBS functions now appear in the Library for Function and processor canvases. The bundled +library now retains all 171 supplied function bodies, with no empty implementation placeholders. +Full numerical equivalence and importing the converted library in the reference application remain +unverified. Redistribution rights for the retained source bodies are not established. +See [architecture.md](architecture.md) for alias resolution and conversion details. + +Explorer now displays native SBS folders, including empty groups and nested resources. Its initial +package, folder and graph context menus support creation, copy/paste, rename, removal, and package +save/reload/close actions. Publishing and additional resource creation menus remain outside this scope. + > **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (portable `.mcmat` materials closed the published-archive gap) · **Target:** the professional node-based material workflow Every known shortfall, most important first. Pick from the top. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 240cf7a8..f8f0a6c9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -8,6 +8,15 @@ Current integration also provides workspace-scoped `material_export`, real Heigh from the assigned material, explicit normal-map convention, and linear bitmap/input previews. The native SBS and primitive-library limitations in [atomic-workflow.md](atomic-workflow.md) remain. +Reusable function instances now preserve SBS package paths and appear in the Library. The converted +standard library contains all 171 supplied function bodies (2,334 nodes), with no empty placeholders. +Local structural and evaluation comparisons do not establish external runtime interoperability, +full numerical equivalence or redistribution rights for the retained source bodies. + +Explorer now preserves native SBS folder hierarchies and provides package, folder and graph context +menus for creation, copying, pasting, renaming, removal and package file actions. Moving items within +a package and removing folder subtrees support undo; empty folders survive saves. + > **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (Files 60% → 70%: portable materials for TextureCraft) · **Target:** the professional node-based material workflow (desktop app; the web app is assessed later) **Overall: ≈ 67%** of a material artist's daily workflow works end to end (engine + UI +