diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index acc9729..84321f3 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -60,6 +60,7 @@ pub fn command_specs() -> &'static [CommandSpec] { 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_library_commands::specs()); v.extend(crate::node_info_commands::specs()); v.extend(crate::atomic_sample_commands::specs()); v.extend(crate::material_cmds::specs()); diff --git a/crates/engine/src/function_library.rs b/crates/engine/src/function_library.rs index ad55a8b..072707f 100644 --- a/crates/engine/src/function_library.rs +++ b/crates/engine/src/function_library.rs @@ -1,21 +1,2 @@ -use materialcraft_core::Package; -use std::{collections::BTreeMap, sync::Arc}; - +/// The bundled function library every session loads (see `node_library`) 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/graph_cmds.rs b/crates/engine/src/graph_cmds.rs index 9f0954e..3c4356e 100644 --- a/crates/engine/src/graph_cmds.rs +++ b/crates/engine/src/graph_cmds.rs @@ -22,7 +22,15 @@ pub(crate) fn specs() -> Vec { }) }), 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.cook", + "Compute graph", + [], + None, + "{full?: bool, graph?: index (another graph of the package cooks at full size into the cache)} cooks now; returns per-node timings and errors", + has_graph, + cook + ), 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!( @@ -153,8 +161,19 @@ fn format(s: &mut Session, p: &J) -> Result { } fn cook(s: &mut Session, p: &J) -> Result { - let cooked = if boolp(p, "full") == Some(true) { s.cook_full(s.graph) } else { s.cook().clone() }; - let g = s.graph()?; + let index = match p.get("graph").filter(|graph| !graph.is_null()) { + None => s.graph, + Some(graph) => { + let index = graph.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad("graph.cook", "`graph` is a graph index"))?; + let graph = s.pkg.graph(index)?; + if graph.function.is_some() { + return Err(bad("graph.cook", "a Function Graph has no outputs to compute")); + } + index + } + }; + let cooked = if index != s.graph || boolp(p, "full") == Some(true) { s.cook_full(index) } else { s.cook().clone() }; + let g = s.pkg.graph(index)?; Ok(json!({ "ms": cooked.ms, "nodes": cooked.nodes.iter().map(|(id, r)| { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index bacdf62..0862a4c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -11,6 +11,9 @@ mod folder_property_commands; pub use explorer_clipboard::ExplorerClipboard; mod function_library; mod function_library_commands; +pub mod node_library; +mod node_library_commands; +pub use node_library::{LibraryCanvas, LibraryEntry, LibraryItem, NodeLibrary}; mod function_variable; mod function_variable_commands; mod function_variables; diff --git a/crates/engine/src/node_library.rs b/crates/engine/src/node_library.rs new file mode 100644 index 0000000..80c4dfb --- /dev/null +++ b/crates/engine/src/node_library.rs @@ -0,0 +1,432 @@ +//! The node library. Every SBS package in the library folder (`assets/sbs`, or the bundled copies) +//! is loaded once per process. A package whose titled frames are library categories ("Filters - +//! Blurs") lays the library out: each node inside a frame becomes an entry in that category. +//! Every other package lends its graphs, which graph instances can use. Native nodes, function +//! operations, FX-Map nodes and graph items fill in what no layout places. + +use materialcraft_core::{Package, PatternNodeKind}; +use materialcraft_formats::sbs::{LayoutItem, library}; +use serde::Serialize; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::{Arc, Mutex}; + +/// The library tree in display order: top-level categories and their sub-categories. The UI adds +/// Favorites above it +pub const CATEGORIES: &[(&str, &[&str])] = &[ + ("Graph items", &[]), + ("Atomic nodes", &[]), + ("FxMap nodes", &[]), + ("Function nodes", &["Constant", "Vector", "Variables", "Samplers", "Cast", "Operator", "Logical", "Comparison", "Function", "Control"]), + ("Texture generators", &["Noises", "Patterns"]), + ("Filters", &["Adjustments", "Blending", "Blurs", "Channels", "Effects", "Normal map", "Tiling", "Transforms"]), + ("Material filters", &["1-click", "Effects", "Transforms", "Blending", "PBR utilities", "Scan processing"]), + ("Mesh-based generators", &["Mask generators", "Weathering", "Utilities"]), + ("Spline & Path tools", &["Spline tools", "Path tools"]), + ("MCF functions", &["Primitives", "Operators", "Transforms"]), + ("Functions", &["Color", "Comparison", "Constant", "Conversion", "Maths", "Parity", "Random", "Transformation", "Various", "Easings"]), + ("3D view", &["HDRI environments", "HDRI tools"]), + ("PBR materials", &["Bricks", "Concrete", "Fabric", "Ground", "Metal", "Paper", "Pavement", "Tiles", "Wood", "Stone"]), + ("Values", &["Constant"]), +]; + +/// Older layouts name categories MaterialCraft has renamed: (old, current) +const RENAMED: &[(&str, &str)] = &[("SDF functions", "MCF functions")]; + +/// Words that place a material in a sub-category when its layout frame names only the top level +const SUB_KEYWORDS: &[(&str, &str, &[&str])] = &[ + ("PBR materials", "Bricks", &["brick"]), + ("PBR materials", "Concrete", &["concrete", "cement"]), + ("PBR materials", "Fabric", &["fabric", "cloth", "textile", "leather"]), + ("PBR materials", "Ground", &["ground", "gravel", "soil", "sand", "dirt", "grass", "mud"]), + ("PBR materials", "Metal", &["metal", "steel", "iron", "copper", "rust"]), + ("PBR materials", "Paper", &["paper", "cardboard"]), + ("PBR materials", "Pavement", &["pavement", "paving", "cobble", "asphalt"]), + ("PBR materials", "Tiles", &["tile"]), + ("PBR materials", "Wood", &["wood", "plank", "bark"]), + ("PBR materials", "Stone", &["stone", "rock", "marble", "granite"]), +]; + +/// The graph kind that can take an entry +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum LibraryCanvas { + Material, + Function, + Pattern, +} + +/// What adding an entry puts in the graph +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(tag = "type", rename_all = "camelCase")] +pub enum LibraryItem { + /// A native node, by catalog id + Node { + def: String, + }, + Comment, + Frame, + Pin, + /// An instance of a graph from a library package + Instance { + package: String, + graph: String, + }, + /// A native function operation + Operation { + operation: String, + }, + /// An instance of a function graph from a library package + FunctionInstance { + package: String, + graph: String, + }, + /// An FX-Map node + Pattern { + kind: PatternNodeKind, + }, + /// An environment image + Bitmap { + resource: String, + }, +} + +impl LibraryItem { + pub fn canvas(&self) -> LibraryCanvas { + match self { + Self::Operation { .. } | Self::FunctionInstance { .. } => LibraryCanvas::Function, + Self::Pattern { .. } => LibraryCanvas::Pattern, + _ => LibraryCanvas::Material, + } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct LibraryEntry { + /// Stable id, e.g. `node:blur`, `function:add`, `sbs://functions.sbs#Functions/Math/Pi` + pub id: String, + pub label: String, + /// `Top` or `Top/Sub`, from [`CATEGORIES`] + pub category: String, + pub description: String, + #[serde(flatten)] + pub item: LibraryItem, + pub canvas: LibraryCanvas, + /// Why the entry can't be added yet (the package it needs is not in MaterialCraft) + #[serde(skip_serializing_if = "Option::is_none")] + pub missing: Option, + /// It can be added, but is incomplete (it uses operations MaterialCraft lacks) + #[serde(skip_serializing_if = "Option::is_none")] + pub warning: Option, +} + +/// A layout placement, before it is resolved against the loaded packages +#[derive(Clone, Debug)] +struct Placement { + category: String, + item: LayoutItem, +} + +/// Everything loaded from the library folder +#[derive(Debug, Default)] +pub struct NodeLibrary { + /// Library packages (layouts excluded) and their own dependencies, by `sbs://` path + pub packages: BTreeMap>, + /// The `sbs://` files that laid the library out + pub layouts: Vec, + pub warnings: Vec, + placements: Vec, +} + +static SHARED: Mutex>> = Mutex::new(None); + +impl NodeLibrary { + /// The process's library, loaded on first use + pub fn shared() -> Arc { + let mut shared = SHARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + shared.get_or_insert_with(|| Arc::new(Self::load(&library::files()))).clone() + } + + /// Read the library folder again (after packages were added or changed on disk) + pub fn reload() -> Arc { + let library = Arc::new(Self::load(&library::files())); + *SHARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(library.clone()); + library + } + + /// Load `files` (`sbs://` paths) + pub fn load(files: &[String]) -> NodeLibrary { + let mut out = NodeLibrary::default(); + for uri in files { + let bytes = match library::read(uri) { + Ok(bytes) => bytes, + Err(error) => { + out.warnings.push(format!("Library package {uri}: {error}")); + continue; + } + }; + // A layout's frames name library categories; anything else is a package of graphs + let placements = match materialcraft_formats::sbs::read_layout(&bytes, uri) { + Ok(frames) => placements(&frames), + Err(error) => { + out.warnings.push(format!("Library package {uri}: {error}")); + continue; + } + }; + if !placements.is_empty() { + out.placements.extend(placements); + out.layouts.push(uri.clone()); + continue; + } + match materialcraft_formats::sbs::read_sbs(&bytes, uri, &crate::file_cmds::linked_files(uri)) { + Ok(mut read) => { + crate::linked_files::normalize_references(&mut read.pkg, uri); + read.warnings.extend(crate::linked_files::load(&mut read.pkg)); + out.warnings.extend(read.warnings); + for (path, package) in std::mem::take(&mut read.pkg.dependencies) { + out.packages.entry(path).or_insert(package); + } + out.packages.insert(uri.clone(), Arc::new(read.pkg)); + } + Err(error) => out.warnings.push(format!("Library package {uri}: {error}")), + } + } + out + } + + /// Every entry, resolved against `dependencies` (a session's loaded packages): layout + /// placements first, then graph items and native nodes no layout placed, then graphs of + /// `sbs://` packages no layout placed + pub fn entries(&self, dependencies: &BTreeMap>) -> Vec { + let mut out = Vec::new(); + let mut ids = BTreeSet::new(); + let mut placed_graphs = BTreeSet::new(); + let mut push = |out: &mut Vec, mut entry: LibraryEntry| { + // The same node may sit in two categories; the id keeps each placement apart + if !ids.insert(entry.id.clone()) { + entry.id = format!("{}@{}", entry.id, entry.category); + if !ids.insert(entry.id.clone()) { + return; + } + } + out.push(entry); + }; + + for (item, category) in [(LibraryItem::Comment, "Comment"), (LibraryItem::Frame, "Frame"), (LibraryItem::Pin, "Pin")] { + let id = format!("item:{}", category.to_ascii_lowercase()); + push(&mut out, entry(id, category, "Graph items", "", item, None)); + } + push(&mut out, entry("node:dot".into(), "Dot node", "Graph items", "A reroute point for wires.", LibraryItem::Node { def: "dot".into() }, None)); + + for placement in &self.placements { + if let LayoutItem::Instance { package, graph, .. } | LayoutItem::FunctionInstance { package, graph } = &placement.item { + placed_graphs.insert((package.clone(), graph.clone())); + } + if let Some(entry) = resolve(placement, dependencies) { + push(&mut out, entry); + } + } + + let listed: BTreeSet = out.iter().map(|entry| entry.id.clone()).collect(); + for definition in materialcraft_nodes::catalog() { + let id = format!("node:{}", definition.id); + if definition.id == "graph_instance" || listed.contains(&id) { + continue; + } + let item = LibraryItem::Node { def: definition.id.into() }; + push(&mut out, entry(id, definition.label, definition.category, definition.description, item, None)); + } + for operation in materialcraft_nodes::function::FUNCTIONS { + let id = format!("function:{}", operation.id); + if listed.contains(&id) { + continue; + } + let category = category_path("Function nodes", Some(operation.category)); + push(&mut out, entry(id, operation.label, &category, "", LibraryItem::Operation { operation: operation.id.into() }, None)); + } + for kind in PatternNodeKind::ALL { + let id = format!("pattern:{}", kind.native_id()); + push(&mut out, entry(id, kind.label(), "FxMap nodes", "", LibraryItem::Pattern { kind }, None)); + } + + for (path, package) in dependencies.iter().filter(|(path, _)| path.starts_with("sbs://")) { + for graph in &package.graphs { + let name = graph.sbs_path(); + if placed_graphs.contains(&(path.clone(), name.clone())) { + continue; + } + let placement = if graph.function.is_some() { + Placement { category: "Functions".into(), item: LayoutItem::FunctionInstance { package: path.clone(), graph: name } } + } else if graph.nodes.iter().any(|node| node.def == "output") { + let category = known_category(&graph.attributes.category).unwrap_or_else(|| "Other".into()); + Placement { category, item: LayoutItem::Instance { package: path.clone(), graph: name, outputs: Vec::new() } } + } else { + continue; + }; + if let Some(entry) = resolve(&placement, dependencies) { + push(&mut out, entry); + } + } + } + out + } +} + +fn entry(id: String, label: &str, category: &str, description: &str, item: LibraryItem, missing: Option) -> LibraryEntry { + let canvas = item.canvas(); + LibraryEntry { id, label: label.into(), category: category.into(), description: description.into(), item, canvas, missing, warning: None } +} + +/// A layout item as an entry, its label and availability taken from the loaded packages +fn resolve(placement: &Placement, dependencies: &BTreeMap>) -> Option { + let category = placement.category.as_str(); + Some(match &placement.item { + LayoutItem::Atomic { node: Some(def), .. } | LayoutItem::Node(def) => { + let definition = materialcraft_nodes::find(def)?; + entry(format!("node:{def}"), definition.label, category, definition.description, LibraryItem::Node { def: def.to_string() }, None) + } + LayoutItem::Atomic { filter, node: None } => { + let item = LibraryItem::Node { def: filter.clone() }; + entry(format!("atomic:{filter}"), &humanize(filter), category, "", item, Some(format!("The atomic `{filter}` node is not in MaterialCraft yet"))) + } + LayoutItem::Operation(operation) => { + let definition = materialcraft_nodes::function::FUNCTIONS.iter().find(|definition| definition.id == operation); + let label = definition.map_or_else(|| humanize(operation), |definition| definition.label.to_string()); + let missing = definition.is_none().then(|| format!("The `{operation}` function node is not in MaterialCraft yet")); + entry(format!("function:{operation}"), &label, category, "", LibraryItem::Operation { operation: operation.clone() }, missing) + } + LayoutItem::Instance { package, graph, .. } | LayoutItem::FunctionInstance { package, graph } => { + let function = matches!(placement.item, LayoutItem::FunctionInstance { .. }); + let source = dependencies.get(package).and_then(|source| source.graph_by_name(graph)).map(|(_, graph)| graph); + let source = source.filter(|source| source.function.is_some() == function); + let label = source.map_or_else(|| humanize(graph), |source| source.display_name().to_string()); + let description = source.map(|source| source.attributes.description.clone()).unwrap_or_default(); + let missing = source.is_none().then(|| format!("Not in MaterialCraft yet: needs {graph} from {package}")); + let item = if function { + LibraryItem::FunctionInstance { package: package.clone(), graph: graph.clone() } + } else { + LibraryItem::Instance { package: package.clone(), graph: graph.clone() } + }; + let mut out = entry(format!("{package}#{graph}"), &label, category, &description, item, missing); + out.category = sub_category(category, graph); + out.warning = source + .and_then(|source| source.function.as_ref()) + .filter(|function| function.output.is_none() || function.nodes.iter().any(|node| node.missing.is_some())) + .map(|_| "This function uses nodes MaterialCraft does not have yet".to_string()); + out + } + // A bitmap anywhere but the 3D view stands for the atomic Bitmap node, not its image + LayoutItem::Bitmap { .. } if !category.starts_with("3D view") => { + let definition = materialcraft_nodes::find("bitmap")?; + entry("node:bitmap".into(), definition.label, category, definition.description, LibraryItem::Node { def: "bitmap".into() }, None) + } + LayoutItem::Bitmap { resource } => { + let name = resource.rsplit('/').next().unwrap_or(resource); + let missing = Some(format!("Not in MaterialCraft yet: the {} image is not bundled", humanize(name))); + entry(format!("bitmap:{resource}"), &humanize(name), category, "", LibraryItem::Bitmap { resource: resource.clone() }, missing) + } + }) +} + +/// The categories of a layout's frames, and what each places +fn placements(frames: &[materialcraft_formats::sbs::LayoutFrame]) -> Vec { + let mut out = Vec::new(); + for frame in frames { + let native = frame.items.iter().any(|item| matches!(item, LayoutItem::Operation(_))); + let Some(category) = frame_category(&frame.title, frame.function, native) else { continue }; + out.extend(frame.items.iter().map(|item| Placement { category: category.clone(), item: item.clone() })); + } + out +} + +/// Letters and digits, lower case: "Spline & Path Tools", "spline & path tools" and +/// "Spline-and-path tools" differ, but "1 click" and "1-click" match +fn key(text: &str) -> String { + text.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect() +} + +/// `Top/Sub` for a frame title. Graph frames read "Top - Sub" (or "Top"); function frames name +/// only the sub-category, under Function nodes when they hold native operations and Functions +/// otherwise +pub fn frame_category(title: &str, function: bool, native_operations: bool) -> Option { + if function { + let top = if native_operations { "Function nodes" } else { "Functions" }; + let (_, subs) = CATEGORIES.iter().find(|(name, _)| *name == top)?; + let sub = subs.iter().find(|sub| key(sub) == key(title))?; + return Some(category_path(top, Some(sub))); + } + + let (top, sub) = title.split_once(" - ").map_or((title, None), |(top, sub)| (top, Some(sub))); + let top = RENAMED.iter().find(|(old, _)| key(old) == key(top)).map_or(top, |(_, current)| current); + let (top, subs) = CATEGORIES.iter().find(|(name, _)| key(name) == key(top))?; + match sub { + None => Some((*top).to_string()), + Some(sub) => subs.iter().find(|name| key(name) == key(sub)).map(|sub| category_path(top, Some(sub))), + } +} + +/// A category text from a graph's attributes, when it names a library category +fn known_category(text: &str) -> Option { + let mut parts = text.split('/'); + let top = parts.next()?; + let (top, subs) = CATEGORIES.iter().find(|(name, _)| key(name) == key(top))?; + let sub = parts.next().and_then(|sub| subs.iter().find(|name| key(name) == key(sub))); + Some(category_path(top, sub.copied())) +} + +fn category_path(top: &str, sub: Option<&str>) -> String { + match sub { + Some(sub) => format!("{top}/{sub}"), + None => top.to_string(), + } +} + +/// The sub-category a graph's name suggests, for layouts that name only a top level +fn sub_category(category: &str, graph: &str) -> String { + if category.contains('/') { + return category.to_string(); + } + let name = graph.rsplit('/').next().unwrap_or(graph).to_ascii_lowercase(); + SUB_KEYWORDS + .iter() + .find(|(top, _, words)| *top == category && words.iter().any(|word| name.contains(word))) + .map_or_else(|| category.to_string(), |(top, sub, _)| category_path(top, Some(sub))) +} + +/// A readable label from an SBS identifier: `3D_perlin_noise` → "3D Perlin Noise" +pub fn humanize(identifier: &str) -> String { + const WORDS: &[(&str, &str)] = &[ + ("2d", "2D"), + ("3d", "3D"), + ("acescg", "ACEScg"), + ("ao", "AO"), + ("bnw", "BnW"), + ("hdr", "HDR"), + ("hdri", "HDRI"), + ("hq", "HQ"), + ("id", "ID"), + ("mg", "MG"), + ("pbr", "PBR"), + ("rgb", "RGB"), + ("rgba", "RGBA"), + ("rgb-a", "RGB-A"), + ("srgb", "sRGB"), + ("uv", "UV"), + ]; + let name = identifier.rsplit('/').next().unwrap_or(identifier); + name.split(['_', ' ']) + .filter(|word| !word.is_empty()) + .map(|word| { + let lower = word.to_ascii_lowercase(); + if let Some((_, known)) = WORDS.iter().find(|(from, _)| *from == lower) { + return (*known).to_string(); + } + let mut chars = word.chars(); + chars.next().map_or_else(String::new, |first| first.to_uppercase().chain(chars).collect()) + }) + .collect::>() + .join(" ") +} + +#[cfg(test)] +#[path = "node_library.test.rs"] +mod tests; diff --git a/crates/engine/src/node_library.test.rs b/crates/engine/src/node_library.test.rs new file mode 100644 index 0000000..c37f571 --- /dev/null +++ b/crates/engine/src/node_library.test.rs @@ -0,0 +1,118 @@ +use super::*; +use materialcraft_core::Graph; + +#[test] +fn frame_titles_map_to_library_categories() { + assert_eq!(frame_category("Texture Generators - Noises", false, false).as_deref(), Some("Texture generators/Noises")); + assert_eq!(frame_category("Spline & Path tools - Path tools", false, false).as_deref(), Some("Spline & Path tools/Path tools")); + assert_eq!(frame_category("Material Filters - 1 click", false, false).as_deref(), Some("Material filters/1-click")); + assert_eq!(frame_category("Mesh-based generators - Weathering", false, false).as_deref(), Some("Mesh-based generators/Weathering")); + assert_eq!(frame_category("PBR Materials", false, false).as_deref(), Some("PBR materials")); + assert_eq!(frame_category("Atomic Nodes", false, false).as_deref(), Some("Atomic nodes")); + // The category MaterialCraft renamed still reads from older layouts + assert_eq!(frame_category("SDF functions - Primitives", false, false).as_deref(), Some("MCF functions/Primitives")); + assert_eq!(frame_category("Functions Inside", false, false), None); + assert_eq!(frame_category("Filters - Nowhere", false, false), None); + assert_eq!(frame_category("Comparison", true, true).as_deref(), Some("Function nodes/Comparison")); + assert_eq!(frame_category("Comparison", true, false).as_deref(), Some("Functions/Comparison")); + assert_eq!(frame_category("Unknown", true, true), None); +} + +#[test] +fn identifiers_read_as_labels() { + assert_eq!(humanize("3D_perlin_noise"), "3D Perlin Noise"); + assert_eq!(humanize("bnw_spots_1"), "BnW Spots 1"); + assert_eq!(humanize("rgb-a_merge"), "RGB-A Merge"); + assert_eq!(humanize("Functions/Math/acescg_to_srgb"), "ACEScg To sRGB"); + assert_eq!(humanize("__"), ""); +} + +#[test] +fn the_bundled_library_fills_every_category_of_the_tree() { + let library = NodeLibrary::shared(); + assert_eq!(library.layouts, vec!["sbs://all_nodes.sbs".to_string()]); + assert!(library.packages.contains_key("sbs://functions.sbs")); + assert!(!library.packages.contains_key("sbs://all_nodes.sbs"), "a layout is not a package of graphs"); + + let entries = library.entries(&library.packages); + let ids: BTreeSet<_> = entries.iter().map(|entry| entry.id.as_str()).collect(); + assert_eq!(ids.len(), entries.len(), "ids are unique"); + let known = |category: &str| { + let mut parts = category.split('/'); + let top = parts.next().unwrap_or(""); + CATEGORIES.iter().any(|(name, subs)| *name == top && parts.next().is_none_or(|sub| subs.contains(&sub))) + }; + for entry in &entries { + assert!(known(&entry.category), "{} sits in unknown category {}", entry.id, entry.category); + } + let count = |category: &str| entries.iter().filter(|entry| entry.category == category).count(); + let find = |id: &str| entries.iter().find(|entry| entry.id == id).unwrap_or_else(|| panic!("no entry {id}")); + + // Every top-level category that has sub-categories, except the new ones, has entries + for (top, subs) in CATEGORIES { + for sub in *subs { + let category = format!("{top}/{sub}"); + if !matches!(*top, "MCF functions" | "Values") && !matches!(category.as_str(), "PBR materials/Pavement" | "PBR materials/Stone") { + assert!(count(&category) > 0, "{category} is empty"); + } + } + } + assert_eq!(count("Texture generators/Noises"), 89); + assert_eq!( + entries.iter().filter(|entry| entry.category == "Graph items").map(|entry| entry.label.as_str()).collect::>(), + ["Comment", "Frame", "Pin", "Dot node"] + ); + assert_eq!(find("node:blur").category, "Atomic nodes"); + assert_eq!(find("node:output").category, "Atomic nodes"); + assert!(find("node:bitmap").missing.is_none(), "the atomic frame's bitmap is the Bitmap node"); + assert!(entries.iter().filter(|entry| entry.category == "Atomic nodes").all(|entry| entry.missing.is_none())); + assert!(entries.iter().filter(|entry| entry.category == "3D view/HDRI environments").all(|entry| entry.missing.is_some())); + assert!(find("node:blur").missing.is_none()); + assert_eq!(find("function:add").category, "Function nodes/Operator"); + assert_eq!(find("pattern:paramset").category, "FxMap nodes"); + + let pi = find("sbs://functions.sbs#Functions/Math/Pi"); + assert_eq!((pi.label.as_str(), pi.category.as_str()), ("Pi", "Functions/Constant")); + assert!(pi.missing.is_none()); + assert_eq!(find("sbs://functions.sbs#Functions/Math/Equality_Float2").category, "Functions/Comparison"); + + let perlin = find("sbs://3d_perlin_noise.sbs#3D_perlin_noise"); + assert_eq!((perlin.label.as_str(), perlin.category.as_str()), ("3D Perlin Noise", "Texture generators/Noises")); + assert!(perlin.missing.is_some(), "library packages MaterialCraft lacks are listed but not addable"); + assert_eq!(find("sbs://materials/pbr/bricks_001.sbs#bricks_001").category, "PBR materials/Bricks"); + assert_eq!(find("sbs://materials/pbr/old_painted_planks.sbs#old_painted_planks").category, "PBR materials/Wood"); + // A node that sits in two frames is listed in both + assert!(entries.iter().filter(|entry| entry.id.starts_with("sbs://paths_tools.sbs#path_to_spline")).count() == 2); +} + +#[test] +fn a_library_package_makes_its_placed_entry_available() { + let library = NodeLibrary::shared(); + let mut dependencies = library.packages.clone(); + let mut graph = Graph::new("3D_perlin_noise"); + graph.add_node("uniform", [0.0; 2]); + graph.add_node("output", [200.0, 0.0]); + let mut package = Package::new("3d_perlin_noise"); + package.graphs.push(graph.clone()); + graph.name = "Loose".into(); + graph.attributes.category = "Filters/Blurs".into(); + package.graphs.push(graph); + dependencies.insert("sbs://3d_perlin_noise.sbs".into(), Arc::new(package)); + + let entries = library.entries(&dependencies); + let perlin = entries.iter().find(|entry| entry.id == "sbs://3d_perlin_noise.sbs#3D_perlin_noise").unwrap(); + assert!(perlin.missing.is_none()); + assert_eq!(perlin.category, "Texture generators/Noises"); + let loose = entries.iter().find(|entry| entry.id == "sbs://3d_perlin_noise.sbs#Loose").unwrap(); + assert_eq!((loose.category.as_str(), loose.canvas), ("Filters/Blurs", LibraryCanvas::Material)); +} + +#[test] +fn unreadable_library_files_warn_instead_of_failing() { + let library = NodeLibrary::load(&["sbs://does_not_exist.sbs".into(), "sbs://../escape.sbs".into()]); + assert!(library.packages.is_empty() && library.layouts.is_empty()); + assert_eq!(library.warnings.len(), 2); + let entries = library.entries(&BTreeMap::new()); + assert!(entries.iter().any(|entry| entry.id == "node:blur" && entry.category == "Atomic nodes")); + assert!(entries.iter().any(|entry| entry.id == "function:add" && entry.category == "Function nodes/Operator")); +} diff --git a/crates/engine/src/node_library_commands.rs b/crates/engine/src/node_library_commands.rs new file mode 100644 index 0000000..29d6709 --- /dev/null +++ b/crates/engine/src/node_library_commands.rs @@ -0,0 +1,131 @@ +//! Library commands: list the categorized library, add an entry to the open graph, and read the +//! library folder again + +use crate::commands::{CommandSpec, always, bad, boolp, has_graph, point, strp}; +use crate::node_library::{CATEGORIES, LibraryCanvas, LibraryEntry, LibraryItem, NodeLibrary}; +use crate::{FunctionGraphTarget, Result, Session, cmd}; +use serde_json::{Value, json}; +use std::collections::BTreeSet; + +const ADD: &str = "library.add"; + +pub(crate) fn specs() -> Vec { + vec![ + cmd!( + "library.tree", + "Library categories", + [], + None, + "{filter?, category? (Top or Top/Sub), canvas? (material|function|pattern)} the library tree and its entries: id, label, category, type, canvas, missing (not addable yet), warning", + always, + tree + ), + cmd!( + "library.add", + "Add library entry", + [], + None, + "{entry (id from library.tree), at? [x, y], snapToGrid?, function?: FunctionGraphTarget} adds a library entry to the open graph (function entries to a Function canvas)", + has_graph, + add + ), + cmd!("library.reload", "Reload library", [], None, "{} reads the SBS library folder again", always, reload), + ] +} + +impl Session { + /// The library's entries, resolved against this session's loaded packages + pub fn library_entries(&self) -> Vec { + self.library.entries(&self.pkg.dependencies) + } +} + +fn tree(session: &mut Session, parameters: &Value) -> Result { + let filter = strp(parameters, "filter").unwrap_or("").to_lowercase(); + let category = strp(parameters, "category").unwrap_or(""); + let canvas = match strp(parameters, "canvas") { + None => None, + Some("material") => Some(LibraryCanvas::Material), + Some("function") => Some(LibraryCanvas::Function), + Some("pattern") => Some(LibraryCanvas::Pattern), + Some(other) => return Err(bad("library.tree", format!("unknown canvas `{other}`: material, function or pattern"))), + }; + let entries: Vec<_> = session + .library_entries() + .into_iter() + .filter(|entry| category.is_empty() || entry.category == category || entry.category.starts_with(&format!("{category}/"))) + .filter(|entry| canvas.is_none_or(|canvas| entry.canvas == canvas)) + .filter(|entry| filter.is_empty() || entry.label.to_lowercase().contains(&filter) || entry.id.to_lowercase().contains(&filter)) + .collect(); + let categories: Vec<_> = CATEGORIES.iter().map(|(name, subcategories)| json!({"name": name, "subcategories": subcategories})).collect(); + Ok(json!({"categories": categories, "layouts": session.library.layouts, "entries": entries})) +} + +fn add(session: &mut Session, parameters: &Value) -> Result { + let id = strp(parameters, "entry").ok_or_else(|| bad(ADD, "`entry` is required (an id from library.tree)"))?; + let entry = session.library_entries().into_iter().find(|entry| entry.id == id).ok_or_else(|| bad(ADD, format!("no library entry `{id}`")))?; + if let Some(missing) = &entry.missing { + return Err(bad(ADD, format!("{}: {missing}", entry.label))); + } + + let at = point(parameters, "at").unwrap_or([0.0, 0.0]); + let snap = boolp(parameters, "snapToGrid").unwrap_or(false); + let function_graph = session.graph()?.function.is_some(); + let target = parameters.get("function").cloned().filter(|target| !target.is_null()); + if entry.canvas == LibraryCanvas::Function { + let target = match target { + Some(target) => serde_json::from_value::(target).map_err(|error| bad(ADD, error.to_string()))?, + None if function_graph => FunctionGraphTarget::Graph, + None => return Err(bad(ADD, format!("{} goes in a Function canvas: open a Function Graph or pass `function`", entry.label))), + }; + let target = serde_json::to_value(target).map_err(|error| bad(ADD, error.to_string()))?; + let result = match &entry.item { + LibraryItem::Operation { operation } => crate::execute( + session, + "graph.function.edit", + &json!({"target": target, "edit": {"action": "add", "operation": operation, "at": at, "snap": snap}}), + )?, + LibraryItem::FunctionInstance { package, graph } => { + crate::execute(session, "library.function.add", &json!({"package": package, "graph": graph, "function": target, "at": at, "snapToGrid": snap}))? + } + _ => return Err(bad(ADD, "unexpected function entry")), + }; + return Ok(json!({"entry": entry.id, "result": result})); + } + if entry.canvas == LibraryCanvas::Pattern { + return Err(bad(ADD, format!("{} is an FX-Map node: add it with graph.pattern.edit", entry.label))); + } + if function_graph { + return Err(bad(ADD, format!("{} goes in a material graph, not a Function Graph", entry.label))); + } + + let result = match &entry.item { + LibraryItem::Node { def } => crate::execute(session, "graph.node.add", &json!({"def": def, "at": at, "snapToGrid": snap}))?, + LibraryItem::Comment => crate::execute(session, "graph.comment.add", &json!({"at": at}))?, + LibraryItem::Frame => crate::execute(session, "graph.frame.add", &json!({"rect": [at[0], at[1], 400.0, 260.0]}))?, + LibraryItem::Pin => crate::execute(session, "graph.pin.add", &json!({"at": at}))?, + LibraryItem::Instance { package, graph } => { + crate::execute(session, "graph.instance.add", &json!({"package": package, "graph": graph, "at": at, "snapToGrid": snap}))? + } + _ => return Err(bad(ADD, format!("{} can't be added to a graph", entry.label))), + }; + Ok(json!({"entry": entry.id, "result": result})) +} + +fn reload(session: &mut Session, _: &Value) -> Result { + let library = NodeLibrary::reload(); + let mut changed = BTreeSet::new(); + for (path, package) in &library.packages { + if session.linked_sources.get(path).is_none_or(|current| current.graphs != package.graphs || current.resources != package.resources) { + session.linked_sources.insert(path.clone(), package.clone()); + changed.insert(path.clone()); + } + } + for warning in &library.warnings { + session.warn(warning.clone()); + } + session.library = library; + session.refresh_links_from(changed); + let entries = session.library_entries(); + Ok(json!({"entries": entries.len(), "available": entries.iter().filter(|entry| entry.missing.is_none()).count(), "layouts": session.library.layouts})) +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index d295571..03517e8 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -157,6 +157,8 @@ pub struct Session { pub cache: Arc>, /// A mesh loaded for the 3D view (`scene: "custom"`): its file name and geometry. pub custom_mesh: Option<(String, Arc)>, + /// The node library loaded from the SBS library folder + pub library: Arc, pub(crate) history: crate::document_history::DocumentHistory, group: Option<(Snapshot, bool)>, decoded: Arc>>, @@ -164,11 +166,9 @@ pub struct Session { impl 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 library = crate::node_library::NodeLibrary::shared(); + for (path, package) in &library.packages { + pkg.dependencies.entry(path.clone()).or_insert_with(|| package.clone()); } let mut session = Session { environment: Default::default(), @@ -201,19 +201,19 @@ impl Session { cook_epoch: 0, cache: Arc::new(Mutex::new(Cache::default())), custom_mesh: None, + library: Default::default(), history: Default::default(), group: None, 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}")), + for warning in &library.warnings { + session.warn(warning.clone()); } + if !library.packages.contains_key(crate::function_library::STANDARD_PACKAGE) { + session.warn(format!("Missing function library: {} did not load", crate::function_library::STANDARD_PACKAGE)); + } + session.library = library; session } diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 4d8f199..a1e6be5 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -20,6 +20,7 @@ mod graph_properties; mod linked_instances; mod linked_resources; mod material_preview; +mod node_library; mod normal_maps; mod open_documents; mod optimization_perf; diff --git a/crates/engine/tests/it/node_library.rs b/crates/engine/tests/it/node_library.rs new file mode 100644 index 0000000..26062ca --- /dev/null +++ b/crates/engine/tests/it/node_library.rs @@ -0,0 +1,82 @@ +use materialcraft_engine::{ + Session, + core::{FunctionGraph, Graph, Package}, + execute, new_session, +}; +use serde_json::{Value, json}; + +fn entries(session: &mut Session, parameters: Value) -> Vec { + execute(session, "library.tree", ¶meters).unwrap()["entries"].as_array().unwrap().clone() +} + +#[test] +fn the_library_tree_lists_categories_and_filters_entries() { + let mut session = new_session(); + let tree = execute(&mut session, "library.tree", &json!({})).unwrap(); + let names: Vec<_> = tree["categories"].as_array().unwrap().iter().map(|category| category["name"].as_str().unwrap()).collect(); + assert_eq!(names[..4], ["Graph items", "Atomic nodes", "FxMap nodes", "Function nodes"]); + assert!(names.contains(&"MCF functions") && !names.contains(&"SDF functions")); + assert_eq!(tree["layouts"], json!(["sbs://all_nodes.sbs"])); + + let noises = entries(&mut session, json!({"category": "Texture generators/Noises"})); + assert_eq!(noises.len(), 89); + assert!(noises.iter().all(|entry| entry["missing"].is_string())); + + let functions = entries(&mut session, json!({"canvas": "function", "filter": "pi"})); + assert!(functions.iter().any(|entry| entry["id"] == "sbs://functions.sbs#Functions/Math/Pi" && entry["type"] == "functionInstance")); + assert!(functions.iter().all(|entry| entry["canvas"] == "function")); + assert!(execute(&mut session, "library.tree", &json!({"canvas": "teapot"})).is_err()); +} + +#[test] +fn library_entries_add_to_the_graph_they_fit() { + let mut session = new_session(); + let before = session.graph().unwrap().nodes.len(); + let added = execute(&mut session, "library.add", &json!({"entry": "node:blur", "at": [32.0, 64.0]})).unwrap(); + assert_eq!(added["entry"], "node:blur"); + let graph = session.graph().unwrap(); + assert_eq!(graph.nodes.len(), before + 1); + assert_eq!(graph.nodes.last().unwrap().def, "blur"); + assert_eq!(graph.nodes.last().unwrap().pos, [32.0, 64.0]); + + for (entry, check) in [("item:comment", "comments"), ("item:frame", "frames"), ("item:pin", "pins")] { + let count = |session: &Session| serde_json::to_value(session.graph().unwrap()).unwrap()[check].as_array().map_or(0, Vec::len); + let previous = count(&session); + execute(&mut session, "library.add", &json!({"entry": entry})).unwrap(); + assert_eq!(count(&session), previous + 1, "{entry}"); + } + + // Library nodes MaterialCraft lacks are listed but refuse to add, naming what they need + let error = execute(&mut session, "library.add", &json!({"entry": "sbs://3d_perlin_noise.sbs#3D_perlin_noise"})).unwrap_err().to_string(); + assert!(error.contains("3d_perlin_noise.sbs"), "{error}"); + assert!(execute(&mut session, "library.add", &json!({"entry": "nothing"})).is_err()); + assert!(execute(&mut session, "library.add", &json!({})).is_err()); + // Function entries need a Function canvas + assert!(execute(&mut session, "library.add", &json!({"entry": "function:add"})).is_err()); + assert!(execute(&mut session, "library.add", &json!({"entry": "pattern:paramset"})).is_err()); + + let mut package = Package::new("Functions"); + let mut graph = Graph::new("Caller"); + graph.function = Some(FunctionGraph::default()); + package.graphs.push(graph); + let mut session = Session::new(package); + execute(&mut session, "library.add", &json!({"entry": "function:add", "at": [0.0, 0.0]})).unwrap(); + execute(&mut session, "library.add", &json!({"entry": "sbs://functions.sbs#Functions/Math/Pi", "at": [140.0, 0.0]})).unwrap(); + let function = session.graph().unwrap().function.as_ref().unwrap(); + assert_eq!(function.nodes.len(), 2); + assert!(function.nodes.iter().any(|node| node.op == "add")); + assert!(function.nodes.iter().any(|node| node.instance.as_ref().is_some_and(|instance| instance.graph == "Functions/Math/Pi"))); + assert!(execute(&mut session, "library.add", &json!({"entry": "node:blur"})).is_err()); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(session.graph().unwrap().function.as_ref().unwrap().nodes.len(), 1); +} + +#[test] +fn reloading_the_library_keeps_open_work_unmodified() { + let mut session = new_session(); + let reloaded = execute(&mut session, "library.reload", &json!({})).unwrap(); + assert!(reloaded["entries"].as_u64().unwrap() > 500); + assert!(reloaded["available"].as_u64().unwrap() > 200); + assert!(!session.modified); + assert!(session.pkg.dependencies.contains_key("sbs://functions.sbs")); +} diff --git a/crates/formats/src/sbs/library.rs b/crates/formats/src/sbs/library.rs index 99c1559..bd3a41a 100644 --- a/crates/formats/src/sbs/library.rs +++ b/crates/formats/src/sbs/library.rs @@ -79,6 +79,70 @@ pub fn read(uri: &str) -> Result, String> { // 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()), + "all_nodes.sbs" => Ok(include_bytes!("../../../../assets/sbs/all_nodes.sbs").to_vec()), _ => Err(format!("Missing library asset {uri}")), } } + +/// The packages bundled into the binary, for installs and the browser without an asset folder +pub const BUNDLED: &[&str] = &["sbs://all_nodes.sbs", "sbs://functions.sbs"]; + +/// Bounds for scanning the library folder: how deep, and how many packages +const MAX_DEPTH: usize = 6; +const MAX_FILES: usize = 2048; + +/// Every SBS package in the library as `sbs://` paths, sorted: the files under the asset folder +/// (resource folders skipped), or the bundled packages when there is no folder +pub fn files() -> Vec { + #[cfg(not(target_arch = "wasm32"))] + { + let root = root(); + if root.is_dir() { + let mut found = Vec::new(); + scan(&root, "", 0, &mut found); + found.sort(); + return found; + } + } + BUNDLED.iter().map(|uri| uri.to_string()).collect() +} + +#[cfg(not(target_arch = "wasm32"))] +fn scan(directory: &std::path::Path, prefix: &str, depth: usize, found: &mut Vec) { + let Ok(entries) = std::fs::read_dir(directory) else { return }; + let mut entries: Vec<_> = entries.flatten().collect(); + entries.sort_by_key(|entry| entry.file_name()); + for entry in entries { + if found.len() >= MAX_FILES { + return; + } + let Some(name) = entry.file_name().to_str().map(str::to_string) else { continue }; + let Ok(kind) = entry.file_type() else { continue }; + let uri = format!("sbs://{prefix}{name}"); + // Symlinks are skipped: `read` refuses files that leave the asset folder anyway + if kind.is_dir() && depth < MAX_DEPTH && !name.ends_with(".resources") && !name.starts_with('.') { + scan(&entry.path(), &format!("{prefix}{name}/"), depth + 1, found); + } else if kind.is_file() && name.to_ascii_lowercase().ends_with(".sbs") && relative_path(&uri).is_ok() { + found.push(uri); + } + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + #[test] + fn the_library_lists_every_package_once_and_bundles_a_fallback() { + let files = files(); + for uri in BUNDLED { + assert!(files.iter().any(|file| file == uri), "{uri} in {files:?}"); + assert!(!read(uri).unwrap().is_empty()); + } + let mut unique = files.clone(); + unique.dedup(); + assert_eq!(unique, files); + assert!(files.iter().all(|file| relative_path(file).is_ok() && file.ends_with(".sbs"))); + } +} diff --git a/crates/formats/src/sbs/library_layout.rs b/crates/formats/src/sbs/library_layout.rs new file mode 100644 index 0000000..337a86b --- /dev/null +++ b/crates/formats/src/sbs/library_layout.rs @@ -0,0 +1,298 @@ +//! Library layouts. An SBS package can lay out a node library: its graphs group nodes in titled +//! frames ("Filters - Blurs"), and a parameter function groups function nodes the same way. This +//! reads the frames and the nodes inside each one; it does not cook anything. The engine decides +//! which frame titles are library categories. + +use super::{ + constant::MAX_XML_NODES, + filter_map::FILTERS, + xml::{child_element, child_value, children_named, parse_floats}, +}; +use crate::{FormatError, Result}; +use roxmltree::Node as XmlNode; +use std::collections::HashMap; + +/// Bounds for hostile layouts: frames and placed nodes kept per file +const MAX_FRAMES: usize = 4096; +const MAX_ITEMS: usize = 65_536; + +/// A titled frame and the nodes inside it, top to bottom +#[derive(Clone, Debug, PartialEq)] +pub struct LayoutFrame { + pub title: String, + /// The frame groups function nodes (it sits in a function graph or a parameter function) + pub function: bool, + pub items: Vec, +} + +/// One node placed in a layout frame +#[derive(Clone, Debug, PartialEq)] +pub enum LayoutItem { + /// An atomic SBS filter by its SBS name, with the MaterialCraft node it reads as (`None` + /// when MaterialCraft has no counterpart yet) + Atomic { filter: String, node: Option<&'static str> }, + /// A graph input (`input_color`, `input_grayscale`, `input_value`) or `output` + Node(&'static str), + /// An instance of graph `graph` from the library package `package` + Instance { package: String, graph: String, outputs: Vec }, + /// A native function operation, e.g. `add` + Operation(String), + /// An instance of function graph `graph` from the library package `package` + FunctionInstance { package: String, graph: String }, + /// A bitmap showing one of the layout package's own resources, e.g. an environment image + Bitmap { resource: String }, +} + +/// The frames of every graph and parameter function in `bytes`, in document order +pub fn read_layout(bytes: &[u8], uri: &str) -> Result> { + let text = std::str::from_utf8(bytes).map_err(|e| FormatError::BadPackage(format!("the SBS file is not UTF-8 text: {e}")))?; + let text = text.trim_start_matches('\u{feff}'); + let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: MAX_XML_NODES }; + let doc = roxmltree::Document::parse_with_options(text, options).map_err(|e| FormatError::BadPackage(format!("the SBS file is not valid XML: {e}")))?; + let root = doc.root_element(); + if root.tag_name().name() != "package" { + return Err(FormatError::BadPackage("not an SBS package (the root element is not )".into())); + } + + let mut dependencies = HashMap::new(); + for dependency in child_element(root, "dependencies").into_iter().flat_map(|d| children_named(d, "dependency")) { + if let (Some(uid), Some(file)) = (child_value(dependency, "uid"), child_value(dependency, "filename")) { + let file = if file == "?himself" { uri } else { file }; + dependencies.insert(uid, file.to_string()); + } + } + + let mut frames = Vec::new(); + let mut items = 0; + for scope in root.descendants().filter(|node| node.is_element()) { + let function = match scope.tag_name().name() { + "graph" if child_element(scope, "compNodes").is_some() => false, + _ if child_element(scope, "paramNodes").is_some() => true, + _ => continue, + }; + let mut scope_frames = scope_frames(scope); + if scope_frames.is_empty() { + continue; + } + + let nodes: Vec<(XmlNode, [f32; 2])> = if function { + child_element(scope, "paramNodes").into_iter().flat_map(|n| children_named(n, "paramNode")).filter_map(|n| Some((n, position(n)?))).collect() + } else { + child_element(scope, "compNodes").into_iter().flat_map(|n| children_named(n, "compNode")).filter_map(|n| Some((n, position(n)?))).collect() + }; + let mut placed: Vec<(usize, [f32; 2], LayoutItem)> = Vec::new(); + for (node, at) in nodes { + if items >= MAX_ITEMS { + break; + } + // The smallest frame holding the node wins, so nested frames keep their own nodes + let Some(frame) = scope_frames + .iter() + .enumerate() + .filter(|(_, (_, rect))| at[0] >= rect[0] && at[1] >= rect[1] && at[0] <= rect[0] + rect[2] && at[1] <= rect[1] + rect[3]) + .min_by(|a, b| (a.1.1[2] * a.1.1[3]).total_cmp(&(b.1.1[2] * b.1.1[3]))) + .map(|(index, _)| index) + else { + continue; + }; + let item = if function { function_item(node, &dependencies) } else { graph_item(scope, node, &dependencies) }; + if let Some(item) = item { + placed.push((frame, at, item)); + items += 1; + } + } + placed.sort_by(|a, b| a.0.cmp(&b.0).then(a.1[1].total_cmp(&b.1[1])).then(a.1[0].total_cmp(&b.1[0]))); + let mut grouped: Vec> = vec![Vec::new(); scope_frames.len()]; + for (frame, _, item) in placed { + if let Some(list) = grouped.get_mut(frame) { + list.push(item); + } + } + for ((title, _), items) in scope_frames.drain(..).zip(grouped) { + if frames.len() >= MAX_FRAMES { + break; + } + frames.push(LayoutFrame { title, function, items }); + } + } + Ok(frames) +} + +/// The titled frames of a graph or function: (title, [x, y, width, height]) +fn scope_frames(scope: XmlNode) -> Vec<(String, [f32; 4])> { + child_element(scope, "GUIObjects") + .into_iter() + .flat_map(|objects| children_named(objects, "GUIObject")) + .filter(|object| child_value(*object, "type") == Some("COMMENT")) + .filter_map(|object| { + let title = child_value(object, "title")?.trim(); + let layout = child_element(object, "GUILayout")?; + let at = parse_floats(child_value(layout, "gpos")?); + let size = parse_floats(child_value(layout, "size")?); + let rect = [*at.first()?, *at.get(1)?, *size.first()?, *size.get(1)?]; + (!title.is_empty() && rect[2] > 0.0 && rect[3] > 0.0).then(|| (title.chars().take(256).collect(), rect)) + }) + .take(MAX_FRAMES) + .collect() +} + +fn position(node: XmlNode) -> Option<[f32; 2]> { + let at = parse_floats(child_value(child_element(node, "GUILayout")?, "gpos")?); + Some([*at.first()?, *at.get(1)?]) +} + +/// `pkg:///Graph/Path?dependency=123` as (graph path, package file) +fn reference(path: &str, dependencies: &HashMap<&str, String>) -> Option<(String, String)> { + let path = path.strip_prefix("pkg:///")?; + let (graph, query) = path.split_once('?').unwrap_or((path, "")); + let uid = query.split('&').find_map(|pair| pair.strip_prefix("dependency="))?; + let package = dependencies.get(uid)?.clone(); + let graph = graph.trim_matches('/'); + (!graph.is_empty()).then(|| (graph.chars().take(1024).collect(), package)) +} + +fn graph_item(graph: XmlNode, node: XmlNode, dependencies: &HashMap<&str, String>) -> Option { + let implementation = child_element(node, "compImplementation")?.children().find(|c| c.is_element())?; + match implementation.tag_name().name() { + "compFilter" => { + let filter = child_value(implementation, "filter")?; + if filter == "bitmap" + && let Some(resource) = string_parameter(implementation, "bitmapresourcepath") + { + let resource = resource.strip_prefix("pkg:///").unwrap_or(resource); + let resource = resource.split_once('?').map_or(resource, |(path, _)| path); + return Some(LayoutItem::Bitmap { resource: resource.chars().take(1024).collect() }); + } + Some(LayoutItem::Atomic { filter: filter.chars().take(128).collect(), node: FILTERS.iter().find(|f| f.sbs == filter).map(|f| f.def) }) + } + "compInstance" => { + let (graph, package) = reference(child_value(implementation, "path")?, dependencies)?; + let outputs = child_element(implementation, "outputBridgings") + .into_iter() + .flat_map(|b| children_named(b, "outputBridging")) + .filter_map(|b| child_value(b, "identifier")) + .take(64) + .map(str::to_string) + .collect(); + Some(LayoutItem::Instance { package, graph, outputs }) + } + "compInputBridge" => { + let entry = child_value(implementation, "entry")?; + let input = child_element(graph, "paraminputs") + .into_iter() + .flat_map(|inputs| children_named(inputs, "paraminput")) + .find(|input| child_value(*input, "uid") == Some(entry)); + Some(LayoutItem::Node(match input.and_then(|input| child_value(input, "type")) { + Some("1") | None => "input_color", + Some("2") => "input_grayscale", + Some(_) => "input_value", + })) + } + "compOutputBridge" => Some(LayoutItem::Node("output")), + _ => None, + } +} + +fn function_item(node: XmlNode, dependencies: &HashMap<&str, String>) -> Option { + let operation = child_value(node, "function")?; + if operation != "instance" { + return Some(LayoutItem::Operation(operation.chars().take(128).collect())); + } + + let path = child_element(node, "funcDatas") + .into_iter() + .flat_map(|datas| children_named(datas, "funcData")) + .find(|data| child_value(*data, "name") == Some("instance")) + .and_then(|data| child_element(data, "constantValue")) + .and_then(|value| child_value(value, "constantValueString"))?; + let (graph, package) = reference(path, dependencies)?; + Some(LayoutItem::FunctionInstance { package, graph }) +} + +fn string_parameter<'a>(filter: XmlNode<'a, '_>, name: &str) -> Option<&'a str> { + child_element(filter, "parameters") + .into_iter() + .flat_map(|parameters| children_named(parameters, "parameter")) + .find(|parameter| child_value(*parameter, "name") == Some(name)) + .and_then(|parameter| child_element(parameter, "paramValue")) + .and_then(|value| child_value(value, "constantValueString")) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + const LAYOUT: &str = r#" + + + + + + + + + + + + + + + + + + </GUIObject> + <GUIObject><type v="COMMENT"/><GUILayout><gpos v="250 0 0"/><size v="100 100"/></GUILayout><title v="Constant"/></GUIObject> + </GUIObjects></dynamicValue></paramValue></parameter></parameters></compFilter></compImplementation></compNode> + </compNodes> + <GUIObjects> + <GUIObject><type v="COMMENT"/><GUILayout><gpos v="0 0 0"/><size v="160 200"/></GUILayout><title v="Texture Generators - Noises"/></GUIObject> + <GUIObject><type v="COMMENT"/><GUILayout><gpos v="400 0 0"/><size v="160 200"/></GUILayout><title v="3D view - HDRI environments"/></GUIObject> + <GUIObject><type v="COMMENT"/><GUILayout><gpos v="0 0 0"/><size v="10 10"/></GUILayout></GUIObject> + </GUIObjects></graph></content></package>"#; + + #[test] + fn frames_list_what_sits_inside_them_top_to_bottom() { + let frames = read_layout(LAYOUT.as_bytes(), "sbs://layout.sbs").unwrap(); + let graph: Vec<_> = frames.iter().filter(|frame| !frame.function).collect(); + assert_eq!(graph.len(), 2); + assert_eq!(graph[0].title, "Texture Generators - Noises"); + assert_eq!( + graph[0].items, + vec![ + LayoutItem::Atomic { filter: "blur".into(), node: Some("blur") }, + LayoutItem::Node("input_grayscale"), + LayoutItem::Atomic { filter: "blend".into(), node: Some("blend") }, + LayoutItem::Instance { package: "sbs://noise.sbs".into(), graph: "perlin_noise".into(), outputs: vec!["output".into()] }, + ] + ); + assert_eq!(graph[1].items, vec![LayoutItem::Bitmap { resource: "Resources/studio".into() }]); + + let function: Vec<_> = frames.iter().filter(|frame| frame.function).collect(); + assert_eq!(function.len(), 2); + assert_eq!(function[0].items, vec![LayoutItem::Operation("add".into())]); + assert_eq!(function[1].items, vec![LayoutItem::FunctionInstance { package: "sbs://functions.sbs".into(), graph: "Functions/Math/Pi".into() }]); + } + + #[test] + fn packages_without_frames_have_no_layout_and_bad_input_errors() { + assert!(read_layout(b"<package><content><graph><compNodes/></graph></content></package>", "sbs://x.sbs").unwrap().is_empty()); + assert!(read_layout(b"<nope/>", "sbs://x.sbs").is_err()); + assert!(read_layout(b"\xff\xfe", "sbs://x.sbs").is_err()); + assert!(read_layout(b"<package><content><graph><compNodes><compNode><GUILayout><gpos v=\"nan\"/></GUILayout></compNode></compNodes><GUIObjects><GUIObject><type v=\"COMMENT\"/><GUILayout><gpos v=\"0 0\"/><size v=\"-5 1e40\"/></GUILayout><title v=\"X\"/></GUIObject></GUIObjects></graph></content></package>", "sbs://x.sbs").unwrap().is_empty()); + } + + #[test] + fn the_bundled_layout_places_the_whole_library() { + let bytes = super::super::library::read("sbs://all_nodes.sbs").unwrap(); + let frames = read_layout(&bytes, "sbs://all_nodes.sbs").unwrap(); + let count = |title: &str| frames.iter().filter(|frame| frame.title == title).map(|frame| frame.items.len()).sum::<usize>(); + assert_eq!(count("Atomic Nodes"), 28); + assert_eq!(count("Texture Generators - Noises"), 89); + assert_eq!(count("Filters - Blurs"), 14); + assert!(frames.iter().filter(|frame| frame.function).count() >= 20); + assert!( + frames.iter().flat_map(|frame| &frame.items).any(|item| matches!(item, LayoutItem::FunctionInstance { graph, .. } if graph == "Functions/Math/Pi")) + ); + } +} diff --git a/crates/formats/src/sbs/mod.rs b/crates/formats/src/sbs/mod.rs index b86db61..ea54381 100644 --- a/crates/formats/src/sbs/mod.rs +++ b/crates/formats/src/sbs/mod.rs @@ -12,6 +12,7 @@ mod group_layout; mod image_input; mod input_bridge; pub mod library; +mod library_layout; mod node_identifiers; mod node_parameter; mod output; @@ -29,6 +30,7 @@ mod warnings; mod xml; pub use constant::SBS_EXT; +pub use library_layout::{LayoutFrame, LayoutItem, read_layout}; pub use read::{is_sbs, read_sbs}; pub use sbs_read::SbsRead; pub use write::write_sbs; diff --git a/crates/ui-egui/src/explorer.rs b/crates/ui-egui/src/explorer.rs index 55b44fd..81cbcdb 100644 --- a/crates/ui-egui/src/explorer.rs +++ b/crates/ui-egui/src/explorer.rs @@ -49,11 +49,12 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { inspected_graph: None, inspected_folder: None, }; - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + let scroll = egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { for (document, package, path, modified) in tree.session.open_packages() { ui.push_id(document, |ui| tree.package(ui, document, package, path, modified)); } }); + tree.state.hovered = ui.rect_contains_pointer(scroll.inner_rect); let action = tree.action; let opened_node = tree.opened_node; let assignment = tree.assignment; @@ -111,6 +112,32 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } } +/// Enter opens, F2 renames and Delete removes the selected graph or folder while the pointer is +/// over the Explorer; elsewhere those keys keep their graph shortcuts. True when a key was used +pub(crate) fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) -> bool { + if !app.ui.explorer.hovered || app.ui.explorer.rename.is_some() { + return false; + } + let Some(target) = app.ui.explorer.selected.clone() else { return false }; + let command = match &target { + ExplorerTarget::Graph { .. } => [(egui::Key::Enter, "graph.open"), (egui::Key::F2, "graph.rename"), (egui::Key::Delete, "graph.delete")] + .into_iter() + .find(|(key, _)| pressed(ctx, *key)), + ExplorerTarget::Folder { .. } if !target.is_resources_root() => { + [(egui::Key::F2, "folder.rename"), (egui::Key::Delete, "folder.remove")].into_iter().find(|(key, _)| pressed(ctx, *key)) + } + _ => None, + }; + let Some((key, command)) = command else { return false }; + ctx.input_mut(|input| input.consume_key(egui::Modifiers::NONE, key)); + actions::invoke(app, ctx, target, command); + true +} + +fn pressed(ctx: &egui::Context, key: egui::Key) -> bool { + ctx.input(|input| input.modifiers.is_none() && input.key_pressed(key)) +} + 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 index bc8af38..b04b908 100644 --- a/crates/ui-egui/src/explorer/actions.rs +++ b/crates/ui-egui/src/explorer/actions.rs @@ -55,15 +55,87 @@ pub(super) fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, target: Ex "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" => { + "file.save" | "file.saveAs" | "file.saveCopyAs" | "file.exportMaterial" | "file.sendToTextureCraft" => { crate::windows::file_action(app, ctx, command); } + crate::menus::EXPLORER_COMPUTE => compute_outputs(app, &target), + crate::menus::EXPLORER_VIEW_OUTPUTS => { + if let ExplorerTarget::Graph { index, .. } = target + && app.run("view.3d.outputs", json!({"graph": index})).is_some() + { + app.ui.dock.focus(crate::docking::Panel::View3d); + } + } + crate::menus::EXPLORER_EXPORT_OUTPUTS => { + if let ExplorerTarget::Graph { index, .. } = target + && (index == app.session.graph || app.run("graph.open", json!({"graph": index})).is_some()) + { + app.ui.windows.export = true; + } + } + crate::menus::EXPLORER_SHOW_IN_FOLDER => show_in_folder(app), + crate::menus::EXPLORER_OPEN_DEPENDENCIES => open_dependencies(app), _ => { app.run(command, target.parameters()); } } } +/// A dependency that is another package file on disk (not a library package or an unsaved one) +pub(super) fn is_package_file(path: &str) -> bool { + !path.starts_with("sbs://") && !path.starts_with("unsaved:") && !path.is_empty() +} + +/// Cook the graph's outputs, or every graph of the package with outputs, at full size +fn compute_outputs(app: &mut MaterialCraftApp, target: &ExplorerTarget) { + let graphs: Vec<usize> = match target { + ExplorerTarget::Graph { index, .. } => vec![*index], + _ => app.session.pkg.graphs.iter().enumerate().filter(|(_, graph)| graph.function.is_none()).map(|(index, _)| index).collect(), + }; + let (mut milliseconds, mut errors) = (0.0, 0); + for index in &graphs { + let Some(result) = app.run("graph.cook", json!({"graph": index, "full": true})) else { return }; + milliseconds += result["ms"].as_f64().unwrap_or(0.0); + errors += result["nodes"].as_array().map_or(0, |nodes| nodes.iter().filter(|node| !node["error"].is_null()).count()); + } + let summary = crate::i18n::trf("Computed {count} graph(s) in {ms} ms", &[("count", &graphs.len()), ("ms", &format!("{milliseconds:.0}"))]); + if errors > 0 { + app.toast(format!("{summary}; {}", crate::i18n::trf("{count} node(s) failed: see the graph", &[("count", &errors)])), true); + } else { + app.toast(summary, false); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn package_path(app: &MaterialCraftApp) -> Option<String> { + app.session.open_packages().into_iter().find(|entry| entry.0 == app.session.document_id).and_then(|entry| entry.2.map(str::to_string)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn show_in_folder(app: &mut MaterialCraftApp) { + let Some(path) = package_path(app) else { return }; + if let Err(error) = craft_update::process::reveal(std::path::Path::new(&path)) { + app.toast(format!("{}: {error}", tr("Could not show the package file")), true); + } +} + +#[cfg(target_arch = "wasm32")] +fn show_in_folder(_: &mut MaterialCraftApp) {} + +/// Open every package file the active package links, next to it in the Explorer +#[cfg(not(target_arch = "wasm32"))] +fn open_dependencies(app: &mut MaterialCraftApp) { + let document = app.session.document_id; + let paths: Vec<String> = app.session.pkg.dependencies.keys().filter(|path| is_package_file(path)).cloned().collect(); + for path in paths { + crate::windows::open_path(app, &path); + } + activate(app, document); +} + +#[cfg(target_arch = "wasm32")] +fn open_dependencies(_: &mut MaterialCraftApp) {} + 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; diff --git a/crates/ui-egui/src/explorer/context_menu.rs b/crates/ui-egui/src/explorer/context_menu.rs index 7b6ef47..0ef8253 100644 --- a/crates/ui-egui/src/explorer/context_menu.rs +++ b/crates/ui-egui/src/explorer/context_menu.rs @@ -1,64 +1,108 @@ use super::ExplorerTarget; -use crate::{i18n::tr, menus}; +use crate::menus::{self, ExplorerRow}; +use crate::{i18n::tr, menus::shortcut_label}; -pub(super) fn show(ui: &mut egui::Ui, target: &ExplorerTarget, paste: bool, reload: bool) -> Option<&'static str> { - ui.set_min_width(190.0); +/// What the right-clicked item allows right now +#[derive(Clone, Copy, Debug, Default)] +pub(super) struct MenuState { + /// The Explorer clipboard holds something to paste + pub paste: bool, + /// The package has a file on disk (reload, show in folder) + pub saved: bool, + /// The package links other package files + pub dependencies: bool, + /// The graph (or, for a package, one of its graphs) has image outputs + pub outputs: bool, +} + +impl MenuState { + fn enabled(&self, command: &str) -> bool { + match command { + "" => false, + "explorer.paste" => self.paste, + "file.reload" | menus::EXPLORER_SHOW_IN_FOLDER => self.saved, + menus::EXPLORER_OPEN_DEPENDENCIES => self.dependencies, + menus::EXPLORER_COMPUTE | menus::EXPLORER_VIEW_OUTPUTS | menus::EXPLORER_EXPORT_OUTPUTS => self.outputs, + _ => true, + } + } +} + +/// Rows the browser can't offer: it has no folders to show or package files to open +fn hidden(command: &str) -> bool { + cfg!(target_arch = "wasm32") && matches!(command, menus::EXPLORER_SHOW_IN_FOLDER | menus::EXPLORER_OPEN_DEPENDENCIES) +} + +fn item(ui: &mut egui::Ui, label: &str, command: &'static str, shortcut: Option<&str>, enabled: bool, action: &mut Option<&'static str>) { + let mut button = egui::Button::new(tr(label)); + if let Some(shortcut) = shortcut { + button = button.shortcut_text(shortcut_label(ui.ctx(), shortcut)); + } + let response = ui.add_enabled(enabled, button); + let response = if command.is_empty() { response.on_disabled_hover_text(tr("Not available yet")) } else { response }; + if response.clicked() { + *action = Some(command); + ui.close(); + } +} + +fn rows(ui: &mut egui::Ui, rows: &[ExplorerRow], state: &MenuState, resources: bool, action: &mut Option<&'static str>) { + for row in rows { + match *row { + ExplorerRow::Separator => { + ui.separator(); + } + ExplorerRow::Item(label, command, shortcut) if !hidden(command) => item(ui, label, command, shortcut, state.enabled(command), action), + ExplorerRow::Item(..) => {} + ExplorerRow::Sub(label, entries) => { + let available = entries.iter().any(|(_, command)| !command.is_empty()); + ui.add_enabled_ui(available, |ui| { + let submenu = ui.menu_button(tr(label), |ui| { + for (entry, command) in entries { + // Resource folders hold folders and resources, not graphs + if resources && label == "New" && *command != "folder.create" { + continue; + } + item(ui, entry, command, None, state.enabled(command), action); + } + }); + submenu.response.on_disabled_hover_text(tr("Not available yet")); + }); + } + } + } +} + +pub(super) fn show(ui: &mut egui::Ui, target: &ExplorerTarget, state: &MenuState) -> Option<&'static str> { + ui.set_min_width(220.0); let mut action = None; let resources = target.is_resources(); - if matches!(target, ExplorerTarget::Package { .. } | ExplorerTarget::Folder { .. }) { - ui.menu_button(tr("New"), |ui| { - for (label, command) in menus::EXPLORER_NEW { - if resources && *command != "folder.create" { - continue; - } - - if ui.button(tr(label)).clicked() { - action = Some(*command); - ui.close(); - } + match target { + ExplorerTarget::Package { .. } => rows(ui, menus::EXPLORER_PACKAGE, state, false, &mut action), + ExplorerTarget::Folder { .. } if resources => { + rows(ui, &[ExplorerRow::Sub("New", menus::EXPLORER_NEW), ExplorerRow::Sub("Import", menus::EXPLORER_IMPORT)], state, true, &mut action); + if !target.is_resources_root() { + ui.separator(); + rows( + ui, + &[ExplorerRow::Item("Rename", "folder.rename", Some("F2")), ExplorerRow::Item("Remove", "folder.remove", Some("Delete"))], + state, + true, + &mut action, + ); } - }); - if matches!(target, ExplorerTarget::Package { .. }) || resources { - ui.menu_button(tr("Import"), |ui| { - for (label, command) in menus::EXPLORER_IMPORT { - if ui.button(tr(label)).clicked() { - action = Some(*command); - ui.close(); - } - } - }); } - ui.separator(); - } - if resources { - if !target.is_resources_root() { - for (label, command) in [("Rename", "folder.rename"), ("Remove", "folder.remove")] { - if ui.button(tr(label)).clicked() { - action = Some(command); - ui.close(); - } + ExplorerTarget::Folder { .. } => { + rows(ui, &[ExplorerRow::Sub("New", menus::EXPLORER_NEW), ExplorerRow::Separator], state, false, &mut action); + rows(ui, menus::EXPLORER_FOLDER, state, false, &mut action); + } + ExplorerTarget::Graph { .. } => rows(ui, menus::EXPLORER_GRAPH, state, false, &mut action), + ExplorerTarget::Resource { .. } => { + for (label, command) in menus::EXPLORER_RESOURCE { + item(ui, label, command, None, true, &mut action); } } - return action; - } - - let entries = match target { - ExplorerTarget::Package { .. } => menus::EXPLORER_PACKAGE, - ExplorerTarget::Folder { .. } => menus::EXPLORER_FOLDER, - ExplorerTarget::Graph { .. } => menus::EXPLORER_GRAPH, - ExplorerTarget::Resource { .. } => menus::EXPLORER_RESOURCE, 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 index 57ccb89..73028d2 100644 --- a/crates/ui-egui/src/explorer/explorer_state.rs +++ b/crates/ui-egui/src/explorer/explorer_state.rs @@ -6,4 +6,7 @@ use serde::{Deserialize, Serialize}; pub struct ExplorerState { pub selected: Option<ExplorerTarget>, pub rename: Option<(ExplorerTarget, String)>, + /// The pointer was over the Explorer last frame, so Enter, F2 and Delete act on its selection + #[serde(skip)] + pub hovered: bool, } diff --git a/crates/ui-egui/src/explorer/explorer_tree.rs b/crates/ui-egui/src/explorer/explorer_tree.rs index 54555ec..5c80cbe 100644 --- a/crates/ui-egui/src/explorer/explorer_tree.rs +++ b/crates/ui-egui/src/explorer/explorer_tree.rs @@ -158,7 +158,13 @@ impl ExplorerTree<'_> { 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) { + let outputs = match target { + ExplorerTarget::Graph { index, .. } => package.graphs.get(*index).is_some_and(|graph| graph.function.is_none()), + _ => package.graphs.iter().any(|graph| graph.function.is_none()), + }; + let dependencies = package.dependencies.keys().any(|path| super::actions::is_package_file(path)); + let state = context_menu::MenuState { paste: self.session.explorer_clipboard.is_some(), saved: reload, dependencies, outputs }; + if let Some(command) = context_menu::show(ui, target, &state) { self.action = Some((target.clone(), command)); } }); diff --git a/crates/ui-egui/src/function/function_library_drag.rs b/crates/ui-egui/src/function/function_library_drag.rs index c16f4cf..71a9011 100644 --- a/crates/ui-egui/src/function/function_library_drag.rs +++ b/crates/ui-egui/src/function/function_library_drag.rs @@ -1,4 +1,5 @@ -pub(super) enum FunctionLibraryDrag { +/// A library function being dragged onto a Function canvas +pub(crate) enum FunctionLibraryDrag { Operation(String), Instance { package: String, graph: String }, } diff --git a/crates/ui-egui/src/function/library.rs b/crates/ui-egui/src/function/library.rs index 2bc4ab2..5c6a63a 100644 --- a/crates/ui-egui/src/function/library.rs +++ b/crates/ui-egui/src/function/library.rs @@ -1,78 +1,26 @@ -use super::function_library_drag::FunctionLibraryDrag; -use crate::{MaterialCraftApp, i18n::tr}; -use egui::{Sense, Ui}; +pub(crate) use super::function_library_drag::FunctionLibraryDrag; +use crate::MaterialCraftApp; use materialcraft_engine::FunctionEdit; -pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - let Some(target) = app.function_editor.as_ref().and_then(|editor| editor.command_target()) else { return }; - - 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)) { - 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() - { +/// Add `entry` to the open Function canvas, after its last node +pub(crate) fn add(app: &mut MaterialCraftApp, entry: &FunctionLibraryDrag) { + if 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); + insert(app, &mut editor, entry, at); app.function_editor = Some(editor); } } +/// The native operations the open Function canvas can take (processors that only compute a +/// value cannot sample images) +pub(crate) fn available_operations(app: &MaterialCraftApp) -> Vec<&'static str> { + app.function_editor + .as_ref() + .and_then(|editor| editor.command_target()) + .map(|target| target.available_operations(&app.session).map(|definition| definition.id).collect()) + .unwrap_or_default() +} + pub(super) fn insert(app: &mut MaterialCraftApp, editor: &mut super::FunctionEditor, entry: &FunctionLibraryDrag, at: [f32; 2]) { match entry { FunctionLibraryDrag::Operation(operation) => { diff --git a/crates/ui-egui/src/graph/input.rs b/crates/ui-egui/src/graph/input.rs index b964a73..9e2a5bb 100644 --- a/crates/ui-egui/src/graph/input.rs +++ b/crates/ui-egui/src/graph/input.rs @@ -247,7 +247,7 @@ pub(super) fn handle( { 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})); + app.run("library.add", json!({"entry": payload.0, "at": at})); } // Keys over the canvas diff --git a/crates/ui-egui/src/graph/library_drag.rs b/crates/ui-egui/src/graph/library_drag.rs index 18bfea4..ae9a149 100644 --- a/crates/ui-egui/src/graph/library_drag.rs +++ b/crates/ui-egui/src/graph/library_drag.rs @@ -1,3 +1,3 @@ -/// A library item being dragged onto the canvas +/// A library entry (its `library.tree` id) being dragged onto the canvas #[derive(Clone, Debug)] pub struct LibraryDrag(pub String); diff --git a/crates/ui-egui/src/graph/mod.rs b/crates/ui-egui/src/graph/mod.rs index cde9113..08076b3 100644 --- a/crates/ui-egui/src/graph/mod.rs +++ b/crates/ui-egui/src/graph/mod.rs @@ -30,7 +30,7 @@ pub(crate) use graph_camera::GraphCamera; use graph_drag::GraphDrag; pub use graph_view::GraphView; pub use library_drag::LibraryDrag; -pub use navigation::add_node_near_selection; +pub use navigation::{add_entry_in_view, add_node_near_selection}; use node_search::NodeSearch; pub use node_style::{NODE_W, header_color, node_label, node_rect, port_color}; pub use port_hit::PortHit; diff --git a/crates/ui-egui/src/graph/navigation.rs b/crates/ui-egui/src/graph/navigation.rs index 6769ee4..98033c6 100644 --- a/crates/ui-egui/src/graph/navigation.rs +++ b/crates/ui-egui/src/graph/navigation.rs @@ -9,6 +9,12 @@ pub(super) fn view_center(app: &MaterialCraftApp) -> Pos2 { pos2(c.pan[0] + v.width() * 0.5 / c.zoom, c.pan[1] + v.height() * 0.5 / c.zoom) } +/// Add library entry `id` (a comment, frame, pin or graph instance) in the middle of the view +pub fn add_entry_in_view(app: &mut MaterialCraftApp, id: &str) { + let c = view_center(app); + app.run("library.add", json!({"entry": id, "at": [c.x - NODE_W * 0.5, c.y - 60.0], "snapToGrid": app.ui.prefs.snap_to_grid})); +} + /// Add `def` right of the last selected node (wired from it when it fits), else mid-view pub fn add_node_near_selection(app: &mut MaterialCraftApp, def: &str) { let sel = app.session.selection.last().copied(); diff --git a/crates/ui-egui/src/library.rs b/crates/ui-egui/src/library.rs index 30c51c9..5227ff3 100644 --- a/crates/ui-egui/src/library.rs +++ b/crates/ui-egui/src/library.rs @@ -1,214 +1,485 @@ -//! The library: a category tree on the left, the matching nodes as preview tiles (or a list) on -//! the right, with search. Drag a tile into the graph, or double-click it to add it next to the -//! selection. +//! The library: a category tree on the left (Favorites, then the library's categories and +//! sub-categories), the matching entries as preview tiles (or a list) on the right, with search and +//! filters. Drag an entry into the graph, or double-click it to add it. Entries the open graph +//! can't take, and library nodes MaterialCraft doesn't have yet, are dimmed. + +use std::sync::Arc; use egui::{Color32, Rect, RichText, Sense, Ui, vec2}; use egui_phosphor::regular as icon; +use materialcraft_engine::node_library::CATEGORIES; +use materialcraft_engine::{LibraryCanvas, LibraryEntry, LibraryItem}; use crate::MaterialCraftApp; +use crate::function::library::FunctionLibraryDrag; +use crate::graph::editor_target::EditorTarget; use crate::graph::{LibraryDrag, header_color}; use crate::i18n::tr; use crate::theme::Tokens; -/// The tree: (top level, its sub-categories as full category paths). -fn tree() -> Vec<(&'static str, Vec<&'static str>)> { - let mut out: Vec<(&'static str, Vec<&'static str>)> = Vec::new(); - for (cat, _) in materialcraft_engine::nodes::categories() { - let top = cat.split('/').next().unwrap_or(cat); - match out.iter_mut().find(|(t, _)| *t == top) { - Some((_, subs)) => { - if cat != top { - subs.push(cat); - } - } - None => out.push((top, if cat != top { vec![cat] } else { Vec::new() })), - } +/// The category key of the Favorites row +pub(crate) const FAVORITES: &str = "@favorites"; +/// Function entries that need more nodes than MaterialCraft has are shown in this color +const WARNING: Color32 = Color32::from_rgb(255, 90, 180); + +fn category_icon(category: &str) -> &'static str { + match category { + FAVORITES => icon::STAR, + "Graph items" => icon::FLOW_ARROW, + "Atomic nodes" => icon::CUBE, + "FxMap nodes" => icon::SPARKLE, + "Function nodes" => icon::FUNCTION, + "Texture generators" => icon::DICE_FIVE, + "Texture generators/Noises" => icon::CLOUD, + "Texture generators/Patterns" => icon::CHECKERBOARD, + "Filters" => icon::FADERS, + "Filters/Adjustments" => icon::CIRCLE_HALF_TILT, + "Filters/Blending" | "Material filters/Blending" => icon::INTERSECT, + "Filters/Blurs" => icon::DROP, + "Filters/Channels" => icon::STACK, + "Filters/Effects" => icon::MAGIC_WAND, + "Filters/Normal map" => icon::COMPASS, + "Filters/Tiling" => icon::SQUARES_FOUR, + "Filters/Transforms" | "Material filters/Transforms" => icon::BOUNDING_BOX, + "Material filters" => icon::SPHERE, + "Material filters/1-click" => icon::CURSOR_CLICK, + "Material filters/Effects" => icon::SPARKLE, + "Material filters/PBR utilities" => icon::WRENCH, + "Material filters/Scan processing" => icon::SCAN, + "Mesh-based generators" => icon::POLYGON, + "Mesh-based generators/Mask generators" => icon::CUBE_TRANSPARENT, + "Mesh-based generators/Weathering" => icon::CLOUD_RAIN, + "Mesh-based generators/Utilities" => icon::TOOLBOX, + "Spline & Path tools" | "Spline & Path tools/Spline tools" => icon::BEZIER_CURVE, + "Spline & Path tools/Path tools" => icon::PATH, + "MCF functions" => icon::MATH_OPERATIONS, + "Functions" => icon::WAVE_SINE, + "3D view" => icon::GLOBE, + "3D view/HDRI environments" => icon::GLOBE_HEMISPHERE_WEST, + "3D view/HDRI tools" => icon::SUN, + "PBR materials" => icon::CIRCLE_HALF, + "Values" => icon::HASH, + _ => match category.split('/').next().unwrap_or("") { + "Function nodes" | "MCF functions" | "Values" => icon::ARROW_SQUARE_OUT, + "Functions" => icon::WAVE_SINE, + "PBR materials" => icon::CIRCLE, + _ => icon::FOLDER_SIMPLE, + }, } - out } -fn category_icon(top: &str) -> &'static str { - match top { - "Atomic nodes" => icon::CUBE, - "Graph items" => icon::FLOW_ARROW, - "Texture generators" => icon::DICE_FIVE, - "Filters" => icon::FADERS, - "Material filters" => icon::SPHERE, - _ => icon::FOLDER_OPEN, +/// The graph the library adds to, and which native function operations it can take +pub(crate) struct Here { + canvas: LibraryCanvas, + operations: Vec<&'static str>, +} + +impl Here { + pub(crate) fn of(app: &MaterialCraftApp) -> Here { + match EditorTarget::resolve(app) { + EditorTarget::Material => Here { canvas: LibraryCanvas::Material, operations: Vec::new() }, + EditorTarget::Pattern => Here { canvas: LibraryCanvas::Pattern, operations: Vec::new() }, + EditorTarget::Function => Here { canvas: LibraryCanvas::Function, operations: crate::function::library::available_operations(app) }, + } } + + /// Whether `entry` can go into the open graph now + pub(crate) fn takes(&self, entry: &LibraryEntry) -> bool { + entry.missing.is_none() + && entry.canvas == self.canvas + && match &entry.item { + LibraryItem::Operation { operation } => self.operations.contains(&operation.as_str()), + _ => true, + } + } + + /// Why `entry` can't go into the open graph, when it can't + fn refusal(&self, entry: &LibraryEntry) -> Option<String> { + if let Some(missing) = &entry.missing { + return Some(missing.clone()); + } + if entry.canvas != self.canvas { + return Some( + match entry.canvas { + LibraryCanvas::Material => tr("Open a graph to add this"), + LibraryCanvas::Function => tr("Open a function graph or a processor's function to add this"), + LibraryCanvas::Pattern => tr("Open an FX-Map to add this"), + } + .to_string(), + ); + } + (!self.takes(entry)).then(|| tr("This function can't use this node").to_string()) + } +} + +/// The library's entries for the open session, rebuilt when its packages change +fn entries(app: &MaterialCraftApp, ctx: &egui::Context) -> Arc<Vec<LibraryEntry>> { + type Cached = (Vec<(String, usize)>, Arc<Vec<LibraryEntry>>); + let mut key: Vec<(String, usize)> = vec![(String::new(), Arc::as_ptr(&app.session.library) as usize)]; + key.extend( + app.session.pkg.dependencies.iter().filter(|(path, _)| path.starts_with("sbs://")).map(|(path, package)| (path.clone(), Arc::as_ptr(package) as usize)), + ); + let id = egui::Id::unique("library-entries"); + if let Some((cached, list)) = ctx.data(|data| data.get_temp::<Arc<Cached>>(id)).as_deref() + && *cached == key + { + return list.clone(); + } + let list = Arc::new(app.session.library_entries()); + ctx.data_mut(|data| data.insert_temp(id, Arc::new((key, list.clone())))); + list } pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - match crate::graph::editor_target::EditorTarget::resolve(app) { - crate::graph::editor_target::EditorTarget::Function => { - crate::function::library::show(app, ui); - return; - } - crate::graph::editor_target::EditorTarget::Pattern => { - crate::pattern::library::show(app, ui); - return; - } - crate::graph::editor_target::EditorTarget::Material => {} - } - let tk = Tokens::get(ui.ctx()); + let here = Here::of(app); + let all = entries(app, ui.ctx()); ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; ui.label(RichText::new(icon::MAGNIFYING_GLASS).color(tk.text_dim)); - let r = ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search")).desired_width((ui.available_width() - 56.0).max(40.0))); - crate::widgets::name(&r, egui::Role::SearchInput, "Search the library"); - if crate::widgets::icon_button(ui, icon::SQUARES_FOUR, tr("Icons"), !app.ui.prefs.library_list, 20.0).clicked() { + let hint = match here.canvas { + LibraryCanvas::Function => tr("Search functions"), + LibraryCanvas::Pattern => tr("Search FX-Map nodes"), + LibraryCanvas::Material => tr("Search"), + }; + let width = (ui.available_width() - 5.0 * 24.0).max(40.0); + let response = ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(hint).desired_width(width)); + crate::widgets::name(&response, egui::Role::SearchInput, "Search the library"); + filter_menu(app, ui); + let selected = app.ui.library_selected.clone(); + let favorite = selected.as_ref().is_some_and(|id| app.ui.library_favorites.contains(id)); + let tooltip = if favorite { tr("Remove from Favorites") } else { tr("Add to Favorites") }; + let star = ui.add_enabled_ui(selected.is_some(), |ui| crate::widgets::icon_button(ui, icon::STAR, tooltip, favorite, 22.0)).inner; + if star.clicked() + && let Some(id) = selected + { + toggle_favorite(app, &id); + } + if crate::widgets::icon_button(ui, icon::ARROWS_CLOCKWISE, tr("Reload library"), false, 22.0).clicked() { + app.run("library.reload", serde_json::json!({})); + } + if crate::widgets::icon_button(ui, icon::SQUARES_FOUR, tr("Icons"), !app.ui.prefs.library_list, 22.0).clicked() { app.ui.prefs.library_list = false; } - if crate::widgets::icon_button(ui, icon::LIST, tr("List"), app.ui.prefs.library_list, 20.0).clicked() { + if crate::widgets::icon_button(ui, icon::LIST, tr("List"), app.ui.prefs.library_list, 22.0).clicked() { app.ui.prefs.library_list = true; } }); ui.add_space(2.0); let avail = ui.available_size(); - let tree_w = (avail.x * 0.36).clamp(90.0, 170.0); + // The tree takes what the tiles leave: one column of tiles in a narrow panel + let tree_w = (avail.x * 0.6).clamp(120.0, 230.0).min(avail.x - 92.0).max(80.0); let top_down = egui::Layout::top_down(egui::Align::Min); ui.horizontal_top(|ui| { ui.allocate_ui_with_layout(vec2(tree_w, avail.y), top_down, |ui| { - egui::ScrollArea::vertical().id_salt("lib-tree").auto_shrink([false, false]).show(ui, |ui| category_tree(app, ui)); + egui::ScrollArea::vertical().id_salt("lib-tree").auto_shrink([false, false]).show(ui, |ui| category_tree(app, ui, &all)); }); ui.separator(); ui.allocate_ui_with_layout(vec2(ui.available_width(), avail.y), top_down, |ui| { - egui::ScrollArea::vertical().id_salt("lib-items").auto_shrink([false, false]).show(ui, |ui| items(app, ui)); + egui::ScrollArea::vertical().id_salt("lib-items").auto_shrink([false, false]).show(ui, |ui| items(app, ui, &all, &here)); }); }); } -fn category_tree(app: &mut MaterialCraftApp, ui: &mut Ui) { +fn filter_menu(app: &mut MaterialCraftApp, ui: &mut Ui) { + let filtered = !app.ui.library_show_missing || !app.ui.library_show_other; + let response = crate::widgets::icon_button(ui, icon::FUNNEL, tr("Filter"), filtered, 22.0); + egui::Popup::menu(&response).show(|ui| { + ui.set_min_width(240.0); + ui.checkbox(&mut app.ui.library_show_missing, tr("Show nodes not in MaterialCraft yet")); + ui.checkbox(&mut app.ui.library_show_other, tr("Show nodes for other graph types")); + }); +} + +fn toggle_favorite(app: &mut MaterialCraftApp, id: &str) { + if let Some(index) = app.ui.library_favorites.iter().position(|favorite| favorite == id) { + app.ui.library_favorites.remove(index); + } else if app.ui.library_favorites.len() < 512 { + app.ui.library_favorites.push(id.to_string()); + } +} + +/// One tree row: an optional disclosure triangle, the category icon and its name +fn tree_row(app: &mut MaterialCraftApp, ui: &mut Ui, label: &str, category: &str, depth: usize, open: Option<bool>, count: usize) { let tk = Tokens::get(ui.ctx()); - let mut row = |ui: &mut Ui, text: String, path: &str, indent: f32| { - let on = app.ui.library_category == path; - let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click()); - crate::widgets::name(&resp, egui::Role::TreeItem, &text); - if on { - ui.painter().rect_filled(r, 4.0, tk.row_selected); - } else if resp.hovered() { - ui.painter().rect_filled(r, 4.0, tk.row_hover); + let selected = app.ui.library_category == category; + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click()); + crate::widgets::name(&response, egui::Role::TreeItem, label); + let response = response.on_hover_text(crate::i18n::trf("{name}: {count} entries", &[("name", &label), ("count", &count)])); + if selected { + ui.painter().rect_filled(rect, 4.0, tk.row_selected); + } else if response.hovered() { + ui.painter().rect_filled(rect, 4.0, tk.row_hover); + } + let indent = 4.0 + depth as f32 * 14.0; + let chevron = Rect::from_min_size(rect.min + vec2(indent, 0.0), vec2(14.0, rect.height())); + if let Some(open) = open { + let symbol = if open { icon::CARET_DOWN } else { icon::CARET_RIGHT }; + ui.painter().text(chevron.center(), egui::Align2::CENTER_CENTER, symbol, egui::FontId::proportional(11.0), tk.text_dim); + } + let x = chevron.right() + 2.0; + let color = if selected { tk.text_strong } else { tk.text }; + ui.painter().text(egui::pos2(x + 7.0, rect.center().y), egui::Align2::CENTER_CENTER, category_icon(category), egui::FontId::proportional(13.0), color); + let font = if depth == 0 { 12.0 } else { 11.5 }; + let galley = crate::widgets::elided(ui.painter(), label.to_string(), font, color, rect.right() - x - 22.0); + ui.painter().galley(egui::pos2(x + 18.0, rect.center().y - galley.size().y * 0.5), galley, color); + if response.clicked() { + let on_chevron = response.interact_pointer_pos().is_some_and(|pointer| chevron.contains(pointer)); + if let Some(open) = open + && (on_chevron || !open || selected) + { + set_open(app, category, !open); } - let g = crate::widgets::elided(ui.painter(), text, 11.5, if on { tk.text_strong } else { tk.text }, r.width() - indent - 4.0); - ui.painter().galley(r.left_center() + vec2(indent, -g.size().y * 0.5), g, tk.text); - if resp.clicked() { - app.ui.library_category = path.to_string(); - } - }; - row(ui, format!("{} {}", icon::SQUARES_FOUR, tr("All nodes")), "", 4.0); - for (top, subs) in tree() { - row(ui, format!("{} {}", category_icon(top), tr(top)), top, 4.0); - for sub in subs { - let name = sub.rsplit('/').next().unwrap_or(sub); - row(ui, tr(name).to_string(), sub, 22.0); + if !on_chevron { + app.ui.library_category = category.to_string(); } } } -/// Atomic library entries matching the current filter -fn entries(app: &MaterialCraftApp) -> Vec<(String, String, &'static str)> { - let search = app.ui.library_search.to_ascii_lowercase(); +fn set_open(app: &mut MaterialCraftApp, category: &str, open: bool) { + if open { + app.ui.library_expanded.insert(category.to_string()); + } else { + app.ui.library_expanded.remove(category); + } +} + +/// How many entries a category holds, its sub-categories included +fn count(entries: &[LibraryEntry], category: &str) -> usize { + entries.iter().filter(|entry| entry.category == category || entry.category.strip_prefix(category).is_some_and(|rest| rest.starts_with('/'))).count() +} + +fn category_tree(app: &mut MaterialCraftApp, ui: &mut Ui, entries: &[LibraryEntry]) { + ui.spacing_mut().item_spacing.y = 1.0; + let favorites = app.ui.library_favorites.len(); + tree_row(app, ui, tr("Favorites"), FAVORITES, 0, None, favorites); + for (top, subs) in CATEGORIES { + let open = (!subs.is_empty()).then(|| app.ui.library_expanded.contains(*top)); + tree_row(app, ui, tr(top), top, 0, open, count(entries, top)); + if open == Some(true) { + for sub in *subs { + let category = format!("{top}/{sub}"); + tree_row(app, ui, tr(sub), &category, 1, None, count(entries, &category)); + } + } + } + // Packages can name categories the tree doesn't have; they go last + let mut extra: Vec<&str> = Vec::new(); + for entry in entries { + let top = entry.category.split('/').next().unwrap_or(""); + if !top.is_empty() && !CATEGORIES.iter().any(|(name, _)| *name == top) && !extra.contains(&top) { + extra.push(top); + } + } + for top in extra { + tree_row(app, ui, tr(top), top, 0, None, count(entries, top)); + } +} + +/// Entries matching the selected category, or the search across the whole library, with what the +/// open graph can take first when searching +pub(crate) fn visible<'a>(app: &MaterialCraftApp, entries: &'a [LibraryEntry], here: &Here) -> Vec<&'a LibraryEntry> { + let search = app.ui.library_search.trim().to_lowercase(); let category = app.ui.library_category.as_str(); - let cat = if category == "@package" { "" } else { category }; - let mut out = Vec::new(); - for d in materialcraft_engine::nodes::catalog() { - if d.id == "graph_instance" { - continue; - } - if !(cat.is_empty() || d.category == cat || d.category.starts_with(&format!("{cat}/"))) { - continue; - } - if !(search.is_empty() || d.label.to_ascii_lowercase().contains(&search) || d.id.contains(&search)) { - continue; - } - out.push((d.id.to_string(), d.label.to_string(), d.category)); - } - out + let mut out: Vec<(u8, &LibraryEntry)> = entries + .iter() + .filter(|entry| app.ui.library_show_missing || entry.missing.is_none()) + .filter(|entry| app.ui.library_show_other || entry.canvas == here.canvas) + .filter_map(|entry| { + if !search.is_empty() { + let label = entry.label.to_lowercase(); + let rank = if label == search { + 0 + } else if label.starts_with(&search) { + 1 + } else if label.contains(&search) || entry.id.to_lowercase().contains(&search) { + 2 + } else { + return None; + }; + return Some((rank + if here.takes(entry) { 0 } else { 3 }, entry)); + } + let fits = match category { + "" => true, + FAVORITES => app.ui.library_favorites.contains(&entry.id), + category => entry.category == category || entry.category.strip_prefix(category).is_some_and(|rest| rest.starts_with('/')), + }; + fits.then_some((0, entry)) + }) + .collect(); + out.sort_by_key(|(rank, _)| *rank); + out.into_iter().map(|(_, entry)| entry).collect() } -fn items(app: &mut MaterialCraftApp, ui: &mut Ui) { +fn items(app: &mut MaterialCraftApp, ui: &mut Ui, entries: &[LibraryEntry], here: &Here) { let tk = Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); - let list = entries(app); + let list = visible(app, entries, here); if list.is_empty() { - ui.label(RichText::new(tr("Nothing matches")).color(tk.text_dim)); + let text = match app.ui.library_category.as_str() { + FAVORITES if app.ui.library_search.trim().is_empty() => tr("Select an entry and click the star to add it to Favorites"), + category if app.ui.library_search.trim().is_empty() && !category.is_empty() => tr("Nothing in this category yet"), + _ => tr("Nothing matches"), + }; + ui.label(RichText::new(text).color(tk.text_dim)); return; } let as_list = app.ui.prefs.library_list; - let tile = vec2(78.0, 98.0); + let tile = vec2(78.0, 100.0); let cols = if as_list { 1 } else { ((ui.available_width() + 4.0) / (tile.x + 4.0)).floor().max(1.0) as usize }; let mut add = None; + let mut favorite = None; for chunk in list.chunks(cols) { ui.horizontal(|ui| { ui.spacing_mut().item_spacing = vec2(4.0, 4.0); - for (id, label, cat) in chunk { + for entry in chunk { let size = if as_list { vec2(ui.available_width(), 26.0) } else { tile }; - let (r, resp) = ui.allocate_exact_size(size, Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::ListItem, label); - if resp.hovered() { - ui.painter().rect_filled(r, 6.0, tk.row_hover); + let (rect, response) = ui.allocate_exact_size(size, Sense::click_and_drag()); + crate::widgets::name(&response, egui::Role::ListItem, &entry.label); + let takes = here.takes(entry); + let selected = app.ui.library_selected.as_deref() == Some(entry.id.as_str()); + if selected { + ui.painter().rect_filled(rect, 6.0, tk.row_selected); + } else if response.hovered() { + ui.painter().rect_filled(rect, 6.0, tk.row_hover); } - let tex = app.thumbs.library(&ctx, id); - let img_rect = if as_list { - Rect::from_min_size(r.min + vec2(2.0, 2.0), vec2(22.0, 22.0)) + let fade = if takes { 1.0 } else { 0.4 }; + let image = if as_list { + Rect::from_min_size(rect.min + vec2(2.0, 2.0), vec2(22.0, 22.0)) } else { - Rect::from_min_size(r.min + vec2(5.0, 4.0), vec2(68.0, 68.0)) + Rect::from_min_size(rect.min + vec2(5.0, 4.0), vec2(68.0, 68.0)) }; - match tex { - Some(t) => { - ui.painter().image(t, img_rect, Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE); - } - None => { - ui.painter().rect_filled(img_rect, 4.0, header_color(id).gamma_multiply(0.7)); - ui.painter().text( - img_rect.center(), - egui::Align2::CENTER_CENTER, - icon::CUBE, - egui::FontId::proportional(img_rect.height() * 0.4), - Color32::WHITE, - ); - } - } - // The category color as a strip, like the node headers. - let strip = Rect::from_min_size(img_rect.left_bottom() - vec2(0.0, 3.0), vec2(img_rect.width(), 3.0)); - ui.painter().rect_filled(strip, 0.0, header_color(id)); + preview(app, ui, &ctx, entry, image, fade); + let color = if entry.warning.is_some() { WARNING } else { tk.text }; + let color = color.gamma_multiply(if takes { 1.0 } else { 0.55 }); if as_list { - let g = crate::widgets::elided(ui.painter(), label.clone(), 11.5, tk.text, r.width() - 34.0); - ui.painter().galley(r.left_center() + vec2(30.0, -g.size().y * 0.5), g, tk.text); + let galley = crate::widgets::elided(ui.painter(), entry.label.clone(), 11.5, color, rect.width() - 34.0); + ui.painter().galley(rect.left_center() + vec2(30.0, -galley.size().y * 0.5), galley, color); } else { - let galley = ui.painter().layout(label.clone(), egui::FontId::proportional(10.5), tk.text, tile.x - 4.0); - let pos = egui::pos2(r.center().x - galley.size().x * 0.5, img_rect.bottom() + 3.0); - ui.painter().galley(pos, galley, tk.text); + let galley = ui.painter().layout(entry.label.clone(), egui::FontId::proportional(10.5), color, tile.x - 4.0); + let pos = egui::pos2(rect.center().x - galley.size().x * 0.5, image.bottom() + 3.0); + ui.painter().with_clip_rect(rect).galley(pos, galley, color); } - let resp = resp.on_hover_text(format!("{label}\n{cat}")); - if resp.drag_started() { - egui::DragAndDrop::set_payload(&ctx, LibraryDrag(id.clone())); + if app.ui.library_favorites.contains(&entry.id) { + ui.painter().text(rect.right_top() + vec2(-8.0, 9.0), egui::Align2::CENTER_CENTER, icon::STAR, egui::FontId::proportional(10.0), tk.accent); } - if resp.double_clicked() { - add = Some(id.clone()); + + let mut tip = format!("{}\n{}", entry.label, tr(&entry.category)); + if !entry.description.is_empty() { + tip.push_str(&format!("\n\n{}", entry.description)); } + if let Some(reason) = here.refusal(entry).or_else(|| entry.warning.clone()) { + tip.push_str(&format!("\n\n{reason}")); + } + let response = response.on_hover_text(tip); + if response.clicked() || response.secondary_clicked() { + app.ui.library_selected = Some(entry.id.clone()); + } + if takes && response.drag_started() { + drag(&ctx, entry); + } + if takes && response.double_clicked() { + add = Some((*entry).clone()); + } + response.context_menu(|ui| { + if ui.add_enabled(takes, egui::Button::new(tr("Add to graph"))).clicked() { + add = Some((*entry).clone()); + ui.close(); + } + let label = if app.ui.library_favorites.contains(&entry.id) { tr("Remove from Favorites") } else { tr("Add to Favorites") }; + if ui.button(label).clicked() { + favorite = Some(entry.id.clone()); + ui.close(); + } + }); } }); } - if let Some(id) = add { - crate::graph::add_node_near_selection(app, &id); + if let Some(id) = favorite { + toggle_favorite(app, &id); + } + if let Some(entry) = add { + add_entry(app, &entry); + } +} + +/// The entry's thumbnail: a cooked preview for native nodes, its category's icon otherwise +fn preview(app: &mut MaterialCraftApp, ui: &Ui, ctx: &egui::Context, entry: &LibraryEntry, rect: Rect, fade: f32) { + let painter = ui.painter(); + let (texture, color) = match &entry.item { + LibraryItem::Node { def } if entry.missing.is_none() && def != "dot" => (app.thumbs.library(ctx, def), header_color(def)), + _ => (None, category_color(&entry.category)), + }; + match texture { + Some(texture) => { + painter.image(texture, rect, Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE.gamma_multiply(fade)); + } + None => { + painter.rect_filled(rect, 4.0, color.gamma_multiply(0.7 * fade)); + let symbol = match &entry.item { + LibraryItem::Comment => icon::CHAT_TEXT, + LibraryItem::Frame => icon::FRAME_CORNERS, + LibraryItem::Pin => icon::PUSH_PIN, + LibraryItem::Node { def } if def == "dot" => icon::DOT_OUTLINE, + _ => category_icon(&entry.category), + }; + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + symbol, + egui::FontId::proportional(rect.height() * 0.42), + Color32::WHITE.gamma_multiply(fade), + ); + } + } + let strip = Rect::from_min_size(rect.left_bottom() - vec2(0.0, 3.0), vec2(rect.width(), 3.0)); + painter.rect_filled(strip, 0.0, color.gamma_multiply(fade)); + if entry.missing.is_some() && rect.height() > 30.0 { + let badge = Rect::from_center_size(rect.right_top() + vec2(-9.0, 9.0), vec2(14.0, 14.0)); + painter.circle_filled(badge.center(), 7.0, Color32::from_black_alpha(160)); + painter.text(badge.center(), egui::Align2::CENTER_CENTER, icon::CLOCK, egui::FontId::proportional(10.0), Color32::WHITE); + } +} + +fn category_color(category: &str) -> Color32 { + match category.split('/').next().unwrap_or("") { + "Graph items" | "Atomic nodes" | "FxMap nodes" => Color32::from_rgb(0x5c, 0x62, 0x6e), + "Function nodes" | "Functions" | "MCF functions" | "Values" => Color32::from_rgb(0x4a, 0x5a, 0x8a), + "Texture generators" if category.ends_with("Patterns") => Color32::from_rgb(0xb3, 0x5a, 0x2c), + "Texture generators" => Color32::from_rgb(0xa8, 0x3c, 0x34), + "Filters" => Color32::from_rgb(0x3b, 0x7f, 0x4c), + "Material filters" | "PBR materials" => Color32::from_rgb(0x3a, 0x66, 0xb0), + "Mesh-based generators" => Color32::from_rgb(0x7a, 0x4f, 0x9e), + "Spline & Path tools" => Color32::from_rgb(0x2f, 0x86, 0x8a), + "3D view" => Color32::from_rgb(0x8a, 0x76, 0x2f), + _ => Color32::from_rgb(0x5c, 0x62, 0x6e), + } +} + +fn drag(ctx: &egui::Context, entry: &LibraryEntry) { + match &entry.item { + LibraryItem::Operation { operation } => egui::DragAndDrop::set_payload(ctx, FunctionLibraryDrag::Operation(operation.clone())), + LibraryItem::FunctionInstance { package, graph } => { + egui::DragAndDrop::set_payload(ctx, FunctionLibraryDrag::Instance { package: package.clone(), graph: graph.clone() }) + } + LibraryItem::Pattern { .. } => {} + _ => egui::DragAndDrop::set_payload(ctx, LibraryDrag(entry.id.clone())), + } +} + +/// Add `entry` to the open graph: native nodes next to the selection, the rest in the view +pub(crate) fn add_entry(app: &mut MaterialCraftApp, entry: &LibraryEntry) { + match &entry.item { + LibraryItem::Operation { operation } => crate::function::library::add(app, &FunctionLibraryDrag::Operation(operation.clone())), + LibraryItem::FunctionInstance { package, graph } => { + crate::function::library::add(app, &FunctionLibraryDrag::Instance { package: package.clone(), graph: graph.clone() }) + } + LibraryItem::Pattern { kind } => crate::pattern::library::add(app, *kind), + LibraryItem::Node { def } => crate::graph::add_node_near_selection(app, def), + _ => crate::graph::add_entry_in_view(app, &entry.id), } } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn open_package_graphs_are_explorer_resources_not_library_entries() { - let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default()); - let mut graph = materialcraft_engine::core::Graph::new("Reusable source"); - graph.add_node("output", [0.0; 2]); - app.session.pkg.graphs.push(graph); - app.ui.library_search = "Reusable source".into(); - assert!(entries(&app).is_empty()); - app.ui.library_search.clear(); - app.ui.library_category = "@package".into(); - assert!(entries(&app).iter().any(|entry| entry.0 == "uniform")); - } -} +#[path = "library.test.rs"] +mod tests; diff --git a/crates/ui-egui/src/library.test.rs b/crates/ui-egui/src/library.test.rs new file mode 100644 index 0000000..63e2233 --- /dev/null +++ b/crates/ui-egui/src/library.test.rs @@ -0,0 +1,103 @@ +use super::*; +use materialcraft_engine::core::NodeId; +use serde_json::json; + +fn app() -> MaterialCraftApp { + MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default()) +} + +fn labels(app: &MaterialCraftApp) -> Vec<String> { + let entries = app.session.library_entries(); + visible(app, &entries, &Here::of(app)).into_iter().map(|entry| entry.label.clone()).collect() +} + +#[test] +fn open_package_graphs_are_explorer_resources_not_library_entries() { + let mut app = app(); + let mut graph = materialcraft_engine::core::Graph::new("Reusable source"); + graph.add_node("output", [0.0; 2]); + app.session.pkg.graphs.push(graph); + app.ui.library_search = "Reusable source".into(); + assert!(labels(&app).is_empty()); + app.ui.library_search.clear(); + app.ui.library_category = "@package".into(); + assert!(labels(&app).is_empty(), "an unknown category lists nothing"); + app.ui.library_category.clear(); + assert!(labels(&app).iter().any(|label| label == "Uniform color")); +} + +#[test] +fn categories_include_their_sub_categories_and_favorites_follow_the_star() { + let mut app = app(); + app.ui.library_category = "Filters".into(); + let filters = labels(&app); + app.ui.library_category = "Filters/Blurs".into(); + let blurs = labels(&app); + assert!(!blurs.is_empty() && blurs.len() < filters.len()); + assert!(blurs.iter().all(|label| filters.contains(label))); + + app.ui.library_category = FAVORITES.into(); + assert!(labels(&app).is_empty()); + toggle_favorite(&mut app, "node:blur"); + toggle_favorite(&mut app, "sbs://functions.sbs#Functions/Math/Pi"); + assert_eq!(labels(&app), ["Blur", "Pi"]); + toggle_favorite(&mut app, "node:blur"); + assert_eq!(labels(&app), ["Pi"]); +} + +#[test] +fn search_puts_what_the_open_graph_takes_first_and_filters_hide_the_rest() { + let mut app = app(); + app.ui.library_search = "blur".into(); + let found = labels(&app); + assert_eq!(found.first().map(String::as_str), Some("Blur")); + let entries = app.session.library_entries(); + let here = Here::of(&app); + let shown = visible(&app, &entries, &here); + let first_refused = shown.iter().position(|entry| !here.takes(entry)).unwrap(); + assert!(shown[first_refused..].iter().all(|entry| !here.takes(entry)), "addable entries come first"); + + app.ui.library_show_missing = false; + app.ui.library_show_other = false; + let entries = app.session.library_entries(); + assert!(visible(&app, &entries, &here).iter().all(|entry| here.takes(entry))); +} + +#[test] +fn processor_functions_take_operations_their_canvas_allows() { + let mut app = app(); + let owner = NodeId(app.run("graph.node.add", json!({"def": "value_processor"})).unwrap()["id"].as_u64().unwrap()); + app.function_editor = Some(crate::function::FunctionEditor::new(app.session.graph, owner, crate::function::FunctionTarget::Parameter("function".into()))); + let here = Here::of(&app); + let entries = app.session.library_entries(); + let find = |id: &str| entries.iter().find(|entry| entry.id == id).unwrap(); + assert!(here.takes(find("function:add"))); + assert!(here.takes(find("sbs://functions.sbs#Functions/Math/Pi"))); + assert!(!here.takes(find("function:samplecol")), "value processors can't sample images"); + assert!(!here.takes(find("node:blur"))); + assert!(here.refusal(find("node:blur")).is_some()); +} + +#[test] +fn every_tree_category_has_an_icon_and_double_click_adds() { + for (top, subs) in CATEGORIES { + assert_ne!(category_icon(top), icon::FOLDER_SIMPLE, "{top}"); + for sub in *subs { + assert_ne!(category_icon(&format!("{top}/{sub}")), icon::FOLDER_SIMPLE, "{top}/{sub}"); + } + } + + let mut app = app(); + let before = app.session.graph().unwrap().nodes.len(); + let entries = app.session.library_entries(); + for id in ["node:blur", "sbs://3d_perlin_noise.sbs#3D_perlin_noise"] { + let entry = entries.iter().find(|entry| entry.id == id).unwrap(); + if Here::of(&app).takes(entry) { + add_entry(&mut app, entry); + } + } + assert_eq!(app.session.graph().unwrap().nodes.len(), before + 1, "only the available entry is added"); + let comments = app.session.graph().unwrap().comments.len(); + add_entry(&mut app, entries.iter().find(|entry| entry.id == "item:comment").unwrap()); + assert_eq!(app.session.graph().unwrap().comments.len(), comments + 1); +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index cdec828..cc70356 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -27,19 +27,67 @@ 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_IMPORT: &[(&str, &str)] = &[("Bitmap", "file.importBitmap"), ("Vector graphics", "file.importVector")]; pub(crate) const EXPLORER_RESOURCE: &[(&str, &str)] = &[("Add to graph", "graph.resource.add")]; -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"), +/// A row of an Explorer context menu +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum ExplorerRow { + /// A label, the action id (empty: not available yet) and the shortcut shown beside it + Item(&'static str, &'static str, Option<&'static str>), + /// A submenu of (label, action id); an empty id is not available yet + Sub(&'static str, &'static [(&'static str, &'static str)]), + Separator, +} +use ExplorerRow::{Item, Separator, Sub}; + +/// Linking keeps a resource outside the package; MaterialCraft only embeds resources so far +pub(crate) const EXPLORER_LINK: &[(&str, &str)] = &[("Bitmap", ""), ("Vector graphics", "")]; +pub(crate) const EXPLORER_SEND_TO: &[(&str, &str)] = &[("TextureCraft", "file.sendToTextureCraft")]; +/// Explorer actions that wrap engine commands or the operating system: computing every output, +/// showing the package file and opening the packages it depends on +pub(crate) const EXPLORER_COMPUTE: &str = "ui.explorer.computeOutputs"; +pub(crate) const EXPLORER_SHOW_IN_FOLDER: &str = "ui.explorer.showInFolder"; +pub(crate) const EXPLORER_OPEN_DEPENDENCIES: &str = "ui.explorer.openDependencies"; +pub(crate) const EXPLORER_VIEW_OUTPUTS: &str = "ui.explorer.viewOutputs"; +pub(crate) const EXPLORER_EXPORT_OUTPUTS: &str = "ui.explorer.exportOutputs"; +pub(crate) const EXPLORER_PACKAGE: &[ExplorerRow] = &[ + Sub("New", EXPLORER_NEW), + Sub("Import", EXPLORER_IMPORT), + Sub("Link", EXPLORER_LINK), + Separator, + Item("Reload", "file.reload", None), + Item("Save", "file.save", Some("Ctrl+S")), + Item("Save as...", "file.saveAs", Some("Ctrl+Shift+S")), + Item("Save a copy as...", "file.saveCopyAs", None), + Separator, + Item("Export material...", "file.exportMaterial", None), + Item("Export with dependencies...", "", None), + Sub("Send to", EXPLORER_SEND_TO), + Separator, + Item("Copy", "explorer.copy", None), + Item("Paste", "explorer.paste", None), + Item("Close package", "package.close", None), + Separator, + Item("Compute outputs", EXPLORER_COMPUTE, None), + Item("Show in folder...", EXPLORER_SHOW_IN_FOLDER, None), + Item("Dependency manager...", "", None), + Item("Open dependencies", EXPLORER_OPEN_DEPENDENCIES, None), +]; +pub(crate) const EXPLORER_FOLDER: &[ExplorerRow] = &[ + Item("Copy", "explorer.copy", None), + Item("Paste", "explorer.paste", None), + Item("Remove", "folder.remove", Some("Delete")), + Item("Rename", "folder.rename", Some("F2")), +]; +pub(crate) const EXPLORER_GRAPH: &[ExplorerRow] = &[ + Item("Open", "graph.open", Some("Enter")), + Item("Copy", "explorer.copy", None), + Item("Paste", "explorer.paste", None), + Item("Remove", "graph.delete", Some("Delete")), + Item("Rename", "graph.rename", Some("F2")), + Separator, + Item("View outputs in 3D view", EXPLORER_VIEW_OUTPUTS, None), + Item("Compute outputs", EXPLORER_COMPUTE, None), + Item("Export outputs...", EXPLORER_EXPORT_OUTPUTS, None), ]; -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] = &[ @@ -350,6 +398,9 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { } let modality = Modality::capture(app, ctx); + if !modality.is_blocked() && crate::explorer::shortcuts(app, ctx) { + return; + } if !modality.is_blocked() { crate::graph::wire_actions::shortcuts(app, ctx); } @@ -590,6 +641,50 @@ mod tests { assert!(app.ui.windows.export); } + #[test] + fn explorer_keys_act_on_its_selection_only_while_hovered() { + use crate::explorer::ExplorerTarget; + let mut app = app(); + app.run("file.new", serde_json::json!({"template": "empty", "name": "Second"})).unwrap(); + let graphs = app.session.pkg.graphs.len(); + let document = app.session.document_id; + app.ui.explorer.selected = Some(ExplorerTarget::Graph { document, index: 0 }); + + // Away from the Explorer, F2 and Delete keep their graph shortcuts + dispatched(egui::Key::F2, egui::Modifiers::NONE, &mut app); + assert!(app.ui.explorer.rename.is_none()); + + app.ui.explorer.hovered = true; + dispatched(egui::Key::Enter, egui::Modifiers::NONE, &mut app); + assert_eq!(app.session.graph, 0); + dispatched(egui::Key::F2, egui::Modifiers::NONE, &mut app); + assert!(matches!(app.ui.explorer.rename, Some((ExplorerTarget::Graph { index: 0, .. }, _)))); + app.ui.explorer.rename = None; + dispatched(egui::Key::Delete, egui::Modifiers::NONE, &mut app); + assert_eq!(app.session.pkg.graphs.len(), graphs - 1); + dispatched(egui::Key::Z, egui::Modifiers::COMMAND, &mut app); + assert_eq!(app.session.pkg.graphs.len(), graphs, "removing a graph undoes"); + } + + #[test] + fn explorer_menus_name_only_actions_that_exist() { + for rows in [EXPLORER_PACKAGE, EXPLORER_FOLDER, EXPLORER_GRAPH] { + for row in rows { + let ids: Vec<&str> = match row { + ExplorerRow::Item(_, id, _) => vec![id], + ExplorerRow::Sub(_, entries) => entries.iter().map(|(_, id)| *id).collect(), + ExplorerRow::Separator => Vec::new(), + }; + for id in ids.into_iter().filter(|id| !id.is_empty()) { + assert!(implemented(id) || id.starts_with("ui.explorer.") || id.starts_with("explorer."), "{id}"); + } + if let ExplorerRow::Item(label, _, Some(shortcut)) = row { + assert!(parse_shortcut(shortcut).is_some(), "{label}: {shortcut}"); + } + } + } + } + #[test] fn the_shortcuts_list_leaves_shortcuts_running() { let mut app = app(); diff --git a/crates/ui-egui/src/pattern/library.rs b/crates/ui-egui/src/pattern/library.rs index b7b1d1e..ed76b92 100644 --- a/crates/ui-egui/src/pattern/library.rs +++ b/crates/ui-egui/src/pattern/library.rs @@ -1,17 +1,12 @@ -use egui::Ui; use materialcraft_engine::core::PatternNodeKind; -use crate::{MaterialCraftApp, i18n::tr}; +use crate::MaterialCraftApp; -pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - ui.label(tr("FX-Map nodes")); - for kind in PatternNodeKind::ALL { - if ui.selectable_label(false, tr(kind.label())).double_clicked() - && let Some(mut editor) = app.pattern_editor.take() - { - editor.menu_at = (editor.pan + app.graph.view.size() * 0.5 / editor.zoom).to_pos2(); - editor.edit(app, materialcraft_engine::PatternEdit::Add { kind, at: editor.menu_at.into(), snap: app.ui.prefs.snap_to_grid }, false); - app.pattern_editor = Some(editor); - } +/// Add an FX-Map node of `kind` in the middle of the open FX-Map canvas +pub(crate) fn add(app: &mut MaterialCraftApp, kind: PatternNodeKind) { + if let Some(mut editor) = app.pattern_editor.take() { + editor.menu_at = (editor.pan + app.graph.view.size() * 0.5 / editor.zoom).to_pos2(); + editor.edit(app, materialcraft_engine::PatternEdit::Add { kind, at: editor.menu_at.into(), snap: app.ui.prefs.snap_to_grid }, false); + app.pattern_editor = Some(editor); } } diff --git a/crates/ui-egui/src/state/ui_state.rs b/crates/ui-egui/src/state/ui_state.rs index 93ffb92..8ec7965 100644 --- a/crates/ui-egui/src/state/ui_state.rs +++ b/crates/ui-egui/src/state/ui_state.rs @@ -16,6 +16,16 @@ pub struct UiState { /// Library: the selected category path ("" = all) and the search text pub library_category: String, pub library_search: String, + /// Library entry ids starred as Favorites, in the order they were added + pub library_favorites: Vec<String>, + /// Expanded library categories + pub library_expanded: std::collections::BTreeSet<String>, + /// Library filters: entries MaterialCraft doesn't have yet, and entries for other graph types + pub library_show_missing: bool, + pub library_show_other: bool, + /// The library entry last clicked + #[serde(skip)] + pub library_selected: Option<String>, /// Recently opened or saved packages, newest first pub recent: Vec<String>, /// New graph dialog fields @@ -46,6 +56,11 @@ impl Default for UiState { image_camera: ImageCamera::default(), library_category: String::new(), library_search: String::new(), + library_favorites: Vec::new(), + library_expanded: Default::default(), + library_show_missing: true, + library_show_other: true, + library_selected: None, recent: Vec::new(), new_graph_kind: materialcraft_engine::core::GraphKind::Material, new_graph_template: "pbr".into(), diff --git a/crates/ui-egui/tests/snapshot.rs b/crates/ui-egui/tests/snapshot.rs index 088f97c..afede05 100644 --- a/crates/ui-egui/tests/snapshot.rs +++ b/crates/ui-egui/tests/snapshot.rs @@ -13,6 +13,9 @@ mod function_variables; #[path = "snapshot/embedded_graphs.rs"] mod embedded_graphs; +#[path = "snapshot/library.rs"] +mod library; + use std::time::Duration; use egui::vec2; @@ -647,7 +650,9 @@ fn explorer_open_targets_the_clicked_graph() { settle(&mut h, 5); h.get_by_label("Export target").click_secondary(); settle(&mut h, 3); - h.get(By::new().role(egui::accesskit::Role::Button).label("Open")).click(); + // Explorer menu items name their shortcut after the label + let open = format!("Open {}", materialcraft_ui_egui::menus::shortcut_label(&h.ctx, "Enter")); + 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); diff --git a/crates/ui-egui/tests/snapshot/explorer.rs b/crates/ui-egui/tests/snapshot/explorer.rs index 2a6ac4b..d4ae9c7 100644 --- a/crates/ui-egui/tests/snapshot/explorer.rs +++ b/crates/ui-egui/tests/snapshot/explorer.rs @@ -13,7 +13,7 @@ fn explorer_can_close_the_last_package_and_all_packages() { settle(&mut harness, 4); harness.get(By::new().role(Role::TreeItem).label("Untitled package")).click_secondary(); settle(&mut harness, 3); - harness.get(By::new().role(Role::Button).label("Close")).click(); + harness.get(By::new().role(Role::Button).label("Close package")).click(); settle(&mut harness, 4); assert!(harness.state().session.open_packages().is_empty()); @@ -86,8 +86,8 @@ fn explorer_empty_packages_have_no_disclosure() { harness.get(By::new().role(Role::TreeItem).label("Empty package")).click_secondary(); settle(&mut harness, 3); - for label in ["Import", "New", "Save As", "Close"] { - assert!(harness.query(By::new().role(Role::Button).label(label)).is_some()); + for label in ["Import", "New", "Save as...", "Close package"] { + assert!(harness.query_all(By::new().role(Role::Button).label_contains(label)).next().is_some(), "{label}"); } harness.key_press(egui::Key::Escape); settle(&mut harness, 3); @@ -357,18 +357,58 @@ fn explorer_folder_tree_and_context_menus() { for (label, expected, screenshot) in [ ("Tools", vec!["New", "Copy", "Paste", "Rename", "Remove"], "explorer-folder-menu"), - ("Explorer menus*", vec!["Import", "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"), + ( + "Explorer menus*", + vec![ + "New", + "Import", + "Link", + "Reload", + "Save", + "Save as...", + "Save a copy as...", + "Export material...", + "Export with dependencies...", + "Send to", + "Copy", + "Paste", + "Close package", + "Compute outputs", + "Show in folder...", + "Dependency manager...", + "Open dependencies", + ], + "explorer-package-menu", + ), + ( + "Helper", + vec!["Open", "Copy", "Paste", "Remove", "Rename", "View outputs in 3D view", "Compute outputs", "Export outputs..."], + "explorer-function-menu", + ), + ( + "Surface", + vec!["Open", "Copy", "Paste", "Remove", "Rename", "View outputs in 3D view", "Compute outputs", "Export outputs..."], + "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}"); + assert!(harness.query_all(By::new().label_contains(label)).next().is_some(), "{screenshot}: {label}"); } - for label in ["Duplicate", "Delete", "Link"] { + for label in ["Duplicate", "Delete"] { assert!(harness.query(button(label)).is_none(), "{screenshot}: unexpected {label}"); } + if screenshot == "explorer-package-menu" { + for unavailable in ["Export with dependencies...", "Dependency manager...", "Show in folder..."] { + assert!(harness.get(button(unavailable)).accesskit_node().is_disabled(), "{unavailable}"); + } + } + // A Function Graph has no image outputs to view, compute or export + if matches!(screenshot, "explorer-function-menu" | "explorer-graph-menu") { + let disabled = harness.get(button("Compute outputs")).accesskit_node().is_disabled(); + assert_eq!(disabled, screenshot == "explorer-function-menu", "{screenshot}"); + } assert!(harness.get(button("Paste")).accesskit_node().is_disabled()); diff --git a/crates/ui-egui/tests/snapshot/library.rs b/crates/ui-egui/tests/snapshot/library.rs new file mode 100644 index 0000000..30e60b0 --- /dev/null +++ b/crates/ui-egui/tests/snapshot/library.rs @@ -0,0 +1,119 @@ +use super::{By, MaterialCraftApp, Queryable, UiState, harness, save, settle, vec2}; +use egui::accesskit::Role; + +fn tree(label: &str) -> By<'_> { + By::new().role(Role::TreeItem).label(label) +} + +fn tile(label: &str) -> By<'_> { + By::new().role(Role::ListItem).label(label) +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn library_tree_shows_every_category_and_adds_what_the_graph_takes() { + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + let app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 6); + + for label in [ + "Favorites", + "Graph items", + "Atomic nodes", + "FxMap nodes", + "Function nodes", + "Texture generators", + "Filters", + "Material filters", + "Mesh-based generators", + "Spline & Path tools", + "MCF functions", + "Functions", + "3D view", + "PBR materials", + "Values", + ] { + assert!(harness.query(tree(label)).is_some(), "{label}"); + } + assert!(harness.query(tree("SDF functions")).is_none(), "the category is MCF functions now"); + + // Graph items, then the atomic nodes with their previews + harness.get(tree("Graph items")).click(); + settle(&mut harness, 3); + for label in ["Comment", "Frame", "Pin", "Dot node"] { + assert!(harness.query(tile(label)).is_some(), "{label}"); + } + harness.get(tree("Atomic nodes")).click(); + settle(&mut harness, 12); + for label in ["Blend", "Blur", "Levels", "Output", "Input color"] { + assert!(harness.query(tile(label)).is_some(), "{label}"); + } + save(&mut harness, &directory, "library-atomic-nodes"); + + // Dragging a tile adds it where it drops + let before = harness.state().session.graph().unwrap().nodes.len(); + let start = harness.get(tile("Blur")).rect().center(); + let end = harness.state().graph.view.center() + vec2(120.0, 80.0); + 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(&mut harness, 5); + let graph = harness.state().session.graph().unwrap(); + assert_eq!(graph.nodes.len(), before + 1); + assert_eq!(graph.nodes.last().unwrap().def, "blur"); + + // Opening a category shows its sub-categories; library nodes MaterialCraft lacks are dimmed + harness.get(tree("Texture generators")).click(); + settle(&mut harness, 3); + harness.get(tree("Noises")).click(); + settle(&mut harness, 4); + assert!(harness.query(tile("3D Perlin Noise")).is_some()); + save(&mut harness, &directory, "library-texture-generators-noises"); + + for (top, subs) in [ + ("Filters", &["Adjustments", "Blending", "Blurs", "Channels", "Effects", "Normal map", "Tiling", "Transforms"][..]), + ("Function nodes", &["Constant", "Vector", "Variables", "Samplers", "Cast", "Operator", "Logical", "Comparison", "Function", "Control"][..]), + ("MCF functions", &["Primitives", "Operators", "Transforms"][..]), + ("PBR materials", &["Bricks", "Concrete", "Fabric", "Ground", "Metal", "Paper", "Pavement", "Tiles", "Wood", "Stone"][..]), + ] { + harness.get(tree(top)).click(); + settle(&mut harness, 3); + for sub in subs { + assert!(harness.query_all(tree(sub)).next().is_some(), "{top}/{sub}"); + } + if top == "PBR materials" { + save(&mut harness, &directory, "library-categories-open"); + } + // Clicking the selected, open category closes it again + harness.get(tree(top)).click(); + settle(&mut harness, 2); + assert!(!harness.state().ui.library_expanded.contains(top), "{top}"); + } + + // A selected tile goes into Favorites with the star + harness.get(tree("Atomic nodes")).click(); + settle(&mut harness, 3); + harness.get(tile("Blend")).click(); + settle(&mut harness, 2); + harness.get(By::new().role(Role::Button).label("Add to Favorites")).click(); + settle(&mut harness, 2); + harness.get(tree("Favorites")).click(); + settle(&mut harness, 3); + assert!(harness.query(tile("Blend")).is_some()); + assert_eq!(harness.state().ui.library_favorites, ["node:blend"]); + save(&mut harness, &directory, "library-favorites"); + + // Search finds entries across the whole library, what the graph takes first + harness.state_mut().ui.library_search = "noise".into(); + settle(&mut harness, 4); + assert!(harness.query(tile("3D Perlin Noise")).is_some()); + save(&mut harness, &directory, "library-search"); +} diff --git a/docs/architecture.md b/docs/architecture.md index 7f2e62c..6b184fa 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -104,6 +104,14 @@ Resource paths resolve beside their owning package: `resources/tile.png` in `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. +Every session loads the whole library folder once per process (`engine::node_library`, cached +until `library.reload`). Each `.sbs` there is either a layout or a package of graphs. A layout's +titled frames ("Filters - Blurs") name Library categories and place the nodes inside them +(`formats::sbs::read_layout`); `assets/sbs/all_nodes.sbs` lays out the reference category tree, +with every library node it instances. Packages join every session's dependencies, so their graphs +can be instanced, and a placed instance becomes available as soon as its package is in the folder. +Installed and browser builds embed `all_nodes.sbs` and `functions.sbs`. + 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 diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 2276d21..22ec6ec 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -113,6 +113,22 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg | `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, `heightScale` (how far the height output raises the mesh, in mesh radii) and `heightLevel` (the height that stays on the surface; 0 = the relief rises out of it), `normalYFlip` (interpret DirectX normal maps; default false/OpenGL), `transparency` (see through where the alpha is below one: the opacity output, else the base color's alpha), `alphaView` (show the alpha channel) | | `view.3d.loadMesh` | `{path}` shows an OBJ, glTF or GLB mesh (scene `custom`) | | `library.list` | `{filter?, category?}`: every node with ports and parameters | +| `library.tree` | `{filter?, category? (Top or Top/Sub), canvas? (material\|function\|pattern)}`: the Library panel's category tree and its entries. Each entry has `id`, `label`, `category`, `type` (`node`, `comment`, `frame`, `pin`, `instance`, `operation`, `functionInstance`, `pattern`, `bitmap`), the `canvas` that takes it, `missing` when MaterialCraft lacks the library package it needs, and `warning` when it can be added but is incomplete | +| `library.add` | `{entry, at?, snapToGrid?, function?: FunctionGraphTarget}`: add a `library.tree` entry to the open graph (function entries to a Function canvas; FX-Map nodes use `graph.pattern.edit`). Entries with `missing` refuse with the reason | +| `library.reload` | `{}`: read the SBS library folder again | +| `graph.cook` | `{full?, graph?: index}`: cook now and return per-node timings and errors; another material graph of the package cooks at full size into the cache | + +## Node library + +Every `.sbs` file in the library folder (`assets/sbs`, or `MATERIALCRAFT_SBS_DIR`; installed and +browser builds use the bundled `all_nodes.sbs` and `functions.sbs`) loads once per process. A +package whose graphs group nodes in titled frames lays the library out: a frame titled +`Top - Sub` (or `Top`) is a category of the Library tree, and every node inside it becomes an +entry there. Function frames name only the sub-category: under Function nodes when they hold +native operations, under Functions otherwise. The older category name "SDF functions" reads as +MCF functions. Other packages lend their graphs: a placed instance becomes available as soon as +its package is in the folder, and unplaced graphs go to their attribute category, or Functions +for function graphs. ## Linked packages diff --git a/docs/gaps.md b/docs/gaps.md index 61dfd61..32d3135 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -14,9 +14,20 @@ Full numerical equivalence and importing the converted library in the reference 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. +Explorer now displays native SBS folders, including empty groups and nested resources. Its +package, folder and graph context menus follow the reference layout: creation, import, save, +export material, send to TextureCraft, copy/paste, close, compute outputs, show in folder, open +dependencies, view outputs in 3D view and export outputs. Enter, F2 and Delete act on the Explorer +selection while the pointer is over it. Linking resources, exporting with dependencies and the +dependency manager are listed but disabled until MaterialCraft has them; copy and paste have no +Explorer shortcut yet. + +The Library panel shows the reference category tree (Favorites, Graph items, Atomic nodes, FxMap +nodes, Function nodes, Texture generators, Filters, Material filters, Mesh-based generators, Spline & +Path tools, MCF functions, Functions, 3D view, PBR materials, Values) filled from the bundled +library layout. 495 of its 787 entries are listed but dimmed: MaterialCraft has no package +for them yet, and each becomes available once its package is in the library folder. MCF functions +and Values have no entries yet; HDRI environment images are not bundled. > **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