diff --git a/Cargo.lock b/Cargo.lock index f6d7264..69db9d5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2463,6 +2463,7 @@ dependencies = [ name = "materialcraft-render" version = "0.1.2" dependencies = [ + "materialcraft-core", "materialcraft-geom", "materialcraft-image", "rayon", diff --git a/crates/core/src/component_usage.rs b/crates/core/src/component_usage.rs new file mode 100644 index 0000000..5c0c6ac --- /dev/null +++ b/crates/core/src/component_usage.rs @@ -0,0 +1,81 @@ +/// Input/output semantics shared by node properties, SBS and texture exports +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ComponentUsage { + pub id: &'static str, + pub label: &'static str, +} + +impl ComponentUsage { + pub const ANY: Self = Self { id: "any", label: "Any" }; + pub const ANY_INDEX: u32 = 9; + + // Existing indices are saved in documents; append new entries without reordering + pub const ALL: &'static [Self] = &[ + Self { id: "baseColor", label: "Base color" }, + Self { id: "normal", label: "Normal" }, + Self { id: "roughness", label: "Roughness" }, + Self { id: "metallic", label: "Metallic" }, + Self { id: "height", label: "Height" }, + Self { id: "ambientOcclusion", label: "Ambient occlusion" }, + Self { id: "emissive", label: "Emissive" }, + Self { id: "opacity", label: "Opacity" }, + Self { id: "specular", label: "Specular" }, + Self::ANY, + Self { id: "diffuse", label: "Diffuse" }, + Self { id: "glossiness", label: "Glossiness" }, + Self { id: "specularLevel", label: "Specular level" }, + Self { id: "specularEdgeColor", label: "Specular edge color" }, + Self { id: "anisotropyLevel", label: "Anisotropy level" }, + Self { id: "anisotropyAngle", label: "Anisotropy angle" }, + Self { id: "IOR", label: "Index of refraction" }, + Self { id: "scattering", label: "Scattering" }, + Self { id: "scatteringColor", label: "Scattering color" }, + Self { id: "scatteringDistance", label: "Scattering distance" }, + Self { id: "scatteringDistanceScale", label: "Scattering distance scale" }, + Self { id: "transmissive", label: "Transmissive" }, + Self { id: "translucency", label: "Translucency" }, + Self { id: "absorptionColor", label: "Absorption color" }, + Self { id: "absorptionDistance", label: "Absorption distance" }, + Self { id: "coatOpacity", label: "Coat opacity" }, + Self { id: "coatColor", label: "Coat color" }, + Self { id: "coatRoughness", label: "Coat roughness" }, + Self { id: "coatSpecularLevel", label: "Coat specular level" }, + Self { id: "coatNormal", label: "Coat normal" }, + Self { id: "coatIOR", label: "Coat index of refraction" }, + Self { id: "sheenOpacity", label: "Sheen opacity" }, + Self { id: "sheenColor", label: "Sheen color" }, + Self { id: "sheenRoughness", label: "Sheen roughness" }, + Self { id: "reflection", label: "Reflection" }, + Self { id: "displacement", label: "Displacement" }, + Self { id: "ambient", label: "Ambient" }, + Self { id: "mask", label: "Mask" }, + Self { id: "blendingmask", label: "Blending mask" }, + Self { id: "bump", label: "Bump" }, + Self { id: "user0", label: "User 0" }, + Self { id: "user1", label: "User 1" }, + Self { id: "user2", label: "User 2" }, + Self { id: "user3", label: "User 3" }, + Self { id: "user4", label: "User 4" }, + Self { id: "user5", label: "User 5" }, + Self { id: "user6", label: "User 6" }, + Self { id: "user7", label: "User 7" }, + ]; + + pub const LABELS: &'static [&'static str] = &{ + let mut labels = [""; Self::ALL.len()]; + let mut index = 0; + while index < labels.len() { + labels[index] = Self::ALL[index].label; + index += 1; + } + labels + }; + + pub fn from_index(index: u32) -> Self { + Self::ALL.get(index as usize).copied().unwrap_or(Self::ANY) + } + + pub fn index(id: &str) -> u32 { + Self::ALL.iter().position(|usage| usage.id.eq_ignore_ascii_case(id.trim())).map_or(Self::ANY_INDEX, |index| index as u32) + } +} diff --git a/crates/core/src/graph.rs b/crates/core/src/graph.rs index be25cac..b54d43e 100644 --- a/crates/core/src/graph.rs +++ b/crates/core/src/graph.rs @@ -138,58 +138,17 @@ impl Graph { } pub fn topo_order(&self) -> Vec { - let mut indeg: BTreeMap = self.nodes.iter().map(|n| (n.id, 0)).collect(); - for c in &self.connections { - if let Some(d) = indeg.get_mut(&c.to) - && self.nodes.iter().any(|n| n.id == c.from) - { - *d += 1; - } - } - let mut ready: Vec = indeg.iter().filter(|(_, d)| **d == 0).map(|(id, _)| *id).collect(); - let mut out = Vec::with_capacity(self.nodes.len()); - while let Some(n) = ready.pop() { - out.push(n); - for c in self.connections.iter().filter(|c| c.from == n) { - if let Some(d) = indeg.get_mut(&c.to) { - *d = d.saturating_sub(1); - if *d == 0 { - ready.push(c.to); - } - } - } - } - out + crate::GraphIndex::new(self).topo_order() } /// Every node upstream of `id` (not including it) pub fn upstream(&self, id: NodeId) -> Vec { - let mut out = Vec::new(); - let mut stack = vec![id]; - while let Some(n) = stack.pop() { - for c in self.connections.iter().filter(|c| c.to == n) { - if !out.contains(&c.from) { - out.push(c.from); - stack.push(c.from); - } - } - } - out + crate::GraphIndex::new(self).upstream(id) } /// Every node downstream of `id` (not including it) pub fn downstream(&self, id: NodeId) -> Vec { - let mut out = Vec::new(); - let mut stack = vec![id]; - while let Some(n) = stack.pop() { - for c in self.connections.iter().filter(|c| c.from == n) { - if !out.contains(&c.to) { - out.push(c.to); - stack.push(c.to); - } - } - } - out + crate::GraphIndex::new(self).downstream(id) } /// The value of exposed input `id` (its default when unset) diff --git a/crates/core/src/graph_index.rs b/crates/core/src/graph_index.rs new file mode 100644 index 0000000..56354b1 --- /dev/null +++ b/crates/core/src/graph_index.rs @@ -0,0 +1,133 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use crate::{Connection, Graph, Node, NodeId}; + +/// Borrowed lookups for one graph operation, rebuilt when the graph changes +pub struct GraphIndex<'a> { + nodes: BTreeMap, + incoming: BTreeMap>, + outgoing: BTreeMap>, +} + +impl<'a> GraphIndex<'a> { + pub fn new(graph: &'a Graph) -> Self { + let mut nodes = BTreeMap::new(); + for node in &graph.nodes { + nodes.entry(node.id).or_insert(node); + } + + let mut incoming: BTreeMap<_, Vec<_>> = BTreeMap::new(); + let mut outgoing: BTreeMap<_, Vec<_>> = BTreeMap::new(); + for connection in &graph.connections { + incoming.entry(connection.to).or_default().push(connection); + outgoing.entry(connection.from).or_default().push(connection); + } + + Self { nodes, incoming, outgoing } + } + + pub fn node(&self, id: NodeId) -> Option<&'a Node> { + self.nodes.get(&id).copied() + } + + pub fn incoming(&self, id: NodeId) -> &[&'a Connection] { + self.incoming.get(&id).map_or(&[], Vec::as_slice) + } + + pub fn input_of(&self, id: NodeId, port: &str) -> Option<&'a Connection> { + self.incoming(id).iter().copied().find(|connection| connection.to_port == port) + } + + pub fn topo_order(&self) -> Vec { + let mut degrees: BTreeMap<_, _> = self.nodes.keys().map(|id| (*id, 0usize)).collect(); + for (id, connections) in &self.incoming { + if let Some(degree) = degrees.get_mut(id) { + *degree = connections.iter().filter(|connection| self.nodes.contains_key(&connection.from)).count(); + } + } + + let mut ready: Vec<_> = degrees.iter().filter(|(_, degree)| **degree == 0).map(|(id, _)| *id).collect(); + let mut ordered = Vec::with_capacity(self.nodes.len()); + while let Some(id) = ready.pop() { + ordered.push(id); + for connection in self.outgoing.get(&id).into_iter().flatten() { + if let Some(degree) = degrees.get_mut(&connection.to) { + *degree = degree.saturating_sub(1); + if *degree == 0 { + ready.push(connection.to); + } + } + } + } + + ordered + } + + pub fn upstream(&self, id: NodeId) -> Vec { + self.connected(id, true) + } + + pub fn downstream(&self, id: NodeId) -> Vec { + self.connected(id, false) + } + + pub fn required_nodes(&self, roots: &[NodeId]) -> BTreeSet { + let mut required: BTreeSet<_> = roots.iter().copied().collect(); + let mut pending = roots.to_vec(); + while let Some(id) = pending.pop() { + for connection in self.incoming(id) { + if required.insert(connection.from) { + pending.push(connection.from); + } + } + } + + required + } + + fn connected(&self, root: NodeId, upstream: bool) -> Vec { + let adjacency = if upstream { &self.incoming } else { &self.outgoing }; + + let mut visited = BTreeSet::new(); + let mut connected = Vec::new(); + let mut pending = vec![root]; + while let Some(id) = pending.pop() { + for connection in adjacency.get(&id).into_iter().flatten() { + let next = if upstream { connection.from } else { connection.to }; + + if visited.insert(next) { + connected.push(next); + pending.push(next); + } + } + } + + connected + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn traversal_preserves_document_order_and_dangling_edge_behavior() { + let mut graph = Graph::new("Traversal"); + let first = graph.add_node("uniform", [0.0; 2]); + let second = graph.add_node("dot", [0.0; 2]); + let third = graph.add_node("blend", [0.0; 2]); + let fourth = graph.add_node("dot", [0.0; 2]); + for (from, to, port) in [(first, second, "input"), (first, third, "foreground"), (second, third, "background"), (NodeId(99), fourth, "input")] { + graph.connections.push(Connection { from, from_port: "output".into(), to, to_port: port.into() }); + } + let index = GraphIndex::new(&graph); + assert_eq!(index.topo_order(), [fourth, first, second, third]); + assert_eq!(index.upstream(third), [first, second]); + assert_eq!(index.downstream(first), [second, third]); + assert_eq!(index.required_nodes(&[third, fourth]), BTreeSet::from([first, second, third, fourth, NodeId(99)])); + assert_eq!(index.input_of(third, "background").unwrap().from, second); + + graph.connections.push(Connection { from: third, from_port: "output".into(), to: first, to_port: "input".into() }); + assert_eq!(GraphIndex::new(&graph).topo_order(), [fourth]); + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 71f876e..3ec6fb6 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -5,6 +5,7 @@ mod attributes; mod base_parameters; mod color; mod comment; +mod component_usage; mod connection; mod core_error; mod curve; @@ -16,7 +17,9 @@ mod function_node; mod gradient; mod gradient_key; mod graph; +mod graph_index; mod graph_kind; +mod material_channel; mod missing_node; mod node; mod node_id; @@ -37,6 +40,7 @@ pub use attributes::Attributes; pub use base_parameters::BaseParameters; pub use color::{linear_to_srgb, parse_color, srgb_to_linear}; pub use comment::Comment; +pub use component_usage::ComponentUsage; pub use connection::Connection; pub use core_error::CoreError; pub use curve::Curve; @@ -48,7 +52,9 @@ pub use function_node::FunctionNode; pub use gradient::Gradient; pub use gradient_key::GradientKey; pub use graph::{Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2}; +pub use graph_index::GraphIndex; pub use graph_kind::GraphKind; +pub use material_channel::MaterialChannel; pub use missing_node::{MISSING_NODE, missing_ports}; pub use node::Node; pub use node_id::NodeId; diff --git a/crates/core/src/material_channel.rs b/crates/core/src/material_channel.rs new file mode 100644 index 0000000..d29a81b --- /dev/null +++ b/crates/core/src/material_channel.rs @@ -0,0 +1,50 @@ +use serde::{Deserialize, Serialize}; + +/// Texture channels supported by the material preview +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum MaterialChannel { + BaseColor, + Normal, + Roughness, + Metallic, + Height, + AmbientOcclusion, + Emissive, + Opacity, +} + +impl MaterialChannel { + pub const ALL: [Self; 8] = + [Self::BaseColor, Self::Normal, Self::Roughness, Self::Metallic, Self::Height, Self::AmbientOcclusion, Self::Emissive, Self::Opacity]; + + pub fn id(self) -> &'static str { + match self { + Self::BaseColor => "baseColor", + Self::Normal => "normal", + Self::Roughness => "roughness", + Self::Metallic => "metallic", + Self::Height => "height", + Self::AmbientOcclusion => "ambientOcclusion", + Self::Emissive => "emissive", + Self::Opacity => "opacity", + } + } + + pub fn label(self) -> &'static str { + match self { + Self::BaseColor => "Base color", + Self::Normal => "Normal", + Self::Roughness => "Roughness", + Self::Metallic => "Metallic", + Self::Height => "Height", + Self::AmbientOcclusion => "Ambient occlusion", + Self::Emissive => "Emissive", + Self::Opacity => "Opacity", + } + } + + pub fn from_id(id: &str) -> Option { + Self::ALL.into_iter().find(|channel| channel.id().eq_ignore_ascii_case(id)).or_else(|| id.eq_ignore_ascii_case("diffuse").then_some(Self::BaseColor)) + } +} diff --git a/crates/core/src/pattern_graph.rs b/crates/core/src/pattern_graph.rs index fcb8055..d0275a8 100644 --- a/crates/core/src/pattern_graph.rs +++ b/crates/core/src/pattern_graph.rs @@ -22,7 +22,15 @@ impl PatternGraph { return Err("pattern graph exceeds the 4096-node limit".into()); } - let id = (1..=4097).find(|id| self.nodes.iter().all(|node| node.id != *id)).ok_or("no available pattern node id")?; + let mut occupied = [false; 4097]; + for node in &self.nodes { + if let Some(slot) = occupied.get_mut(node.id.saturating_sub(1) as usize) + && node.id != 0 + { + *slot = true; + } + } + let id = occupied.iter().position(|occupied| !occupied).ok_or("no available pattern node id")? as u32 + 1; self.nodes.push(PatternNode { id, kind, @@ -76,3 +84,25 @@ impl PatternGraph { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn allocation_reuses_the_lowest_hole_and_ignores_out_of_range_ids() { + let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); + let template = graph.nodes[0].clone(); + graph.nodes = [0, 2, 4097, u32::MAX].map(|id| PatternNode { id, ..template.clone() }).to_vec(); + assert_eq!(graph.add(PatternNodeKind::Dot).unwrap(), 1); + assert_eq!(graph.add(PatternNodeKind::Dot).unwrap(), 3); + graph.nodes.retain(|node| node.id != 2); + assert_eq!(graph.add(PatternNodeKind::Dot).unwrap(), 2); + assert_eq!(graph.root, Some(1)); + + graph.nodes.resize(4096, template); + let before = graph.clone(); + assert!(graph.add(PatternNodeKind::Dot).is_err()); + assert_eq!(graph, before); + } +} diff --git a/crates/engine/src/alignment_commands.rs b/crates/engine/src/alignment_commands.rs new file mode 100644 index 0000000..168f18c --- /dev/null +++ b/crates/engine/src/alignment_commands.rs @@ -0,0 +1,95 @@ +use crate::commands::{CommandSpec, bad, has_graph, strp}; +use crate::selection_target::SelectionTarget; +use crate::{Result, Session, cmd}; +use materialcraft_core::Value; +use serde_json::Value as Json; + +pub(crate) fn specs() -> Vec { + vec![cmd!( + "graph.align", + "Align nodes", + [], + None, + "{mode: left|right|top|bottom|hcenter|vcenter|hdistribute|vdistribute, ids?: required for Function/FX-Map, pattern?: owner node id, function?: FunctionGraphTarget, graph?: owning graph index}", + has_graph, + align + )] +} + +fn align(session: &mut Session, parameters: &Json) -> Result { + let mode = strp(parameters, "mode").unwrap_or("left"); + let ids: Vec = parameters + .get("ids") + .and_then(Json::as_array) + .map(|ids| ids.iter().filter_map(Json::as_u64).collect()) + .unwrap_or_else(|| session.selection.iter().map(|id| id.0).collect()); + let target = SelectionTarget::resolve(session, parameters)?; + if target.is_some() && parameters.get("ids").and_then(Json::as_array).is_none() { + return Err(bad("graph.align", "ids are required for a Function Graph or FX-Map")); + } + match target { + Some(SelectionTarget::Function(target)) => { + let mut graph = target.current(session)?.clone(); + align_selected(graph.nodes.iter_mut().map(|node| (u64::from(node.id), &mut node.pos)).collect(), &ids, mode)?; + crate::graph_validation::function(&graph).map_err(|error| bad("graph.align", error))?; + session.edit("Align nodes", |session| target.replace(session, graph))?; + } + Some(SelectionTarget::Pattern(owner)) => { + let mut graph = SelectionTarget::pattern(session, owner)?.clone(); + align_selected(graph.nodes.iter_mut().map(|node| (u64::from(node.id), &mut node.position)).collect(), &ids, mode)?; + crate::graph_validation::pattern(&graph).map_err(|error| bad("graph.align", error))?; + session.edit("Align nodes", |session| { + session.graph_mut()?.node_mut(owner)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph))); + Ok(()) + })?; + } + None => { + session.edit("Align nodes", |session| { + align_selected(session.graph_mut()?.nodes.iter_mut().map(|node| (node.id.0, &mut node.pos)).collect(), &ids, mode) + })?; + } + } + Ok(Json::Null) +} + +fn align_selected(mut positions: Vec<(u64, &mut [f32; 2])>, ids: &[u64], mode: &str) -> Result<()> { + let present: std::collections::BTreeSet<_> = positions.iter().map(|(id, _)| *id).collect(); + if let Some(id) = ids.iter().find(|id| !present.contains(id)) { + return Err(bad("graph.align", format!("no node {id}"))); + } + let selected: std::collections::BTreeSet<_> = ids.iter().copied().collect(); + positions.retain(|(id, _)| selected.contains(id)); + align_positions(positions.into_iter().map(|(_, position)| position).collect(), mode) +} + +fn align_positions(mut positions: Vec<&mut [f32; 2]>, mode: &str) -> Result<()> { + let axis = match mode { + "left" | "right" | "hcenter" | "hdistribute" => 0, + "top" | "bottom" | "vcenter" | "vdistribute" => 1, + other => return Err(bad("graph.align", format!("unknown mode `{other}`"))), + }; + + if positions.len() < 2 { + return Ok(()); + } + + let minimum = positions.iter().map(|position| position[axis]).fold(f32::MAX, f32::min); + let maximum = positions.iter().map(|position| position[axis]).fold(f32::MIN, f32::max); + if mode.ends_with("distribute") { + positions.sort_by(|left, right| left[axis].total_cmp(&right[axis])); + let step = (maximum - minimum) / (positions.len() - 1) as f32; + for (index, position) in positions.iter_mut().enumerate() { + position[axis] = minimum + step * index as f32; + } + } else { + let value = match mode { + "left" | "top" => minimum, + "right" | "bottom" => maximum, + _ => (minimum + maximum) * 0.5, + }; + for position in positions { + position[axis] = value; + } + } + Ok(()) +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 0d95597..8c7089f 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -51,7 +51,9 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::atomic_sample_commands::specs()); v.extend(crate::material_cmds::specs()); v.extend(crate::edit_cmds::specs()); + v.extend(crate::embedded_edit_commands::specs()); v.extend(crate::graph_cmds::specs()); + v.extend(crate::alignment_commands::specs()); v.extend(crate::annotation_commands::specs()); v.extend(crate::frame_commands::specs()); v.extend(crate::function_commands::specs()); @@ -62,6 +64,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::connection_commands::specs()); v.extend(crate::value_input_commands::specs()); v.extend(crate::view_cmds::specs()); + v.extend(crate::material_preview_commands::specs()); v.extend(crate::wire_cmds::specs()); v }) @@ -74,6 +77,9 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> { /// Run a command by id with JSON params (empty params = defaults, never a dialog) pub fn execute(s: &mut Session, id: &str, params: &J) -> Result { let spec = find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; + if let Some(result) = crate::selection_commands::execute(s, id, params) { + return result; + } (spec.enabled)(s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?; let result = (spec.run)(s, params)?; if !s.selection.is_empty() || s.annotation_selection.is_some_and(|selection| !s.graph().is_ok_and(|graph| selection.exists(graph))) { @@ -90,7 +96,9 @@ pub fn list(s: &Session, filter: Option<&str>) -> J { command_specs() .iter() .filter(|c| f.as_ref().is_none_or(|f| c.id.to_ascii_lowercase().contains(f) || c.label.to_ascii_lowercase().contains(f))) - .map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params, "enabled": (c.enabled)(s).is_ok()})) + .map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": if crate::selection_commands::supports(c.id) { + format!("{}; optional function: FunctionGraphTarget or pattern: owner node id, graph: owning graph index; embedded targets use explicit ids; copy returns clip", c.params) + } else { c.params.to_string() }, "enabled": crate::selection_commands::enabled(s, c.id, &J::Null).unwrap_or_else(|| (c.enabled)(s).is_ok())})) .collect(), ) } diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs index fcc8ac6..92cbddd 100644 --- a/crates/engine/src/edit_cmds.rs +++ b/crates/engine/src/edit_cmds.rs @@ -126,7 +126,7 @@ fn insert_clip(s: &mut Session, clip: &Clip, at: Option<[f32; 2]>, offset: [f32; map.insert(n.id, id); let mut c = n.clone(); c.id = id; - c.pos = crate::graph_grid::snap_position([n.pos[0] + shift[0], n.pos[1] + shift[1]], snap); + c.pos = crate::graph_grid::translate(n.pos, shift, snap); g.nodes.push(c); } for c in &clip.connections { diff --git a/crates/engine/src/embedded_clipboard.rs b/crates/engine/src/embedded_clipboard.rs new file mode 100644 index 0000000..10e7758 --- /dev/null +++ b/crates/engine/src/embedded_clipboard.rs @@ -0,0 +1,9 @@ +use materialcraft_core::{FunctionNode, PatternNode}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum EmbeddedClipboard { + Function { source: String, nodes: Vec }, + Pattern { source: String, nodes: Vec }, +} diff --git a/crates/engine/src/embedded_edit_commands.rs b/crates/engine/src/embedded_edit_commands.rs new file mode 100644 index 0000000..71eb2d7 --- /dev/null +++ b/crates/engine/src/embedded_edit_commands.rs @@ -0,0 +1,88 @@ +use crate::{ + FunctionEdit, FunctionGraphTarget, PatternEdit, Result, Session, cmd, + commands::{CommandSpec, bad, has_graph}, +}; + +use materialcraft_core::{NodeId, Value}; +use serde_json::{Value as Json, json}; + +pub(crate) fn specs() -> Vec { + vec![ + cmd!( + "graph.function.edit", + "Edit function node", + [], + None, + "{target?: {kind: graph|parameter|dynamic|pattern, node?, owner?, parameter?}, edit: {action: add|move|connect|value|output, ...}, merge?: false}", + has_graph, + function + ), + cmd!( + "graph.pattern.edit", + "Edit FX-Map node", + [], + None, + "{id: owner, edit: {action: add|move|connect|disconnect|root|value, ...}, merge?: false}", + has_graph, + pattern + ), + cmd!("edit.finish", "Finish edit gesture", [], None, "{} ends the current undo group", crate::commands::always, |session, _| { + session.finish_edit(); + Ok(Json::Null) + }), + ] +} + +fn commit(session: &mut Session, label: &str, key: Option, run: impl FnOnce(&mut Session) -> Result) -> Result { + match key { + Some(key) => session.edit_merged(&key, label, run), + None => session.edit(label, run), + } +} + +fn function(session: &mut Session, parameters: &Json) -> Result { + let target: FunctionGraphTarget = serde_json::from_value(parameters.get("target").cloned().unwrap_or_else(|| json!({"kind": "graph"}))) + .map_err(|error| bad("graph.function.edit", error.to_string()))?; + let edit: FunctionEdit = + serde_json::from_value(parameters.get("edit").cloned().unwrap_or(Json::Null)).map_err(|error| bad("graph.function.edit", error.to_string()))?; + let current = target.current(session)?; + if let FunctionEdit::Add { operation, .. } = &edit + && !target.available_operations(session).any(|definition| definition.id == operation) + { + return Err(bad("graph.function.edit", "this operation is not available in the target function graph")); + } + let mut graph = current.clone(); + let result = edit.apply(&mut graph).map_err(|error| bad("graph.function.edit", error))?; + crate::graph_validation::function(&graph).map_err(|error| bad("graph.function.edit", error))?; + let key = (parameters.get("merge").and_then(Json::as_bool) == Some(true)) + .then(|| edit.merge_key()) + .flatten() + .map(|key| format!("function:{}:{target:?}:{key}", session.graph)); + commit(session, "Edit Function Graph", key, |session| { + target.replace(session, graph)?; + Ok(result) + }) +} + +fn pattern(session: &mut Session, parameters: &Json) -> Result { + let id = NodeId(parameters.get("id").and_then(Json::as_u64).ok_or_else(|| bad("graph.pattern.edit", "id is required"))?); + let node = session.graph()?.node(id)?; + if node.def != "fx_map" { + return Err(bad("graph.pattern.edit", "the node is not an FX-Map")); + } + let value = node.params.get("pattern").or_else(|| materialcraft_nodes::find(&node.def)?.param("pattern").map(|parameter| ¶meter.default)); + let Some(Value::PatternGraph(graph)) = value else { return Err(bad("graph.pattern.edit", "missing FX-Map graph")) }; + let mut graph = (**graph).clone(); + let edit: PatternEdit = + serde_json::from_value(parameters.get("edit").cloned().unwrap_or(Json::Null)).map_err(|error| bad("graph.pattern.edit", error.to_string()))?; + let result = edit.apply(&mut graph).map_err(|error| bad("graph.pattern.edit", error))?; + crate::graph_validation::pattern(&graph).map_err(|error| bad("graph.pattern.edit", error))?; + let key = (parameters.get("merge").and_then(Json::as_bool) == Some(true)) + .then(|| edit.merge_key()) + .flatten() + .map(|key| format!("pattern:{}:{}:{key}", session.graph, id.0)); + commit(session, "Edit FX-Map graph", key, |session| { + session.graph_mut()?.node_mut(id)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph))); + Ok(result) + }) +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 0837b5a..6d99b63 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -83,6 +83,7 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result { }; session.pkg.graphs.push(graph); session.graph = session.pkg.graphs.len() - 1; + session.open_material_preview(); session.selection.clear(); session.annotation_selection = None; session.view2d.node = None; @@ -101,9 +102,12 @@ fn new_package(s: &mut Session, p: &J) -> Result { pub fn replace_package(s: &mut Session, pkg: Package, path: Option) { s.pkg = pkg; s.clipboard = None; + s.embedded_clipboard = None; s.clear_decoded(); s.path = path; s.graph = 0; + s.material_preview = crate::MaterialPreview::for_graph(&s.pkg, 0); + s.clear_preview_results(); s.selection.clear(); s.annotation_selection = None; s.view2d.node = None; @@ -130,6 +134,7 @@ pub fn open_bytes_linked(session: &mut Session, bytes: &[u8], name: Option Vec { - vec![cmd!("graph.function.set", "Edit Function Graph", [], None, "{function} replaces the current function graph", has_graph, set)] + vec![cmd!( + "graph.function.set", + "Edit Function Graph", + [], + None, + "{function, target?: {kind: graph|parameter|dynamic|pattern, node?, owner?, parameter?}} replaces a function graph", + has_graph, + set + )] } fn set(session: &mut Session, parameters: &Json) -> Result { - if session.graph()?.function.is_none() { - return Err(bad("graph.function.set", "the current graph is not a Function Graph")); - } + let target: FunctionGraphTarget = serde_json::from_value(parameters.get("target").cloned().unwrap_or_else(|| json!({"kind": "graph"}))) + .map_err(|error| bad("graph.function.set", error.to_string()))?; + target.current(session)?; let graph: FunctionGraph = serde_json::from_value(parameters.get("function").cloned().unwrap_or(Json::Null)).map_err(|error| bad("graph.function.set", error.to_string()))?; - materialcraft_nodes::function::node_types(&graph).map_err(|error| bad("graph.function.set", error))?; + crate::graph_validation::function(&graph).map_err(|error| bad("graph.function.set", error))?; session.edit("Edit Function Graph", |session| { - session.graph_mut()?.function = Some(graph); + target.replace(session, graph)?; Ok(json!({})) }) } diff --git a/crates/engine/src/function_edit.rs b/crates/engine/src/function_edit.rs new file mode 100644 index 0000000..2449432 --- /dev/null +++ b/crates/engine/src/function_edit.rs @@ -0,0 +1,105 @@ +use materialcraft_core::{FunctionGraph, FunctionNode, Value}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value as Json, json}; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(tag = "action", rename_all = "camelCase")] +pub enum FunctionEdit { + Add { + operation: String, + at: [f32; 2], + #[serde(default)] + snap: bool, + }, + Move { + ids: Vec, + by: [f32; 2], + #[serde(default)] + snap: bool, + }, + Connect { + from: u32, + to: u32, + input: usize, + }, + Value { + id: u32, + value: Value, + }, + Output { + id: u32, + }, +} + +impl FunctionEdit { + pub(crate) fn apply(&self, graph: &mut FunctionGraph) -> Result { + match self { + Self::Add { operation, at, snap } => { + if graph.nodes.len() >= 4096 { + return Err("the function exceeds the 4096-node limit".into()); + } + let definition = materialcraft_nodes::function::definition(operation).ok_or("unknown function operation")?; + let id = graph.next_id(); + graph.nodes.push(FunctionNode { + id, + type_code: 0, + op: operation.clone(), + inputs: vec![None; definition.inputs.len()], + value: materialcraft_nodes::function::default_value(operation), + pos: crate::graph_grid::snap_position(*at, *snap), + }); + if graph.output.is_none() { + graph.output = Some(id); + } + return Ok(json!({"id": id})); + } + Self::Move { ids, by, snap } => { + for id in ids { + if graph.node(*id).is_none() { + return Err(format!("no function node {id}")); + } + } + for node in &mut graph.nodes { + if ids.contains(&node.id) { + node.pos = crate::graph_grid::translate(node.pos, *by, *snap); + } + } + } + Self::Connect { from, to, input } => { + if from == to || graph.node(*from).is_none() { + return Err("invalid function source".into()); + } + let node = graph.nodes.iter_mut().find(|node| node.id == *to).ok_or("missing function destination")?; + let count = materialcraft_nodes::function::definition(&node.op).map_or(0, |definition| definition.inputs.len()); + if *input >= count { + return Err("invalid function input".into()); + } + node.inputs.resize(count, None); + if let Some(slot) = node.inputs.get_mut(*input) { + *slot = Some(*from); + } + } + Self::Value { id, value } => { + let node = graph.nodes.iter_mut().find(|node| node.id == *id).ok_or("missing function node")?; + if node.value.is_none() { + return Err("the operation has no editable value".into()); + } + node.value = Some(value.clone()); + } + Self::Output { id } => { + if graph.node(*id).is_none() { + return Err("missing output node".into()); + } + graph.output = Some(*id); + } + } + Ok(Json::Null) + } + + pub(crate) fn merge_key(&self) -> Option { + match self { + Self::Value { id, .. } => Some(format!("value:{id}")), + _ => None, + } + } +} diff --git a/crates/engine/src/function_graph_target.rs b/crates/engine/src/function_graph_target.rs new file mode 100644 index 0000000..883355a --- /dev/null +++ b/crates/engine/src/function_graph_target.rs @@ -0,0 +1,80 @@ +use crate::{Result, Session, commands::bad}; +use materialcraft_core::{FunctionGraph, NodeId, Value}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum FunctionGraphTarget { + #[default] + Graph, + Parameter { + node: NodeId, + parameter: String, + }, + Dynamic { + node: NodeId, + parameter: String, + }, + Pattern { + owner: NodeId, + node: u32, + parameter: String, + }, +} + +impl FunctionGraphTarget { + pub fn available_operations(&self, session: &Session) -> impl Iterator + use<> { + let value_processor = matches!(self, Self::Parameter { node, parameter } + if parameter == "function" && session.graph().ok().and_then(|graph| graph.node(*node).ok()).is_some_and(|node| node.def == "value_processor")); + materialcraft_nodes::function::FUNCTIONS.iter().filter(move |operation| !value_processor || !matches!(operation.id, "samplelum" | "samplecol")) + } + + pub fn current<'a>(&self, session: &'a Session) -> Result<&'a FunctionGraph> { + let document = session.graph()?; + let value = match self { + Self::Graph => return document.function.as_ref().ok_or_else(|| bad("graph.function.edit", "no Function Graph is open")), + Self::Dynamic { node, parameter } => { + return document.node(*node)?.functions.get(parameter).ok_or_else(|| bad("graph.function.edit", "missing parameter function")); + } + Self::Parameter { node, parameter } => { + let node = document.node(*node)?; + node.params.get(parameter).or_else(|| materialcraft_nodes::find(&node.def)?.param(parameter).map(|parameter| ¶meter.default)) + } + Self::Pattern { owner, node, parameter } => { + let Some(Value::PatternGraph(graph)) = document.node(*owner)?.params.get("pattern") else { + return Err(bad("graph.function.edit", "missing FX-Map graph")); + }; + + graph.nodes.iter().find(|candidate| candidate.id == *node).and_then(|node| node.parameters.get(parameter)) + } + }; + + match value { + Some(Value::Function(graph)) => Ok(graph), + _ => Err(bad("graph.function.edit", "missing function")), + } + } + + pub(crate) fn replace(&self, session: &mut Session, function: FunctionGraph) -> Result<()> { + self.current(session)?; + let document = session.graph_mut()?; + match self { + Self::Graph => document.function = Some(function), + Self::Dynamic { node, parameter } => { + document.node_mut(*node)?.functions.insert(parameter.clone(), function); + } + Self::Parameter { node, parameter } => { + document.node_mut(*node)?.params.insert(parameter.clone(), Value::Function(Box::new(function))); + } + Self::Pattern { owner, node, parameter } => { + let Some(Value::PatternGraph(graph)) = document.node_mut(*owner)?.params.get_mut("pattern") else { + return Err(bad("graph.function.edit", "missing FX-Map graph")); + }; + + let node = graph.nodes.iter_mut().find(|candidate| candidate.id == *node).ok_or_else(|| bad("graph.function.edit", "missing FX-Map node"))?; + node.parameters.insert(parameter.clone(), Value::Function(Box::new(function))); + } + } + Ok(()) + } +} diff --git a/crates/engine/src/graph_cmds.rs b/crates/engine/src/graph_cmds.rs index 9edee5c..852fff2 100644 --- a/crates/engine/src/graph_cmds.rs +++ b/crates/engine/src/graph_cmds.rs @@ -51,7 +51,6 @@ pub(crate) fn specs() -> Vec { cmd!("graph.select", "Select nodes", [], None, "{ids, add?: bool}", has_graph, select), cmd!("graph.selectUpstream", "Select upstream nodes", [], None, "{ids?}", has_selection, |s, p| select_stream(s, p, true)), cmd!("graph.selectDownstream", "Select downstream nodes", [], None, "{ids?}", has_selection, |s, p| select_stream(s, p, false)), - cmd!("graph.align", "Align nodes", [], None, "{mode: left|right|top|bottom|hcenter|vcenter|hdistribute|vdistribute, ids?}", has_selection, align), cmd!( "graph.createFromSelection", "Create graph from selection", @@ -79,6 +78,7 @@ fn graph_index(s: &Session, p: &J) -> Result { fn open(s: &mut Session, p: &J) -> Result { let i = graph_index(s, p)?; s.graph = i; + s.open_material_preview(); s.selection.clear(); s.annotation_selection = None; s.view2d.node = None; @@ -110,7 +110,10 @@ fn delete(s: &mut Session, p: &J) -> Result { let i = graph_index(s, p)?; s.edit("Delete graph", |s| { s.pkg.graphs.remove(i); + s.material_preview.remove_graph(i); + s.clear_preview_results(); s.clipboard = None; + s.embedded_clipboard = None; s.graph = s.graph.min(s.pkg.graphs.len().saturating_sub(1)); s.selection.clear(); s.annotation_selection = None; @@ -126,6 +129,7 @@ fn duplicate(s: &mut Session, p: &J) -> Result { g.name = s.pkg.unique_graph_name(&g.name); s.pkg.graphs.push(g); s.graph = s.pkg.graphs.len() - 1; + s.open_material_preview(); s.selection.clear(); s.annotation_selection = None; Ok(json!({"graph": s.graph})) @@ -350,41 +354,6 @@ fn select_stream(s: &mut Session, p: &J, up: bool) -> Result { Ok(json!({"selected": s.selection.len()})) } -fn align(s: &mut Session, p: &J) -> Result { - let ids = ids_param(s, "graph.align", p)?; - let mode = strp(p, "mode").unwrap_or("left").to_string(); - s.edit("Align nodes", |s| { - let g = s.graph_mut()?; - let mut nodes: Vec<&mut materialcraft_core::Node> = g.nodes.iter_mut().filter(|n| ids.contains(&n.id)).collect(); - if nodes.len() < 2 { - return Ok(J::Null); - } - let xs: Vec = nodes.iter().map(|n| n.pos[0]).collect(); - let ys: Vec = nodes.iter().map(|n| n.pos[1]).collect(); - let (minx, maxx) = (xs.iter().copied().fold(f32::MAX, f32::min), xs.iter().copied().fold(f32::MIN, f32::max)); - let (miny, maxy) = (ys.iter().copied().fold(f32::MAX, f32::min), ys.iter().copied().fold(f32::MIN, f32::max)); - match mode.as_str() { - "left" => nodes.iter_mut().for_each(|n| n.pos[0] = minx), - "right" => nodes.iter_mut().for_each(|n| n.pos[0] = maxx), - "top" => nodes.iter_mut().for_each(|n| n.pos[1] = miny), - "bottom" => nodes.iter_mut().for_each(|n| n.pos[1] = maxy), - "hcenter" => nodes.iter_mut().for_each(|n| n.pos[0] = (minx + maxx) * 0.5), - "vcenter" => nodes.iter_mut().for_each(|n| n.pos[1] = (miny + maxy) * 0.5), - "hdistribute" | "vdistribute" => { - let k = usize::from(mode == "vdistribute"); - nodes.sort_by(|a, b| a.pos[k].total_cmp(&b.pos[k])); - let (lo, hi) = if k == 0 { (minx, maxx) } else { (miny, maxy) }; - let step = (hi - lo) / (nodes.len() - 1) as f32; - for (i, n) in nodes.iter_mut().enumerate() { - n.pos[k] = lo + step * i as f32; - } - } - other => return Err(bad("graph.align", format!("unknown mode `{other}`"))), - } - Ok(J::Null) - }) -} - fn from_selection(s: &mut Session, p: &J) -> Result { let ids = ids_param(s, "graph.createFromSelection", p)?; let base = strp(p, "name").unwrap_or("Sub_graph").to_string(); @@ -415,7 +384,7 @@ fn from_selection(s: &mut Session, p: &J) -> Result { } let ident = format!("output_{}", outputs.len() + 1); let id = sub.add_node("output", [rect[0] + rect[2] + 80.0, rect[1] + outputs.len() as f32 * 120.0]); - let usage = materialcraft_nodes::atomic::USAGE_IDS.len() as u32 - 1; + let usage = materialcraft_core::ComponentUsage::ANY_INDEX; sub.node_mut(id)?.params.extend([("identifier".to_string(), Value::Text(ident.clone())), ("usage".to_string(), Value::Enum(usage))]); sub.connect(c.from, &c.from_port, id, "input")?; outputs.push((c.from, c.from_port.clone(), ident)); diff --git a/crates/engine/src/graph_edit/editable_graph.rs b/crates/engine/src/graph_edit/editable_graph.rs new file mode 100644 index 0000000..b34f416 --- /dev/null +++ b/crates/engine/src/graph_edit/editable_graph.rs @@ -0,0 +1,17 @@ +/// The data access needed by shared function and pattern editing operations +pub trait EditableGraph { + type Node: Clone; + + const LINKS_ARE_INPUTS: bool; + const RELINK: bool; + + fn nodes(&self) -> &[Self::Node]; + fn nodes_mut(&mut self) -> &mut Vec; + fn id(node: &Self::Node) -> u32; + fn position(node: &mut Self::Node) -> &mut [f32; 2]; + fn links(node: &Self::Node) -> &[Option]; + fn links_mut(node: &mut Self::Node) -> &mut [Option]; + fn result(&mut self) -> &mut Option; + fn check_capacity(&self, additional: usize) -> Result<(), String>; + fn insert(&mut self, node: Self::Node) -> Result; +} diff --git a/crates/engine/src/graph_edit/function_graph.rs b/crates/engine/src/graph_edit/function_graph.rs new file mode 100644 index 0000000..eba3947 --- /dev/null +++ b/crates/engine/src/graph_edit/function_graph.rs @@ -0,0 +1,45 @@ +use super::EditableGraph; +use materialcraft_core::{FunctionGraph, FunctionNode}; + +impl EditableGraph for FunctionGraph { + type Node = FunctionNode; + + const LINKS_ARE_INPUTS: bool = true; + const RELINK: bool = true; + + fn nodes(&self) -> &[FunctionNode] { + &self.nodes + } + fn nodes_mut(&mut self) -> &mut Vec { + &mut self.nodes + } + fn id(node: &FunctionNode) -> u32 { + node.id + } + fn position(node: &mut FunctionNode) -> &mut [f32; 2] { + &mut node.pos + } + fn links(node: &FunctionNode) -> &[Option] { + &node.inputs + } + fn links_mut(node: &mut FunctionNode) -> &mut [Option] { + &mut node.inputs + } + fn result(&mut self) -> &mut Option { + &mut self.output + } + + fn check_capacity(&self, additional: usize) -> Result<(), String> { + if self.nodes.len().saturating_add(additional) > 4096 { + return Err("function exceeds the 4096-node limit".into()); + } + Ok(()) + } + + fn insert(&mut self, mut node: FunctionNode) -> Result { + let id = self.next_id(); + node.id = id; + self.nodes.push(node); + Ok(id) + } +} diff --git a/crates/engine/src/graph_edit/mod.rs b/crates/engine/src/graph_edit/mod.rs new file mode 100644 index 0000000..1215fe9 --- /dev/null +++ b/crates/engine/src/graph_edit/mod.rs @@ -0,0 +1,9 @@ +//! Editing rules shared by Function Graphs and FX-Map graphs + +mod editable_graph; +mod function_graph; +mod pattern_graph; +mod selection; + +pub use editable_graph::EditableGraph; +pub use selection::{enabled, read, remove, run}; diff --git a/crates/engine/src/graph_edit/pattern_graph.rs b/crates/engine/src/graph_edit/pattern_graph.rs new file mode 100644 index 0000000..fd98af8 --- /dev/null +++ b/crates/engine/src/graph_edit/pattern_graph.rs @@ -0,0 +1,47 @@ +use super::EditableGraph; +use materialcraft_core::{PatternGraph, PatternNode}; + +impl EditableGraph for PatternGraph { + type Node = PatternNode; + + const LINKS_ARE_INPUTS: bool = false; + const RELINK: bool = false; + + fn nodes(&self) -> &[PatternNode] { + &self.nodes + } + fn nodes_mut(&mut self) -> &mut Vec { + &mut self.nodes + } + fn id(node: &PatternNode) -> u32 { + node.id + } + fn position(node: &mut PatternNode) -> &mut [f32; 2] { + &mut node.position + } + fn links(node: &PatternNode) -> &[Option] { + &node.children + } + fn links_mut(node: &mut PatternNode) -> &mut [Option] { + &mut node.children + } + fn result(&mut self) -> &mut Option { + &mut self.root + } + + fn check_capacity(&self, additional: usize) -> Result<(), String> { + if self.nodes.len().saturating_add(additional) > 4096 { + return Err("pattern graph exceeds the 4096-node limit".into()); + } + Ok(()) + } + + fn insert(&mut self, mut node: PatternNode) -> Result { + let id = self.add(node.kind)?; + node.id = id; + if let Some(destination) = self.nodes.last_mut() { + *destination = node; + } + Ok(id) + } +} diff --git a/crates/engine/src/graph_edit/selection.rs b/crates/engine/src/graph_edit/selection.rs new file mode 100644 index 0000000..9037d42 --- /dev/null +++ b/crates/engine/src/graph_edit/selection.rs @@ -0,0 +1,127 @@ +use super::EditableGraph; +use std::collections::{BTreeMap, BTreeSet}; + +pub fn enabled(selection: &[u32], clipboard: &[G::Node], command: &str) -> Option { + Some(match command { + "graph.select" | "edit.selectAll" | "edit.selectNone" => true, + "edit.paste" | "edit.pasteWithoutLinks" => !clipboard.is_empty(), + "edit.copy" | "edit.cut" | "edit.delete" | "edit.duplicate" | "edit.duplicateWithoutLinks" | "graph.selectUpstream" | "graph.selectDownstream" => { + !selection.is_empty() + } + "edit.deleteRelink" => G::RELINK && !selection.is_empty(), + "graph.node.disable" => false, + _ => return None, + }) +} + +pub fn run( + graph: &mut G, + selection: &mut Vec, + clipboard: &mut Vec, + command: &str, + at: [f32; 2], + snap: bool, +) -> Result { + if read(graph, selection, clipboard, command) { + return Ok(false); + } + match command { + "edit.cut" => { + *clipboard = selected::(graph, selection); + return Ok(remove(graph, selection, false)); + } + "edit.delete" | "edit.deleteRelink" => return Ok(remove(graph, selection, G::RELINK && command == "edit.deleteRelink")), + "edit.duplicate" | "edit.duplicateWithoutLinks" | "edit.paste" | "edit.pasteWithoutLinks" => { + let duplicate = command.starts_with("edit.duplicate"); + let mut nodes = if duplicate { selected::(graph, selection) } else { clipboard.clone() }; + graph.check_capacity(nodes.len())?; + let anchor = nodes.first_mut().map_or([0.0; 2], |node| *G::position(node)); + let offset = if duplicate { [32.0; 2] } else { [at[0] - anchor[0], at[1] - anchor[1]] }; + let present: BTreeSet<_> = graph.nodes().iter().map(G::id).collect(); + let mut ids = BTreeMap::new(); + for mut node in nodes { + let original = G::id(&node); + let position = G::position(&mut node); + *position = crate::graph_grid::translate(*position, offset, snap); + ids.insert(original, graph.insert(node)?); + } + let inserted: BTreeSet<_> = ids.values().copied().collect(); + for node in graph.nodes_mut().iter_mut().filter(|node| inserted.contains(&G::id(node))) { + for link in G::links_mut(node) { + *link = link.and_then(|id| ids.get(&id).copied().or_else(|| (!command.ends_with("WithoutLinks") && present.contains(&id)).then_some(id))); + } + } + *selection = ids.values().copied().collect(); + return Ok(!ids.is_empty()); + } + _ => {} + } + Ok(false) +} + +fn selected(graph: &G, selection: &[u32]) -> Vec { + let selection: BTreeSet<_> = selection.iter().copied().collect(); + graph.nodes().iter().filter(|node| selection.contains(&G::id(node))).cloned().collect() +} + +pub fn remove(graph: &mut G, selection: &mut Vec, relink: bool) -> bool { + let selection_set: BTreeSet<_> = selection.iter().copied().collect(); + let replacements: BTreeMap<_, _> = graph + .nodes() + .iter() + .filter(|node| selection_set.contains(&G::id(node))) + .map(|node| (G::id(node), if relink { G::links(node).first().copied().flatten() } else { None })) + .collect(); + graph.nodes_mut().retain(|node| !selection_set.contains(&G::id(node))); + for node in graph.nodes_mut() { + for link in G::links_mut(node) { + let mut seen = BTreeSet::new(); + while let Some(id) = *link { + let Some(replacement) = replacements.get(&id) else { break }; + + if !seen.insert(id) { + *link = None; + break; + } + *link = *replacement; + } + } + } + if graph.result().is_some_and(|id| selection_set.contains(&id)) { + *graph.result() = None; + } + selection.clear(); + !replacements.is_empty() +} + +/// Apply selection and copy actions without cloning or mutating the graph +pub fn read(graph: &G, selection: &mut Vec, clipboard: &mut Vec, command: &str) -> bool { + match command { + "edit.selectAll" => *selection = graph.nodes().iter().map(G::id).collect(), + "edit.selectNone" => selection.clear(), + "graph.select" => {} + "edit.copy" => *clipboard = selected::(graph, selection), + "graph.selectUpstream" | "graph.selectDownstream" => { + let follow_links = (command == "graph.selectUpstream") == G::LINKS_ARE_INPUTS; + let mut neighbors: BTreeMap> = BTreeMap::new(); + for node in graph.nodes() { + for link in G::links(node).iter().flatten() { + let (from, to) = if follow_links { (G::id(node), *link) } else { (*link, G::id(node)) }; + neighbors.entry(from).or_default().push(to); + } + } + let mut visited = BTreeSet::new(); + let mut pending = selection.clone(); + while let Some(id) = pending.pop() { + if visited.insert(id) + && let Some(next) = neighbors.get(&id) + { + pending.extend(next); + } + } + *selection = visited.into_iter().collect(); + } + _ => return false, + } + true +} diff --git a/crates/engine/src/graph_grid.rs b/crates/engine/src/graph_grid.rs index 4d65981..c4550a0 100644 --- a/crates/engine/src/graph_grid.rs +++ b/crates/engine/src/graph_grid.rs @@ -6,3 +6,8 @@ pub fn snap_position(position: [f32; 2], enabled: bool) -> [f32; 2] { if enabled { (coordinate / GRID_SPACING).round() * GRID_SPACING } else { coordinate } }) } + +/// Apply the same movement and snapping rule during a drag preview and its commit +pub fn translate(position: [f32; 2], offset: [f32; 2], snap: bool) -> [f32; 2] { + snap_position([position[0] + offset[0], position[1] + offset[1]], snap) +} diff --git a/crates/engine/src/graph_validation.rs b/crates/engine/src/graph_validation.rs new file mode 100644 index 0000000..aaec284 --- /dev/null +++ b/crates/engine/src/graph_validation.rs @@ -0,0 +1,50 @@ +use materialcraft_core::{FunctionGraph, PatternGraph, Value}; + +fn function_structure(graph: &FunctionGraph) -> Result<(), String> { + materialcraft_nodes::function::node_types(graph)?; + if graph.nodes.iter().any(|node| node.pos.iter().any(|coordinate| !coordinate.is_finite())) { + return Err("function node positions must be finite".into()); + } + Ok(()) +} + +pub(crate) fn pattern(graph: &PatternGraph) -> Result<(), String> { + pattern_structure(graph)?; + values(graph.nodes.iter().flat_map(|node| node.parameters.values())) +} + +pub(crate) fn function(graph: &FunctionGraph) -> Result<(), String> { + function_structure(graph)?; + values(graph.nodes.iter().filter_map(|node| node.value.as_ref())) +} + +pub(crate) fn value(value: &Value) -> Result<(), String> { + values(std::iter::once(value)) +} + +fn values<'a>(values: impl Iterator) -> Result<(), String> { + // Nested graph values are checked without recursive traversal + let mut pending: Vec<_> = values.collect(); + while let Some(value) = pending.pop() { + match value { + Value::Function(graph) => { + function_structure(graph)?; + pending.extend(graph.nodes.iter().filter_map(|node| node.value.as_ref())); + } + Value::PatternGraph(graph) => { + pattern_structure(graph)?; + pending.extend(graph.nodes.iter().flat_map(|node| node.parameters.values())); + } + _ => {} + } + } + Ok(()) +} + +fn pattern_structure(graph: &PatternGraph) -> Result<(), String> { + graph.validate()?; + if graph.nodes.iter().any(|node| node.position.iter().any(|coordinate| !coordinate.is_finite())) { + return Err("pattern node positions must be finite".into()); + } + Ok(()) +} diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 82a0adb..5658d5e 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -61,6 +61,13 @@ pub fn session(s: &Session, graph: Option) -> J { "selection": s.selection.iter().map(|i| i.0).collect::>(), "view2d": s.view2d, "view3d": s.view3d, + "material3d": { + "assignments": s.material_preview, + "channels": s.material_preview.sources(&s.pkg).into_iter().map(|(channel, source)| { + let image = s.material_image(&source); + json!({"channel": channel, "source": source, "size": image.map(|image| [image.w, image.h]), "mean": image.map(|image| image.mean())}) + }).collect::>(), + }, "previewSize": s.preview_size, "camera": s.camera, "cookMs": s.cooked.ms, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index fea2ea0..a2a8846 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1,10 +1,26 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod material_preview; +mod material_preview_commands; +mod material_source; +mod preview_cook; +pub use material_preview::MaterialPreview; +pub use material_source::MaterialSource; +pub use preview_cook::PreviewCook; + +mod alignment_commands; +mod embedded_clipboard; +mod graph_validation; +pub mod selection_commands; +mod selection_target; +pub use embedded_clipboard::EmbeddedClipboard; +pub use selection_target::SelectionTarget; pub mod commands; pub mod edit_cmds; pub mod file_cmds; pub mod graph_cmds; +pub mod graph_edit; pub mod graph_grid; pub mod inspect; pub mod material_cmds; @@ -59,3 +75,11 @@ mod pattern_graph_commands; mod snapshot; pub use annotation_selection::AnnotationSelection; pub use frame_contents::FrameContents; + +mod embedded_edit_commands; +mod function_edit; +mod function_graph_target; +mod pattern_edit; +pub use function_edit::FunctionEdit; +pub use function_graph_target::FunctionGraphTarget; +pub use pattern_edit::PatternEdit; diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index 3de28a4..f19d8c1 100644 --- a/crates/engine/src/material_cmds.rs +++ b/crates/engine/src/material_cmds.rs @@ -3,6 +3,7 @@ use std::collections::BTreeMap; use serde_json::{Value as J, json}; +use materialcraft_core::ComponentUsage; use materialcraft_core::Graph; #[cfg(any(test, not(target_arch = "wasm32")))] use materialcraft_core::Value; @@ -10,7 +11,6 @@ use materialcraft_formats::material::{FORMAT, ImageInput, Manifest, MapEntry, Pa use materialcraft_formats::{Depth, encode}; #[cfg(test)] use materialcraft_image::Image; -use materialcraft_nodes::atomic::USAGE_IDS; #[cfg(not(target_arch = "wasm32"))] use crate::commands::u64p; @@ -83,7 +83,14 @@ pub fn material_bytes(s: &Session, gi: usize, o: &MaterialOptions) -> Result>().join(", ") + ), + )); } let manifest = Manifest { format: FORMAT.into(), diff --git a/crates/engine/src/material_preview.rs b/crates/engine/src/material_preview.rs new file mode 100644 index 0000000..ba56c6b --- /dev/null +++ b/crates/engine/src/material_preview.rs @@ -0,0 +1,93 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::hash::{Hash, Hasher}; + +use materialcraft_core::{MaterialChannel, Package}; +use materialcraft_image::Image; +use serde::{Deserialize, Serialize}; + +use crate::{MaterialSource, Session}; + +/// Automatic graph outputs with explicit channel overrides +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct MaterialPreview { + pub graph: Option, + pub channels: BTreeMap, +} + +impl MaterialPreview { + pub fn for_graph(package: &Package, graph: usize) -> Self { + Self { graph: package.graphs.get(graph).filter(|graph| graph.function.is_none()).map(|_| graph), channels: BTreeMap::new() } + } + + pub fn sources(&self, package: &Package) -> BTreeMap { + let mut sources = BTreeMap::new(); + if let Some(index) = self.graph + && let Some(graph) = package.graphs.get(index) + { + for node in graph.nodes.iter().filter(|node| node.def == "output") { + let source = MaterialSource { graph: index, node: node.id, port: "output".into() }; + if let Some(channel) = MaterialChannel::from_id(materialcraft_eval::output_usage(node)) + && source.is_image(package) + { + sources.entry(channel).or_insert(source); + } + } + } + sources.extend(self.channels.clone()); + sources + } + + pub fn graphs(&self) -> BTreeSet { + self.graph.into_iter().chain(self.channels.values().map(|source| source.graph)).collect() + } + + pub(crate) fn remove_graph(&mut self, graph: usize) { + self.graph = self.graph.filter(|index| *index != graph).map(|index| if index > graph { index - 1 } else { index }); + self.channels.retain(|_, source| source.graph != graph); + for source in self.channels.values_mut() { + if source.graph > graph { + source.graph -= 1; + } + } + } +} + +impl Session { + /// Show a material graph on open, retaining the material while editing functions + pub(crate) fn open_material_preview(&mut self) { + if self.graph().is_ok_and(|graph| graph.function.is_none()) { + self.material_preview = MaterialPreview::for_graph(&self.pkg, self.graph); + } + } + + pub(crate) fn clear_preview_results(&mut self) { + self.cooked_graph = None; + self.material_cooked.clear(); + } + + pub fn material_image(&self, source: &MaterialSource) -> Option<&Image> { + let port = source.port_index(&self.pkg)?; + let cooked = self.preview_cooked(source.graph)?; + cooked.image(source.node, port) + } + + fn preview_cooked(&self, graph: usize) -> Option<&materialcraft_eval::Cooked> { + if self.cooked_graph == Some(graph) { Some(&self.cooked) } else { self.material_cooked.get(&graph) } + } + + /// Assigned image channels, including sources outside the open graph + pub fn material_maps(&self) -> Vec<(&'static str, &Image)> { + self.material_preview.sources(&self.pkg).into_iter().filter_map(|(channel, source)| Some((channel.id(), self.material_image(&source)?))).collect() + } + + /// Assignment and cooked content both invalidate the rendered preview + pub fn material_key(&self) -> u64 { + let mut hash = std::collections::hash_map::DefaultHasher::new(); + for (channel, source) in self.material_preview.sources(&self.pkg) { + let result = self.preview_cooked(source.graph).and_then(|cooked| cooked.nodes.get(&source.node)); + let port = source.port_index(&self.pkg); + (channel, &source, port, result.map(|result| result.key)).hash(&mut hash); + } + hash.finish() + } +} diff --git a/crates/engine/src/material_preview_commands.rs b/crates/engine/src/material_preview_commands.rs new file mode 100644 index 0000000..bc6f5e8 --- /dev/null +++ b/crates/engine/src/material_preview_commands.rs @@ -0,0 +1,100 @@ +use materialcraft_core::{MaterialChannel, NodeId}; +use serde_json::{Value, json}; + +use crate::commands::{CommandSpec, always, bad, boolp, has_graph, u64p}; +use crate::{MaterialPreview, MaterialSource, Result, Session, cmd}; + +pub(crate) fn specs() -> Vec { + vec![ + cmd!( + "view.3d.outputs", + "View outputs in 3D view", + ["Tools"], + None, + "{graph?: index or name, reset?: bool} assigns image outputs by usage; reset clears other assignments without moving the camera", + has_graph, + outputs + ), + cmd!( + "view.3d.assign", + "View output in 3D view", + [], + None, + "{graph?: index or name, node?: selected node, port?: index or identifier, channel: baseColor|normal|roughness|metallic|height|ambientOcclusion|emissive|opacity, reset?: bool}", + has_graph, + assign + ), + cmd!("view.3d.clear", "Clear material assignments", [], None, "{} clears the material without resetting the scene or camera", always, |session, _| { + session.material_preview = MaterialPreview::default(); + session.dirty = true; + Ok(Value::Null) + }), + ] +} + +fn graph_index(session: &Session, parameters: &Value, command: &str) -> Result { + let graph = match parameters.get("graph") { + None => session.graph, + Some(Value::String(name)) => session.pkg.graph_by_name(name).map(|(index, _)| index).ok_or_else(|| bad(command, format!("no graph `{name}`")))?, + Some(value) => value.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad(command, "graph must be an index or name"))?, + }; + if session.pkg.graph(graph)?.function.is_some() { + return Err(bad(command, "a Function Graph has no material image outputs")); + } + Ok(graph) +} + +fn outputs(session: &mut Session, parameters: &Value) -> Result { + let graph = graph_index(session, parameters, "view.3d.outputs")?; + let material = MaterialPreview::for_graph(&session.pkg, graph); + let sources = material.sources(&session.pkg); + if sources.is_empty() { + return Err(bad("view.3d.outputs", "no image outputs have supported material usages; assign an image to a channel with View in 3D view")); + } + if boolp(parameters, "reset") == Some(true) { + session.material_preview = material; + } else { + session.material_preview.channels.extend(sources); + } + session.dirty = true; + Ok(json!(session.material_preview)) +} + +fn assign(session: &mut Session, parameters: &Value) -> Result { + const COMMAND: &str = "view.3d.assign"; + let graph = graph_index(session, parameters, COMMAND)?; + let channel = parameters + .get("channel") + .and_then(Value::as_str) + .and_then(MaterialChannel::from_id) + .ok_or_else(|| bad(COMMAND, "choose a supported material channel"))?; + let node = match parameters.get("node") { + Some(_) => NodeId(u64p(parameters, "node").ok_or_else(|| bad(COMMAND, "node must be an ID"))?), + None if graph == session.graph => *session.selection.last().ok_or_else(|| bad(COMMAND, "select a node or supply its ID"))?, + None => return Err(bad(COMMAND, "node is required for another graph")), + }; + let source_graph = session.pkg.graph(graph)?; + let source_node = source_graph.node(node)?; + let ports = if source_node.def == "output" { + vec!["output".to_string()] + } else { + materialcraft_eval::ports(&session.pkg, source_graph, source_node).1.into_iter().map(|port| port.id).collect() + }; + let port = match parameters.get("port") { + None => ports.first(), + Some(Value::String(name)) => ports.iter().find(|port| *port == name), + Some(value) => value.as_u64().and_then(|index| usize::try_from(index).ok()).and_then(|index| ports.get(index)), + } + .cloned() + .ok_or_else(|| bad(COMMAND, "no such image output port"))?; + let source = MaterialSource { graph, node, port }; + if !source.is_image(&session.pkg) { + return Err(bad(COMMAND, "the 3D view needs an image, not a scalar, vector or unresolved output")); + } + if boolp(parameters, "reset") == Some(true) { + session.material_preview = MaterialPreview::default(); + } + session.material_preview.channels.insert(channel, source); + session.dirty = true; + Ok(json!(session.material_preview)) +} diff --git a/crates/engine/src/material_source.rs b/crates/engine/src/material_source.rs new file mode 100644 index 0000000..f6ac8be --- /dev/null +++ b/crates/engine/src/material_source.rs @@ -0,0 +1,62 @@ +use materialcraft_core::{NodeId, Package}; +use serde::{Deserialize, Serialize}; + +/// An image assigned to a material channel, independent of editor selection +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct MaterialSource { + pub graph: usize, + pub node: NodeId, + pub port: String, +} + +impl MaterialSource { + pub fn is_image(&self, package: &Package) -> bool { + let mut graph_index = self.graph; + let mut node_id = self.node; + let mut port = self.port.clone(); + let mut visited = std::collections::BTreeSet::new(); + loop { + if !visited.insert((graph_index, node_id, port.clone())) { + return false; + } + let Some(graph) = package.graphs.get(graph_index) else { return false }; + let Ok(node) = graph.node(node_id) else { return false }; + + match node.def.as_str() { + "output" | "dot" => { + let Some(connection) = graph.input_of(node_id, "input") else { return true }; + + node_id = connection.from; + port = connection.from_port.clone(); + } + "graph_instance" => { + let Some((index, graph)) = materialcraft_eval::instance_graph(package, node) else { return false }; + let Some(output) = graph.nodes.iter().find(|node| node.def == "output" && materialcraft_eval::identifier(node) == port) else { + return false; + }; + + graph_index = index; + node_id = output.id; + port = "output".into(); + } + _ => { + return materialcraft_eval::ports(package, graph, node) + .1 + .iter() + .any(|output| output.id == port && output.kind != materialcraft_nodes::PortKind::Value) + && materialcraft_nodes::output_value_type(graph, node_id).is_ok_and(|value| value.is_none()); + } + } + } + } + + pub fn port_index(&self, package: &Package) -> Option { + let graph = package.graphs.get(self.graph)?; + let node = graph.node(self.node).ok()?; + if node.def == "output" { + return (self.port == "output").then_some(0); + } + + materialcraft_eval::ports(package, graph, node).1.iter().position(|port| port.id == self.port) + } +} diff --git a/crates/engine/src/node_cmds.rs b/crates/engine/src/node_cmds.rs index 7fa6b3e..34efaa7 100644 --- a/crates/engine/src/node_cmds.rs +++ b/crates/engine/src/node_cmds.rs @@ -83,6 +83,7 @@ fn add(s: &mut Session, p: &J) -> Result { pd.default.coerce_json(v).ok_or_else(|| bad("graph.node.add", format!("`{k}` takes a {}", pd.default.type_name())))? }; + crate::graph_validation::value(&v).map_err(|error| bad("graph.node.add", error))?; params.push((k.clone(), v)); } } @@ -136,7 +137,7 @@ fn move_nodes(s: &mut Session, p: &J) -> Result { if let Some(t) = to { n.pos = snap_position(t, snap); } else if let Some(d) = by { - n.pos = snap_position([n.pos[0] + d[0], n.pos[1] + d[1]], snap); + n.pos = crate::graph_grid::translate(n.pos, d, snap); } } Ok(J::Null) @@ -198,9 +199,7 @@ fn set_param(s: &mut Session, p: &J) -> Result { v }; - if let Value::PatternGraph(graph) = &value { - graph.validate().map_err(|error| bad("graph.node.param", error))?; - } + crate::graph_validation::value(&value).map_err(|error| bad("graph.node.param", error))?; s.edit_merged(&format!("param:{}:{param}", id.0), "Set parameter", |s| { s.graph_mut()?.node_mut(id)?.params.insert(param.clone(), value); @@ -315,9 +314,7 @@ fn set_function(s: &mut Session, p: &J) -> Result { }, }; - if f.nodes.len() > 4096 { - return Err(bad("graph.node.function", "the function is too large")); - } + crate::graph_validation::function(&f).map_err(|error| bad("graph.node.function", error))?; s.edit_merged(&format!("fn:{}:{param}", id.0), "Set parameter function", |s| { s.graph_mut()?.node_mut(id)?.functions.insert(param.clone(), f); Ok(J::Null) diff --git a/crates/engine/src/node_graph_commands.rs b/crates/engine/src/node_graph_commands.rs index 3686f75..112d24a 100644 --- a/crates/engine/src/node_graph_commands.rs +++ b/crates/engine/src/node_graph_commands.rs @@ -1,8 +1,7 @@ -use materialcraft_core::NodeId; use serde_json::{Value, json}; use crate::commands::{CommandSpec, bad}; -use crate::{Result, Session, cmd}; +use crate::{FunctionGraphTarget, Session, cmd}; pub(crate) fn specs() -> Vec { vec![cmd!( @@ -10,32 +9,29 @@ pub(crate) fn specs() -> Vec { "Edit node graph", ["Edit"], Some("Ctrl+E"), - "{} resolves the selected FX-Map graph to {node, parameter}; UI invocation opens its editor", - enabled, - edit + "{} resolves the selected FX-Map, processor or local graph instance to {kind, node, parameter?, graph?}; UI invocation opens it in the graph panel", + |session| resolve(session).map(|_| ()), + |session, _| resolve(session).map_err(|error| bad("graph.node.edit", error)) )] } -fn selected_node(session: &Session) -> std::result::Result { +fn resolve(session: &Session) -> std::result::Result { if session.annotation_selection.is_some() { - return Err("select an FX-Map node".into()); + return Err("select a node with an editable graph".into()); } - - let id = session.selection.last().copied().ok_or("select an FX-Map node")?; + let id = session.selection.last().copied().ok_or("select a node with an editable graph")?; let graph = session.graph().map_err(|error| error.to_string())?; let node = graph.node(id).map_err(|error| error.to_string())?; - if node.def != "fx_map" { - return Err("the selected node has no editable FX-Map graph".into()); + match node.def.as_str() { + "fx_map" => Ok(json!({"kind": "pattern", "node": id, "parameter": "pattern"})), + "pixel_processor" | "value_processor" => { + FunctionGraphTarget::Parameter { node: id, parameter: "function".into() }.current(session).map_err(|error| error.to_string())?; + Ok(json!({"kind": "function", "node": id, "parameter": "function"})) + } + "graph_instance" => { + let (index, _) = materialcraft_eval::instance_graph(&session.pkg, node).ok_or("the referenced graph is missing")?; + Ok(json!({"kind": "graph", "node": id, "graph": index})) + } + _ => Err("the selected node has no editable graph".into()), } - - Ok(id) -} - -fn enabled(session: &Session) -> std::result::Result<(), String> { - selected_node(session).map(|_| ()) -} - -fn edit(session: &mut Session, _: &Value) -> Result { - let node = selected_node(session).map_err(|error| bad("graph.node.edit", error))?; - Ok(json!({"node": node.0, "parameter": "pattern"})) } diff --git a/crates/engine/src/pattern_edit.rs b/crates/engine/src/pattern_edit.rs new file mode 100644 index 0000000..5a47936 --- /dev/null +++ b/crates/engine/src/pattern_edit.rs @@ -0,0 +1,114 @@ +use materialcraft_core::{PatternGraph, PatternNodeKind, Value}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value as Json, json}; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(tag = "action", rename_all = "camelCase")] +pub enum PatternEdit { + Add { + kind: PatternNodeKind, + at: [f32; 2], + #[serde(default)] + snap: bool, + }, + Move { + ids: Vec, + by: [f32; 2], + #[serde(default)] + snap: bool, + }, + Connect { + parent: u32, + slot: usize, + child: u32, + }, + Disconnect { + node: u32, + slot: Option, + }, + Root { + id: u32, + }, + Value { + id: u32, + parameter: String, + value: Option, + }, +} + +impl PatternEdit { + pub(crate) fn apply(&self, graph: &mut PatternGraph) -> Result { + match self { + Self::Add { kind, at, snap } => { + let id = graph.add(*kind)?; + if let Some(node) = graph.nodes.last_mut() { + node.position = crate::graph_grid::snap_position(*at, *snap); + } + return Ok(json!({"id": id})); + } + Self::Move { ids, by, snap } => { + for id in ids { + if !graph.nodes.iter().any(|node| node.id == *id) { + return Err(format!("no FX-Map node {id}")); + } + } + for node in &mut graph.nodes { + if ids.contains(&node.id) { + node.position = crate::graph_grid::translate(node.position, *by, *snap); + } + } + } + Self::Connect { parent, slot, child } => { + if !graph.nodes.iter().any(|node| node.id == *child) { + return Err("missing child node".into()); + } + let destination = + graph.nodes.iter_mut().find(|node| node.id == *parent).and_then(|node| node.children.get_mut(*slot)).ok_or("invalid child slot")?; + *destination = Some(*child); + } + Self::Disconnect { node, slot } => { + if let Some(slot) = slot { + let destination = graph + .nodes + .iter_mut() + .find(|candidate| candidate.id == *node) + .and_then(|node| node.children.get_mut(*slot)) + .ok_or("invalid child slot")?; + *destination = None; + } else { + for child in graph.nodes.iter_mut().flat_map(|node| &mut node.children) { + if *child == Some(*node) { + *child = None; + } + } + } + } + Self::Root { id } => { + if !graph.nodes.iter().any(|node| node.id == *id) { + return Err("missing root node".into()); + } + graph.root = Some(*id); + } + Self::Value { id, parameter, value } => { + let node = graph.nodes.iter_mut().find(|node| node.id == *id).ok_or("missing FX-Map node")?; + let definition = materialcraft_nodes::pattern::definition(node.kind).ok_or("unknown FX-Map node")?; + if !definition.params.iter().any(|candidate| candidate.id == parameter) { + return Err("unknown FX-Map parameter".into()); + } + if let Some(value) = value { + node.parameters.insert(parameter.clone(), value.clone()); + } else { + node.parameters.remove(parameter); + } + } + } + Ok(Json::Null) + } + + pub(crate) fn merge_key(&self) -> Option { + match self { + Self::Value { id, parameter, .. } => Some(format!("value:{id}:{parameter}")), + _ => None, + } + } +} diff --git a/crates/engine/src/pattern_graph_commands.rs b/crates/engine/src/pattern_graph_commands.rs index 6e0118c..95c38eb 100644 --- a/crates/engine/src/pattern_graph_commands.rs +++ b/crates/engine/src/pattern_graph_commands.rs @@ -16,10 +16,7 @@ fn set(session: &mut Session, parameters: &Json) -> Result { let graph: PatternGraph = serde_json::from_value(parameters.get("pattern").cloned().unwrap_or(Json::Null)).map_err(|error| bad("graph.pattern.set", error.to_string()))?; - graph.validate().map_err(|error| bad("graph.pattern.set", error))?; - if graph.nodes.iter().any(|node| node.position.iter().any(|coordinate| !coordinate.is_finite())) { - return Err(bad("graph.pattern.set", "node positions must be finite")); - } + crate::graph_validation::pattern(&graph).map_err(|error| bad("graph.pattern.set", error))?; session.edit("Edit FX-Map graph", |session| { session.graph_mut()?.node_mut(id)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph))); diff --git a/crates/engine/src/preview_cook.rs b/crates/engine/src/preview_cook.rs new file mode 100644 index 0000000..1a225f2 --- /dev/null +++ b/crates/engine/src/preview_cook.rs @@ -0,0 +1,32 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::{Arc, Mutex}; + +use materialcraft_core::Package; +use materialcraft_eval::{Cache, Cooked, Options}; + +/// One background result for the editor and the assigned material sources +#[derive(Default)] +pub struct PreviewCook { + pub graph: usize, + pub cooked: Cooked, + pub materials: BTreeMap, +} + +impl PreviewCook { + pub fn run(package: &Package, graph: usize, materials: &BTreeSet, options: &Options<'_>, cache: &Arc>) -> Self { + let mut result = Self { graph, cooked: materialcraft_eval::cook(package, graph, options, cache), materials: BTreeMap::new() }; + for &index in materials { + if result.cancelled() { + break; + } + if index != graph && package.graphs.get(index).is_some() { + result.materials.insert(index, materialcraft_eval::cook(package, index, options, cache)); + } + } + result + } + + pub fn cancelled(&self) -> bool { + self.cooked.cancelled || self.materials.values().any(|cooked| cooked.cancelled) + } +} diff --git a/crates/engine/src/selection_commands.rs b/crates/engine/src/selection_commands.rs new file mode 100644 index 0000000..e49913f --- /dev/null +++ b/crates/engine/src/selection_commands.rs @@ -0,0 +1,191 @@ +//! Targeted selection and clipboard commands for standalone and embedded graphs + +use crate::{EmbeddedClipboard, Result, Session, commands::bad, graph_edit, selection_target::SelectionTarget}; +use materialcraft_core::{FunctionGraph, NodeId, PatternGraph, Value}; +use serde_json::{Value as Json, json}; + +pub fn supports(command: &str) -> bool { + matches!( + command, + "graph.select" + | "edit.selectAll" + | "edit.selectNone" + | "edit.copy" + | "edit.cut" + | "edit.paste" + | "edit.pasteWithoutLinks" + | "edit.delete" + | "edit.deleteRelink" + | "edit.duplicate" + | "edit.duplicateWithoutLinks" + | "graph.selectUpstream" + | "graph.selectDownstream" + ) +} + +fn selected(session: &Session, target: &SelectionTarget, parameters: &Json) -> Result> { + if let Some(ids) = parameters.get("ids") { + return serde_json::from_value(ids.clone()).map_err(|error| bad("graph selection", error.to_string())); + } + if target.standalone() { + return session.selection.iter().map(|id| u32::try_from(id.0).map_err(|_| bad("graph selection", "invalid function node id"))).collect(); + } + Ok(Vec::new()) +} + +pub fn enabled(session: &Session, command: &str, parameters: &Json) -> Option { + if !handles(session, command, parameters) { + return None; + } + let target = match SelectionTarget::resolve(session, parameters) { + Ok(Some(target)) => target, + Ok(None) => return None, + Err(_) => return Some(false), + }; + let selection = match selected(session, &target, parameters) { + Ok(selection) => selection, + Err(_) => return Some(false), + }; + enabled_for(session, &target, &selection, command) +} + +pub fn enabled_for(session: &Session, target: &SelectionTarget, selection: &[u32], command: &str) -> Option { + if !supports(command) { + return None; + } + match target { + SelectionTarget::Function(target) => { + if target.current(session).is_err() { + return Some(false); + } + let nodes = match &session.embedded_clipboard { + Some(EmbeddedClipboard::Function { nodes, .. }) => nodes.as_slice(), + _ => &[], + }; + graph_edit::enabled::(selection, nodes, command) + } + SelectionTarget::Pattern(owner) => { + if SelectionTarget::pattern(session, *owner).is_err() { + return Some(false); + } + let nodes = match &session.embedded_clipboard { + Some(EmbeddedClipboard::Pattern { nodes, .. }) => nodes.as_slice(), + _ => &[], + }; + graph_edit::enabled::(selection, nodes, command) + } + } +} + +fn handles(session: &Session, command: &str, parameters: &Json) -> bool { + supports(command) + && !(parameters.get("function").is_none() + && parameters.get("pattern").is_none() + && session.annotation_selection.is_some() + && matches!(command, "edit.delete" | "edit.deleteRelink")) +} + +pub(crate) fn execute(session: &mut Session, command: &str, parameters: &Json) -> Option> { + if !handles(session, command, parameters) { + return None; + } + match SelectionTarget::resolve(session, parameters) { + Ok(Some(target)) => Some(run(session, command, parameters, target)), + Ok(None) => None, + Err(error) => Some(Err(error)), + } +} + +fn run(session: &mut Session, command: &str, parameters: &Json, target: SelectionTarget) -> Result { + let source = target.source(session)?; + let mut selection = selected(session, &target, parameters)?; + if command == "graph.select" && target.standalone() && parameters.get("add").and_then(Json::as_bool) == Some(true) { + for id in session.selection.iter().filter_map(|id| u32::try_from(id.0).ok()) { + if !selection.contains(&id) { + selection.push(id); + } + } + } + let copied_count = selection.len(); + let at = crate::commands::point(parameters, "at").unwrap_or([0.0; 2]); + let snap = parameters.get("snapToGrid").and_then(Json::as_bool).unwrap_or(false); + let supplied: Option = + parameters.get("clip").cloned().map(serde_json::from_value).transpose().map_err(|error| bad(command, error.to_string()))?; + let clipboard = supplied.as_ref().or(session.embedded_clipboard.as_ref()); + let copying = matches!(command, "edit.copy" | "edit.cut"); + let updated_clipboard = match &target { + SelectionTarget::Function(function) => { + let (nodes, origin) = match clipboard { + Some(EmbeddedClipboard::Function { nodes, source }) => (nodes.as_slice(), source.as_str()), + _ => (&[][..], ""), + }; + let (graph, copied) = apply(function.current(session)?, &mut selection, nodes, paste_command(command, origin == source), at, snap)?; + if let Some(graph) = graph { + crate::graph_validation::function(&graph).map_err(|error| bad(command, error))?; + session.edit("Edit Function Graph", |session| function.replace(session, graph))?; + } + copying.then_some(EmbeddedClipboard::Function { source, nodes: copied }) + } + SelectionTarget::Pattern(owner) => { + let (nodes, origin) = match clipboard { + Some(EmbeddedClipboard::Pattern { nodes, source }) => (nodes.as_slice(), source.as_str()), + _ => (&[][..], ""), + }; + let (graph, copied) = apply(SelectionTarget::pattern(session, *owner)?, &mut selection, nodes, paste_command(command, origin == source), at, snap)?; + if let Some(graph) = graph { + crate::graph_validation::pattern(&graph).map_err(|error| bad(command, error))?; + session.edit("Edit FX-Map graph", |session| { + session.graph_mut()?.node_mut(*owner)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph))); + Ok(()) + })?; + } + copying.then_some(EmbeddedClipboard::Pattern { source, nodes: copied }) + } + }; + if target.standalone() { + session.selection = selection.iter().map(|id| NodeId(u64::from(*id))).collect(); + session.annotation_selection = None; + } + let mut result = json!({"ids": selection, "selected": selection.len()}); + if copying { + result["clip"] = json!(updated_clipboard); + result["copied"] = json!(copied_count); + } + if let Some(clipboard) = updated_clipboard { + session.embedded_clipboard = Some(clipboard); + } + Ok(result) +} + +fn paste_command(command: &str, same_source: bool) -> &str { + if command == "edit.paste" && !same_source { "edit.pasteWithoutLinks" } else { command } +} + +fn apply( + graph: &G, + selection: &mut Vec, + clipboard: &[G::Node], + command: &str, + at: [f32; 2], + snap: bool, +) -> Result<(Option, Vec)> { + if !matches!(command, "edit.selectAll" | "edit.selectNone") { + let present: std::collections::BTreeSet<_> = graph.nodes().iter().map(G::id).collect(); + if selection.iter().any(|id| !present.contains(id)) { + return Err(bad(command, "selection contains a missing node")); + } + } + if graph_edit::enabled::(selection, clipboard, command) != Some(true) { + return Err(bad(command, "the selection or clipboard does not support this action")); + } + let mut copied = Vec::new(); + if graph_edit::read(graph, selection, &mut copied, command) { + return Ok((None, copied)); + } + if command.starts_with("edit.paste") { + copied = clipboard.to_vec(); + } + let mut edited = graph.clone(); + let changed = graph_edit::run(&mut edited, selection, &mut copied, command, at, snap).map_err(|error| bad(command, error))?; + Ok((changed.then_some(edited), copied)) +} diff --git a/crates/engine/src/selection_target.rs b/crates/engine/src/selection_target.rs new file mode 100644 index 0000000..663ea20 --- /dev/null +++ b/crates/engine/src/selection_target.rs @@ -0,0 +1,51 @@ +use crate::{FunctionGraphTarget, Result, Session, commands::bad}; +use materialcraft_core::{NodeId, PatternGraph, Value}; +use serde_json::Value as Json; + +#[derive(Clone, Debug)] +pub enum SelectionTarget { + Function(FunctionGraphTarget), + Pattern(NodeId), +} + +impl SelectionTarget { + pub(crate) fn resolve(session: &Session, parameters: &Json) -> Result> { + if parameters.get("function").is_some() && parameters.get("pattern").is_some() { + return Err(bad("graph selection", "specify function or pattern, not both")); + } + if let Some(graph) = parameters.get("graph") + && graph.as_u64() != Some(session.graph as u64) + { + return Err(bad("graph selection", "the owning graph is no longer active")); + } + if let Some(target) = parameters.get("function") { + let target = serde_json::from_value(target.clone()).map_err(|error| bad("graph selection", error.to_string()))?; + return Ok(Some(Self::Function(target))); + } + if let Some(owner) = parameters.get("pattern") { + let owner = owner.as_u64().ok_or_else(|| bad("graph selection", "pattern must be an owner node id"))?; + return Ok(Some(Self::Pattern(NodeId(owner)))); + } + Ok(session.graph()?.function.as_ref().map(|_| Self::Function(FunctionGraphTarget::Graph))) + } + + pub(crate) fn standalone(&self) -> bool { + matches!(self, Self::Function(FunctionGraphTarget::Graph)) + } + + pub(crate) fn source(&self, session: &Session) -> Result { + Ok(format!("{}:{self:?}", session.graph()?.name)) + } + + pub(crate) fn pattern(session: &Session, owner: NodeId) -> Result<&PatternGraph> { + let node = session.graph()?.node(owner)?; + if node.def != "fx_map" { + return Err(bad("graph selection", "the node is not an FX-Map")); + } + let value = node.params.get("pattern").or_else(|| materialcraft_nodes::find(&node.def)?.param("pattern").map(|parameter| ¶meter.default)); + match value { + Some(Value::PatternGraph(graph)) => Ok(graph), + _ => Err(bad("graph selection", "missing FX-Map graph")), + } + } +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index ca5a9fe..3e3d274 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -124,6 +124,9 @@ pub struct Session { pub annotation_selection: Option, pub view2d: View2d, pub view3d: View3d, + pub material_preview: crate::MaterialPreview, + pub(crate) cooked_graph: Option, + pub(crate) material_cooked: std::collections::BTreeMap, /// Cap on node output size while editing (`None` = full size). pub preview_size: Option, /// 3D view camera preferences (set with [`Session::set_camera_prefs`]). @@ -133,6 +136,7 @@ pub struct Session { /// What the last opened SBS package held that MaterialCraft couldn't read; empty after a clean open. pub load_warnings: Vec, pub clipboard: Option, + pub embedded_clipboard: Option, /// The last cook of the open graph. pub cooked: Cooked, /// Set when the graph changed and needs cooking. @@ -151,6 +155,9 @@ pub struct Session { impl Session { pub fn new(pkg: Package) -> Session { Session { + material_preview: crate::MaterialPreview::for_graph(&pkg, 0), + cooked_graph: None, + material_cooked: std::collections::BTreeMap::new(), pkg, path: None, graph: 0, @@ -164,6 +171,7 @@ impl Session { log: Vec::new(), load_warnings: Vec::new(), clipboard: None, + embedded_clipboard: None, cooked: Cooked::default(), dirty: true, cache: Arc::new(Mutex::new(Cache::default())), @@ -190,6 +198,7 @@ impl Session { graph: self.graph, selection: self.selection.clone(), annotation_selection: self.annotation_selection, + material_preview: self.material_preview.clone(), label: label.into(), } } @@ -217,6 +226,11 @@ impl Session { r } + /// End the current gesture without adding an undo step + pub fn finish_edit(&mut self) { + self.merge_key = None; + } + fn edit_inner(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result) -> Result { let snap = self.snapshot(label); match f(self) { @@ -241,6 +255,8 @@ impl Session { self.graph = s.graph.min(self.pkg.graphs.len().saturating_sub(1)); self.selection = s.selection; self.annotation_selection = s.annotation_selection; + self.material_preview = s.material_preview; + self.clear_preview_results(); } /// Mark the document modified and in need of a cook. @@ -319,11 +335,22 @@ impl Session { let dec = self.resource_decoder(); let mut opts = Options::new(&dec); opts.max_size = self.preview_size; - self.cooked = materialcraft_eval::cook(&self.pkg, self.graph, &opts, &self.cache); + let cooked = crate::PreviewCook::run(&self.pkg, self.graph, &self.material_preview.graphs(), &opts, &self.cache); + self.accept_preview(cooked); self.dirty = false; &self.cooked } + /// Publish a completed editor and material cook together + pub fn accept_preview(&mut self, result: crate::PreviewCook) { + if result.graph != self.graph || result.cancelled() { + return; + } + self.cooked_graph = Some(result.graph); + self.cooked = result.cooked; + self.material_cooked = result.materials; + } + /// Cook graph `gi` at full size, without touching the preview results. pub fn cook_full(&self, gi: usize) -> Cooked { let dec = self.resource_decoder(); @@ -358,12 +385,6 @@ impl Session { self.view3d.target = self.camera.clamp_target(self.view3d.target); } - /// The open graph's material channels for the 3D view: usage id → image. - pub fn material_maps(&self) -> Vec<(&'static str, &Image)> { - let Ok(g) = self.graph() else { return Vec::new() }; - materialcraft_eval::outputs(g, &self.cooked).into_iter().filter_map(|(_, usage, _, img)| Some((usage, img?))).collect() - } - /// Show a mesh file in the 3D view (OBJ, glTF, GLB). pub fn load_mesh_bytes(&mut self, name: &str, bytes: &[u8]) -> Result<()> { let mesh = materialcraft_formats::mesh::load_mesh(name, bytes)?; diff --git a/crates/engine/src/snapshot.rs b/crates/engine/src/snapshot.rs index 110c7ca..b09078c 100644 --- a/crates/engine/src/snapshot.rs +++ b/crates/engine/src/snapshot.rs @@ -7,5 +7,6 @@ pub(crate) struct Snapshot { pub(crate) graph: usize, pub(crate) selection: Vec, pub(crate) annotation_selection: Option, + pub(crate) material_preview: crate::MaterialPreview, pub(crate) label: String, } diff --git a/crates/engine/tests/atomics.rs b/crates/engine/tests/atomics.rs index 61001b9..8660a3b 100644 --- a/crates/engine/tests/atomics.rs +++ b/crates/engine/tests/atomics.rs @@ -171,17 +171,30 @@ fn levels_preserve_independent_rgba_parameters_in_sbs() { } #[test] -fn selected_pattern_graph_is_resolved_without_changing_the_document() { +fn selected_node_graph_is_resolved_without_changing_the_document() { let mut session = materialcraft_engine::new_session(); assert!(execute(&mut session, "graph.node.edit", &json!({})).is_err()); - let node = execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap(); - let original = session.pkg.clone(); - let history = session.history(); - - assert_eq!(execute(&mut session, "graph.node.edit", &json!({})).unwrap(), json!({"node": node, "parameter": "pattern"})); - assert_eq!(session.pkg, original); - assert_eq!(session.history(), history); - + for (definition, kind, parameter) in + [("fx_map", "pattern", "pattern"), ("pixel_processor", "function", "function"), ("value_processor", "function", "function")] + { + let node = execute(&mut session, "graph.node.add", &json!({"def": definition})).unwrap()["id"].as_u64().unwrap(); + let original = session.pkg.clone(); + let history = session.history(); + assert_eq!(execute(&mut session, "graph.node.edit", &json!({})).unwrap(), json!({"kind": kind, "node": node, "parameter": parameter})); + assert_eq!(session.pkg, original); + assert_eq!(session.history(), history); + } execute(&mut session, "graph.node.add", &json!({"def": "uniform"})).unwrap(); assert!(execute(&mut session, "graph.node.edit", &json!({})).is_err()); + + let node = session.graph_mut().unwrap().add_node("graph_instance", [0.0; 2]); + session.graph_mut().unwrap().node_mut(node).unwrap().params.insert("graph".into(), Value::Text("Child".into())); + session.selection = vec![node]; + assert!(execute(&mut session, "graph.node.edit", &json!({})).is_err()); + session.pkg.graphs.push(materialcraft_engine::core::Graph::new("Child")); + let original = session.pkg.clone(); + let history = session.history(); + assert_eq!(execute(&mut session, "graph.node.edit", &json!({})).unwrap(), json!({"kind": "graph", "node": node, "graph": 1})); + assert_eq!(session.pkg, original); + assert_eq!(session.history(), history); } diff --git a/crates/engine/tests/embedded_edit.rs b/crates/engine/tests/embedded_edit.rs new file mode 100644 index 0000000..c995c2e --- /dev/null +++ b/crates/engine/tests/embedded_edit.rs @@ -0,0 +1,319 @@ +use materialcraft_engine::{ + FunctionGraphTarget, Session, + core::{FunctionGraph, NodeId, PatternGraph, PatternNodeKind, Value}, + execute, new_session, +}; +use serde_json::json; + +fn function_session(kind: &str) -> (Session, FunctionGraphTarget) { + let mut session = new_session(); + let target = match kind { + "graph" => { + execute(&mut session, "file.new", &json!({"kind": "function"})).unwrap(); + FunctionGraphTarget::Graph + } + "pattern" => { + let owner = NodeId(execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); + let node = graph.nodes[0].id; + graph.nodes[0].parameters.insert("patternrotation".into(), Value::Function(Box::default())); + execute(&mut session, "graph.pattern.set", &json!({"id": owner.0, "pattern": graph})).unwrap(); + FunctionGraphTarget::Pattern { owner, node, parameter: "patternrotation".into() } + } + _ => { + let node = NodeId(execute(&mut session, "graph.node.add", &json!({"def": "pixel_processor"})).unwrap()["id"].as_u64().unwrap()); + if kind == "dynamic" { + session.graph_mut().unwrap().node_mut(node).unwrap().functions.insert("test".into(), FunctionGraph::default()); + FunctionGraphTarget::Dynamic { node, parameter: "test".into() } + } else { + FunctionGraphTarget::Parameter { node, parameter: "function".into() } + } + } + }; + execute(&mut session, "graph.function.set", &json!({"target": target, "function": FunctionGraph::default()})).unwrap(); + session.reset_history(); + (session, target) +} + +#[test] +fn creation_and_connections_use_the_same_rules_for_every_function_target() { + for kind in ["graph", "parameter", "dynamic", "pattern"] { + let (mut session, target) = function_session(kind); + let mut ids = Vec::new(); + for operation in ["const_float1", "mul"] { + let result = execute( + &mut session, + "graph.function.edit", + &json!({"target": target, "edit": {"action": "add", "operation": operation, "at": [19, -19], "snap": true}}), + ) + .unwrap(); + ids.push(result["id"].as_u64().unwrap() as u32); + } + let graph = target.current(&session).unwrap(); + assert_eq!(graph.node(ids[1]).unwrap().inputs, vec![None, None]); + assert_eq!(graph.node(ids[1]).unwrap().pos, [32.0, -32.0]); + assert_eq!(graph.output, Some(ids[0])); + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "connect", "from": ids[0], "to": ids[1], "input": 0}})) + .unwrap(); + assert_eq!(target.current(&session).unwrap().node(ids[1]).unwrap().inputs[0], Some(ids[0])); + let before = session.pkg.clone(); + for edit in [ + json!({"action": "connect", "from": ids[1], "to": ids[1], "input": 0}), + json!({"action": "connect", "from": ids[0], "to": ids[1], "input": 1000000}), + json!({"action": "add", "operation": "unknown", "at": [0, 0]}), + ] { + assert!(execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": edit})).is_err()); + assert_eq!(session.pkg, before); + } + } +} + +#[test] +fn value_gestures_merge_but_separate_edits_undo_independently() { + for kind in ["graph", "parameter", "dynamic", "pattern"] { + let (mut session, target) = function_session(kind); + let added = + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": "const_float1", "at": [0, 0]}})) + .unwrap(); + let id = added["id"].as_u64().unwrap(); + let initial = target.current(&session).unwrap().node(id as u32).unwrap().value.clone(); + session.reset_history(); + for value in [1.0, 2.0, 3.0] { + execute( + &mut session, + "graph.function.edit", + &json!({"target": target, "merge": true, "edit": {"action": "value", "id": id, "value": Value::Float(value)}}), + ) + .unwrap(); + } + assert_eq!(session.history().len(), 1, "{kind}"); + execute(&mut session, "edit.finish", &json!({})).unwrap(); + for value in [4.0, 5.0] { + execute( + &mut session, + "graph.function.edit", + &json!({"target": target, "merge": true, "edit": {"action": "value", "id": id, "value": Value::Float(value)}}), + ) + .unwrap(); + } + assert_eq!(session.history().len(), 2, "{kind}"); + session.undo(); + assert_eq!(target.current(&session).unwrap().node(id as u32).unwrap().value, Some(Value::Float(3.0))); + session.undo(); + assert_eq!(target.current(&session).unwrap().node(id as u32).unwrap().value, initial); + for _ in 0..2 { + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": "mul", "at": [0, 0]}})).unwrap(); + } + session.undo(); + assert_eq!(target.current(&session).unwrap().nodes.len(), 2); + } +} + +#[test] +fn pattern_value_gestures_and_invalid_connections_are_atomic() { + let mut session = new_session(); + let owner = execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap(); + let result = execute(&mut session, "graph.pattern.edit", &json!({"id": owner, "edit": {"action": "add", "kind": "paramset", "at": [0, 0]}})).unwrap(); + let id = result["id"].as_u64().unwrap(); + session.reset_history(); + for value in [1.0, 2.0, 3.0] { + execute( + &mut session, + "graph.pattern.edit", + &json!({"id": owner, "merge": true, "edit": {"action": "value", "id": id, "parameter": "patternrotation", "value": Value::Float(value)}}), + ) + .unwrap(); + } + assert_eq!(session.history().len(), 1); + execute(&mut session, "edit.finish", &json!({})).unwrap(); + execute( + &mut session, + "graph.pattern.edit", + &json!({"id": owner, "merge": true, "edit": {"action": "value", "id": id, "parameter": "patternrotation", "value": Value::Float(4.0)}}), + ) + .unwrap(); + assert_eq!(session.history().len(), 2); + let before = session.pkg.clone(); + assert!(execute(&mut session, "graph.pattern.edit", &json!({"id": owner, "edit": {"action": "connect", "parent": id, "slot": 0, "child": id}})).is_err()); + assert_eq!(session.pkg, before); + assert!(execute(&mut session, "graph.function.edit", &json!({"target": {"kind": "pattern", "owner": owner, "node": id, "parameter": "absent"}, "edit": {"action": "add", "operation": "mul", "at": [0, 0]}})).is_err()); + assert_eq!(session.pkg, before); +} + +#[test] +fn selection_commands_work_without_a_ui_for_every_function_target() { + for kind in ["graph", "parameter", "dynamic", "pattern"] { + let (mut session, target) = function_session(kind); + for operation in ["const_float1", "passthrough"] { + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": operation, "at": [0, 0]}})).unwrap(); + } + let target_parameters = if kind == "graph" { json!({}) } else { json!({"function": target}) }; + let parent_selection = session.selection.clone(); + session.reset_history(); + let selected = execute(&mut session, "edit.selectAll", &target_parameters).unwrap(); + assert_eq!(selected["selected"], 2, "{kind}"); + let mut parameters = target_parameters.clone(); + parameters["ids"] = selected["ids"].clone(); + let copied = execute(&mut session, "edit.copy", ¶meters).unwrap(); + assert_eq!(copied["copied"], 2); + assert!(session.history().is_empty()); + let duplicated = execute(&mut session, "edit.duplicate", ¶meters).unwrap(); + assert_eq!(target.current(&session).unwrap().nodes.len(), 4); + parameters["ids"] = duplicated["ids"].clone(); + execute(&mut session, "edit.delete", ¶meters).unwrap(); + assert_eq!(target.current(&session).unwrap().nodes.len(), 2); + parameters["ids"] = json!([]); + parameters["clip"] = copied["clip"].clone(); + execute(&mut session, "edit.paste", ¶meters).unwrap(); + assert_eq!(target.current(&session).unwrap().nodes.len(), 4); + if kind != "graph" { + assert_eq!(session.selection, parent_selection, "embedded commands changed the parent selection"); + } + } +} + +#[test] +fn rejected_function_duplicate_preserves_document_selection_clipboard_and_history() { + let (mut session, target) = function_session("graph"); + let mut graph = FunctionGraph::default(); + for _ in 0..2049 { + graph.add("passthrough", &[], None); + } + execute(&mut session, "graph.function.set", &json!({"function": graph})).unwrap(); + execute(&mut session, "edit.selectAll", &json!({})).unwrap(); + execute(&mut session, "edit.copy", &json!({})).unwrap(); + let before = session.pkg.clone(); + let selection = session.selection.clone(); + let clipboard = serde_json::to_value(&session.embedded_clipboard).unwrap(); + let history = session.history(); + assert!(execute(&mut session, "edit.duplicate", &json!({})).is_err()); + assert_eq!(session.pkg, before); + assert_eq!(session.selection, selection); + assert_eq!(serde_json::to_value(&session.embedded_clipboard).unwrap(), clipboard); + assert_eq!(session.history(), history); + assert_eq!(target.current(&session).unwrap().nodes.len(), 2049); +} + +#[test] +fn graph_validation_is_shared_by_creation_legacy_setters_and_targeted_edits() { + let mut cyclic = FunctionGraph::default(); + let id = cyclic.add("passthrough", &[], None); + cyclic.nodes[0].inputs = vec![Some(id)]; + cyclic.output = Some(id); + let mut session = new_session(); + let owner = execute(&mut session, "graph.node.add", &json!({"def": "pixel_processor"})).unwrap()["id"].as_u64().unwrap(); + let before = session.pkg.clone(); + for (command, parameters) in [ + ("graph.node.add", json!({"def": "pixel_processor", "params": {"function": Value::Function(Box::new(cyclic.clone()))}})), + ("graph.node.param", json!({"id": owner, "param": "function", "value": Value::Function(Box::new(cyclic.clone()))})), + ("graph.node.function", json!({"id": owner, "param": "color_mode", "function": cyclic})), + ("graph.function.set", json!({"target": {"kind": "parameter", "node": owner, "parameter": "function"}, "function": cyclic})), + ] { + let error = execute(&mut session, command, ¶meters).unwrap_err().to_string(); + assert!(error.contains("cycle"), "{command}: {error}"); + assert_eq!(session.pkg, before); + } + let owner = execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap(); + let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); + graph.nodes[0].parameters.insert("patternrotation".into(), Value::Function(Box::new(cyclic.clone()))); + let before = session.pkg.clone(); + for (command, parameters) in [ + ("graph.pattern.set", json!({"id": owner, "pattern": graph})), + ("graph.node.param", json!({"id": owner, "param": "pattern", "value": Value::PatternGraph(Box::new(graph))})), + ( + "graph.pattern.edit", + json!({"id": owner, "edit": {"action": "value", "id": 1, "parameter": "patternrotation", "value": Value::Function(Box::new(cyclic))}}), + ), + ] { + assert!(execute(&mut session, command, ¶meters).unwrap_err().to_string().contains("cycle"), "{command}"); + assert_eq!(session.pkg, before); + } +} + +#[test] +fn pattern_selection_commands_and_cross_graph_clipboards_keep_ownership() { + let mut session = new_session(); + let owner = execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap(); + let selected = execute(&mut session, "edit.selectAll", &json!({"pattern": owner})).unwrap(); + let parameters = json!({"pattern": owner, "ids": selected["ids"]}); + execute(&mut session, "edit.copy", ¶meters).unwrap(); + let before = session.pkg.clone(); + assert!(execute(&mut session, "edit.deleteRelink", ¶meters).is_err()); + assert!(execute(&mut session, "edit.delete", &json!({"pattern": owner, "ids": [1], "graph": 99})).is_err()); + assert_eq!(session.pkg, before); + execute(&mut session, "edit.duplicate", ¶meters).unwrap(); + assert_eq!(session.selection, vec![NodeId(owner)]); + + let (mut session, _) = function_session("graph"); + let mut graph = FunctionGraph::default(); + let source = graph.add_constant(Value::Float(1.0)); + let child = graph.add("passthrough", &[source], None); + execute(&mut session, "graph.function.set", &json!({"function": graph})).unwrap(); + let copied = execute(&mut session, "edit.copy", &json!({"ids": [child]})).unwrap(); + execute(&mut session, "graph.duplicate", &json!({})).unwrap(); + let pasted = execute(&mut session, "edit.paste", &json!({"clip": copied["clip"]})).unwrap(); + let id = pasted["ids"][0].as_u64().unwrap() as u32; + assert_eq!(session.graph().unwrap().function.as_ref().unwrap().node(id).unwrap().inputs, vec![None]); +} + +#[test] +fn alignment_targets_embedded_functions_and_undo_restores_them() { + for kind in ["parameter", "dynamic", "pattern"] { + let (mut session, target) = function_session(kind); + for at in [[10, 30], [50, 90]] { + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": "const_float1", "at": at}})).unwrap(); + } + let before = session.pkg.clone(); + execute(&mut session, "graph.align", &json!({"function": target, "ids": [1, 2], "mode": "left"})).unwrap(); + let positions: Vec<_> = target.current(&session).unwrap().nodes.iter().map(|node| node.pos).collect(); + assert_eq!(positions, vec![[10.0, 30.0], [10.0, 90.0]]); + session.undo().unwrap(); + assert_eq!(session.pkg, before); + } +} + +#[test] +fn replacing_a_package_discards_embedded_clipboard_provenance() { + let (mut session, _) = function_session("graph"); + execute(&mut session, "graph.function.edit", &json!({"edit": {"action": "add", "operation": "const_float1", "at": [0, 0]}})).unwrap(); + execute(&mut session, "edit.selectAll", &json!({})).unwrap(); + execute(&mut session, "edit.copy", &json!({})).unwrap(); + assert!(session.embedded_clipboard.is_some()); + let package = session.pkg.clone(); + materialcraft_engine::file_cmds::replace_package(&mut session, package, None); + assert!(session.embedded_clipboard.is_none()); +} + +#[test] +fn processor_node_availability_is_shared_and_preserves_existing_sampler_graphs() { + for definition in ["pixel_processor", "value_processor"] { + let mut session = new_session(); + let node = NodeId(execute(&mut session, "graph.node.add", &json!({"def": definition})).unwrap()["id"].as_u64().unwrap()); + let target = FunctionGraphTarget::Parameter { node, parameter: "function".into() }; + let operations: Vec<_> = target.available_operations(&session).map(|operation| operation.id).collect(); + let full_catalog = materialcraft_engine::nodes::function::FUNCTIONS; + let sampling = definition == "pixel_processor"; + assert_eq!(operations.len(), full_catalog.len() - if sampling { 0 } else { 2 }); + assert!(operations.contains(&"add")); + for sampler in ["samplelum", "samplecol"] { + assert_eq!(operations.contains(&sampler), sampling); + let original = session.pkg.clone(); + let history = session.history(); + let result = + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": sampler, "at": [0, 0]}})); + assert_eq!(result.is_ok(), sampling); + if !sampling { + assert_eq!(session.pkg, original); + assert_eq!(session.history(), history); + } + } + let mut existing = FunctionGraph::default(); + existing.add("samplelum", &[], Some(Value::Int2([0, 1]))); + execute(&mut session, "graph.function.set", &json!({"target": target, "function": existing})).unwrap(); + assert_eq!(target.current(&session).unwrap().nodes[0].op, "samplelum"); + } + for kind in ["graph", "pattern", "dynamic"] { + let (session, target) = function_session(kind); + assert_eq!(target.available_operations(&session).count(), materialcraft_engine::nodes::function::FUNCTIONS.len()); + } +} diff --git a/crates/engine/tests/graph_alignment.rs b/crates/engine/tests/graph_alignment.rs new file mode 100644 index 0000000..88be9f4 --- /dev/null +++ b/crates/engine/tests/graph_alignment.rs @@ -0,0 +1,93 @@ +use materialcraft_engine::{ + Session, + core::{FunctionGraph, PatternGraph, PatternNodeKind, Value}, + execute, new_session, +}; +use serde_json::json; + +fn positions(session: &Session, kind: &str, owner: u64) -> Vec<[f32; 2]> { + let graph = session.graph().unwrap(); + match kind { + "function" => graph.function.as_ref().unwrap().nodes.iter().map(|node| node.pos).collect(), + "pattern" => { + let Value::PatternGraph(pattern) = &graph.node(materialcraft_engine::core::NodeId(owner)).unwrap().params["pattern"] else { + panic!("missing pattern") + }; + pattern.nodes.iter().map(|node| node.position).collect() + } + _ => graph.nodes.iter().map(|node| node.pos).collect(), + } +} + +#[test] +fn alignment_and_undo_target_only_the_active_graph_kind() { + for kind in ["material", "function", "pattern"] { + let mut session = new_session(); + let coordinates = [[0.0, 0.0], [32.0, 96.0], [256.0, 192.0]]; + let mut owner = 0; + let ids: Vec = match kind { + "function" => { + execute(&mut session, "file.new", &json!({"kind": "function"})).unwrap(); + let mut graph = FunctionGraph::default(); + for position in coordinates { + graph.add_constant(Value::Float(1.0)); + graph.nodes.last_mut().unwrap().pos = position; + } + let ids = graph.nodes.iter().map(|node| u64::from(node.id)).collect(); + execute(&mut session, "graph.function.set", &json!({"function": graph})).unwrap(); + ids + } + "pattern" => { + owner = execute(&mut session, "graph.node.add", &json!({"def": "fx_map", "at": [700, 800]})).unwrap()["id"].as_u64().unwrap(); + let mut graph = PatternGraph::default(); + for position in coordinates { + graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes.last_mut().unwrap().position = position; + } + let ids = graph.nodes.iter().map(|node| u64::from(node.id)).collect(); + execute(&mut session, "graph.pattern.set", &json!({"id": owner, "pattern": graph})).unwrap(); + ids + } + _ => coordinates + .into_iter() + .map(|position| execute(&mut session, "graph.node.add", &json!({"def": "uniform", "at": position})).unwrap()["id"].as_u64().unwrap()) + .collect(), + }; + let original = session.pkg.clone(); + for (mode, expected) in [("left", vec![[0.0, 0.0], [0.0, 96.0], [0.0, 192.0]]), ("hdistribute", vec![[0.0, 0.0], [128.0, 96.0], [256.0, 192.0]])] { + let mut parameters = json!({"ids": ids, "mode": mode}); + if kind == "pattern" { + parameters["pattern"] = json!(owner); + } + execute(&mut session, "graph.align", ¶meters).unwrap(); + assert_eq!(positions(&session, kind, owner), expected, "{kind}: {mode}"); + if kind == "pattern" { + assert_eq!(session.graph().unwrap().nodes[0].pos, [700.0, 800.0]); + assert_eq!(session.graph().unwrap().nodes.len(), 1); + } + session.undo().unwrap(); + assert_eq!(session.pkg, original); + parameters["ids"] = json!([u64::MAX]); + assert!(execute(&mut session, "graph.align", ¶meters).is_err()); + assert_eq!(session.pkg, original); + parameters["ids"] = json!(ids); + parameters["mode"] = json!("invalid"); + assert!(execute(&mut session, "graph.align", ¶meters).is_err()); + assert_eq!(session.pkg, original); + } + } +} + +#[test] +fn malformed_embedded_targets_never_fall_back_to_parent_selection() { + let mut session = new_session(); + for position in [[0, 0], [200, 100]] { + execute(&mut session, "graph.node.add", &json!({"def": "fx_map", "at": position})).unwrap(); + } + execute(&mut session, "edit.selectAll", &json!({})).unwrap(); + let original = session.pkg.clone(); + for parameters in [json!({"pattern": "invalid", "mode": "left"}), json!({"pattern": 1, "mode": "left"})] { + assert!(execute(&mut session, "graph.align", ¶meters).is_err()); + assert_eq!(session.pkg, original); + } +} diff --git a/crates/engine/tests/graph_edit.rs b/crates/engine/tests/graph_edit.rs new file mode 100644 index 0000000..a892a9a --- /dev/null +++ b/crates/engine/tests/graph_edit.rs @@ -0,0 +1,130 @@ +use materialcraft_engine::{ + core::{FunctionGraph, PatternGraph, PatternNodeKind, Value}, + graph_edit::{self, EditableGraph}, +}; + +fn exercise_clipboard(mut graph: G, chain: [u32; 3]) { + let mut selection = vec![chain[1], chain[2]]; + let mut clipboard = Vec::new(); + let before = graph.nodes().len(); + graph_edit::run(&mut graph, &mut selection, &mut clipboard, "edit.copy", [0.0; 2], true).unwrap(); + for command in ["edit.paste", "edit.pasteWithoutLinks"] { + graph_edit::run(&mut graph, &mut selection, &mut clipboard, command, [19.0, 19.0], true).unwrap(); + assert_eq!(selection.len(), 2); + let first = graph.nodes().iter().find(|node| G::id(node) == selection[0]).unwrap(); + let second = graph.nodes().iter().find(|node| G::id(node) == selection[1]).unwrap(); + assert_eq!(G::links(second)[0], Some(selection[0])); + assert_eq!(G::links(first)[0], if command == "edit.paste" { Some(chain[0]) } else { None }); + assert!(graph_edit::remove(&mut graph, &mut selection, false)); + assert_eq!(graph.nodes().len(), before); + } + + for command in ["graph.selectUpstream", "graph.selectDownstream"] { + selection = vec![chain[1]]; + graph_edit::run(&mut graph, &mut selection, &mut clipboard, command, [0.0; 2], false).unwrap(); + let follow_links = (command == "graph.selectUpstream") == G::LINKS_ARE_INPUTS; + let mut expected = if follow_links { vec![chain[0], chain[1]] } else { vec![chain[1], chain[2]] }; + expected.sort(); + assert_eq!(selection, expected); + } +} + +#[test] +fn function_and_pattern_clipboards_keep_internal_links_and_respect_direction() { + let mut function = FunctionGraph::default(); + let a = function.add_constant(Value::Float(1.0)); + let b = function.add("passthrough", &[a], None); + let c = function.add("passthrough", &[b], None); + exercise_clipboard(function, [a, b, c]); + + let mut pattern = PatternGraph::default(); + let a = pattern.add(PatternNodeKind::Dot).unwrap(); + let b = pattern.add(PatternNodeKind::Dot).unwrap(); + let c = pattern.add(PatternNodeKind::Dot).unwrap(); + pattern.nodes[1].children[0] = Some(a); + pattern.nodes[2].children[0] = Some(b); + exercise_clipboard(pattern, [a, b, c]); +} + +#[test] +fn pattern_paste_capacity_failure_is_atomic_and_root_is_preserved() { + let mut graph = PatternGraph::with_root(PatternNodeKind::Dot); + let node = graph.nodes[0].clone(); + graph.nodes = (1..4096).map(|id| materialcraft_engine::core::PatternNode { id, ..node.clone() }).collect(); + let before = graph.clone(); + let mut clipboard = vec![node.clone(), node]; + let mut selection = vec![1]; + assert!(graph_edit::run(&mut graph, &mut selection, &mut clipboard, "edit.paste", [0.0; 2], true).is_err()); + assert_eq!(graph, before); + assert_eq!(selection, vec![1]); +} + +#[test] +fn function_delete_relinks_chains_and_clears_a_deleted_output() { + let mut graph = FunctionGraph::default(); + let a = graph.add_constant(Value::Float(1.0)); + let b = graph.add("passthrough", &[a], None); + let c = graph.add("passthrough", &[b], None); + let d = graph.add("passthrough", &[c], None); + graph.output = Some(d); + assert!(graph_edit::remove(&mut graph, &mut vec![b, c], true)); + assert_eq!(graph.node(d).unwrap().inputs, vec![Some(a)]); + assert_eq!(graph.output, Some(d)); + assert!(graph_edit::remove(&mut graph, &mut vec![d], false)); + assert_eq!(graph.output, None); +} + +#[test] +fn pattern_clipboard_preserves_selection_order_when_ids_have_holes() { + let mut graph = PatternGraph::default(); + for _ in 0..3 { + graph.add(PatternNodeKind::Quadrant).unwrap(); + } + graph.nodes.remove(1); + let id = graph.add(PatternNodeKind::Quadrant).unwrap(); + assert_eq!(id, 2); + let mut selection = vec![2, 3]; + let mut clipboard = Vec::new(); + graph_edit::run(&mut graph, &mut selection, &mut clipboard, "edit.duplicate", [0.0; 2], false).unwrap(); + assert_eq!(selection, vec![5, 4]); +} + +#[test] +#[ignore = "release timing probe; run explicitly with --ignored --nocapture"] +fn connected_selection_performance() { + use std::{collections::BTreeSet, time::Instant}; + + let mut graph = FunctionGraph::default(); + for id in 1..=4096 { + graph.nodes.push(materialcraft_engine::core::FunctionNode { + id, + op: "passthrough".into(), + type_code: 0, + inputs: if id == 1 { vec![] } else { vec![Some(id - 1)] }, + value: None, + pos: [0.0; 2], + }); + } + let mut before = Vec::new(); + let mut after = Vec::new(); + for _ in 0..3 { + let start = Instant::now(); + let mut visited = BTreeSet::new(); + let mut pending = vec![1]; + while let Some(id) = pending.pop() { + if visited.insert(id) { + pending.extend(graph.nodes.iter().filter(|node| node.inputs.contains(&Some(id))).map(|node| node.id)); + } + } + let expected: Vec<_> = visited.into_iter().collect(); + before.push(start.elapsed().as_secs_f64() * 1000.0); + let mut selection = vec![1]; + let start = Instant::now(); + graph_edit::run(std::hint::black_box(&mut graph), &mut selection, &mut Vec::new(), "graph.selectDownstream", [0.0; 2], false).unwrap(); + after.push(start.elapsed().as_secs_f64() * 1000.0); + assert_eq!(selection, expected); + } + before.sort_by(f64::total_cmp); + after.sort_by(f64::total_cmp); + println!("4096-node downstream selection, median of three: scan {:.3} ms; shared index {:.3} ms", before[1], after[1]); +} diff --git a/crates/engine/tests/material_preview.rs b/crates/engine/tests/material_preview.rs new file mode 100644 index 0000000..054af70 --- /dev/null +++ b/crates/engine/tests/material_preview.rs @@ -0,0 +1,263 @@ +use materialcraft_engine::{ + MaterialPreview, MaterialSource, Session, + core::{Graph, MaterialChannel, NodeId, Package, Value}, + execute, new_session, +}; +use serde_json::json; + +fn add(session: &mut Session, definition: &str, params: serde_json::Value) -> NodeId { + NodeId(execute(session, "graph.node.add", &json!({"def": definition, "params": params})).unwrap()["id"].as_u64().unwrap()) +} + +fn source(session: &mut Session, color: [f32; 4]) -> NodeId { + add(session, "uniform", json!({"color_mode": true, "color": color})) +} + +fn output(session: &mut Session, source: NodeId, usage: u32) -> NodeId { + let output = add(session, "output", json!({"usage": usage})); + execute(session, "graph.connect", &json!({"from": source, "to": output})).unwrap(); + output +} + +fn instance(session: &mut Session, graph: &str) -> NodeId { + let node = session.graph_mut().unwrap().add_node("graph_instance", [0.0; 2]); + session.graph_mut().unwrap().node_mut(node).unwrap().params.insert("graph".into(), Value::Text(graph.into())); + node +} + +fn color(session: &mut Session, channel: &str) -> [f32; 4] { + session.cook(); + session.material_maps().into_iter().find(|(usage, _)| *usage == channel).unwrap().1.get(0, 0, false) +} + +#[test] +fn explicit_assignment_shows_unclassified_output_and_tracks_edits() { + let mut session = new_session(); + session.preview_size = Some(16); + let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + let output = output(&mut session, red, 9); + session.cook(); + assert!(session.material_maps().is_empty()); + let history = session.history(); + let package = session.pkg.clone(); + execute(&mut session, "view.3d.assign", &json!({"node": output, "channel": "baseColor"})).unwrap(); + assert_eq!(session.history(), history); + assert_eq!(session.pkg, package); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + let key = session.material_key(); + execute(&mut session, "graph.node.param", &json!({"id": red, "param": "color", "value": [0.1, 0.8, 0.2, 1.0]})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.1, 0.8, 0.2, 1.0]); + assert_ne!(session.material_key(), key); + let inspection = execute(&mut session, "session.inspect", &json!({})).unwrap(); + assert_eq!(inspection["material3d"]["channels"][0]["size"], json!([16, 16])); +} + +#[test] +fn automatic_outputs_follow_usage_and_do_not_follow_selection() { + let mut session = new_session(); + session.preview_size = Some(16); + let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + let blue = source(&mut session, [0.1, 0.1, 0.8, 1.0]); + let output = output(&mut session, red, 0); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "graph.select", &json!({"ids": [blue]})).unwrap(); + execute(&mut session, "view.2d", &json!({"node": blue})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "graph.node.param", &json!({"id": output, "param": "usage", "value": 4})).unwrap(); + assert_eq!(color(&mut session, "height"), [0.8, 0.1, 0.1, 1.0]); + assert!(session.material_maps().iter().all(|(channel, _)| *channel != "baseColor")); +} + +#[test] +fn graph_application_and_material_reset_preserve_camera_and_scene() { + let mut session = new_session(); + session.preview_size = Some(16); + let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + output(&mut session, red, 0); + let blue = source(&mut session, [0.1, 0.1, 0.8, 1.0]); + execute(&mut session, "view.3d.assign", &json!({"node": blue, "channel": "baseColor"})).unwrap(); + execute(&mut session, "view.3d.assign", &json!({"node": blue, "channel": "roughness"})).unwrap(); + execute(&mut session, "view.3d", &json!({"scene": "sphere", "yaw": 70, "distance": 4, "environment": "sunset"})).unwrap(); + let view = session.view3d.clone(); + execute(&mut session, "view.3d.outputs", &json!({})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + assert!(session.material_maps().iter().any(|(channel, _)| *channel == "roughness")); + execute(&mut session, "view.3d.outputs", &json!({"reset": true})).unwrap(); + session.cook(); + assert_eq!(session.material_maps().len(), 1); + assert_eq!(session.view3d, view); + execute(&mut session, "view.3d.clear", &json!({})).unwrap(); + assert!(session.material_maps().is_empty()); + assert_eq!(session.view3d, view); +} + +#[test] +fn assignments_survive_function_editing_and_undo_without_retargeting_node_ids() { + let mut session = new_session(); + session.preview_size = Some(16); + let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "view.3d.assign", &json!({"node": red, "channel": "baseColor"})).unwrap(); + session.cook(); + execute(&mut session, "file.new", &json!({"kind": "function", "name": "Function"})).unwrap(); + assert_eq!(session.material_maps()[0].1.get(0, 0, false), [0.8, 0.1, 0.1, 1.0], "keep the previous material while the worker cooks"); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "file.new", &json!({"template": "empty", "name": "Blue"})).unwrap(); + let blue = source(&mut session, [0.1, 0.1, 0.8, 1.0]); + assert_eq!(red, blue); + execute(&mut session, "view.3d.assign", &json!({"graph": 0, "node": red, "channel": "baseColor"})).unwrap(); + execute(&mut session, "graph.node.param", &json!({"id": blue, "param": "color", "value": [0.2, 0.2, 0.9, 1.0]})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "graph.rename", &json!({"graph": 0, "name": "Renamed"})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "graph.delete", &json!({"graph": 0})).unwrap(); + session.cook(); + assert!(session.material_maps().is_empty()); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "file.newPackage", &json!({})).unwrap(); + assert!(session.material_preview.channels.is_empty()); +} + +#[test] +fn opening_material_graph_automatically_applies_its_outputs() { + let mut session = new_session(); + session.preview_size = Some(16); + let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + output(&mut session, red, 0); + execute(&mut session, "file.new", &json!({"template": "empty", "name": "Blue"})).unwrap(); + let blue = source(&mut session, [0.1, 0.1, 0.8, 1.0]); + output(&mut session, blue, 0); + assert_eq!(color(&mut session, "baseColor"), [0.1, 0.1, 0.8, 1.0]); + execute(&mut session, "graph.open", &json!({"graph": 0})).unwrap(); + assert!(session.material_maps().is_empty(), "stale results must not cross graph IDs"); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); +} + +#[test] +fn invalid_assignments_are_atomic_including_scalar_instance_outputs() { + let mut session = new_session(); + session.preview_size = Some(16); + let image = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "view.3d.assign", &json!({"node": image, "channel": "baseColor"})).unwrap(); + let value = add(&mut session, "input_value", json!({})); + let value_output = output(&mut session, value, 0); + let mut graph = Graph::new("Values"); + let input = graph.add_node("input_value", [0.0; 2]); + let out = graph.add_node("output", [100.0, 0.0]); + graph.node_mut(out).unwrap().params.insert("identifier".into(), Value::Text("value".into())); + graph.connect(input, "output", out, "input").unwrap(); + session.pkg.graphs.push(graph); + let instance = instance(&mut session, "Values"); + let before = session.material_preview.clone(); + let history = session.history(); + let package = session.pkg.clone(); + for parameters in [ + json!({"node": image, "channel": "unknown", "reset": true}), + json!({"node": image, "channel": "baseColor", "port": 999, "reset": true}), + json!({"node": image, "channel": "baseColor", "graph": 999, "reset": true}), + json!({"node": value, "channel": "baseColor", "reset": true}), + json!({"node": value_output, "channel": "baseColor", "reset": true}), + json!({"node": instance, "port": "value", "channel": "baseColor", "reset": true}), + ] { + assert!(execute(&mut session, "view.3d.assign", ¶meters).is_err(), "{parameters}"); + assert_eq!(session.material_preview, before); + assert_eq!(session.history(), history); + assert_eq!(session.pkg, package); + } + assert!(execute(&mut session, "view.3d.outputs", &json!({"graph": "Values", "reset": true})).is_err()); + assert_eq!(session.material_preview, before); +} + +#[test] +fn multiple_graph_channels_and_multi_output_instances_use_the_correct_ports() { + let mut package = Package::new("Test"); + let mut graph = Graph::new("Colors"); + graph.size = [4, 4]; + for (name, color) in [("red", [0.8, 0.1, 0.1, 1.0]), ("blue", [0.1, 0.1, 0.8, 1.0])] { + let image = graph.add_node("uniform", [0.0; 2]); + graph.node_mut(image).unwrap().params.insert("color".into(), Value::Color(color)); + let output = graph.add_node("output", [100.0, 0.0]); + graph.node_mut(output).unwrap().params.insert("identifier".into(), Value::Text(name.into())); + graph.connect(image, "output", output, "input").unwrap(); + } + package.graphs.push(graph); + package.graphs.push(Graph::new("Instances")); + let mut session = Session::new(package); + execute(&mut session, "graph.open", &json!({"graph": 1})).unwrap(); + let instance = instance(&mut session, "Colors"); + execute(&mut session, "view.3d.assign", &json!({"node": instance, "port": "blue", "channel": "baseColor"})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.1, 0.1, 0.8, 1.0]); + let key = session.material_key(); + execute(&mut session, "view.3d.assign", &json!({"node": instance, "port": 0, "channel": "baseColor"})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + assert_ne!(session.material_key(), key); + execute(&mut session, "view.3d.assign", &json!({"graph": "Colors", "node": 1, "channel": "emissive"})).unwrap(); + assert_eq!(color(&mut session, "emissive"), [0.8, 0.1, 0.1, 1.0]); + assert_eq!(session.graph, 1); +} + +#[test] +fn removing_an_earlier_graph_adjusts_sources_and_undo_restores_them() { + let mut session = new_session(); + execute(&mut session, "file.new", &json!({"template": "empty"})).unwrap(); + let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "view.3d.assign", &json!({"node": red, "channel": "baseColor"})).unwrap(); + execute(&mut session, "graph.delete", &json!({"graph": 0})).unwrap(); + assert_eq!(session.material_preview.channels[&MaterialChannel::BaseColor].graph, 0); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(session.material_preview.channels[&MaterialChannel::BaseColor].graph, 1); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + let before = session.material_key(); + execute(&mut session, "graph.select", &json!({"ids": [red]})).unwrap(); + execute(&mut session, "edit.delete", &json!({})).unwrap(); + session.cook(); + assert!(session.material_maps().is_empty()); + assert_ne!(session.material_key(), before); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); +} + +#[test] +fn source_cycles_are_rejected_without_recursion() { + let mut package = Package::new("Cycle"); + let mut graph = Graph::new("Cycle"); + let instance = graph.add_node("graph_instance", [0.0; 2]); + graph.node_mut(instance).unwrap().params.insert("graph".into(), Value::Text("Cycle".into())); + let output = graph.add_node("output", [100.0, 0.0]); + graph.node_mut(output).unwrap().params.insert("identifier".into(), Value::Text("loop".into())); + graph.connect(instance, "loop", output, "input").unwrap(); + package.graphs.push(graph); + let source = MaterialSource { graph: 0, node: instance, port: "loop".into() }; + assert!(!source.is_image(&package)); + assert!(MaterialPreview::for_graph(&package, 0).sources(&package).is_empty()); +} + +#[test] +fn diffuse_usage_previews_as_base_color_and_unknown_usages_stay_unassigned() { + use materialcraft_engine::core::ComponentUsage; + + let mut session = new_session(); + session.preview_size = Some(16); + let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + let output = output(&mut session, red, ComponentUsage::index("diffuse")); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + for usage in [ComponentUsage::ANY_INDEX, u32::MAX, ComponentUsage::index("coatRoughness")] { + session.graph_mut().unwrap().node_mut(output).unwrap().params.insert("usage".into(), Value::Enum(usage)); + assert!(session.material_maps().is_empty(), "usage {usage} must not become a different channel"); + } +} + +#[test] +fn extracted_graph_outputs_remain_unclassified() { + let mut session = new_session(); + let uniform = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + output(&mut session, uniform, 0); + execute(&mut session, "graph.select", &json!({"ids": [uniform]})).unwrap(); + execute(&mut session, "graph.createFromSelection", &json!({"name": "Extracted"})).unwrap(); + let (_, graph) = session.pkg.graph_by_name("Extracted").unwrap(); + let output = graph.nodes.iter().find(|node| node.def == "output").unwrap(); + assert_eq!(materialcraft_engine::eval::output_usage(output), "any"); +} diff --git a/crates/engine/tests/optimization_perf.rs b/crates/engine/tests/optimization_perf.rs new file mode 100644 index 0000000..2ebcf7e --- /dev/null +++ b/crates/engine/tests/optimization_perf.rs @@ -0,0 +1,84 @@ +//! Focused optimization benchmarks: release, ignored, serial, with --nocapture +use std::{collections::BTreeMap, hint::black_box, sync::Mutex, time::Instant}; + +use materialcraft_core::{Connection, FunctionGraph, Graph, Package, PatternGraph, PatternNodeKind, Value}; +use materialcraft_eval::{Cache, Options, cook}; +use materialcraft_nodes::{CookContext, find, resolve_params}; + +fn median_ms(mut run: impl FnMut()) -> f64 { + let mut samples = [0.0; 3]; + for sample in &mut samples { + let start = Instant::now(); + run(); + *sample = start.elapsed().as_secs_f64() * 1000.0; + } + samples.sort_by(f64::total_cmp); + samples[1] +} + +#[test] +#[ignore = "optimization benchmark"] +fn optimization_baseline() { + for count in [128, 1024, 4096] { + let ms = median_ms(|| { + let mut graph = PatternGraph::default(); + for _ in 0..count { + graph.add(PatternNodeKind::Quadrant).unwrap(); + } + black_box(graph); + }); + println!("pattern_add,{count},{ms:.3}"); + } + + let mut function = FunctionGraph::default(); + let position = function.add("get_float2", &[], Some(Value::Text("$pos".into()))); + let horizontal = function.add("swizzle1", &[position], Some(Value::Int(0))); + let factor = function.add_constant(Value::Float(0.5)); + function.output = Some(function.add("mul", &[horizontal, factor], None)); + let definition = find("pixel_processor").unwrap(); + let mut parameters = resolve_params(definition, &BTreeMap::new()); + parameters.insert("function".into(), Value::Function(Box::new(function))); + parameters.insert("color_mode".into(), Value::Bool(false)); + for size in [512, 2048] { + for count in [0, 16] { + let variables = (0..count).map(|index| (format!("input_{index}"), Value::Float(index as f32))).collect(); + let context = CookContext { w: size, h: size, seed: 7, tile: true, inputs: &[], params: ¶meters, resource: &|_| None, vars: &variables }; + let ms = median_ms(|| { + black_box((definition.cook)(&context).unwrap()); + }); + println!("pixel_processor,{size},{count},{ms:.3}"); + } + } + + for count in [128, 1024, 4096] { + for branching in [false, true] { + let mut graph = Graph::new("Benchmark"); + graph.size = [4, 4]; + let source = graph.add_node("uniform", [0.0; 2]); + let mut previous = source; + for _ in 1..count { + let node = graph.add_node("dot", [0.0; 2]); + graph.connections.push(Connection { + from: if branching { source } else { previous }, + from_port: "output".into(), + to: node, + to_port: "input".into(), + }); + previous = node; + } + let mut package = Package::new("Benchmark"); + package.graphs.push(graph); + let options = Options::new(&|_| None); + let cache = Mutex::new(Cache::default()); + let initial = cook(&package, 0, &options, &cache); + assert_eq!(initial.nodes.len(), count); + assert!(initial.nodes.values().all(|result| result.error.is_none())); + let ms = median_ms(|| { + let cooked = cook(&package, 0, &options, &cache); + assert!(cooked.nodes.values().all(|result| result.cached)); + black_box(cooked); + }); + println!("warm_cook,{count},{branching},{ms:.3}"); + } + } +} diff --git a/crates/eval/src/cache_key.rs b/crates/eval/src/cache_key.rs index 0929b05..0f52227 100644 --- a/crates/eval/src/cache_key.rs +++ b/crates/eval/src/cache_key.rs @@ -1,4 +1,7 @@ +use crate::{identifier, instance_graph}; +use materialcraft_core::{Node, Package, Value}; use materialcraft_image::Image; +use std::collections::{BTreeMap, HashSet}; use std::hash::{DefaultHasher, Hash, Hasher}; pub(crate) fn image_key(i: &Image) -> u64 { @@ -11,3 +14,63 @@ pub(crate) fn hash_of(v: &impl Hash) -> u64 { v.hash(&mut h); h.finish() } + +pub(crate) fn graph_tree_hash(pkg: &Package, gi: usize) -> u64 { + let mut h = DefaultHasher::new(); + let mut pending = vec![gi]; + let mut seen = HashSet::new(); + while let Some(index) = pending.pop() { + if !seen.insert(index) { + continue; + } + let Some(graph) = pkg.graphs.get(index) else { continue }; + + index.hash(&mut h); + serde_json::to_string(graph).unwrap_or_default().hash(&mut h); + for n in &graph.nodes { + if let Some(Value::Text(name)) = n.params.get("resource") { + pkg.resource(name).map(|r| r.bytes.content_hash()).hash(&mut h); + } + if n.def == "graph_instance" + && let Some((si, _)) = instance_graph(pkg, n) + { + pending.push(si); + } + } + } + h.finish() +} + +pub(crate) fn variable_key(node: &Node, parameters: &BTreeMap, variables: &BTreeMap) -> u64 { + let mut names = std::collections::BTreeSet::new(); + let mut pending: Vec<&Value> = parameters.values().collect(); + while let Some(value) = pending.pop() { + match value { + Value::Function(graph) => { + for function in &graph.nodes { + if (function.op.starts_with("get_") || function.op == "isdefined") + && let Some(Value::Text(name)) = &function.value + { + names.insert(name.as_str()); + } + } + } + Value::PatternGraph(graph) => { + pending.extend(graph.nodes.iter().flat_map(|node| node.parameters.values())); + } + _ => {} + } + } + + let input_identifier = identifier(node); + if node.def == "input_value" { + names.insert(&input_identifier); + } + + let mut hasher = DefaultHasher::new(); + for name in names { + name.hash(&mut hasher); + variables.get(name).map(|value| serde_json::to_string(value).unwrap_or_default()).hash(&mut hasher); + } + hasher.finish() +} diff --git a/crates/eval/src/graph_execution.rs b/crates/eval/src/graph_execution.rs index c33c3f2..64eac00 100644 --- a/crates/eval/src/graph_execution.rs +++ b/crates/eval/src/graph_execution.rs @@ -1,400 +1,47 @@ -use std::collections::{BTreeMap, HashSet}; -use std::hash::{DefaultHasher, Hash, Hasher}; -use std::sync::atomic::Ordering; -use std::sync::{Arc, Mutex}; +use crate::{Cache, Cooked, Options, now_ms}; +use crate::{node_execution::cook_node, prepared_graph::PreparedGraph}; +use materialcraft_core::{Package, Value}; +use materialcraft_image::Image; +use std::{ + collections::BTreeMap, + sync::{Mutex, atomic::Ordering}, +}; -use materialcraft_core::{Graph, Node, NodeId, Package, Value}; -use materialcraft_image::{Image, Kind}; -use materialcraft_nodes::{CookContext, clamp_params, find, resolve_params}; +pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mutex) -> Cooked { + let started_ms = now_ms(); + let mut cooked = Cooked::default(); + let Some(graph) = package.graphs.get(graph_index) else { return cooked }; -use crate::cache_key::{hash_of, image_key}; -use crate::{Cache, Cooked, MAX_DEPTH, NodeOutput, NodeResult, Options, Port, identifier, instance_graph, node_size, ports}; - -/// The magenta image a failed node shows -pub fn error_image(w: u32, h: u32) -> Image { - Image::filled(w, h, Kind::Color, [1.0, 0.0, 1.0, 1.0]) -} - -/// Lock the cache, recovering from a poisoned lock (a cache entry is never half-written) -fn lock(cache: &Mutex) -> std::sync::MutexGuard<'_, Cache> { - cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner) -} - -pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &Mutex) -> Cooked { - let t0 = now_ms(); - let mut out = Cooked::default(); - let Some(graph) = pkg.graphs.get(gi) else { return out }; // The top-level graph's input nodes show their preview images; the caller's images win let bound; - let opts = if opts.depth == 0 && !graph.input_images.is_empty() { - let mut inputs: BTreeMap = graph.input_images.iter().filter_map(|(id, res)| Some((id.clone(), (opts.resource)(res)?))).collect(); - inputs.extend(opts.inputs.iter().map(|(k, v)| (k.clone(), v.clone()))); - bound = Options { only: opts.only.clone(), inputs, overrides: opts.overrides.clone(), graph_stack: opts.graph_stack.clone(), ..*opts }; + let options = if options.depth == 0 && !graph.input_images.is_empty() { + let mut inputs: BTreeMap = + graph.input_images.iter().filter_map(|(id, resource)| Some((id.clone(), (options.resource)(resource)?))).collect(); + inputs.extend(options.inputs.iter().map(|(name, value)| (name.clone(), value.clone()))); + bound = Options { only: options.only.clone(), inputs, overrides: options.overrides.clone(), graph_stack: options.graph_stack.clone(), ..*options }; &bound } else { - opts + options }; - let order = graph.topo_order(); - let needed: Option> = opts.only.as_ref().map(|ids| { - let mut s: std::collections::BTreeSet = ids.iter().copied().collect(); - for id in ids { - s.extend(graph.upstream(*id)); - } - s - }); + let prepared = PreparedGraph::new(package, graph, options.only.as_deref()); + // Exposed parameter values: the graph's own, then the caller's overrides - let mut vars: BTreeMap = graph.exposed.iter().filter_map(|e| graph.input_value(&e.id).map(|v| (e.id.clone(), v.clone()))).collect(); - for (k, v) in &opts.overrides { - vars.insert(k.clone(), v.clone()); + let mut variables: BTreeMap = + graph.exposed.iter().filter_map(|exposed| graph.input_value(&exposed.id).map(|value| (exposed.id.clone(), value.clone()))).collect(); + for (name, value) in &options.overrides { + variables.insert(name.clone(), value.clone()); } - for id in order { - if needed.as_ref().is_some_and(|s| !s.contains(&id)) { - continue; - } - if opts.cancel.is_some_and(|c| c.load(Ordering::Relaxed)) { - out.cancelled = true; + for &id in &prepared.order { + if options.cancel.is_some_and(|cancel| cancel.load(Ordering::Relaxed)) { + cooked.cancelled = true; break; } - let Ok(node) = graph.node(id) else { continue }; - let r = cook_node(pkg, gi, graph, node, &out, &vars, opts, cache); - out.nodes.insert(id, r); + let Some(node) = prepared.index.node(id) else { continue }; + + let result = cook_node(package, graph_index, graph, &prepared, node, &cooked, &variables, options, cache); + cooked.nodes.insert(id, result); } - out.ms = (now_ms() - t0) as f32; - out -} - -pub(crate) fn graph_tree_hash(pkg: &Package, gi: usize) -> u64 { - let mut h = DefaultHasher::new(); - let mut pending = vec![gi]; - let mut seen = HashSet::new(); - while let Some(index) = pending.pop() { - if !seen.insert(index) { - continue; - } - let Some(graph) = pkg.graphs.get(index) else { continue }; - index.hash(&mut h); - serde_json::to_string(graph).unwrap_or_default().hash(&mut h); - for n in &graph.nodes { - if let Some(Value::Text(name)) = n.params.get("resource") { - pkg.resource(name).map(|r| r.bytes.content_hash()).hash(&mut h); - } - if n.def == "graph_instance" - && let Some((si, _)) = instance_graph(pkg, n) - { - pending.push(si); - } - } - } - h.finish() -} - -fn cook_node( - pkg: &Package, - gi: usize, - graph: &Graph, - node: &Node, - done: &Cooked, - vars: &BTreeMap, - opts: &Options, - cache: &Mutex, -) -> NodeResult { - let (in_ports, out_ports) = ports(pkg, graph, node); - let def = find(&node.def); - // Gather inputs by port order, with their keys - let mut inputs = Vec::new(); - let mut incoming = Vec::new(); - let mut input_keys = Vec::new(); - let mut variables = vars.clone(); - let mut input_error = None; - for port in &in_ports { - let source = graph.input_of(node.id, &port.id).and_then(|connection| { - let result = done.nodes.get(&connection.from)?; - let source_node = graph.node(connection.from).ok()?; - let index = ports(pkg, graph, source_node).1.iter().position(|output| output.id == connection.from_port)?; - Some((result.outputs.get(index)?.clone(), result.key ^ hash_of(&index))) - }); - input_keys.push(source.as_ref().map_or(0, |source| source.1)); - let output = source.map(|source| source.0); - - if let Some(expected) = node.input_values.get(&port.id) { - let value = match output.as_ref() { - Some(NodeOutput::Value(value)) if materialcraft_core::ValueType::of(value) == Some(*expected) => value.clone(), - Some(_) => { - input_error = Some(format!("input `{}` requires {}", port.id, expected.label())); - expected.default_value() - } - None => expected.default_value(), - }; - - variables.insert(port.id.clone(), value); - } else { - if output.as_ref().is_some_and(|output| output.as_value().is_some()) && !matches!(node.def.as_str(), "output" | "dot") { - input_error = Some(format!("input `{}` requires an image", port.id)); - } - inputs.push(output.as_ref().and_then(NodeOutput::as_image).cloned()); - } - - incoming.push(output); - } - let vars = &variables; - let first = inputs.iter().flatten().next().map(|i| (i.w, i.h)); - let (w, h) = node_size(graph, def, node, first, opts.max_size); - let fail = |msg: String, key: u64| NodeResult { - outputs: Arc::new(vec![NodeOutput::Image(error_image(w, h)); out_ports.len().max(1)]), - error: Some(msg), - ms: 0.0, - key, - cached: false, - }; - - if let Some(error) = input_error { - return fail(error, 0); - } - - // Parameters: defaults, overrides, then bindings to exposed inputs - let mut params = match def { - Some(d) if node.def != "graph_instance" => resolve_params(d, &node.params), - _ => node.params.clone(), - }; - - for (param, exposed) in &node.bindings { - if let (Some(v), Some(cur)) = (vars.get(exposed), params.get(param)) - && let Some(c) = cur.coerce_json(&serde_json::to_value(v).unwrap_or_default()) - { - params.insert(param.clone(), c); - } - } - let seed = (graph.seed as u32).wrapping_mul(0x9e37_79b9).wrapping_add(node.base.seed as u32); - // Dynamic parameters: functions of the graph's inputs, evaluated once per cook - for (param, f) in &node.functions { - let Some(cur) = params.get(param) else { continue }; - match materialcraft_nodes::function::compile(f, seed) { - Ok(prog) => { - let context = materialcraft_nodes::function::EvaluationContext { - position: [0.5; 2], - size: [w as f32, h as f32], - images: &[], - tile: true, - variables: vars, - }; - - let value = match prog.evaluate(&context, &mut materialcraft_nodes::function::EvaluationState::default()) { - Ok(value) => value, - Err(error) => return fail(format!("function of `{param}`: {error}"), 0), - }; - - if let Some(c) = cur.coerce_json(&serde_json::to_value(value).unwrap_or_default()) { - params.insert(param.clone(), c); - } - } - Err(e) => return fail(format!("function of `{param}`: {e}"), 0), - } - } - // Hard limits on whatever files, bindings and functions supplied (a value can't hang a cook) - if let Some(d) = def - && node.def != "graph_instance" - { - clamp_params(d, &mut params); - } - let tile = node.base.tiling[0] && node.base.tiling[1]; - // Input nodes read the caller's image for their identifier - let input_img = node.def.starts_with("input_").then(|| opts.inputs.get(&identifier(node))).flatten(); - let res_hash = match params.get("resource") { - Some(Value::Text(name)) => pkg.resource(name).map_or(0, |r| r.bytes.content_hash()), - _ => 0, - }; - - let sub_hash = if node.def == "graph_instance" { instance_graph(pkg, node).map_or(0, |(si, _)| graph_tree_hash(pkg, si)) } else { 0 }; - let key = hash_of(&( - &node.def, - serde_json::to_string(¶ms).unwrap_or_default(), - (w, h, seed, tile, node.disabled), - &input_keys, - res_hash, - sub_hash, - input_img.map(image_key), - variable_key(node, ¶ms, vars), - )); - if let Some(v) = lock(cache).get(key) { - return NodeResult { outputs: v, error: None, ms: 0.0, key, cached: true }; - } - let t0 = now_ms(); - let result: Result, String> = if node.disabled { - let output = incoming.iter().flatten().next().cloned().unwrap_or_else(|| NodeOutput::Image(Image::filled(w, h, Kind::Gray, [0.0; 4]))); - Ok(vec![output; out_ports.len().max(1)]) - } else if node.def == "input_value" { - let value = vars.get(&identifier(node)).or_else(|| params.get("default")).cloned().unwrap_or(Value::Float(0.0)); - Ok(vec![NodeOutput::Value(value)]) - } else if node.def == "value_processor" { - evaluate_value(¶ms, vars, seed, [w, h], &inputs, tile).map(|value| vec![NodeOutput::Value(value)]) - } else if matches!(node.def.as_str(), "output" | "dot") && incoming.first().and_then(Option::as_ref).is_some_and(|output| output.as_value().is_some()) { - incoming.first().and_then(Clone::clone).map(|output| vec![output]).ok_or("missing value input".into()) - } else if let Some(image) = input_img { - let image = image.resize(w, h, tile); - let image = if node.def == "input_grayscale" { image.to_gray() } else { image }; - Ok(vec![NodeOutput::Image(image)]) - } else if node.def == materialcraft_core::MISSING_NODE { - let name = if node.label.is_empty() { "this node" } else { node.label.as_str() }; - Err(format!("unsupported node `{name}`")) - } else if node.def == "graph_instance" { - cook_instance(pkg, gi, node, &in_ports, &out_ports, &inputs, ¶ms, (w, h), opts, cache) - .map(|images| images.into_iter().map(NodeOutput::Image).collect()) - } else if let Some(definition) = def { - let context = CookContext { w, h, seed, tile, inputs: &inputs, params: ¶ms, resource: opts.resource, vars }; - (definition.cook)(&context).map(|images| images.into_iter().map(NodeOutput::Image).collect()) - } else { - Err(format!("unknown node `{}`", node.def)) - }; - - match result { - Ok(imgs) if imgs.len() == out_ports.len().max(1) || out_ports.is_empty() => { - let v = Arc::new(imgs); - lock(cache).put(key, v.clone()); - NodeResult { outputs: v, error: None, ms: (now_ms() - t0) as f32, key, cached: false } - } - Ok(imgs) => fail(format!("`{}` made {} images for {} outputs", node.def, imgs.len(), out_ports.len()), key), - Err(e) => fail(e, key), - } -} - -/// Whether graph `from` reaches `target`, without recursive stack growth -pub(crate) fn instances_reach(pkg: &Package, from: usize, target: usize) -> bool { - let mut pending = vec![from]; - let mut seen = HashSet::new(); - while let Some(index) = pending.pop() { - if !seen.insert(index) { - continue; - } - let Some(graph) = pkg.graphs.get(index) else { continue }; - for (si, _) in graph.nodes.iter().filter(|n| n.def == "graph_instance").filter_map(|n| instance_graph(pkg, n)) { - if si == target { - return true; - } - pending.push(si); - } - } - false -} - -fn cook_instance( - pkg: &Package, - gi: usize, - node: &Node, - in_ports: &[Port], - out_ports: &[Port], - inputs: &[Option], - params: &BTreeMap, - size: (u32, u32), - opts: &Options, - cache: &Mutex, -) -> Result, String> { - if opts.depth >= MAX_DEPTH { - return Err("graph instances nest too deep (does a graph use itself?)".into()); - } - let (sub_gi, sub) = instance_graph(pkg, node).ok_or("the instanced graph does not exist")?; - if sub_gi == gi || opts.graph_stack.contains(&sub_gi) || instances_reach(pkg, sub_gi, gi) { - return Err(format!("graph `{}` uses itself through a graph instance", sub.name)); - } - let mut o = Options::new(opts.resource); - o.max_size = opts.max_size; - o.cancel = opts.cancel; - o.depth = opts.depth + 1; - o.graph_stack = opts.graph_stack.clone(); - o.graph_stack.push(gi); - o.inputs = in_ports.iter().zip(inputs).filter_map(|(p, i)| Some((p.id.clone(), i.clone()?))).collect(); - o.overrides = params.iter().filter(|(k, _)| sub.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect(); - let cooked = cook(pkg, sub_gi, &o, cache); - if cooked.cancelled { - return Err("cancelled".into()); - } - Ok(out_ports - .iter() - .map(|p| { - sub.nodes - .iter() - .find(|n| n.def == "output" && identifier(n) == p.id) - .and_then(|n| cooked.image(n.id, 0)) - .map(|i| i.resize(size.0, size.1, true)) - .unwrap_or_else(|| Image::filled(size.0, size.1, Kind::Gray, [0.0; 4])) - }) - .collect()) -} - -/// The graph's output nodes with their usage id and image, in node order -pub fn outputs<'c>(graph: &Graph, cooked: &'c Cooked) -> Vec<(NodeId, &'static str, String, Option<&'c Image>)> { - graph - .nodes - .iter() - .filter(|n| n.def == "output") - .map(|n| { - let usage = n.params.get("usage").and_then(Value::as_i32).unwrap_or(0).clamp(0, materialcraft_nodes::atomic::USAGE_IDS.len() as i32 - 1) as usize; - (n.id, materialcraft_nodes::atomic::USAGE_IDS.get(usage).copied().unwrap_or("any"), identifier(n), cooked.image(n.id, 0)) - }) - .collect() -} - -/// Milliseconds since the first call (0 on the web, where `std::time::Instant` is unavailable) -pub fn now_ms() -> f64 { - #[cfg(not(target_arch = "wasm32"))] - { - static START: std::sync::OnceLock = std::sync::OnceLock::new(); - START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64() * 1000.0 - } - #[cfg(target_arch = "wasm32")] - 0.0 -} - -fn evaluate_value( - parameters: &BTreeMap, - variables: &BTreeMap, - seed: u32, - size: [u32; 2], - images: &[Option], - tile: bool, -) -> Result { - use materialcraft_nodes::function::{EvaluationContext, EvaluationState, compile}; - - let Some(Value::Function(graph)) = parameters.get("function") else { - return Err("missing value function".into()); - }; - - let program = compile(graph, seed)?; - let context = EvaluationContext { position: [0.5; 2], size: size.map(|side| side as f32), images, tile, variables }; - - program.evaluate(&context, &mut EvaluationState::default()) -} - -fn variable_key(node: &Node, parameters: &BTreeMap, variables: &BTreeMap) -> u64 { - let mut names = std::collections::BTreeSet::new(); - let mut pending: Vec<&Value> = parameters.values().collect(); - while let Some(value) = pending.pop() { - match value { - Value::Function(graph) => { - for function in &graph.nodes { - if (function.op.starts_with("get_") || function.op == "isdefined") - && let Some(Value::Text(name)) = &function.value - { - names.insert(name.as_str()); - } - } - } - Value::PatternGraph(graph) => { - pending.extend(graph.nodes.iter().flat_map(|node| node.parameters.values())); - } - _ => {} - } - } - - let input_identifier = identifier(node); - if node.def == "input_value" { - names.insert(&input_identifier); - } - - let mut hasher = DefaultHasher::new(); - for name in names { - name.hash(&mut hasher); - variables.get(name).map(|value| serde_json::to_string(value).unwrap_or_default()).hash(&mut hasher); - } - hasher.finish() + cooked.ms = (now_ms() - started_ms) as f32; + cooked } diff --git a/crates/eval/src/graph_instance.rs b/crates/eval/src/graph_instance.rs new file mode 100644 index 0000000..6a700fd --- /dev/null +++ b/crates/eval/src/graph_instance.rs @@ -0,0 +1,71 @@ +use crate::{Cache, MAX_DEPTH, Options, Port, cook, identifier, instance_graph}; +use materialcraft_core::{Node, Package, Value}; +use materialcraft_image::{Image, Kind}; +use std::{ + collections::{BTreeMap, HashSet}, + sync::Mutex, +}; + +/// Whether graph `from` reaches `target`, without recursive stack growth +pub(crate) fn instances_reach(pkg: &Package, from: usize, target: usize) -> bool { + let mut pending = vec![from]; + let mut seen = HashSet::new(); + while let Some(index) = pending.pop() { + if !seen.insert(index) { + continue; + } + let Some(graph) = pkg.graphs.get(index) else { continue }; + + for (si, _) in graph.nodes.iter().filter(|n| n.def == "graph_instance").filter_map(|n| instance_graph(pkg, n)) { + if si == target { + return true; + } + pending.push(si); + } + } + false +} + +pub(crate) fn cook_instance( + pkg: &Package, + gi: usize, + node: &Node, + in_ports: &[Port], + out_ports: &[Port], + inputs: &[Option], + params: &BTreeMap, + size: (u32, u32), + opts: &Options, + cache: &Mutex, +) -> Result, String> { + if opts.depth >= MAX_DEPTH { + return Err("graph instances nest too deep (does a graph use itself?)".into()); + } + let (sub_gi, sub) = instance_graph(pkg, node).ok_or("the instanced graph does not exist")?; + if sub_gi == gi || opts.graph_stack.contains(&sub_gi) || instances_reach(pkg, sub_gi, gi) { + return Err(format!("graph `{}` uses itself through a graph instance", sub.name)); + } + let mut o = Options::new(opts.resource); + o.max_size = opts.max_size; + o.cancel = opts.cancel; + o.depth = opts.depth + 1; + o.graph_stack = opts.graph_stack.clone(); + o.graph_stack.push(gi); + o.inputs = in_ports.iter().zip(inputs).filter_map(|(p, i)| Some((p.id.clone(), i.clone()?))).collect(); + o.overrides = params.iter().filter(|(k, _)| sub.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect(); + let cooked = cook(pkg, sub_gi, &o, cache); + if cooked.cancelled { + return Err("cancelled".into()); + } + Ok(out_ports + .iter() + .map(|p| { + sub.nodes + .iter() + .find(|n| n.def == "output" && identifier(n) == p.id) + .and_then(|n| cooked.image(n.id, 0)) + .map(|i| i.resize(size.0, size.1, true)) + .unwrap_or_else(|| Image::filled(size.0, size.1, Kind::Gray, [0.0; 4])) + }) + .collect()) +} diff --git a/crates/eval/src/graph_output.rs b/crates/eval/src/graph_output.rs new file mode 100644 index 0000000..e96e0ff --- /dev/null +++ b/crates/eval/src/graph_output.rs @@ -0,0 +1,17 @@ +use crate::{Cooked, identifier}; +use materialcraft_core::{ComponentUsage, Graph, Node, NodeId, Value}; + +pub fn output_usage(node: &Node) -> &'static str { + let index = match node.params.get("usage") { + None => 0, + Some(Value::Enum(index)) => *index, + Some(value) => value.as_i32().map_or(ComponentUsage::ANY_INDEX, |index| index.max(0) as u32), + }; + ComponentUsage::from_index(index).id +} +use materialcraft_image::Image; + +/// The graph's output nodes with their usage id and image, in node order +pub fn outputs<'c>(graph: &Graph, cooked: &'c Cooked) -> Vec<(NodeId, &'static str, String, Option<&'c Image>)> { + graph.nodes.iter().filter(|n| n.def == "output").map(|n| (n.id, output_usage(n), identifier(n), cooked.image(n.id, 0))).collect() +} diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index 2ee3b73..bee0092 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -5,21 +5,33 @@ mod cache; mod cache_key; mod cooked; mod graph_execution; +mod graph_instance; +mod graph_output; +mod node_execution; mod node_output; mod node_result; mod node_size; mod options; +mod parameter; mod port; +mod ports; +mod prepared_graph; +mod time; +mod value_execution; mod value_input_label; pub use cache::Cache; pub use cooked::Cooked; -pub use graph_execution::{cook, error_image, now_ms, outputs}; +pub use graph_execution::cook; +pub use graph_output::{output_usage, outputs}; +pub use node_execution::error_image; pub use node_output::NodeOutput; pub use node_result::NodeResult; pub use node_size::node_size; pub use options::Options; -pub use port::{Port, identifier, instance_graph, ports}; +pub use port::Port; +pub use ports::{identifier, instance_graph, ports, ports_with_connections}; +pub use time::now_ms; pub use value_input_label::value_input_label; pub const MAX_DEPTH: u32 = 8; diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs new file mode 100644 index 0000000..ac4b945 --- /dev/null +++ b/crates/eval/src/node_execution.rs @@ -0,0 +1,158 @@ +use crate::{Cache, Cooked, NodeOutput, NodeResult, Options, identifier, instance_graph, node_size, now_ms}; +use crate::{ + cache_key::{graph_tree_hash, hash_of, image_key, variable_key}, + graph_instance::cook_instance, + parameter::resolve_parameters, + prepared_graph::PreparedGraph, + value_execution::evaluate_value, +}; +use materialcraft_core::{Graph, Node, Package, Value}; +use materialcraft_image::{Image, Kind}; +use materialcraft_nodes::{CookContext, find}; +use std::{ + collections::BTreeMap, + sync::{Arc, Mutex}, +}; + +/// The magenta image a failed node shows +pub fn error_image(w: u32, h: u32) -> Image { + Image::filled(w, h, Kind::Color, [1.0, 0.0, 1.0, 1.0]) +} + +/// Lock the cache, recovering from a poisoned lock (a cache entry is never half-written) +fn lock(cache: &Mutex) -> std::sync::MutexGuard<'_, Cache> { + cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +pub(crate) fn cook_node( + pkg: &Package, + gi: usize, + graph: &Graph, + prepared: &PreparedGraph<'_>, + node: &Node, + done: &Cooked, + vars: &BTreeMap, + opts: &Options, + cache: &Mutex, +) -> NodeResult { + let (in_ports, out_ports) = prepared.ports(node.id); + let def = find(&node.def); + // Gather inputs by port order, with their keys + let mut inputs = Vec::new(); + let mut incoming = Vec::new(); + let mut input_keys = Vec::new(); + let mut variables = std::borrow::Cow::Borrowed(vars); + let mut input_error = None; + for port in in_ports { + let source = prepared.index.input_of(node.id, &port.id).and_then(|connection| { + let result = done.nodes.get(&connection.from)?; + let index = prepared.ports(connection.from).1.iter().position(|output| output.id == connection.from_port)?; + Some((result.outputs.get(index)?, result.key ^ hash_of(&index))) + }); + input_keys.push(source.as_ref().map_or(0, |source| source.1)); + let output = source.map(|source| source.0); + + if let Some(expected) = node.input_values.get(&port.id) { + let value = match output.as_ref() { + Some(NodeOutput::Value(value)) if materialcraft_core::ValueType::of(value) == Some(*expected) => value.clone(), + Some(_) => { + input_error = Some(format!("input `{}` requires {}", port.id, expected.label())); + expected.default_value() + } + None => expected.default_value(), + }; + + variables.to_mut().insert(port.id.clone(), value); + } else { + if output.as_ref().is_some_and(|output| output.as_value().is_some()) && !matches!(node.def.as_str(), "output" | "dot") { + input_error = Some(format!("input `{}` requires an image", port.id)); + } + inputs.push(output.and_then(NodeOutput::as_image).cloned()); + } + + incoming.push(output); + } + let vars = &variables; + let first = inputs.iter().flatten().next().map(|i| (i.w, i.h)); + let (w, h) = node_size(graph, def, node, first, opts.max_size); + let fail = |msg: String, key: u64| NodeResult { + outputs: Arc::new(vec![NodeOutput::Image(error_image(w, h)); out_ports.len().max(1)]), + error: Some(msg), + ms: 0.0, + key, + cached: false, + }; + + if let Some(error) = input_error { + return fail(error, 0); + } + + let seed = (graph.seed as u32).wrapping_mul(0x9e37_79b9).wrapping_add(node.base.seed as u32); + let params = match resolve_parameters(node, def, vars, seed, [w, h]) { + Ok(parameters) => parameters, + Err(error) => return fail(error, 0), + }; + + let tile = node.base.tiling[0] && node.base.tiling[1]; + // Input nodes read the caller's image for their identifier + let input_img = node.def.starts_with("input_").then(|| opts.inputs.get(&identifier(node))).flatten(); + let res_hash = match params.get("resource") { + Some(Value::Text(name)) => pkg.resource(name).map_or(0, |r| r.bytes.content_hash()), + _ => 0, + }; + + let sub_hash = if node.def == "graph_instance" { instance_graph(pkg, node).map_or(0, |(si, _)| graph_tree_hash(pkg, si)) } else { 0 }; + + let key = hash_of(&( + &node.def, + serde_json::to_string(¶ms).unwrap_or_default(), + (w, h, seed, tile, node.disabled), + &input_keys, + res_hash, + sub_hash, + input_img.map(image_key), + variable_key(node, ¶ms, vars), + )); + if let Some(v) = lock(cache).get(key) { + return NodeResult { outputs: v, error: None, ms: 0.0, key, cached: true }; + } + let t0 = now_ms(); + let result: Result, String> = if node.disabled { + let output = incoming.iter().find_map(|output| *output).cloned().unwrap_or_else(|| NodeOutput::Image(Image::filled(w, h, Kind::Gray, [0.0; 4]))); + Ok(vec![output; out_ports.len().max(1)]) + } else if node.def == "input_value" { + let value = vars.get(&identifier(node)).or_else(|| params.get("default")).cloned().unwrap_or(Value::Float(0.0)); + Ok(vec![NodeOutput::Value(value)]) + } else if node.def == "value_processor" { + evaluate_value(¶ms, vars, seed, [w, h], &inputs, tile).map(|value| vec![NodeOutput::Value(value)]) + } else if matches!(node.def.as_str(), "output" | "dot") && incoming.first().and_then(Option::as_ref).is_some_and(|output| output.as_value().is_some()) { + incoming.first().copied().flatten().cloned().map(|output| vec![output]).ok_or("missing value input".into()) + } else if let Some(image) = input_img { + let image = image.resize(w, h, tile); + let image = if node.def == "input_grayscale" { image.to_gray() } else { image }; + + Ok(vec![NodeOutput::Image(image)]) + } else if node.def == materialcraft_core::MISSING_NODE { + let name = if node.label.is_empty() { "this node" } else { node.label.as_str() }; + + Err(format!("unsupported node `{name}`")) + } else if node.def == "graph_instance" { + cook_instance(pkg, gi, node, in_ports, out_ports, &inputs, ¶ms, (w, h), opts, cache) + .map(|images| images.into_iter().map(NodeOutput::Image).collect()) + } else if let Some(definition) = def { + let context = CookContext { w, h, seed, tile, inputs: &inputs, params: ¶ms, resource: opts.resource, vars }; + (definition.cook)(&context).map(|images| images.into_iter().map(NodeOutput::Image).collect()) + } else { + Err(format!("unknown node `{}`", node.def)) + }; + + match result { + Ok(imgs) if imgs.len() == out_ports.len().max(1) || out_ports.is_empty() => { + let v = Arc::new(imgs); + lock(cache).put(key, v.clone()); + NodeResult { outputs: v, error: None, ms: (now_ms() - t0) as f32, key, cached: false } + } + Ok(imgs) => fail(format!("`{}` made {} images for {} outputs", node.def, imgs.len(), out_ports.len()), key), + Err(e) => fail(e, key), + } +} diff --git a/crates/eval/src/parameter.rs b/crates/eval/src/parameter.rs new file mode 100644 index 0000000..5d2a7b5 --- /dev/null +++ b/crates/eval/src/parameter.rs @@ -0,0 +1,58 @@ +use materialcraft_core::{Node, Value}; +use materialcraft_nodes::{NodeDefinition, clamp_params, resolve_params}; +use std::collections::BTreeMap; + +pub(crate) fn resolve_parameters( + node: &Node, + def: Option<&NodeDefinition>, + vars: &BTreeMap, + seed: u32, + size: [u32; 2], +) -> Result, String> { + // Parameters: defaults, overrides, then bindings to exposed inputs + let mut params = match def { + Some(d) if node.def != "graph_instance" => resolve_params(d, &node.params), + _ => node.params.clone(), + }; + + for (param, exposed) in &node.bindings { + if let (Some(v), Some(cur)) = (vars.get(exposed), params.get(param)) + && let Some(c) = cur.coerce_json(&serde_json::to_value(v).unwrap_or_default()) + { + params.insert(param.clone(), c); + } + } + // Dynamic parameters: functions of the graph's inputs, evaluated once per cook + for (param, f) in &node.functions { + let Some(cur) = params.get(param) else { continue }; + + match materialcraft_nodes::function::compile(f, seed) { + Ok(prog) => { + let context = materialcraft_nodes::function::EvaluationContext { + position: [0.5; 2], + size: size.map(|side| side as f32), + images: &[], + tile: true, + variables: vars, + }; + + let value = match prog.evaluate(&context, &mut materialcraft_nodes::function::EvaluationState::default()) { + Ok(value) => value, + Err(error) => return Err(format!("function of `{param}`: {error}")), + }; + + if let Some(c) = cur.coerce_json(&serde_json::to_value(value).unwrap_or_default()) { + params.insert(param.clone(), c); + } + } + Err(e) => return Err(format!("function of `{param}`: {e}")), + } + } + // Hard limits on whatever files, bindings and functions supplied (a value can't hang a cook) + if let Some(d) = def + && node.def != "graph_instance" + { + clamp_params(d, &mut params); + } + Ok(params) +} diff --git a/crates/eval/src/port.rs b/crates/eval/src/port.rs index cde2aa2..2c35bbd 100644 --- a/crates/eval/src/port.rs +++ b/crates/eval/src/port.rs @@ -1,5 +1,4 @@ -use materialcraft_core::{Graph, Node, Package, Value}; -use materialcraft_nodes::{PortKind, find}; +use materialcraft_nodes::PortKind; #[derive(Clone, Debug, PartialEq)] pub struct Port { @@ -7,88 +6,3 @@ pub struct Port { pub label: String, pub kind: PortKind, } - -/// The input and output ports of a node in its package -pub fn ports(package: &Package, graph: &Graph, node: &Node) -> (Vec, Vec) { - if node.def == "graph_instance" { - let Some((_, graph)) = instance_graph(package, node) else { - return (Vec::new(), Vec::new()); - }; - - let graph_ports = |definition: &str| -> Vec { - graph - .nodes - .iter() - .filter(|node| node.def == definition || (definition == "input" && node.def.starts_with("input_"))) - .map(|node| { - let id = identifier(node); - let kind = match node.def.as_str() { - "input_grayscale" => PortKind::Gray, - "input_color" => PortKind::Color, - _ => PortKind::Any, - }; - - Port { label: id.clone(), id, kind } - }) - .collect() - }; - - return (graph_ports("input"), graph_ports("output")); - } - - if node.def == materialcraft_core::MISSING_NODE { - let (inputs, outputs) = materialcraft_core::missing_ports(node); - let inputs = inputs.into_iter().map(|id| Port { label: id.clone(), id, kind: PortKind::Any }).collect(); - let outputs = - outputs.into_iter().map(|(id, grayscale)| Port { label: id.clone(), id, kind: if grayscale { PortKind::Gray } else { PortKind::Color } }).collect(); - - return (inputs, outputs); - } - - let Some(definition) = find(&node.def) else { - return (Vec::new(), Vec::new()); - }; - - let catalog_port = |port: &materialcraft_nodes::PortDefinition| Port { id: port.id.into(), label: port.label.into(), kind: port.kind }; - let mut inputs: Vec = node - .input_values - .iter() - .map(|(identifier, value_type)| Port { - id: identifier.clone(), - label: format!("{} ({})", crate::value_input_label(identifier), value_type.label()), - kind: PortKind::Value, - }) - .collect(); - inputs.extend(definition.inputs.iter().map(catalog_port)); - if let Some(prefix) = materialcraft_nodes::image_input_prefix(&node.def) { - let count = graph - .connections - .iter() - .filter(|connection| connection.to == node.id) - .filter_map(|connection| connection.to_port.strip_prefix(prefix)?.parse::().ok()) - .filter(|index| *index < materialcraft_nodes::MAX_IMAGE_INPUTS) - .map(|index| index + 2) - .max() - .unwrap_or(1) - .min(materialcraft_nodes::MAX_IMAGE_INPUTS); - inputs.extend((1..count).map(|index| Port { id: format!("{prefix}{index}"), label: format!("Input image {index}"), kind: PortKind::Any })); - } - - (inputs, definition.outputs.iter().map(catalog_port).collect()) -} - -/// The graph a graph-instance node refers to -pub fn instance_graph<'a>(pkg: &'a Package, node: &Node) -> Option<(usize, &'a Graph)> { - match node.params.get("graph") { - Some(Value::Text(name)) => pkg.graph_by_name(name), - _ => None, - } -} - -/// An input or output node's identifier (its `identifier` parameter, default "input"/"output") -pub fn identifier(n: &Node) -> String { - match n.params.get("identifier") { - Some(Value::Text(s)) if !s.is_empty() => s.clone(), - _ => if n.def == "output" { "output" } else { "input" }.into(), - } -} diff --git a/crates/eval/src/ports.rs b/crates/eval/src/ports.rs new file mode 100644 index 0000000..1ceb1f3 --- /dev/null +++ b/crates/eval/src/ports.rs @@ -0,0 +1,95 @@ +use crate::Port; +use materialcraft_core::{Graph, Node, Package, Value}; +use materialcraft_nodes::{PortKind, find}; + +/// The input and output ports of a node in its package +pub fn ports(package: &Package, graph: &Graph, node: &Node) -> (Vec, Vec) { + ports_with_connections(package, node, graph.connections.iter().filter(|connection| connection.to == node.id)) +} + +/// Resolve ports using the node's incoming connections in document order +pub fn ports_with_connections<'a>( + package: &Package, + node: &Node, + incoming: impl IntoIterator, +) -> (Vec, Vec) { + if node.def == "graph_instance" { + let Some((_, graph)) = instance_graph(package, node) else { + return (Vec::new(), Vec::new()); + }; + + let graph_ports = |definition: &str| -> Vec { + graph + .nodes + .iter() + .filter(|node| node.def == definition || (definition == "input" && node.def.starts_with("input_"))) + .map(|node| { + let id = identifier(node); + let kind = match node.def.as_str() { + "input_grayscale" => PortKind::Gray, + "input_color" => PortKind::Color, + _ => PortKind::Any, + }; + + Port { label: id.clone(), id, kind } + }) + .collect() + }; + + return (graph_ports("input"), graph_ports("output")); + } + + if node.def == materialcraft_core::MISSING_NODE { + let (inputs, outputs) = materialcraft_core::missing_ports(node); + let inputs = inputs.into_iter().map(|id| Port { label: id.clone(), id, kind: PortKind::Any }).collect(); + let outputs = + outputs.into_iter().map(|(id, grayscale)| Port { label: id.clone(), id, kind: if grayscale { PortKind::Gray } else { PortKind::Color } }).collect(); + + return (inputs, outputs); + } + + let Some(definition) = find(&node.def) else { + return (Vec::new(), Vec::new()); + }; + + let catalog_port = |port: &materialcraft_nodes::PortDefinition| Port { id: port.id.into(), label: port.label.into(), kind: port.kind }; + let mut inputs: Vec = node + .input_values + .iter() + .map(|(identifier, value_type)| Port { + id: identifier.clone(), + label: format!("{} ({})", crate::value_input_label(identifier), value_type.label()), + kind: PortKind::Value, + }) + .collect(); + inputs.extend(definition.inputs.iter().map(catalog_port)); + if let Some(prefix) = materialcraft_nodes::image_input_prefix(&node.def) { + let count = incoming + .into_iter() + .filter_map(|connection| connection.to_port.strip_prefix(prefix)?.parse::().ok()) + .filter(|index| *index < materialcraft_nodes::MAX_IMAGE_INPUTS) + .map(|index| index + 2) + .max() + .unwrap_or(1) + .min(materialcraft_nodes::MAX_IMAGE_INPUTS); + inputs.extend((1..count).map(|index| Port { id: format!("{prefix}{index}"), label: format!("Input image {index}"), kind: PortKind::Any })); + } + + (inputs, definition.outputs.iter().map(catalog_port).collect()) +} + +/// The graph a graph-instance node refers to +pub fn instance_graph<'a>(pkg: &'a Package, node: &Node) -> Option<(usize, &'a Graph)> { + match node.params.get("graph") { + Some(Value::Text(name)) => pkg.graph_by_name(name), + _ => None, + } +} + +/// An input or output node's identifier (its `identifier` parameter, default "input"/"output") +pub fn identifier(n: &Node) -> String { + match n.params.get("identifier") { + Some(Value::Text(s)) if !s.is_empty() => s.clone(), + _ => if n.def == "output" { "output" } else { "input" }.into(), + } +} diff --git a/crates/eval/src/prepared_graph.rs b/crates/eval/src/prepared_graph.rs new file mode 100644 index 0000000..7a25bf4 --- /dev/null +++ b/crates/eval/src/prepared_graph.rs @@ -0,0 +1,31 @@ +use crate::{Port, ports_with_connections}; +use materialcraft_core::{Graph, GraphIndex, NodeId, Package}; +use std::collections::BTreeMap; + +/// Port definitions resolved once for a cook, alongside borrowed graph lookups +pub(crate) struct PreparedGraph<'a> { + pub index: GraphIndex<'a>, + pub order: Vec, + ports: BTreeMap, Vec)>, +} + +impl<'a> PreparedGraph<'a> { + pub fn new(package: &Package, graph: &'a Graph, roots: Option<&[NodeId]>) -> Self { + let index = GraphIndex::new(graph); + let needed = roots.map(|roots| index.required_nodes(roots)); + let order: Vec<_> = index.topo_order().into_iter().filter(|id| needed.as_ref().is_none_or(|needed| needed.contains(id))).collect(); + let ports = order + .iter() + .filter_map(|id| { + let node = index.node(*id)?; + Some((*id, ports_with_connections(package, node, index.incoming(*id).iter().copied()))) + }) + .collect(); + + Self { index, order, ports } + } + + pub fn ports(&self, id: NodeId) -> (&[Port], &[Port]) { + self.ports.get(&id).map_or((&[], &[]), |(inputs, outputs)| (inputs.as_slice(), outputs.as_slice())) + } +} diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index 30dad6b..9c714b4 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -1,4 +1,4 @@ -use crate::graph_execution::{graph_tree_hash, instances_reach}; +use crate::{cache_key::graph_tree_hash, graph_instance::instances_reach}; use materialcraft_core::{NodeId, Package, Value}; use materialcraft_image::{Image, Kind}; use std::sync::Mutex; @@ -242,3 +242,32 @@ fn input_change_recooks_only_readers() { } assert!(!second.nodes[&reader].cached, "the reader must re-cook"); } + +#[test] +fn partial_cooks_keep_shared_dependencies_and_first_duplicate_node() { + let mut graph = Graph::new("Partial cook"); + graph.size = [4, 4]; + let source = graph.add_node("uniform", [0.0; 2]); + let first = graph.add_node("dot", [0.0; 2]); + let second = graph.add_node("dot", [0.0; 2]); + let unrelated = graph.add_node("uniform", [0.0; 2]); + graph.connect(source, "output", first, "input").unwrap(); + graph.connect(source, "output", second, "input").unwrap(); + + let mut duplicate = graph.node(source).unwrap().clone(); + duplicate.def = "input_value".into(); + graph.nodes.push(duplicate); + let mut package = Package::new("Partial cook"); + package.graphs.push(graph); + let cache = Mutex::new(Cache::default()); + let mut options = Options::new(&no_res); + options.only = Some(vec![first, second]); + + let cooked = cook(&package, 0, &options, &cache); + assert_eq!(cooked.nodes.len(), 3); + assert!(!cooked.nodes.contains_key(&unrelated)); + for id in [source, first, second] { + assert!(cooked.nodes[&id].error.is_none()); + assert!(cooked.image(id, 0).is_some()); + } +} diff --git a/crates/eval/src/time.rs b/crates/eval/src/time.rs new file mode 100644 index 0000000..033626a --- /dev/null +++ b/crates/eval/src/time.rs @@ -0,0 +1,10 @@ +/// Milliseconds since the first call (0 on the web, where `std::time::Instant` is unavailable) +pub fn now_ms() -> f64 { + #[cfg(not(target_arch = "wasm32"))] + { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64() * 1000.0 + } + #[cfg(target_arch = "wasm32")] + 0.0 +} diff --git a/crates/eval/src/value_execution.rs b/crates/eval/src/value_execution.rs new file mode 100644 index 0000000..ee72c63 --- /dev/null +++ b/crates/eval/src/value_execution.rs @@ -0,0 +1,23 @@ +use materialcraft_core::Value; +use materialcraft_image::Image; +use std::collections::BTreeMap; + +pub(crate) fn evaluate_value( + parameters: &BTreeMap, + variables: &BTreeMap, + seed: u32, + size: [u32; 2], + images: &[Option], + tile: bool, +) -> Result { + use materialcraft_nodes::function::{EvaluationContext, EvaluationState, compile}; + + let Some(Value::Function(graph)) = parameters.get("function") else { + return Err("missing value function".into()); + }; + + let program = compile(graph, seed)?; + let context = EvaluationContext { position: [0.5; 2], size: size.map(|side| side as f32), images, tile, variables }; + + program.evaluate(&context, &mut EvaluationState::default()) +} diff --git a/crates/formats/src/material/archive.rs b/crates/formats/src/material/archive.rs index 2781c83..1c8a1de 100644 --- a/crates/formats/src/material/archive.rs +++ b/crates/formats/src/material/archive.rs @@ -16,7 +16,20 @@ const SOURCE: &str = "source.sbs"; /// Whether maps of `usage` hold colors (stored sRGB-encoded) rather than data (linear) pub fn srgb_usage(usage: &str) -> bool { - matches!(usage, "baseColor" | "emissive" | "specular") + matches!( + usage, + "baseColor" + | "diffuse" + | "emissive" + | "specular" + | "specularEdgeColor" + | "scatteringColor" + | "absorptionColor" + | "coatColor" + | "sheenColor" + | "reflection" + | "ambient" + ) } /// Whether other apps can set a value of this type from the manifest diff --git a/crates/formats/src/sbs/canvas.rs b/crates/formats/src/sbs/canvas.rs index efb3450..c4d536f 100644 --- a/crates/formats/src/sbs/canvas.rs +++ b/crates/formats/src/sbs/canvas.rs @@ -1,6 +1,10 @@ use super::sbs_writer::SbsWriter; +use super::warnings::Warnings; +use super::xml::{child_element, child_value, children_named, parse_floats}; use super::xml::{format_float, xml_escape}; +use materialcraft_core::{Comment, Frame, Pin, srgb_to_linear}; use materialcraft_core::{Graph, linear_to_srgb}; +use roxmltree::Node as XmlNode; use std::fmt::Write as _; pub(super) fn write_canvas_items(output: &mut String, graph: &Graph, writer: &mut SbsWriter) { @@ -43,3 +47,41 @@ pub(super) fn write_canvas_items(output: &mut String, graph: &Graph, writer: &mu output.push_str(""); } + +pub(super) fn read_canvas_items(element: XmlNode, graph: &mut Graph, warnings: &mut Warnings) { + for item in child_element(element, "GUIObjects").into_iter().flat_map(|objects| children_named(objects, "GUIObject")) { + let layout = child_element(item, "GUILayout"); + let position = layout.and_then(|layout| child_value(layout, "gpos")).map(parse_floats).unwrap_or_default(); + let size = layout.and_then(|layout| child_value(layout, "size")).map(parse_floats).unwrap_or_default(); + let x = position.first().copied().unwrap_or(0.0); + let y = position.get(1).copied().unwrap_or(0.0); + let width = size.first().copied().unwrap_or(180.0).max(8.0); + let height = size.get(1).copied().unwrap_or(70.0).max(8.0); + let text = child_value(item, "GUIName").unwrap_or("").to_string(); + + match child_value(item, "type") { + Some("COMMENT") if child_value(item, "isFrameVisible") == Some("1") => { + let channels = child_value(item, "frameColor").map(parse_floats).unwrap_or_default(); + let color = match channels.as_slice() { + &[red, green, blue, alpha, ..] => [srgb_to_linear(red), srgb_to_linear(green), srgb_to_linear(blue), alpha], + _ => [0.2, 0.4, 0.8, 0.25], + }; + let title = child_value(item, "title").unwrap_or("").to_string(); + let title_visible = child_value(item, "isTitleVisible") != Some("0"); + let id = graph.alloc_id(); + + graph.frames.push(Frame { id, title, title_visible, description: text, rect: [x, y, width, height], color }); + } + Some("COMMENT") => { + let id = graph.alloc_id(); + graph.comments.push(Comment { id, text, pos: [x, y], size: [width, height] }); + } + Some("PIN") => { + let id = graph.alloc_id(); + graph.pins.push(Pin { id, name: text, pos: [x, y] }); + } + Some(other) => warnings.add(format!("graph `{}`: canvas item `{other}` is not supported", graph.name)), + None => {} + } + } +} diff --git a/crates/formats/src/sbs/component_usage.rs b/crates/formats/src/sbs/component_usage.rs new file mode 100644 index 0000000..37b08b0 --- /dev/null +++ b/crates/formats/src/sbs/component_usage.rs @@ -0,0 +1,22 @@ +use materialcraft_core::{ComponentUsage, Node, Value}; +use roxmltree::Node as XmlNode; +use std::fmt::Write as _; + +use super::xml::{child_element, child_value}; + +pub(super) fn read(element: XmlNode) -> u32 { + child_element(element, "usages") + .and_then(|usages| child_element(usages, "usage")) + .and_then(|usage| child_value(usage, "name")) + .map_or(ComponentUsage::ANY_INDEX, ComponentUsage::index) +} + +pub(super) fn write(out: &mut String, node: &Node, default: u32) { + let index = match node.params.get("usage") { + None => default, + Some(Value::Enum(index)) => *index, + Some(value) => value.as_i32().map_or(ComponentUsage::ANY_INDEX, |index| index.max(0) as u32), + }; + let id = ComponentUsage::from_index(index).id; + let _ = write!(out, ""); +} diff --git a/crates/formats/src/sbs/input_bridge.rs b/crates/formats/src/sbs/input_bridge.rs index f800707..73c86a3 100644 --- a/crates/formats/src/sbs/input_bridge.rs +++ b/crates/formats/src/sbs/input_bridge.rs @@ -3,5 +3,6 @@ use materialcraft_core::Value; pub(super) struct InputBridge { pub identifier: String, pub type_code: u32, + pub usage: u32, pub default: Value, } diff --git a/crates/formats/src/sbs/mod.rs b/crates/formats/src/sbs/mod.rs index 7083cb5..b3545a6 100644 --- a/crates/formats/src/sbs/mod.rs +++ b/crates/formats/src/sbs/mod.rs @@ -1,5 +1,6 @@ mod base_parameters; mod canvas; +mod component_usage; mod connection; mod constant; mod embedded; @@ -24,9 +25,12 @@ mod warnings; mod xml; pub use constant::SBS_EXT; +pub use read::{is_sbs, read_sbs}; pub use sbs_read::SbsRead; -pub use sbs_reader::{is_sbs, read_sbs}; -pub use sbs_writer::write_sbs; +pub use write::write_sbs; #[cfg(test)] mod tests; + +mod read; +mod write; diff --git a/crates/formats/src/sbs/output.rs b/crates/formats/src/sbs/output.rs index 865975b..8c75847 100644 --- a/crates/formats/src/sbs/output.rs +++ b/crates/formats/src/sbs/output.rs @@ -1,15 +1,5 @@ use materialcraft_nodes::PortKind; -pub(super) fn usage_index(name: &str) -> u32 { - let ids = materialcraft_nodes::atomic::USAGE_IDS; - let name = name.trim(); - let index = ids.iter().position(|u| u.eq_ignore_ascii_case(name)).or_else(|| name.eq_ignore_ascii_case("diffuse").then_some(0)); - index.unwrap_or(ids.len().saturating_sub(1)) as u32 -} - -pub(super) fn usage_name(index: u32) -> &'static str { - materialcraft_nodes::atomic::USAGE_IDS.get(index as usize).copied().unwrap_or("any") -} pub(super) fn output_type(graph: &materialcraft_core::Graph, id: materialcraft_core::NodeId, port: &str) -> u32 { if let Ok(Some(kind)) = materialcraft_nodes::output_value_type(graph, id) { return kind as u32; diff --git a/crates/formats/src/sbs/read.rs b/crates/formats/src/sbs/read.rs new file mode 100644 index 0000000..1958dd9 --- /dev/null +++ b/crates/formats/src/sbs/read.rs @@ -0,0 +1,99 @@ +use super::{ + constant::{MAX_GRAPHS, MAX_SBS_BYTES, MAX_XML_NODES, SNIFF_BYTES}, + placeholder::report_placeholders, + sbs_read::SbsRead, + sbs_reader::{SbsReader, unique_name}, + warnings::Warnings, + xml::{child_element, child_value, children_named}, +}; +use crate::{FormatError, Result}; +use materialcraft_core::{Graph, Package}; +use roxmltree::Node as XmlNode; +use std::collections::HashMap; + +pub fn read_sbs(bytes: &[u8], name: &str, linked: &dyn Fn(&str) -> Option>) -> Result { + if bytes.len() > MAX_SBS_BYTES { + return Err(FormatError::BadPackage(format!("the SBS file is over the {} MB limit", MAX_SBS_BYTES >> 20))); + } + + 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 warnings = Warnings::default(); + let file_stem = name.rsplit(['/', '\\']).next().unwrap_or(name); + let file_stem = file_stem.rsplit_once('.').map_or(file_stem, |(stem, _)| stem).trim(); + let package_name = match child_value(root, "identifier").map(str::trim) { + Some(id) if !id.is_empty() && id != "Unsaved Package" => id.to_string(), + _ if !file_stem.is_empty() => file_stem.to_string(), + _ => "Untitled package".to_string(), + }; + + let mut reader = + SbsReader { text, warnings: &mut warnings, dependencies: HashMap::new(), graph_names: HashMap::new(), resource_names: HashMap::new(), node_count: 0 }; + 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")) { + reader.dependencies.insert(uid.to_string(), file.to_string()); + } + } + + // Load resources before resolving graph references + let content = child_element(root, "content"); + let mut pkg = Package::new(&package_name); + let mut graph_elements: Vec<(String, XmlNode)> = Vec::new(); + if let Some(content) = content { + reader.collect_items(content, "", &mut pkg, &mut graph_elements, linked); + } + + // Name every graph first so instances can refer to graphs defined later in the file + let mut names: Vec = Vec::new(); + for (path, graph) in graph_elements.iter().take(MAX_GRAPHS) { + let identifier = child_value(*graph, "identifier").unwrap_or("").trim(); + let unique = unique_name(&names, if identifier.is_empty() { "Graph" } else { identifier }); + reader.graph_names.insert(path.clone(), unique.clone()); + names.push(unique); + } + if graph_elements.len() > MAX_GRAPHS { + reader.warnings.add(format!("only the first {MAX_GRAPHS} graphs were read")); + } + + for ((_, graph), name) in graph_elements.iter().zip(names) { + let graph = reader.read_graph(*graph, name); + pkg.graphs.push(graph); + } + if pkg.graphs.is_empty() { + reader.warnings.add("the package has no graphs MaterialCraft can open; an empty graph was added"); + pkg.graphs.push(Graph::new("Graph")); + } + + report_placeholders(&pkg, reader.warnings); + Ok(SbsRead { pkg, warnings: warnings.finish() }) +} +pub fn is_sbs(bytes: &[u8]) -> bool { + let head = String::from_utf8_lossy(&bytes[..bytes.len().min(SNIFF_BYTES)]); + let mut rest = head.trim_start_matches('\u{feff}'); + + // Skip the XML declaration and comments before the root element + loop { + rest = rest.trim_start(); + let (skip_open, skip_close) = if rest.starts_with("") + } else if rest.starts_with("") + } else { + break; + }; + + match rest[skip_open.len()..].find(skip_close) { + Some(end) => rest = &rest[skip_open.len() + end + skip_close.len()..], + None => return false, + } + } + + rest.strip_prefix("' || c == '/' || c.is_whitespace())) +} diff --git a/crates/formats/src/sbs/sbs_reader.rs b/crates/formats/src/sbs/sbs_reader.rs index 12f0bdb..ffde83e 100644 --- a/crates/formats/src/sbs/sbs_reader.rs +++ b/crates/formats/src/sbs/sbs_reader.rs @@ -1,23 +1,20 @@ use super::base_parameters::read_base_params; +use super::component_usage; use super::connection::connect_all; -use super::constant::{MAX_GRAPHS, MAX_NODES, MAX_RESOURCES, MAX_SBS_BYTES, MAX_XML_NODES}; -use super::constant::{NODE_HALF_SIZE, SELF_DEPENDENCY, SNIFF_BYTES}; +use super::constant::{MAX_NODES, MAX_RESOURCES}; +use super::constant::{NODE_HALF_SIZE, SELF_DEPENDENCY}; use super::embedded::decode_embedded; use super::filter_map::{BASE_PARAMS, FilterMap, HANDLED_PARAMS, filter_by_sbs_name}; use super::function_graph; use super::input_bridge::InputBridge; -use super::output::usage_index; -use super::placeholder::{add_placeholder_input, fill_placeholder, placeholder_outputs, report_placeholders}; +use super::placeholder::{add_placeholder_input, fill_placeholder, placeholder_outputs}; use super::read_node::ReadNode; -use super::sbs_read::SbsRead; use super::sbs_value::{SbsValue, exposed_default, sbs_constant, to_natural_value, to_param_value}; use super::type_code; use super::warnings::Warnings; use super::xml::{child_element, child_value, children_named, parse_floats}; -use crate::{FormatError, Result}; use materialcraft_core::{ - Comment, Connection, ExposedParameter, Frame, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, Package, Pin, Resource, ResourceBytes, - Value, srgb_to_linear, + ComponentUsage, Connection, ExposedParameter, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, Package, Resource, ResourceBytes, Value, }; use materialcraft_nodes::find; use roxmltree::Node as XmlNode; @@ -100,10 +97,12 @@ impl<'text> SbsReader<'text, '_> { match bytes { Some(data) => { let ext = if kind == "svg" { "svg".to_string() } else { format }; + pkg.resources.push(Resource::new(name.clone(), crate::safe_file_name(&format!("{name}.{ext}")), ResourceBytes::new(data))); } None => { let why = if why_missing.is_empty() { "it has no data".to_string() } else { why_missing }; + self.warnings.add(format!("resource `{path}` could not be loaded: {why}")); } } @@ -150,7 +149,7 @@ impl<'text> SbsReader<'text, '_> { } }); if let Some(dynamic) = dynamic { - self.read_canvas_items(dynamic, &mut graph); + super::canvas::read_canvas_items(dynamic, &mut graph, self.warnings); } return graph; } @@ -167,6 +166,7 @@ impl<'text> SbsReader<'text, '_> { } let Some(uid) = child_value(*comp_node, "uid").map(str::to_string) else { continue }; + if read_nodes.contains_key(&uid) { self.warnings.add(format!("graph `{name}`: duplicate node uid {uid} skipped")); continue; @@ -189,7 +189,7 @@ impl<'text> SbsReader<'text, '_> { let wires = self.read_wires(&mut graph, &comp_nodes, &read_nodes); connect_all(&mut graph, wires, self.warnings); - self.read_canvas_items(element, &mut graph); + super::canvas::read_canvas_items(element, &mut graph, self.warnings); graph } pub(super) fn read_graph_inputs(&mut self, element: XmlNode, graph: &mut Graph) -> HashMap { @@ -202,7 +202,10 @@ impl<'text> SbsReader<'text, '_> { .and_then(sbs_constant) .and_then(|value| to_param_value(&Value::Color([0.5, 0.5, 0.5, 1.0]), &value, 0)) .unwrap_or(Value::Color([0.5, 0.5, 0.5, 1.0])); - image_inputs.insert(child_value(input, "uid").unwrap_or("").to_string(), InputBridge { identifier: id, type_code: code as u32, default }); + image_inputs.insert( + child_value(input, "uid").unwrap_or("").to_string(), + InputBridge { identifier: id, type_code: code as u32, usage: component_usage::read(input), default }, + ); continue; } if graph.exposed.iter().any(|e| e.id == id) { @@ -211,7 +214,10 @@ impl<'text> SbsReader<'text, '_> { let default = exposed_default(code, child_element(input, "defaultValue").and_then(sbs_constant).as_ref()); if child_value(input, "isConnectable") == Some("1") { - image_inputs.insert(child_value(input, "uid").unwrap_or("").to_string(), InputBridge { identifier: id, type_code: code as u32, default }); + image_inputs.insert( + child_value(input, "uid").unwrap_or("").to_string(), + InputBridge { identifier: id, type_code: code as u32, usage: component_usage::read(input), default }, + ); continue; } let label = child_element(input, "attributes").and_then(|a| child_value(a, "label")).filter(|l| !l.is_empty()).unwrap_or(&id).to_string(); @@ -238,6 +244,7 @@ impl<'text> SbsReader<'text, '_> { for comp_node in comp_nodes { let Some(to) = child_value(*comp_node, "uid").and_then(|u| read_nodes.get(u)) else { continue }; + for connection in child_element(*comp_node, "connections").into_iter().flat_map(|c| children_named(c, "connection")) { let sbs_input = child_value(connection, "identifier").unwrap_or(""); let Some(from) = child_value(connection, "connRef").and_then(|u| read_nodes.get(u)) else { @@ -275,44 +282,6 @@ impl<'text> SbsReader<'text, '_> { wires } - pub(super) fn read_canvas_items(&mut self, element: XmlNode, graph: &mut Graph) { - for item in child_element(element, "GUIObjects").into_iter().flat_map(|objects| children_named(objects, "GUIObject")) { - let layout = child_element(item, "GUILayout"); - let position = layout.and_then(|layout| child_value(layout, "gpos")).map(parse_floats).unwrap_or_default(); - let size = layout.and_then(|layout| child_value(layout, "size")).map(parse_floats).unwrap_or_default(); - let x = position.first().copied().unwrap_or(0.0); - let y = position.get(1).copied().unwrap_or(0.0); - let width = size.first().copied().unwrap_or(180.0).max(8.0); - let height = size.get(1).copied().unwrap_or(70.0).max(8.0); - let text = child_value(item, "GUIName").unwrap_or("").to_string(); - - match child_value(item, "type") { - Some("COMMENT") if child_value(item, "isFrameVisible") == Some("1") => { - let channels = child_value(item, "frameColor").map(parse_floats).unwrap_or_default(); - let color = match channels.as_slice() { - &[red, green, blue, alpha, ..] => [srgb_to_linear(red), srgb_to_linear(green), srgb_to_linear(blue), alpha], - _ => [0.2, 0.4, 0.8, 0.25], - }; - let title = child_value(item, "title").unwrap_or("").to_string(); - let title_visible = child_value(item, "isTitleVisible") != Some("0"); - let id = graph.alloc_id(); - - graph.frames.push(Frame { id, title, title_visible, description: text, rect: [x, y, width, height], color }); - } - Some("COMMENT") => { - let id = graph.alloc_id(); - graph.comments.push(Comment { id, text, pos: [x, y], size: [width, height] }); - } - Some("PIN") => { - let id = graph.alloc_id(); - graph.pins.push(Pin { id, name: text, pos: [x, y] }); - } - Some(other) => self.warnings.add(format!("graph `{}`: canvas item `{other}` is not supported", graph.name)), - None => {} - } - } - } - pub(super) fn read_node( &mut self, graph: &mut Graph, @@ -354,6 +323,7 @@ impl<'text> SbsReader<'text, '_> { if let Some(node) = node { let identifier = input.map_or("input", |input| input.identifier.as_str()); node.params.insert("identifier".into(), Value::Text(identifier.to_string())); + node.params.insert("usage".into(), Value::Enum(input.map_or(ComponentUsage::ANY_INDEX, |input| input.usage))); if let Some(input) = input { node.params.insert("default".into(), input.default.clone()); } @@ -363,7 +333,7 @@ impl<'text> SbsReader<'text, '_> { } "compOutputBridge" => { let output = child_value(implementation, "output").unwrap_or(""); - let (identifier, usage) = outputs.get(output).cloned().unwrap_or_else(|| ("output".into(), usage_index("any"))); + let (identifier, usage) = outputs.get(output).cloned().unwrap_or_else(|| ("output".into(), ComponentUsage::ANY_INDEX)); let (id, index, node) = push_node(graph, "output", pos); if let Some(node) = node { node.params.insert("identifier".into(), Value::Text(identifier)); @@ -465,6 +435,7 @@ impl<'text> SbsReader<'text, '_> { } let Some(dynamic) = child_element(param_value, "dynamicValue") else { return }; + match function_graph::read(dynamic) { Ok(graph) if matches!(like, Value::Function(_)) => { node.params.insert(id.to_string(), Value::Function(Box::new(graph))); @@ -513,93 +484,6 @@ impl<'text> SbsReader<'text, '_> { } } } -pub fn read_sbs(bytes: &[u8], name: &str, linked: &dyn Fn(&str) -> Option>) -> Result { - if bytes.len() > MAX_SBS_BYTES { - return Err(FormatError::BadPackage(format!("the SBS file is over the {} MB limit", MAX_SBS_BYTES >> 20))); - } - - 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 warnings = Warnings::default(); - let file_stem = name.rsplit(['/', '\\']).next().unwrap_or(name); - let file_stem = file_stem.rsplit_once('.').map_or(file_stem, |(stem, _)| stem).trim(); - let package_name = match child_value(root, "identifier").map(str::trim) { - Some(id) if !id.is_empty() && id != "Unsaved Package" => id.to_string(), - _ if !file_stem.is_empty() => file_stem.to_string(), - _ => "Untitled package".to_string(), - }; - - let mut reader = - SbsReader { text, warnings: &mut warnings, dependencies: HashMap::new(), graph_names: HashMap::new(), resource_names: HashMap::new(), node_count: 0 }; - 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")) { - reader.dependencies.insert(uid.to_string(), file.to_string()); - } - } - - // Load resources before resolving graph references - let content = child_element(root, "content"); - let mut pkg = Package::new(&package_name); - let mut graph_elements: Vec<(String, XmlNode)> = Vec::new(); - if let Some(content) = content { - reader.collect_items(content, "", &mut pkg, &mut graph_elements, linked); - } - - // Name every graph first so instances can refer to graphs defined later in the file - let mut names: Vec = Vec::new(); - for (path, graph) in graph_elements.iter().take(MAX_GRAPHS) { - let identifier = child_value(*graph, "identifier").unwrap_or("").trim(); - let unique = unique_name(&names, if identifier.is_empty() { "Graph" } else { identifier }); - reader.graph_names.insert(path.clone(), unique.clone()); - names.push(unique); - } - if graph_elements.len() > MAX_GRAPHS { - reader.warnings.add(format!("only the first {MAX_GRAPHS} graphs were read")); - } - - for ((_, graph), name) in graph_elements.iter().zip(names) { - let graph = reader.read_graph(*graph, name); - pkg.graphs.push(graph); - } - if pkg.graphs.is_empty() { - reader.warnings.add("the package has no graphs MaterialCraft can open; an empty graph was added"); - pkg.graphs.push(Graph::new("Graph")); - } - - report_placeholders(&pkg, reader.warnings); - Ok(SbsRead { pkg, warnings: warnings.finish() }) -} -pub fn is_sbs(bytes: &[u8]) -> bool { - let head = String::from_utf8_lossy(&bytes[..bytes.len().min(SNIFF_BYTES)]); - let mut rest = head.trim_start_matches('\u{feff}'); - - // Skip the XML declaration and comments before the root element - loop { - rest = rest.trim_start(); - let (skip_open, skip_close) = if rest.starts_with("") - } else if rest.starts_with("") - } else { - break; - }; - - match rest[skip_open.len()..].find(skip_close) { - Some(end) => rest = &rest[skip_open.len() + end + skip_close.len()..], - None => return false, - } - } - - rest.strip_prefix("' || c == '/' || c.is_whitespace())) -} - pub(super) fn unique_name(taken: &[String], base: &str) -> String { let free = |name: &str| !taken.iter().any(|t| t == name); if free(base) { @@ -616,10 +500,7 @@ pub(super) fn read_graph_outputs(element: XmlNode) -> HashMap // SBS colors are stored as displayed (sRGB); MaterialCraft's are linear Value::Color(_) if value.component_count() >= 3 => { let alpha = if value.component_count() >= 4 { f(3) } else { 1.0 }; + Value::Color([srgb_to_linear(f(0)), srgb_to_linear(f(1)), srgb_to_linear(f(2)), alpha]) } Value::Color(_) => { @@ -137,21 +138,9 @@ pub(super) fn exposed_default(code: i64, value: Option<&SbsValue>) -> Value { } pub(super) fn exposed_type_code(value: &Value) -> i64 { - use type_code::*; - - match value { - Value::Bool(_) => BOOL, - Value::Int(_) | Value::Enum(_) => INT1, - Value::Int2(_) => INT2, - Value::Int3(_) => INT3, - Value::Int4(_) => INT4, - Value::Float(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_) | Value::PatternGraph(_) => FLOAT1, - Value::Float2(_) => FLOAT2, - Value::Float3(_) => FLOAT3, - Value::Float4(_) | Value::Color(_) => FLOAT4, - Value::Text(_) => STRING, - } + materialcraft_core::ValueType::of(value).map_or(type_code::FLOAT1, |kind| i64::from(kind as u32)) } + pub(super) fn constant_xml(value: &Value) -> Option { let join = |xs: &[f32]| xs.iter().map(|x| format_float(*x)).collect::>().join(" "); let (tag, text) = match value { diff --git a/crates/formats/src/sbs/sbs_writer.rs b/crates/formats/src/sbs/sbs_writer.rs index c87aeb1..6915524 100644 --- a/crates/formats/src/sbs/sbs_writer.rs +++ b/crates/formats/src/sbs/sbs_writer.rs @@ -1,18 +1,17 @@ use super::base_parameters::base_params_xml; use super::canvas::write_canvas_items; -use super::constant::FORMAT_VERSION; -use super::constant::{FIRST_UID, NODE_HALF_SIZE, SELF_DEPENDENCY}; -use super::embedded::encode_embedded; +use super::component_usage; +use super::constant::NODE_HALF_SIZE; use super::filter_map::filter_by_def; use super::function_graph; use super::node_identifiers::NodeIdentifiers; use super::node_parameter::{param_xml, special_filter_params_xml, text_param}; -use super::output::{output_type, usage_name}; +use super::output::output_type; use super::sbs_value::{constant_xml, exposed_type_code}; use super::type_code; use super::xml::{format_float, is_parameters_element, xml_escape}; use crate::{FormatError, Result}; -use materialcraft_core::{Connection, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, Package, Value, missing_ports}; +use materialcraft_core::{ComponentUsage, Connection, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, Package, Value, missing_ports}; use materialcraft_nodes::find; use std::collections::{BTreeMap, HashMap}; use std::fmt::Write as _; @@ -120,6 +119,7 @@ impl SbsWriter { out.push_str(""); for wire in wires { let Some(from_uid) = node_uids.get(&wire.from) else { continue }; + let Some((_, _, output_uid)) = node_outputs.get(&wire.from).and_then(|o| o.iter().find(|(port, _, _)| *port == wire.from_port)) else { continue; }; @@ -169,6 +169,7 @@ impl SbsWriter { let uid = self.next_uid(); entries.insert(node.id, uid); let fallback = if node.def == "input_value" { Value::Float(0.0) } else { Value::Color([0.5, 0.5, 0.5, 1.0]) }; + let value = node.params.get("default").unwrap_or(&fallback); let default = constant_xml(value).unwrap_or_default(); let code = match node.def.as_str() { @@ -179,14 +180,17 @@ impl SbsWriter { let _ = write!( out, - "{default}", + "{default}", xml_escape(&text_param(node, "identifier", "input")) ); + component_usage::write(out, node, ComponentUsage::ANY_INDEX); + out.push_str(""); } for exposed in &graph.exposed { let default = constant_xml(graph.inputs.get(&exposed.id).unwrap_or(&exposed.default)).unwrap_or_else(|| "".into()); let group = if exposed.group.is_empty() { String::new() } else { format!("", xml_escape(&exposed.group)) }; + let _ = write!( out, "{default}{group}", @@ -209,18 +213,19 @@ impl SbsWriter { for node in graph.nodes.iter().filter(|n| n.def == "output") { let uid = self.next_uid(); output_uids.insert(node.id, uid); - let usage = node.params.get("usage").and_then(Value::as_i32).unwrap_or(0).max(0) as u32; let code = output_type(graph, node.id, "output"); let channels = format!(""); let identifier = text_param(node, "identifier", "output"); let label = if node.label.is_empty() { identifier.clone() } else { node.label.clone() }; + let _ = write!( out, - "{channels}", + "", xml_escape(&identifier), - xml_escape(&label), - usage_name(usage) + xml_escape(&label) ); + component_usage::write(out, node, 0); + let _ = write!(out, "{channels}"); } out.push_str(""); @@ -276,6 +281,7 @@ impl SbsWriter { let value_of = |id: &str| node.params.get(id).or_else(|| catalog_def.param(id).map(|p| &p.default)); for (sbs_name, mc_name) in filter.params { let Some(value) = value_of(mc_name) else { continue }; + let binding = node.bindings.get(*mc_name).map(|identifier| function_graph::binding(identifier, value)).transpose().map_err(FormatError::Io)?; let function = node.functions.get(*mc_name).or(binding.as_ref()).or_else(|| match value { @@ -311,62 +317,6 @@ impl SbsWriter { Ok(()) } } -pub fn write_sbs(pkg: &Package) -> Result> { - let mut writer = SbsWriter { last_uid: FIRST_UID, external_packages: BTreeMap::new() }; - let self_uid = writer.next_uid(); - - let mut content = String::from(""); - for graph in &pkg.graphs { - if graph.function.is_some() { - super::standalone_function::write(&mut content, graph, &mut writer)?; - } else { - writer.write_graph(&mut content, pkg, graph, self_uid)?; - } - } - if !pkg.resources.is_empty() { - let _ = write!(content, "", writer.next_uid()); - for resource in &pkg.resources { - let svg = resource.file.to_ascii_lowercase().ends_with(".svg"); - let ext = resource.file.rsplit_once('.').map_or("png", |(_, e)| e); - let _ = write!( - content, - "", - xml_escape(&resource.name), - writer.next_uid(), - if svg { "svg" } else { "bitmap" }, - xml_escape(ext), - resource.bytes.len(), - encode_embedded(resource.bytes.as_slice())? - ); - } - content.push_str(""); - } - content.push_str(""); - - let mut out = String::with_capacity(content.len() + 4096); - let _ = write!( - out, - "", - xml_escape(&pkg.name) - ); - let write_dependency = |out: &mut String, file: &str, uid: u64| { - let _ = write!( - out, - "", - xml_escape(file) - ); - }; - - write_dependency(&mut out, SELF_DEPENDENCY, self_uid); - for (file, uid) in &writer.external_packages { - write_dependency(&mut out, file, *uid); - } - out.push_str(""); - out.push_str(&content); - - out.push_str("\n"); - Ok(out.into_bytes()) -} pub(super) type WrittenOutputs = Vec<(String, u32, u64)>; pub(super) fn write_bridgings(out: &mut String, outputs: &[(String, u32, u64)]) { diff --git a/crates/formats/src/sbs/tests.rs b/crates/formats/src/sbs/tests.rs index ce058f1..5b1c1dc 100644 --- a/crates/formats/src/sbs/tests.rs +++ b/crates/formats/src/sbs/tests.rs @@ -1,6 +1,6 @@ use super::embedded::{base64_engine, decode_embedded, encode_embedded}; -use super::sbs_reader::{is_sbs, read_sbs}; -use super::sbs_writer::write_sbs; +use super::read::{is_sbs, read_sbs}; +use super::write::write_sbs; use base64::Engine as _; use materialcraft_core::{Frame, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Package, Resource, ResourceBytes, SizeMode, Value, missing_ports}; @@ -81,6 +81,7 @@ fn structural_round_trip() { assert_eq!(back.nodes[1].params.get("intensity"), Some(&Value::Float(4.5))); let Some(Value::Color(color)) = back.nodes[2].params.get("color") else { panic!("uniform color") }; + assert!((color[0] - 0.25).abs() < 1e-3 && (color[2] - 0.75).abs() < 1e-3); assert_eq!(back.nodes[3].params.get("mode"), Some(&Value::Enum(3))); assert_eq!(back.nodes[4].params.get("usage"), Some(&Value::Enum(4))); @@ -242,6 +243,7 @@ fn native_function_fixture_retains_operation_types_and_ports() { assert!(read.warnings.is_empty(), "{:?}", read.warnings); let back = read_sbs(&write_sbs(&read.pkg).unwrap(), "values.sbs", &no_linked_files).unwrap(); let Value::Function(function) = &back.pkg.graphs[0].nodes[0].params["function"] else { panic!("missing function") }; + assert_eq!(function.nodes[0].value, Some(Value::Int(16_777_217))); assert_eq!(function.nodes[2].op, "add"); assert_eq!(function.nodes[2].type_code, 16); @@ -301,3 +303,61 @@ fn navigation_pins_round_trip_in_graphs_and_functions() { assert_eq!(reopened.pkg.graphs[0].pins, *pins); } } + +#[test] +fn component_usages_round_trip_without_reassigning_existing_indices() { + use materialcraft_core::ComponentUsage; + + let original = ["baseColor", "normal", "roughness", "metallic", "height", "ambientOcclusion", "emissive", "opacity", "specular", "any"]; + for (index, id) in original.iter().enumerate() { + assert_eq!(ComponentUsage::from_index(index as u32).id, *id); + } + assert_eq!(ComponentUsage::from_index(u32::MAX), ComponentUsage::ANY); + assert_eq!(ComponentUsage::index("futureUsage"), ComponentUsage::ANY_INDEX); + assert_eq!(ComponentUsage::index(" DIFFUSE "), ComponentUsage::index("diffuse")); + + let mut package = Package::new("Usage round trip"); + let mut graph = Graph::new("Usages"); + for definition in ["output", "input_color", "input_grayscale", "input_value"] { + for (index, usage) in ComponentUsage::ALL.iter().enumerate() { + let id = graph.add_node(definition, [index as f32 * 160.0, 0.0]); + graph + .node_mut(id) + .unwrap() + .params + .extend([("identifier".into(), Value::Text(format!("{definition}_{}", usage.id))), ("usage".into(), Value::Enum(index as u32))]); + } + } + package.graphs.push(graph); + let xml = write_sbs(&package).unwrap(); + let restored = read_sbs(&xml, "usages.sbs", &no_linked_files).unwrap(); + assert!(restored.warnings.is_empty(), "{:?}", restored.warnings); + assert_eq!(restored.pkg.graphs[0].nodes.len(), package.graphs[0].nodes.len()); + for (original, node) in package.graphs[0].nodes.iter().zip(&restored.pkg.graphs[0].nodes) { + assert_eq!(node.def, original.def); + assert_eq!(node.params.get("usage"), original.params.get("usage")); + assert_eq!(node.params.get("identifier"), original.params.get("identifier")); + } +} + +#[test] +fn input_usage_defaults_and_unknown_metadata_stay_unclassified() { + use materialcraft_core::ComponentUsage; + + let mut package = Package::new("Input usages"); + let mut graph = Graph::new("Inputs"); + for definition in ["input_color", "input_grayscale", "input_value"] { + graph.add_node(definition, [0.0; 2]); + } + package.graphs.push(graph); + let saved = String::from_utf8(write_sbs(&package).unwrap()).unwrap(); + let usage = ""; + assert_eq!(saved.matches(usage).count(), 3); + for xml in [saved.clone(), saved.replace(usage, ""), saved.replace("", "")] { + let restored = read_sbs(xml.as_bytes(), "inputs.sbs", &no_linked_files).unwrap(); + assert_eq!(restored.pkg.graphs[0].nodes.len(), 3); + for node in &restored.pkg.graphs[0].nodes { + assert_eq!(node.params.get("usage"), Some(&Value::Enum(ComponentUsage::ANY_INDEX))); + } + } +} diff --git a/crates/formats/src/sbs/type_code.rs b/crates/formats/src/sbs/type_code.rs index 8b54143..4db589f 100644 --- a/crates/formats/src/sbs/type_code.rs +++ b/crates/formats/src/sbs/type_code.rs @@ -1,12 +1,14 @@ +use materialcraft_core::ValueType; + pub const COLOR_IMAGE: i64 = 1; pub const GRAY_IMAGE: i64 = 2; -pub const BOOL: i64 = 4; -pub const INT1: i64 = 16; -pub const INT2: i64 = 32; -pub const INT3: i64 = 64; -pub const INT4: i64 = 128; -pub const FLOAT1: i64 = 256; -pub const FLOAT2: i64 = 512; -pub const FLOAT3: i64 = 1024; -pub const FLOAT4: i64 = 2048; -pub const STRING: i64 = 16384; +pub const BOOL: i64 = ValueType::Boolean as i64; +pub const INT1: i64 = ValueType::Integer as i64; +pub const INT2: i64 = ValueType::Integer2 as i64; +pub const INT3: i64 = ValueType::Integer3 as i64; +pub const INT4: i64 = ValueType::Integer4 as i64; +pub const FLOAT1: i64 = ValueType::Float as i64; +pub const FLOAT2: i64 = ValueType::Float2 as i64; +pub const FLOAT3: i64 = ValueType::Float3 as i64; +pub const FLOAT4: i64 = ValueType::Float4 as i64; +pub const STRING: i64 = ValueType::String as i64; diff --git a/crates/formats/src/sbs/write.rs b/crates/formats/src/sbs/write.rs new file mode 100644 index 0000000..dbed697 --- /dev/null +++ b/crates/formats/src/sbs/write.rs @@ -0,0 +1,66 @@ +use super::{ + constant::{FIRST_UID, FORMAT_VERSION, SELF_DEPENDENCY}, + embedded::encode_embedded, + sbs_writer::SbsWriter, + xml::xml_escape, +}; +use crate::Result; +use materialcraft_core::Package; +use std::{collections::BTreeMap, fmt::Write as _}; + +pub fn write_sbs(pkg: &Package) -> Result> { + let mut writer = SbsWriter { last_uid: FIRST_UID, external_packages: BTreeMap::new() }; + let self_uid = writer.next_uid(); + + let mut content = String::from(""); + for graph in &pkg.graphs { + if graph.function.is_some() { + super::standalone_function::write(&mut content, graph, &mut writer)?; + } else { + writer.write_graph(&mut content, pkg, graph, self_uid)?; + } + } + if !pkg.resources.is_empty() { + let _ = write!(content, "", writer.next_uid()); + for resource in &pkg.resources { + let svg = resource.file.to_ascii_lowercase().ends_with(".svg"); + let ext = resource.file.rsplit_once('.').map_or("png", |(_, e)| e); + let _ = write!( + content, + "", + xml_escape(&resource.name), + writer.next_uid(), + if svg { "svg" } else { "bitmap" }, + xml_escape(ext), + resource.bytes.len(), + encode_embedded(resource.bytes.as_slice())? + ); + } + content.push_str(""); + } + content.push_str(""); + + let mut out = String::with_capacity(content.len() + 4096); + let _ = write!( + out, + "", + xml_escape(&pkg.name) + ); + let write_dependency = |out: &mut String, file: &str, uid: u64| { + let _ = write!( + out, + "", + xml_escape(file) + ); + }; + + write_dependency(&mut out, SELF_DEPENDENCY, self_uid); + for (file, uid) in &writer.external_packages { + write_dependency(&mut out, file, *uid); + } + out.push_str(""); + out.push_str(&content); + + out.push_str("\n"); + Ok(out.into_bytes()) +} diff --git a/crates/nodes/src/atomic/input_color.rs b/crates/nodes/src/atomic/input_color.rs index 6cea4ef..fa94be9 100644 --- a/crates/nodes/src/atomic/input_color.rs +++ b/crates/nodes/src/atomic/input_color.rs @@ -1,5 +1,6 @@ use super::GRAPH_ITEMS; use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_core::ComponentUsage; use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { @@ -8,6 +9,7 @@ pub(super) fn definition() -> NodeDefinition { .atomic() .generator() .text("identifier", "Identifier", "input") + .component_usage(ComponentUsage::ANY_INDEX) .color("default", "Default color", [0.5, 0.5, 0.5, 1.0]) .color_out() .cook(input_color_default) diff --git a/crates/nodes/src/atomic/input_grayscale.rs b/crates/nodes/src/atomic/input_grayscale.rs index ac1f1f1..80900df 100644 --- a/crates/nodes/src/atomic/input_grayscale.rs +++ b/crates/nodes/src/atomic/input_grayscale.rs @@ -1,5 +1,6 @@ use super::GRAPH_ITEMS; use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_core::ComponentUsage; use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { @@ -8,6 +9,7 @@ pub(super) fn definition() -> NodeDefinition { .atomic() .generator() .text("identifier", "Identifier", "input") + .component_usage(ComponentUsage::ANY_INDEX) .color("default", "Default value", [0.5, 0.5, 0.5, 1.0]) .gray_out() .cook(input_gray_default) diff --git a/crates/nodes/src/atomic/input_value.rs b/crates/nodes/src/atomic/input_value.rs index b28aa98..4178e2c 100644 --- a/crates/nodes/src/atomic/input_value.rs +++ b/crates/nodes/src/atomic/input_value.rs @@ -1,11 +1,13 @@ use super::GRAPH_ITEMS; use crate::{NodeDefinition, PortKind, node}; +use materialcraft_core::ComponentUsage; pub(super) fn definition() -> NodeDefinition { node("input_value", "Input Value", GRAPH_ITEMS) .desc("A typed value input of the graph.") .atomic() .text("identifier", "Identifier", "value") + .component_usage(ComponentUsage::ANY_INDEX) .float("default", "Default", 0.0, 0.0, 0.0) .output("output", "Value", PortKind::Value) .cook(crate::node_definition_builder::no_cook) diff --git a/crates/nodes/src/atomic/mod.rs b/crates/nodes/src/atomic/mod.rs index 7cea532..33a2a17 100644 --- a/crates/nodes/src/atomic/mod.rs +++ b/crates/nodes/src/atomic/mod.rs @@ -37,8 +37,6 @@ use direction::direction; pub const ATOMIC: &str = "Atomic nodes"; pub const GRAPH_ITEMS: &str = "Graph items"; -pub const USAGES: &[&str] = &["Base color", "Normal", "Roughness", "Metallic", "Height", "Ambient occlusion", "Emissive", "Opacity", "Specular", "Any"]; -pub const USAGE_IDS: &[&str] = &["baseColor", "normal", "roughness", "metallic", "height", "ambientOcclusion", "emissive", "opacity", "specular", "any"]; pub use levels::levels_fn; pub use normal::height_to_normal; diff --git a/crates/nodes/src/atomic/output.rs b/crates/nodes/src/atomic/output.rs index 775d820..62202a2 100644 --- a/crates/nodes/src/atomic/output.rs +++ b/crates/nodes/src/atomic/output.rs @@ -1,5 +1,5 @@ +use super::GRAPH_ITEMS; use super::dot::passthrough; -use super::{GRAPH_ITEMS, USAGES}; use crate::{NodeDefinition, PortKind, node}; use materialcraft_image::{Image, Kind}; @@ -9,7 +9,7 @@ pub(super) fn definition() -> NodeDefinition { .atomic() .any_in("input", "Input") .text("identifier", "Identifier", "output") - .choice("usage", "Usage", USAGES, 0) + .component_usage(0) .cook(passthrough) } diff --git a/crates/nodes/src/function/operation.rs b/crates/nodes/src/function/operation.rs index 0b27e04..b206d62 100644 --- a/crates/nodes/src/function/operation.rs +++ b/crates/nodes/src/function/operation.rs @@ -14,8 +14,8 @@ pub(crate) fn evaluate( context: &EvaluationContext<'_>, ) -> Result { let op = instruction.definition.id; - let first = || arguments.first().ok_or("missing first operand".to_string()); - let second = || arguments.get(1).ok_or("missing second operand".to_string()); + let first = || arguments.first().ok_or("missing first operand"); + let second = || arguments.get(1).ok_or("missing second operand"); let name = || match &instruction.value { Some(Value::Text(name)) => Ok(name.as_str()), _ => Err("variable name must be a string".to_string()), @@ -26,22 +26,26 @@ pub(crate) fn evaluate( if value_type::type_code(&value) != instruction.type_code { return Err("constant has the wrong type".into()); } + return Ok(value); } + if op.starts_with("get_") { let name = name()?; let value = match name { "$pos" => Value::Float2(context.position), "$size" => Value::Float2(context.size), "$sizelog2" => Value::Float2(context.size.map(f32::log2)), - _ => variables.get(name).cloned().ok_or_else(|| format!("undefined variable `{name}`"))?, + _ => variables.get(name).or_else(|| context.variables.get(name)).cloned().ok_or_else(|| format!("undefined variable `{name}`"))?, }; if value_type::type_code(&value) != instruction.type_code { return Err(format!("variable `{name}` has the wrong type for {op}")); } + return Ok(value); } + if op.starts_with("to") || op.contains("vector") || op.contains("swizzle") { return super::vector::evaluate(op, arguments, instruction.value.as_ref()); } @@ -53,11 +57,15 @@ pub(crate) fn evaluate( if name.is_empty() || name.starts_with('$') { return Err("use a nonempty user variable name".into()); } + let value = first()?.clone(); variables.insert(name.to_string(), value.clone()); value } - "isdefined" => Value::Bool(variables.contains_key(name()?) || matches!(name()?, "$pos" | "$size" | "$sizelog2")), + "isdefined" => { + let name = name()?; + Value::Bool(variables.contains_key(name) || context.variables.contains_key(name) || matches!(name, "$pos" | "$size" | "$sizelog2")) + } "and" => Value::Bool(boolean(first()?)? && boolean(second()?)?), "or" => Value::Bool(boolean(first()?)? || boolean(second()?)?), "not" => Value::Bool(!boolean(first()?)?), diff --git a/crates/nodes/src/function/processor.rs b/crates/nodes/src/function/processor.rs index 3b25818..ee07720 100644 --- a/crates/nodes/src/function/processor.rs +++ b/crates/nodes/src/function/processor.rs @@ -31,6 +31,7 @@ pub(crate) fn pixel_processor(context: &CookContext) -> CookResult { let program = compile(graph, context.seed)?; let gray = !context.b("color_mode"); let kind = if gray { Kind::Gray } else { Kind::Color }; + let (width, height) = materialcraft_image::clamp_size(context.w, context.h); let channels = kind.channels(); let mut data = vec![0.0; width as usize * height as usize * channels]; @@ -44,7 +45,7 @@ pub(crate) fn pixel_processor(context: &CookContext) -> CookResult { variables: context.vars, }; - let result = pixel(program.evaluate(&evaluation, state)?, gray)?; + let result = pixel(program.evaluate_pixel(&evaluation, state)?, gray)?; target.copy_from_slice(result.get(..channels).ok_or("invalid output channels")?); } Ok(()) diff --git a/crates/nodes/src/function/program.rs b/crates/nodes/src/function/program.rs index 0ee75a5..f9fffe9 100644 --- a/crates/nodes/src/function/program.rs +++ b/crates/nodes/src/function/program.rs @@ -20,23 +20,35 @@ impl Program { } fn instruction(&self, index: usize) -> Result<&Instruction, String> { - self.instructions.get(index).ok_or("invalid function instruction".into()) + self.instructions.get(index).ok_or_else(|| "invalid function instruction".into()) } fn input(&self, index: usize, slot: usize) -> Result { - self.instruction(index)?.inputs.get(slot).copied().ok_or("missing function input".into()) + self.instruction(index)?.inputs.get(slot).copied().ok_or_else(|| "missing function input".into()) } pub fn evaluate(&self, context: &EvaluationContext<'_>, state: &mut EvaluationState) -> Result { + state.variables.clone_from(context.variables); + self.run(context, state) + } + + // Pixel assignments are local; only the general evaluator exports the complete environment + pub(super) fn evaluate_pixel(&self, context: &EvaluationContext<'_>, state: &mut EvaluationState) -> Result { + state.variables.clear(); + self.run(context, state) + } + + fn run(&self, context: &EvaluationContext<'_>, state: &mut EvaluationState) -> Result { use EvaluationStep::*; + state.steps.clear(); state.values.clear(); state.registers.clear(); state.registers.resize(self.instructions.len(), None); - state.variables.clone_from(context.variables); state.random = context.variables.get("$randomseed").and_then(Value::as_i32).map_or(self.seed, |seed| seed as u32); state.steps.push(Enter(self.output)); let mut remaining_steps = MAX_EVALUATION_STEPS; + while let Some(step) = state.steps.pop() { remaining_steps = remaining_steps.checked_sub(1).ok_or("function exceeded its execution budget; check loop termination")?; match step { @@ -71,17 +83,20 @@ impl Program { let arguments = state.values.get(base..).ok_or("invalid function operands")?; let result = operation::evaluate(instruction, arguments, &mut state.variables, &mut state.random, context) .map_err(|error| format!("{} ({}): {error}", instruction.definition.label, instruction.id))?; + state.values.truncate(base); if instruction.pure && let Some(register) = state.registers.get_mut(index) { *register = Some(result.clone()); } + state.values.push(result); } Branch(index) => { let condition = state.values.pop().ok_or("missing branch condition")?; let slot = if value_type::boolean(&condition)? { 1 } else { 2 }; + state.steps.push(Enter(self.input(index, slot)?)); } Sequence(index) => { @@ -116,6 +131,7 @@ impl Program { if value_type::type_code(&result) != expected { return Err(format!("function returned {}, expected native type {expected}", result.type_name())); } + Ok(result) } } diff --git a/crates/nodes/src/function/tests.rs b/crates/nodes/src/function/tests.rs index 6793d58..7e4756b 100644 --- a/crates/nodes/src/function/tests.rs +++ b/crates/nodes/src/function/tests.rs @@ -162,3 +162,51 @@ fn deep_graphs_shared_inputs_and_cycles_do_not_recurse() { graph.output = Some(previous); assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(1_073_741_824.0)); } + +#[test] +fn pixel_assignments_are_local_and_match_exported_evaluation() { + let mut graph = FunctionGraph::default(); + let current = graph.add("get_float1", &[], Some(Value::Text("counter".into()))); + let one = graph.add_constant(Value::Float(1.0)); + let next = graph.add("add", &[current, one], None); + let assign = graph.add("set", &[next], Some(Value::Text("counter".into()))); + let get = graph.add("get_float1", &[], Some(Value::Text("counter".into()))); + graph.output = Some(graph.add("sequence", &[assign, get], None)); + let program = compile(&graph, 7).unwrap(); + let mut pixel_state = EvaluationState::default(); + for initial in [3.0, 10.0, -2.0] { + let variables = BTreeMap::from([("counter".into(), Value::Float(initial)), ("untouched".into(), Value::Text("keep".into()))]); + let context = EvaluationContext { position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables }; + let mut exported = EvaluationState::default(); + let expected = program.evaluate(&context, &mut exported).unwrap(); + for _ in 0..2 { + assert_eq!(program.evaluate_pixel(&context, &mut pixel_state).unwrap(), expected); + } + assert_eq!(expected, Value::Float(initial + 1.0)); + assert_eq!(variables["counter"], Value::Float(initial)); + assert_eq!(exported.variables()["counter"], expected); + assert_eq!(exported.variables()["untouched"], variables["untouched"]); + } + + let read_only = compile(&FunctionGraph::constant(Value::Float(0.5)), 7).unwrap(); + let context = EvaluationContext { position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &BTreeMap::new() }; + assert_eq!(read_only.evaluate_pixel(&context, &mut pixel_state).unwrap(), Value::Float(0.5)); + assert!(pixel_state.variables().is_empty()); +} + +#[test] +fn pixel_random_seed_and_defined_variables_match_general_evaluation() { + let mut graph = FunctionGraph::default(); + let maximum = graph.add_constant(Value::Float(1.0)); + let random = graph.add("rand", &[maximum], None); + let defined = graph.add("isdefined", &[], Some(Value::Text("known".into()))); + let zero = graph.add_constant(Value::Float(0.0)); + graph.output = Some(graph.add("ifelse", &[defined, random, zero], None)); + let program = compile(&graph, 7).unwrap(); + let mut state = EvaluationState::default(); + for variables in [BTreeMap::from([("$randomseed".into(), Value::Int(42)), ("known".into(), Value::Bool(true))]), BTreeMap::new()] { + let context = EvaluationContext { position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables }; + let expected = program.evaluate(&context, &mut EvaluationState::default()).unwrap(); + assert_eq!(program.evaluate_pixel(&context, &mut state).unwrap(), expected); + } +} diff --git a/crates/nodes/src/node_definition_builder.rs b/crates/nodes/src/node_definition_builder.rs index 52697c4..f53a264 100644 --- a/crates/nodes/src/node_definition_builder.rs +++ b/crates/nodes/src/node_definition_builder.rs @@ -1,5 +1,5 @@ use crate::{Cook, CookContext, CookResult, NodeDefinition, ParameterDefinition, PortDefinition, PortKind}; -use materialcraft_core::{Curve, FunctionGraph, Gradient, PatternGraph, Value}; +use materialcraft_core::{ComponentUsage, Curve, FunctionGraph, Gradient, PatternGraph, Value}; pub(crate) fn no_cook(_: &CookContext) -> CookResult { Err("this node is cooked by the graph evaluator".into()) @@ -120,6 +120,10 @@ impl NodeDefinitionBuilder { self } + pub fn component_usage(self, default: u32) -> NodeDefinitionBuilder { + self.choice("usage", "Component Usage", ComponentUsage::LABELS, default) + } + pub fn text(self, id: &'static str, label: &'static str, d: &str) -> NodeDefinitionBuilder { self.push(id, label, Value::Text(d.into()), 0.0, 0.0) } diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 0229b1e..a2fe2a0 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -9,6 +9,7 @@ license.workspace = true workspace = true [dependencies] +materialcraft-core = { workspace = true } materialcraft-geom = { workspace = true } materialcraft-image = { workspace = true } rayon = { workspace = true } diff --git a/crates/render/src/preview.rs b/crates/render/src/preview.rs index 634ed0d..5ae587d 100644 --- a/crates/render/src/preview.rs +++ b/crates/render/src/preview.rs @@ -32,16 +32,18 @@ impl Maps { pub fn from_usages<'a>(items: impl IntoIterator) -> Maps { let mut m = Maps::default(); for (usage, img) in items { - let slot = match usage { - "baseColor" => &mut m.base_color, - "normal" => &mut m.normal, - "roughness" => &mut m.roughness, - "metallic" => &mut m.metallic, - "height" => &mut m.height, - "ambientOcclusion" => &mut m.ao, - "emissive" => &mut m.emissive, - "opacity" => &mut m.opacity, - _ => continue, + use materialcraft_core::MaterialChannel; + let Some(channel) = MaterialChannel::from_id(usage) else { continue }; + + let slot = match channel { + MaterialChannel::BaseColor => &mut m.base_color, + MaterialChannel::Normal => &mut m.normal, + MaterialChannel::Roughness => &mut m.roughness, + MaterialChannel::Metallic => &mut m.metallic, + MaterialChannel::Height => &mut m.height, + MaterialChannel::AmbientOcclusion => &mut m.ao, + MaterialChannel::Emissive => &mut m.emissive, + MaterialChannel::Opacity => &mut m.opacity, }; if slot.is_none() { *slot = Some(img.clone()); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 2a0b8f6..2d92d21 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -240,20 +240,25 @@ pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p: } "ui.inspect" => { let rect = |r: egui::Rect| json!([r.min.x, r.min.y, r.width(), r.height()]); + let target = crate::graph::editor_target::EditorTarget::resolve(app); + let (view, nodes, ports) = (app.graph.view, &app.graph.rects, &app.graph.ports); ok(json!({ "state": app.ui, - "graphView": rect(app.graph.view), + "graphView": rect(view), "selection": app.session.selection, "inspectedNode": app.graph.inspected_node, - "subgraph": app.pattern_editor.as_ref().filter(|_| crate::pattern::active(app)) - .map(|editor| json!({"kind": "pattern", "graph": editor.graph, "node": editor.node.0, "selection": editor.selection, "inspectedNode": editor.inspected_node})) - .or_else(|| app.function_editor.as_ref().filter(|editor| matches!(editor.target, crate::function::FunctionTarget::Graph(_))) - .map(|editor| json!({"kind": "function", "graph": app.session.graph, "selection": editor.selection, "inspectedNode": editor.inspected_node}))), + "subgraph": match target { + crate::graph::editor_target::EditorTarget::Function => app.function_editor.as_ref() + .map(|editor| json!({"kind": "function", "graph": app.session.graph, "node": editor.node, "target": editor.command_target(), "selection": editor.selection, "inspectedNode": editor.inspected_node})), + crate::graph::editor_target::EditorTarget::Pattern => app.pattern_editor.as_ref() + .map(|editor| json!({"kind": "pattern", "graph": editor.graph, "node": editor.node.0, "selection": editor.selection, "inspectedNode": editor.inspected_node})), + crate::graph::editor_target::EditorTarget::Material => None, + }, "annotationSelection": app.session.annotation_selection, "frames": app.graph.frames.iter().map(|(id, bounds)| json!({"id": id, "rect": rect(*bounds)})).collect::>(), "comments": app.graph.comments.iter().map(|(id, bounds)| json!({"id": id, "rect": rect(*bounds)})).collect::>(), - "nodes": app.graph.rects.iter().map(|(id, r)| json!({"id": id.0, "rect": rect(*r)})).collect::>(), - "ports": app.graph.ports.iter().map(|port| json!({ + "nodes": nodes.iter().map(|(id, r)| json!({"id": id.0, "rect": rect(*r)})).collect::>(), + "ports": ports.iter().map(|port| json!({ "node": port.node.0, "port": port.port, "label": port.label, diff --git a/crates/ui-egui/src/cook.rs b/crates/ui-egui/src/cook.rs index bab9167..f2828a9 100644 --- a/crates/ui-egui/src/cook.rs +++ b/crates/ui-egui/src/cook.rs @@ -3,13 +3,13 @@ use std::sync::mpsc::{Receiver, TryRecvError}; -use materialcraft_engine::eval::Cooked; +use materialcraft_engine::PreviewCook; use crate::MaterialCraftApp; #[derive(Default)] pub struct Cooker { - rx: Option>, + rx: Option>, /// Stops the running cook between nodes once its result is stale. #[cfg(not(target_arch = "wasm32"))] cancel: Option>, @@ -28,11 +28,11 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { if let Some(rx) = &app.cooker.rx { match rx.try_recv() { Ok(c) => { - if c.cancelled { + if c.cancelled() { // A stopped cook is partial: keep the previous results and cook again. app.session.dirty = true; } else if !app.session.dirty { - app.session.cooked = c; + app.session.accept_preview(c); } app.cooker.rx = None; app.cooker.started = None; @@ -78,6 +78,7 @@ fn start(app: &mut MaterialCraftApp, now: f64) { s.dirty = false; let pkg = s.pkg.clone(); let (gi, max) = (s.graph, s.preview_size); + let materials = s.material_preview.graphs(); let cache = s.cache.clone(); let dec = s.resource_decoder(); let (tx, rx) = std::sync::mpsc::channel(); @@ -88,7 +89,7 @@ fn start(app: &mut MaterialCraftApp, now: f64) { let mut opts = Options::new(&dec); opts.max_size = max; opts.cancel = Some(&thread_flag); - let cooked = materialcraft_engine::eval::cook(&pkg, gi, &opts, &cache); + let cooked = PreviewCook::run(&pkg, gi, &materials, &opts, &cache); let _ = tx.send(cooked); }); match spawned { diff --git a/crates/ui-egui/src/cook_cancellation.test.rs b/crates/ui-egui/src/cook_cancellation.test.rs index d4f7c69..cb4ab3d 100644 --- a/crates/ui-egui/src/cook_cancellation.test.rs +++ b/crates/ui-egui/src/cook_cancellation.test.rs @@ -1,11 +1,12 @@ use super::*; +use materialcraft_engine::eval::Cooked; use std::sync::{ Arc, atomic::{AtomicBool, Ordering}, mpsc, }; -fn waiting() -> (MaterialCraftApp, mpsc::Sender, Arc) { +fn waiting() -> (MaterialCraftApp, mpsc::Sender, Arc) { let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default()); app.session.cook(); app.session.cooked.ms = 123.0; @@ -26,7 +27,7 @@ fn rapid_edits_wait_for_the_cancelled_worker() { assert!(flag.load(Ordering::Relaxed)); assert!(Arc::ptr_eq(app.cooker.cancel.as_ref().unwrap(), &flag)); } - tx.send(Cooked { cancelled: true, ..Default::default() }).unwrap(); + tx.send(PreviewCook { cooked: Cooked { cancelled: true, ..Default::default() }, ..Default::default() }).unwrap(); drive(&mut app, &egui::Context::default()); assert!(!app.session.dirty, "latest snapshot should start once the worker ends"); assert_eq!(app.session.cooked.ms, 123.0, "partial results replaced the display"); @@ -35,7 +36,7 @@ fn rapid_edits_wait_for_the_cancelled_worker() { #[test] fn ready_results_are_discarded_when_an_edit_is_pending() { let (mut app, tx, _) = waiting(); - tx.send(Cooked { ms: 7.0, ..Default::default() }).unwrap(); + tx.send(PreviewCook { cooked: Cooked { ms: 7.0, ..Default::default() }, ..Default::default() }).unwrap(); app.session.dirty = true; drive(&mut app, &egui::Context::default()); assert_eq!(app.session.cooked.ms, 123.0); diff --git a/crates/ui-egui/src/explorer.rs b/crates/ui-egui/src/explorer.rs index 8c565f6..1d22730 100644 --- a/crates/ui-egui/src/explorer.rs +++ b/crates/ui-egui/src/explorer.rs @@ -1,4 +1,4 @@ -//! The package tree, its graphs, named outputs and resources +//! The package tree, its graphs, inputs, outputs and resources use egui::{RichText, Ui}; @@ -36,17 +36,29 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { ui.label(RichText::new(format!("{} {name}", icon::PACKAGE)).strong().color(tk.text_strong)); let mut open: Option = None; let mut action: Option<(&str, usize)> = None; - let mut output = None; + let mut selected_node = None; + let mut assignment = None; for (index, graph) in app.session.pkg.graphs.iter().enumerate() { let active = index == app.session.graph; let function = graph.function.is_some(); let mut header = |ui: &mut Ui| { let symbol = if function { icon::FUNCTION } else { icon::TREE_STRUCTURE }; let response = tree_row::show(ui, &graph.name, symbol, active); + if !function { + response.interact(egui::Sense::drag()).dnd_set_drag_payload(crate::graph_drag_payload::GraphDragPayload { name: graph.name.clone() }); + } if response.clicked() { open = Some(index); } response.context_menu(|ui| { + if !function { + for (label, command) in [("View outputs in 3D view", "view3d"), ("Reset and view outputs in 3D view", "reset3d")] { + if ui.button(tr(label)).clicked() { + action = Some((command, index)); + ui.close(); + } + } + } for (label, command) in [("Open", "open"), ("Export outputs...", "export"), ("Duplicate", "duplicate"), ("Delete", "delete")] { if ui.button(tr(label)).clicked() { action = Some((command, index)); @@ -66,15 +78,21 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let id = ui.make_persistent_id(("graph", index, &graph.name)); egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true).show_header(ui, header).body(|ui| { - ui.indent("outputs", |ui| { - for node in graph.nodes.iter().filter(|node| node.def == "output") { + ui.indent("graph-ports", |ui| { + for node in graph.nodes.iter().filter(|node| matches!(node.def.as_str(), "output" | "input_color" | "input_grayscale" | "input_value")) { ui.push_id(node.id, |ui| { - let name = materialcraft_engine::eval::identifier(node); + let name = crate::graph::node_label(node); let selected = active && app.session.selection.contains(&node.id); - let response = tree_row::show(ui, &name, icon::IMAGE, selected); + let symbol = if node.def == "input_value" { icon::FUNCTION } else { icon::IMAGE }; + let response = tree_row::show(ui, &name, symbol, selected); + response.context_menu(|ui| { + if let Some(parameters) = crate::material_preview_menu::show(ui, &app.session, index, node.id) { + assignment = Some(parameters); + } + }); if response.clicked() || response.double_clicked() { - output = Some((index, node.id, response.double_clicked())); + selected_node = Some((index, node.id, response.double_clicked())); } }); } @@ -84,7 +102,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { if let Some(i) = open { app.run("graph.open", json!({"graph": i})); } - if let Some((index, node, preview)) = output { + if let Some((index, node, preview)) = selected_node { if index != app.session.graph && app.run("graph.open", json!({"graph": index})).is_none() { return; } @@ -101,7 +119,13 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } } + if let Some(parameters) = assignment { + app.run("view.3d.assign", parameters); + } match action { + Some((command @ ("view3d" | "reset3d"), graph)) => { + app.run("view.3d.outputs", json!({"graph": graph, "reset": command == "reset3d"})); + } Some(("open", i)) => { app.run("graph.open", json!({"graph": i})); } diff --git a/crates/ui-egui/src/function/actions.rs b/crates/ui-egui/src/function/actions.rs new file mode 100644 index 0000000..0f55c9b --- /dev/null +++ b/crates/ui-egui/src/function/actions.rs @@ -0,0 +1,49 @@ +use super::{FunctionEditor, FunctionTarget}; +use crate::MaterialCraftApp; + +pub(super) fn editor_enabled(app: &MaterialCraftApp, editor: &FunctionEditor, command: &str) -> Option { + let standalone = matches!(editor.target, FunctionTarget::Graph); + if standalone && app.session.annotation_selection.is_some() && matches!(command, "edit.delete" | "edit.deleteRelink") { + return None; + } + if let Some(target) = editor.command_target() + && let Some(enabled) = materialcraft_engine::selection_commands::enabled_for( + &app.session, + &materialcraft_engine::SelectionTarget::Function(target), + &editor.selection, + command, + ) + { + return Some(enabled && editor.current(app).is_some()); + } + match command { + "edit.undo" | "edit.redo" | "edit.finish" | "graph.cook" | "ui.graph.snapToGrid" => None, + "ui.graph.previousPin" | "ui.graph.nextPin" | "graph.comment.add" | "graph.frame.add" | "graph.pin.add" if standalone => None, + command if command.starts_with("graph.") || command.starts_with("ui.graph.") || command.starts_with("edit.") => Some(false), + _ => None, + } +} + +pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option { + app.function_editor.as_ref().and_then(|editor| editor_enabled(app, editor, command)) +} + +pub(super) fn invoke_editor(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, command: &str) -> bool { + let Some(allowed) = editor_enabled(app, editor, command) else { return false }; + + if !allowed { + return true; + } + + let parameters = editor.selection_parameters(command); + crate::graph::selection_commands::invoke(app, &mut editor.selection, command, parameters); + true +} + +pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool { + let Some(mut editor) = app.function_editor.take() else { return false }; + + let handled = invoke_editor(app, &mut editor, command); + app.function_editor = Some(editor); + handled +} diff --git a/crates/ui-egui/src/function/canvas.rs b/crates/ui-egui/src/function/canvas.rs index 8b39ce1..1ee7ba7 100644 --- a/crates/ui-egui/src/function/canvas.rs +++ b/crates/ui-egui/src/function/canvas.rs @@ -1,572 +1,58 @@ -//! Function canvas edits are committed through engine commands - -use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2}; -use egui_phosphor::regular as icon; -use materialcraft_engine::core::Value; -use materialcraft_engine::core::{FunctionGraph, FunctionNode}; -use materialcraft_engine::nodes::function::FUNCTIONS; +use super::{FunctionEditor, FunctionTarget}; +use crate::{MaterialCraftApp, graph::GraphCamera, i18n::tr}; +use egui::Ui; +use materialcraft_engine::FunctionEdit; use serde_json::json; -use crate::MaterialCraftApp; -use crate::graph::node_card; -use crate::i18n::tr; -use crate::theme::Tokens; +pub(super) fn canvas(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) { + let Some(frame) = super::render::paint(app, editor, ui) else { return }; -use super::{FunctionDrag, FunctionEditor, FunctionTarget, port_label::port_label}; - -fn arity(op: &str) -> usize { - FUNCTIONS.iter().find(|o| o.id == op).map_or(0, |o| o.inputs.len()) -} - -fn label(op: &str) -> &'static str { - FUNCTIONS.iter().find(|o| o.id == op).map_or("?", |o| o.label) -} - -fn category_color(op: &str) -> Color32 { - match FUNCTIONS.iter().find(|o| o.id == op).map_or("", |o| o.category) { - "Constant" => Color32::from_rgb(0x5c, 0x62, 0x6e), - "Variables" => Color32::from_rgb(0x6d, 0x52, 0xb5), - "Samplers" => Color32::from_rgb(0xa8, 0x3c, 0x34), - "Vector" | "Cast" => Color32::from_rgb(0x3a, 0x66, 0xb0), - "Operator" => Color32::from_rgb(0x3b, 0x7f, 0x4c), - "Logical" | "Comparison" | "Control" => Color32::from_rgb(0xb3, 0x5a, 0x2c), - _ => Color32::from_rgb(0x1e, 0x8a, 0xa0), - } -} - -fn visible_inputs(node: &FunctionNode) -> usize { - let count = arity(&node.op); - crate::graph::input_visibility::count((0..count).map(|index| node.inputs.get(index).is_some_and(Option::is_some)), 1) -} - -fn node_rect(node: &FunctionNode, previews: bool) -> Rect { - node_card::bounds(node.pos, visible_inputs(node), 1, previews, node.op == "passthrough") -} - -fn in_port(node: &FunctionNode, bounds: Rect, index: usize) -> Pos2 { - node_card::port(bounds, index, visible_inputs(node), false, node.op == "passthrough") -} - -fn out_port(node: &FunctionNode, bounds: Rect) -> Pos2 { - node_card::port(bounds, 0, 1, true, node.op == "passthrough") -} - -pub(super) fn current(app: &MaterialCraftApp, editor: &FunctionEditor) -> Option { - if let FunctionTarget::Graph(index) = editor.target { - return app.session.pkg.graphs.get(index)?.function.clone(); - } - - let node = app.session.graph().ok()?.node(editor.node?).ok()?; - let value = match &editor.target { - FunctionTarget::Graph(_) => return None, - FunctionTarget::Dynamic(parameter) => return node.functions.get(parameter).cloned(), - FunctionTarget::Parameter(parameter) => { - node.params.get(parameter).or_else(|| materialcraft_engine::nodes::find(&node.def)?.param(parameter).map(|parameter| ¶meter.default))? - } - FunctionTarget::Pattern { node: id, parameter } => { - let Value::PatternGraph(graph) = node.params.get("pattern")? else { return None }; - graph.nodes.iter().find(|node| node.id == *id)?.parameters.get(parameter)? - } - }; - - match value { - Value::Function(function) => Some((**function).clone()), - _ => None, - } -} - -pub(super) fn commit(app: &mut MaterialCraftApp, editor: &FunctionEditor, graph: &FunctionGraph) { - match &editor.target { - FunctionTarget::Graph(_) => { - app.run("graph.function.set", json!({"function": graph})); - } - FunctionTarget::Dynamic(parameter) => { - app.run("graph.node.function", json!({"id": editor.node.map(|node| node.0), "param": parameter, "function": graph})); - } - FunctionTarget::Parameter(parameter) => { - let value = Value::Function(Box::new(graph.clone())); - app.run("graph.node.param", json!({"id": editor.node.map(|node| node.0), "param": parameter, "value": value})); - } - FunctionTarget::Pattern { node: id, parameter } => { - let Some(mut pattern) = - app.session.graph().ok().and_then(|graph| graph.node(editor.node?).ok()).and_then(|node| node.params.get("pattern")).cloned() - else { - return; - }; - - if let Value::PatternGraph(pattern) = &mut pattern - && let Some(node) = pattern.nodes.iter_mut().find(|node| node.id == *id) - { - node.parameters.insert(parameter.clone(), Value::Function(Box::new(graph.clone()))); - } - app.run("graph.node.param", json!({"id": editor.node.map(|node| node.0), "param": "pattern", "value": pattern})); - } - } -} - -/// Draw the editor window when one is open -pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { - if app.function_editor.as_ref().is_some_and(|editor| matches!(editor.target, FunctionTarget::Graph(_))) { - return; - } - - let Some(mut e) = app.function_editor.take() else { return }; - let Some(mut g) = current(app, &e) else { return }; - let title = app.session.graph().ok().and_then(|gr| gr.node(e.node?).ok()).map(crate::graph::node_label).unwrap_or_default(); - let mut open = true; - let mut changed = false; - let what = if e.target.parameter() == "function" { tr("Function").to_string() } else { format!("{} {}", tr("Function"), e.target.parameter()) }; - egui::Window::new(format!("{title} - {what}")) - .id(egui::Id::unique(("fn-editor", e.node, &e.target))) - .open(&mut open) - .default_size(vec2(760.0, 460.0)) - .resizable(true) - .show(ctx, |ui| { - let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.label( - egui::RichText::new(tr("Right-click or Space to add operations; drag from an output dot to an input; the starred node is the result.")) - .size(11.0) - .color(tk.text_dim), - ); - }); - changed = canvas(app, &mut e, &mut g, ui); - }); - if changed { - commit(app, &e, &g); - } - if open { - app.function_editor = Some(e); - } -} - -pub(crate) fn show_graph(app: &mut MaterialCraftApp, ui: &mut Ui) { - let index = app.session.graph; - let mut editor = - app.function_editor.take().filter(|editor| editor.target == FunctionTarget::Graph(index)).unwrap_or_else(|| FunctionEditor::standalone(index)); - let Some(mut graph) = current(app, &editor) else { return }; - - ui.horizontal(|ui| { - if ui.button(tr("Frame all")).clicked() { - editor.framed = false; - } - ui.checkbox(&mut app.ui.prefs.snap_to_grid, tr("Snap to grid")); - if graph.output.is_none() { - ui.label(tr("Set a node as the output")); - } - }); - if canvas(app, &mut editor, &mut graph, ui) { - commit(app, &editor, &graph); - } - app.function_editor = Some(editor); -} - -fn preview_rect(app: &MaterialCraftApp, editor: &FunctionEditor, node: &FunctionNode, snap: bool) -> Rect { - let mut bounds = node_rect(node, app.ui.prefs.thumbnails); - if let Some(FunctionDrag::Node(d, delta)) = &editor.drag - && (*d == node.id || editor.selection.contains(&node.id)) - { - let position = materialcraft_engine::graph_grid::snap_position([node.pos[0] + delta.x, node.pos[1] + delta.y], snap); - bounds = bounds.translate(vec2(position[0] - node.pos[0], position[1] - node.pos[1])); - } - if matches!(editor.target, FunctionTarget::Graph(_)) { - bounds = bounds.translate(crate::graph::annotation_canvas::offset(app, |contents| contents.function_nodes.contains(&node.id))); - } - bounds -} - -fn canvas(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, graph: &mut FunctionGraph, ui: &mut Ui) -> bool { - editor.selection.retain(|id| graph.node(*id).is_some()); - editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node); - let snap = app.ui.prefs.snap_to_grid; - let standalone = matches!(editor.target, FunctionTarget::Graph(_)); - let tokens = Tokens::get(ui.ctx()); - let (canvas_bounds, response) = ui.allocate_exact_size(ui.available_size().max(vec2(200.0, 200.0)), Sense::click_and_drag()); - crate::widgets::name(&response, egui::Role::Canvas, "Function Graph"); - let painter = ui.painter_at(canvas_bounds); - painter.rect_filled(canvas_bounds, 4.0, Color32::from_rgb(0x26, 0x28, 0x2c)); + let standalone = matches!(editor.target, FunctionTarget::Graph); + app.ui.frame_all = false; if standalone { - app.graph.view = canvas_bounds; - app.graph.rects.clear(); - app.graph.ports.clear(); - app.graph.wires.clear(); + app.ui.graph_camera = frame.camera.state(); + app.graph.frames = frame.frames.iter().map(|frame| (frame.id, frame.rect)).collect(); + app.graph.comments = frame.comments.clone(); } - - if !editor.framed || (standalone && app.ui.frame_all) { - if standalone { - app.ui.frame_all = false; - } - - editor.framed = true; - let mut destination = - graph.nodes.iter().map(|node| node_rect(node, app.ui.prefs.thumbnails)).fold(Rect::NOTHING, |combined, bounds| combined.union(bounds)); - if standalone && let Ok(document) = app.session.graph() { - for frame in &document.frames { - destination = destination.union(Rect::from_min_size(pos2(frame.rect[0], frame.rect[1] - 32.0), vec2(frame.rect[2], frame.rect[3] + 32.0))); - } - } - if destination.is_finite() && destination.width() > 0.0 { - let destination = destination.expand(30.0); - editor.zoom = (canvas_bounds.width() / destination.width()).min(canvas_bounds.height() / destination.height()).clamp(0.3, 1.2); - editor.pan = destination.center().to_vec2() - canvas_bounds.size() * 0.5 / editor.zoom; - } + if frame.clear_annotation { + app.run("graph.annotation.select", json!({})); } - - let to_screen = |position: Pos2, editor: &FunctionEditor| canvas_bounds.min + (position.to_vec2() - editor.pan) * editor.zoom; - let to_graph = |source: Pos2, editor: &FunctionEditor| ((source - canvas_bounds.min) / editor.zoom + editor.pan).to_pos2(); - let mut changed = false; - let pointer = ui.input(|input| input.pointer.hover_pos()); - - // Zoom and pan - if response.hovered() { - let scroll = ui.input(|input| input.smooth_scroll_delta.y); - if scroll.abs() > 0.0 - && let Some(pointer_position) = pointer + for (id, value) in frame.values { + editor.edit(app, FunctionEdit::Value { id, value }, true); + } + for (id, response) in &frame.nodes { + if response.secondary_clicked() + && let Some(pointer) = response.interact_pointer_pos() { - let before = to_graph(pointer_position, editor); - editor.zoom = (editor.zoom * (scroll * 0.0025).exp()).clamp(0.3, 2.5); - editor.pan = before.to_vec2() - (pointer_position - canvas_bounds.min) / editor.zoom; + editor.menu_at = frame.camera.to_graph(pointer); } - } - - let camera = crate::graph::GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom }; - let document = standalone.then(|| app.session.graph().ok().cloned()).flatten(); - let frame_hits = document.as_ref().map(|graph| crate::graph::annotation_canvas::frames(app, ui, graph, &camera)).unwrap_or_default(); - if standalone { - app.graph.frames = frame_hits.iter().map(|frame| (frame.id, frame.rect)).collect(); - } - crate::graph::canvas::grid(&painter, &camera, canvas_bounds); - - // Wires - for node in &graph.nodes { - let bounds = preview_rect(app, editor, node, snap); - for (input_index, source_id) in node.inputs.iter().enumerate() { - if let Some(source) = source_id.and_then(|source| graph.node(source)) { - let source_position = to_screen(out_port(source, preview_rect(app, editor, source, snap)), editor); - let destination = to_screen(in_port(node, bounds, input_index), editor); - let control_offset = ((destination.x - source_position.x).abs() * 0.5).max(24.0); - painter.add(egui::epaint::CubicBezierShape::from_points_stroke( - [source_position, source_position + vec2(control_offset, 0.0), destination - vec2(control_offset, 0.0), destination], - false, - Color32::TRANSPARENT, - Stroke::new(2.0, Color32::from_gray(0xb4)), - )); - } - } - } - - // Nodes - let font = FontId::proportional((11.0 * editor.zoom).min(16.0)); - let mut remove: Option = None; - let mut set_output: Option = None; - let mut ports: Vec<(u32, Option, Pos2)> = Vec::new(); - let ids: Vec = graph.nodes.iter().map(|node| node.id).collect(); - for id in ids { - let Some(node_index) = graph.nodes.iter().position(|node| node.id == id) else { continue }; - - let node = &graph.nodes[node_index]; - let bounds = preview_rect(app, editor, node, snap); - let screen_rect = Rect::from_min_max(to_screen(bounds.min, editor), to_screen(bounds.max, editor)); - if standalone { - app.graph.rects.push((materialcraft_engine::core::NodeId(u64::from(id)), screen_rect)); - } - - let dot = node.op == "passthrough"; - let show_labels = crate::graph::port_label::visible(ui, screen_rect); - let is_output = graph.output == Some(id); - let selected = editor.selection.contains(&id); - let outline = if selected { - tokens.accent - } else if dot { - Color32::from_gray(0xb4) - } else { - Color32::from_gray(0x10) - }; - - if dot { - node_card::paint_dot(&painter, screen_rect, outline); - } else { - node_card::paint(&painter, screen_rect, editor.zoom, label(&node.op), category_color(&node.op)); - node_card::outline(&painter, screen_rect, editor.zoom, Stroke::new(if selected { 2.0 } else { 1.0 }, outline)); - let body = node_card::body(screen_rect, editor.zoom); - if node.value.is_none() { - painter.text(body.center(), Align2::CENTER_CENTER, icon::CODE, FontId::proportional(30.0 * editor.zoom), tokens.text_dim); - } - if is_output { - let header = node_card::header(screen_rect, editor.zoom); - painter.text(header.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, icon::STAR, font.clone(), Color32::GOLD); - } - } - - let port_radius = (4.5 * editor.zoom).clamp(2.5, 7.0); - let port_color = crate::graph::port_color(materialcraft_engine::nodes::PortKind::Value); - if let Some(definition) = materialcraft_engine::nodes::function::definition(&node.op) { - for (input_index, identifier) in definition.inputs.iter().take(visible_inputs(node)).enumerate() { - let position = to_screen(in_port(node, bounds, input_index), editor); - painter.circle(position, port_radius, port_color, Stroke::new(1.0, Color32::from_gray(0x18))); - if show_labels { - crate::graph::port_label::paint( - &painter, - position - vec2(10.0, 0.0), - Align2::RIGHT_CENTER, - port_label(identifier), - editor.zoom, - tokens.text_strong, - ); - } - ports.push((id, Some(input_index), position)); - } - } - - let output_position = to_screen(out_port(node, bounds), editor); - painter.circle(output_position, port_radius, port_color, Stroke::new(1.0, Color32::from_gray(0x18))); - if show_labels { - crate::graph::port_label::paint( - &painter, - output_position + vec2(10.0, 0.0), - Align2::LEFT_CENTER, - port_label("output"), - editor.zoom, - tokens.text_strong, - ); - } - ports.push((id, None, output_position)); - - let body = ui.interact(screen_rect, ui.scope_id().with(("fn-node", id)), Sense::click_and_drag()); - crate::widgets::name(&body, egui::Role::Button, label(&graph.nodes[node_index].op)); - - if !dot && node.value.is_some() { - let content = node_card::body(screen_rect, editor.zoom).shrink(6.0 * editor.zoom); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(content)); - child.set_clip_rect(content.intersect(canvas_bounds)); - if let Some(value) = graph.nodes[node_index].value.as_mut() { - changed |= crate::value_editor::show(&mut child, value); - } - } - - if (body.contains_pointer() && ui.input(|input| input.pointer.primary_pressed())) || body.secondary_clicked() { - let modifiers = if body.secondary_clicked() { egui::Modifiers::NONE } else { ui.input(|input| input.modifiers) }; - crate::graph::node_selection::select(&mut editor.selection, Some(id), modifiers); - if standalone && app.session.annotation_selection.is_some() { - app.run("graph.annotation.select", json!({})); - } - } - - if body.drag_started() && editor.selection.contains(&id) && editor.drag.is_none() && !app.graph.is_dragging() { - editor.drag = Some(FunctionDrag::Node(id, Vec2::ZERO)); - } - - body.context_menu(|ui| { - changed |= super::context_menu::show(app, editor, graph, ui); + response.context_menu(|ui| { + super::context_menu::show(app, editor, ui); ui.separator(); - if ui.button(format!("{} {}", icon::STAR, tr("Set as output node"))).clicked() { - set_output = Some(id); - ui.close(); - } - if ui.button(format!("{} {}", icon::X, tr("Delete"))).clicked() { - remove = Some(id); + if ui.button(format!("{} {}", egui_phosphor::regular::STAR, tr("Set as output node"))).clicked() { + editor.edit(app, FunctionEdit::Output { id: *id }, false); ui.close(); } }); } - - if let Some(id) = set_output { - graph.output = Some(id); - changed = true; - } - - if let Some(id) = remove { - graph.nodes.retain(|node| node.id != id); - for node in &mut graph.nodes { - for source in &mut node.inputs { - if *source == Some(id) { - *source = None; - } - } - } - if graph.output == Some(id) { - graph.output = None; - } - changed = true; - } - + let on_annotation = ui + .input(|input| input.pointer.hover_pos()) + .is_some_and(|pointer| frame.frames.iter().any(|frame| frame.contains(pointer)) || frame.comments.iter().any(|(_, rect)| rect.contains(pointer))); + super::input::handle(app, editor, ui, &frame.response, &frame.ports, &frame.geometry.rects, on_annotation); + frame.geometry.publish(&mut app.graph, frame.response.rect); if standalone { - app.graph.ports = ports - .iter() - .map(|(id, input, position)| { - let identifier = input - .and_then(|slot| { - let node = graph.node(*id)?; - materialcraft_engine::nodes::function::definition(&node.op)?.inputs.get(slot).copied() - }) - .unwrap_or(if input.is_some() { "input" } else { "output" }); - - crate::graph::PortHit { - node: materialcraft_engine::core::NodeId(u64::from(*id)), - port: input.map_or_else(|| "output".into(), |slot| slot.to_string()), - label: port_label(identifier).into(), - output: input.is_none(), - kind: materialcraft_engine::nodes::PortKind::Value, - pos: *position, - } - }) - .collect(); - app.ui.graph_camera.pan = [editor.pan.x, editor.pan.y]; - app.ui.graph_camera.zoom = editor.zoom; - } - - // Gestures: wires from output dots, panning - let near = |pointer_position: Pos2| { - ports - .iter() - .filter(|(id, _, position)| { - let dot = graph.node(*id).is_some_and(|node| node.op == "passthrough"); - let radius = if dot { (3.5 * editor.zoom).max(2.0) } else { 9.0 }; - position.distance(pointer_position) < radius - }) - .min_by(|first, second| first.2.distance(pointer_position).total_cmp(&second.2.distance(pointer_position))) - .cloned() - }; - if response.drag_started_by(egui::PointerButton::Middle) || (response.drag_started() && ui.input(|input| input.modifiers.alt)) { - editor.drag = Some(FunctionDrag::Pan); - } else if ui.input(|input| input.pointer.primary_pressed()) - && editor.drag.is_none() - && !app.graph.is_dragging() - && let Some(pointer_position) = pointer - && canvas_bounds.contains(pointer_position) - && let Some((id, None, _)) = near(pointer_position) - { - editor.drag = Some(FunctionDrag::Wire(id)); - } - - let delta = ui.input(|input| input.pointer.delta()); - match &mut editor.drag { - Some(FunctionDrag::Node(_, offset)) => *offset += delta / editor.zoom, - Some(FunctionDrag::Pan) => editor.pan -= delta / editor.zoom, - Some(FunctionDrag::Wire(id)) => { - if let (Some(pointer_position), Some(source_id)) = (pointer, ports.iter().find(|(node, source, _)| node == id && source.is_none())) { - painter.line_segment([source_id.2, pointer_position], Stroke::new(2.0, tokens.accent)); - } - } - None => {} - } - - if ui.input(|input| input.pointer.any_released()) { - match editor.drag.take() { - Some(FunctionDrag::Node(id, offset)) => { - if offset.length() > 0.5 { - for node in graph.nodes.iter_mut().filter(|node| node.id == id || editor.selection.contains(&node.id)) { - node.pos = materialcraft_engine::graph_grid::snap_position([node.pos[0] + offset.x, node.pos[1] + offset.y], snap); - } - changed = true; - } - } - Some(FunctionDrag::Wire(source_id)) => { - if let Some(pointer_position) = pointer - && let Some((destination_id, Some(slot), _)) = near(pointer_position) - && destination_id != source_id - && !reaches(graph, destination_id, source_id) - && let Some(node) = graph.nodes.iter_mut().find(|node| node.id == destination_id) - { - if node.inputs.len() <= slot { - node.inputs.resize(slot + 1, None); - } - node.inputs[slot] = Some(source_id); - changed = true; - } - } - _ => {} - } - } - - if response.clicked() { - crate::graph::node_selection::select(&mut editor.selection, None, ui.input(|input| input.modifiers)); - } - - // Adding operations - if response.secondary_clicked() - && let Some(pointer_position) = pointer - { - editor.menu_at = to_graph(pointer_position, editor); - } - if response.hovered() - && ui.input(|input| input.key_pressed(egui::Key::Space)) - && let Some(pointer_position) = pointer - { - editor.menu_at = to_graph(pointer_position, editor); - egui::Popup::open_id(ui.ctx(), response.id.with("menu")); - } - response.context_menu(|ui| { - changed |= super::context_menu::show(app, editor, graph, ui); - }); - - if let Some(document) = &document { - let comments = crate::graph::annotation_canvas::comments(app, ui, document, &camera); - app.graph.comments = comments.clone(); - crate::graph::annotation_canvas::pins(app, ui, document, &camera); if editor.drag.is_none() { - crate::graph::annotation_input::handle(app, ui, &camera, &frame_hits, &comments); + let camera = GraphCamera { origin: frame.response.rect.min, pan: editor.pan, zoom: editor.zoom }; + crate::graph::annotation_input::handle(app, ui, &camera, &frame.frames, &frame.comments); if app.session.annotation_selection.is_some() { editor.selection.clear(); } } + app.ui.graph_camera = crate::state::GraphCamera { pan: editor.pan.into(), zoom: editor.zoom }; + app.session.selection = editor.selection.iter().map(|id| materialcraft_engine::core::NodeId(u64::from(*id))).collect(); + } else { + app.graph.frames.clear(); + app.graph.comments.clear(); } - editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node).filter(|id| graph.node(*id).is_some()); - changed -} - -// Wiring b into a is invalid when a already feeds b -fn reaches(g: &FunctionGraph, a: u32, b: u32) -> bool { - let mut stack = vec![b]; - let mut seen = std::collections::BTreeSet::new(); - while let Some(n) = stack.pop() { - if n == a { - return true; - } - if !seen.insert(n) { - continue; - } - if let Some(node) = g.node(n) { - stack.extend(node.inputs.iter().flatten()); - } - } - false -} - -pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option { - if app.session.annotation_selection.is_some() || !app.session.graph().is_ok_and(|graph| graph.function.is_some()) { - return None; - } - super::selection::enabled(app.function_editor.as_ref()?, command) -} - -pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool { - if enabled(app, command).is_none() { - return false; - } - let Some(mut editor) = app.function_editor.take() else { return false }; - if let Some(mut graph) = current(app, &editor) - && super::selection::run(&mut editor, &mut graph, command, app.ui.prefs.snap_to_grid) - { - commit(app, &editor, &graph); - } - app.function_editor = Some(editor); - true -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn cycles_are_detected() { - let mut g = FunctionGraph::default(); - let a = g.add("get_float2", &[], Some(Value::Text("$pos".into()))); - let b = g.add("swizzle1", &[a], Some(Value::Int(0))); - // a feeds b: wiring b into a would loop - assert!(reaches(&g, a, b)); - assert!(!reaches(&g, b, a)); - assert_eq!(arity("add"), 2); - assert!(materialcraft_engine::nodes::function::default_value("const_float1").is_some()); - } + editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node); } diff --git a/crates/ui-egui/src/function/context_menu.rs b/crates/ui-egui/src/function/context_menu.rs index 1f8430d..8a49ded 100644 --- a/crates/ui-egui/src/function/context_menu.rs +++ b/crates/ui-egui/src/function/context_menu.rs @@ -1,32 +1,31 @@ -use super::{FunctionEditor, FunctionTarget, selection}; -use crate::{MaterialCraftApp, i18n::tr, menus}; +use super::{FunctionEditor, FunctionTarget}; +use crate::{MaterialCraftApp, graph::edit_menu, i18n::tr, menus}; use egui::Ui; -use materialcraft_engine::{ - core::{FunctionGraph, FunctionNode}, - nodes::function::{FUNCTIONS, default_value}, -}; +use materialcraft_engine::FunctionEdit; use serde_json::json; -pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, graph: &mut FunctionGraph, ui: &mut Ui) -> bool { - let mut changed = false; +pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) { + let Some(target) = editor.command_target() else { return }; + let mut add = None; - let standalone = matches!(editor.target, FunctionTarget::Graph(_)); + let standalone = matches!(editor.target, FunctionTarget::Graph); ui.set_min_width(290.0); ui.menu_button(tr("Add node"), |ui| { - let entries = FUNCTIONS.iter().filter(|operation| operation.id != "passthrough").map(|operation| (operation.id, operation.label, operation.category)); + let entries = target + .available_operations(&app.session) + .filter(|operation| operation.id != "passthrough") + .map(|operation| (operation.id, operation.label, operation.category)); add = crate::graph::add_node_menu::show(ui, entries); }); - if standalone { for (label, command, parameters) in [ ("Add Comment", "graph.comment.add", json!({"at": [editor.menu_at.x, editor.menu_at.y]})), ("Add Frame", "graph.frame.add", json!({"rect": [editor.menu_at.x, editor.menu_at.y, 400, 260]})), ("Add Navigation pin", "graph.pin.add", json!({"at": [editor.menu_at.x, editor.menu_at.y]})), ] { - if ui.button(tr(label)).clicked() { + if edit_menu::button(ui, label, command, true) { app.run(command, parameters); editor.selection.clear(); - ui.close(); } } } @@ -35,64 +34,24 @@ pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, grap ui.close(); } ui.separator(); - - if ui.add(egui::Button::new(tr("Save package")).shortcut_text("Ctrl+S")).clicked() { + if edit_menu::button(ui, "Save package", "file.save", menus::enabled(app, "file.save")) { menus::invoke(app, ui.ctx(), "file.save"); - ui.close(); } - for (label, command) in [ - ("Paste", "edit.paste"), - ("Paste without link", "edit.pasteWithoutLinks"), - ("Select all", "edit.selectAll"), - ("Previous pin", "ui.graph.previousPin"), - ("Next pin", "ui.graph.nextPin"), - ("Copy selection", "edit.copy"), - ("Delete selection", "edit.delete"), - ("Delete and relink", "edit.deleteRelink"), - ("Duplicate selection", "edit.duplicate"), - ("Duplicate selection without link", "edit.duplicateWithoutLinks"), - ("Select upstream nodes", "graph.selectUpstream"), - ("Select downstream nodes", "graph.selectDownstream"), - ("Disable selection", "graph.node.disable"), - ] { - if command == "edit.copy" { - ui.separator(); - } - let annotation = standalone && app.session.annotation_selection.is_some() && matches!(command, "edit.delete" | "edit.deleteRelink"); - let enabled = if annotation { true } else { selection::enabled(editor, command).unwrap_or_else(|| standalone && menus::enabled(app, command)) }; - let mut button = egui::Button::new(tr(label)); - if let Some(shortcut) = menus::shortcut_of(command) { - button = button.shortcut_text(shortcut); - } - if ui.add_enabled(enabled, button).clicked() { - if annotation { - app.run(command, json!({})); - } else if command.starts_with("ui.") { - menus::invoke(app, ui.ctx(), command); - editor.pan = app.ui.graph_camera.pan.into(); - } else { - changed |= selection::run(editor, graph, command, app.ui.prefs.snap_to_grid); + if let Some(command) = + edit_menu::selection(ui, |command| super::actions::editor_enabled(app, editor, command).unwrap_or_else(|| menus::enabled(app, command))) + && !super::actions::invoke_editor(app, editor, command) + { + app.run(command, json!({})); + } + if standalone { + for (label, command) in [("Previous pin", "ui.graph.previousPin"), ("Next pin", "ui.graph.nextPin")] { + if edit_menu::button(ui, label, command, menus::enabled(app, command)) { + crate::graph::actions::invoke(app, command); + editor.set_camera(app.ui.graph_camera); } - ui.close(); } } - if let Some(operation) = add { - let id = graph.next_id(); - let inputs = FUNCTIONS.iter().find(|definition| definition.id == operation).map_or(0, |definition| definition.inputs.len()); - graph.nodes.push(FunctionNode { - id, - type_code: 0, - op: operation.into(), - inputs: vec![None; inputs], - value: default_value(operation), - pos: materialcraft_engine::graph_grid::snap_position([editor.menu_at.x, editor.menu_at.y], app.ui.prefs.snap_to_grid), - }); - editor.selection = vec![id]; - if graph.output.is_none() { - graph.output = Some(id); - } - changed = true; + editor.edit(app, FunctionEdit::Add { operation: operation.into(), at: editor.menu_at.into(), snap: app.ui.prefs.snap_to_grid }, false); } - changed } diff --git a/crates/ui-egui/src/function/function_canvas.rs b/crates/ui-egui/src/function/function_canvas.rs new file mode 100644 index 0000000..16b6099 --- /dev/null +++ b/crates/ui-egui/src/function/function_canvas.rs @@ -0,0 +1,16 @@ +use super::function_port::FunctionPort; +use crate::graph::{GraphCamera, canvas_geometry::CanvasGeometry, frame_hit::FrameHit}; +use egui::{Rect, Response}; +use materialcraft_engine::core::Value; + +pub(super) struct FunctionCanvas { + pub response: Response, + pub camera: GraphCamera, + pub geometry: CanvasGeometry, + pub ports: Vec, + pub nodes: Vec<(u32, Response)>, + pub values: Vec<(u32, Value)>, + pub frames: Vec, + pub comments: Vec<(u64, Rect)>, + pub clear_annotation: bool, +} diff --git a/crates/ui-egui/src/function/function_drag.rs b/crates/ui-egui/src/function/function_drag.rs index 4d38ae5..d8ee7cb 100644 --- a/crates/ui-egui/src/function/function_drag.rs +++ b/crates/ui-egui/src/function/function_drag.rs @@ -3,5 +3,6 @@ use egui::Vec2; pub(super) enum FunctionDrag { Node(u32, Vec2), Wire(u32), - Pan, + Box { start: egui::Pos2 }, + Pan(egui::PointerButton), } diff --git a/crates/ui-egui/src/function/function_editor.rs b/crates/ui-egui/src/function/function_editor.rs index fe8f39a..b6d8eee 100644 --- a/crates/ui-egui/src/function/function_editor.rs +++ b/crates/ui-egui/src/function/function_editor.rs @@ -1,29 +1,45 @@ +use crate::MaterialCraftApp; use egui::{Pos2, Vec2, vec2}; +use materialcraft_engine::core::FunctionGraph; use materialcraft_engine::core::NodeId; +use serde_json::json; use super::{FunctionDrag, FunctionTarget}; pub struct FunctionEditor { pub node: Option, + pub graph: usize, pub(crate) selection: Vec, pub(crate) inspected_node: Option, - pub(super) clipboard: Vec, pub target: FunctionTarget, pub(super) pan: Vec2, pub(super) zoom: f32, pub(super) drag: Option, pub(super) menu_at: Pos2, - pub(super) framed: bool, + pub(crate) framed: bool, } impl FunctionEditor { pub fn standalone(graph: usize) -> Self { + Self::with_target(graph, None, FunctionTarget::Graph) + } + + pub(crate) fn set_camera(&mut self, camera: crate::state::GraphCamera) { + self.pan = camera.pan.into(); + self.zoom = camera.zoom; + } + + pub fn new(graph: usize, node: NodeId, target: FunctionTarget) -> Self { + Self::with_target(graph, Some(node), target) + } + + fn with_target(graph: usize, node: Option, target: FunctionTarget) -> Self { Self { - node: None, - target: FunctionTarget::Graph(graph), + graph, + node, + target, selection: Vec::new(), inspected_node: None, - clipboard: Vec::new(), pan: vec2(-40.0, -40.0), zoom: 1.0, drag: None, @@ -32,18 +48,43 @@ impl FunctionEditor { } } - pub fn new(node: NodeId, target: FunctionTarget) -> FunctionEditor { - FunctionEditor { - node: Some(node), - selection: Vec::new(), - inspected_node: None, - clipboard: Vec::new(), - target, - pan: vec2(-40.0, -40.0), - zoom: 1.0, - drag: None, - menu_at: Pos2::ZERO, - framed: false, + pub(crate) fn current<'a>(&self, app: &'a MaterialCraftApp) -> Option<&'a FunctionGraph> { + if self.graph != app.session.graph { + return None; + } + + self.command_target()?.current(&app.session).ok() + } + + pub(crate) fn command_target(&self) -> Option { + use materialcraft_engine::FunctionGraphTarget; + Some(match &self.target { + FunctionTarget::Graph => FunctionGraphTarget::Graph, + FunctionTarget::Parameter(parameter) => FunctionGraphTarget::Parameter { node: self.node?, parameter: parameter.clone() }, + FunctionTarget::Dynamic(parameter) => FunctionGraphTarget::Dynamic { node: self.node?, parameter: parameter.clone() }, + FunctionTarget::Pattern { node, parameter } => FunctionGraphTarget::Pattern { owner: self.node?, node: *node, parameter: parameter.clone() }, + }) + } + + pub(crate) fn edit(&mut self, app: &mut MaterialCraftApp, edit: materialcraft_engine::FunctionEdit, merge: bool) { + if self.current(app).is_none() { + return; + } + let Some(target) = self.command_target() else { return }; + + if let Some(result) = app.run("graph.function.edit", json!({"target": target, "edit": edit, "merge": merge})) + && let Some(id) = result.get("id").and_then(serde_json::Value::as_u64).and_then(|id| u32::try_from(id).ok()) + { + self.selection = vec![id]; + if self.target == FunctionTarget::Graph { + app.session.selection = vec![NodeId(u64::from(id))]; + app.session.annotation_selection = None; + } } } + + pub(crate) fn selection_parameters(&self, command: &str) -> serde_json::Value { + let selection = if matches!(command, "edit.selectAll" | "edit.selectNone") { &[][..] } else { self.selection.as_slice() }; + json!({"graph": self.graph, "function": self.command_target(), "ids": selection, "at": [self.menu_at.x, self.menu_at.y]}) + } } diff --git a/crates/ui-egui/src/function/function_port.rs b/crates/ui-egui/src/function/function_port.rs new file mode 100644 index 0000000..84da44c --- /dev/null +++ b/crates/ui-egui/src/function/function_port.rs @@ -0,0 +1,9 @@ +use egui::Pos2; + +pub(super) struct FunctionPort { + pub node: u32, + pub slot: Option, + pub position: Pos2, + pub radius: f32, + pub label: &'static str, +} diff --git a/crates/ui-egui/src/function/function_target.rs b/crates/ui-egui/src/function/function_target.rs index 4f83a48..e20523b 100644 --- a/crates/ui-egui/src/function/function_target.rs +++ b/crates/ui-egui/src/function/function_target.rs @@ -1,6 +1,6 @@ #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum FunctionTarget { - Graph(usize), + Graph, Parameter(String), Dynamic(String), Pattern { node: u32, parameter: String }, @@ -9,7 +9,7 @@ pub enum FunctionTarget { impl FunctionTarget { pub fn parameter(&self) -> &str { match self { - Self::Graph(_) => "", + Self::Graph => "", Self::Parameter(parameter) | Self::Dynamic(parameter) | Self::Pattern { parameter, .. } => parameter, } } diff --git a/crates/ui-egui/src/function/geometry.rs b/crates/ui-egui/src/function/geometry.rs new file mode 100644 index 0000000..605c186 --- /dev/null +++ b/crates/ui-egui/src/function/geometry.rs @@ -0,0 +1,51 @@ +use super::{FunctionDrag, FunctionEditor, FunctionTarget}; +use crate::{MaterialCraftApp, graph::node_card}; +use egui::{Color32, Pos2, Rect, vec2}; +use materialcraft_engine::core::FunctionNode; + +pub(super) fn arity(op: &str) -> usize { + materialcraft_engine::nodes::function::definition(op).map_or(0, |o| o.inputs.len()) +} + +pub(super) fn category_color(category: &str) -> Color32 { + match category { + "Constant" => Color32::from_rgb(0x5c, 0x62, 0x6e), + "Variables" => Color32::from_rgb(0x6d, 0x52, 0xb5), + "Samplers" => Color32::from_rgb(0xa8, 0x3c, 0x34), + "Vector" | "Cast" => Color32::from_rgb(0x3a, 0x66, 0xb0), + "Operator" => Color32::from_rgb(0x3b, 0x7f, 0x4c), + "Logical" | "Comparison" | "Control" => Color32::from_rgb(0xb3, 0x5a, 0x2c), + _ => Color32::from_rgb(0x1e, 0x8a, 0xa0), + } +} + +pub(super) fn visible_inputs(node: &FunctionNode) -> usize { + let count = arity(&node.op); + crate::graph::input_visibility::count((0..count).map(|index| node.inputs.get(index).is_some_and(Option::is_some)), 1) +} + +pub(super) fn node_rect(node: &FunctionNode, previews: bool) -> Rect { + node_card::bounds(node.pos, visible_inputs(node), 1, previews, node.op == "passthrough") +} + +pub(super) fn in_port(node: &FunctionNode, bounds: Rect, index: usize) -> Pos2 { + node_card::port(bounds, index, visible_inputs(node), false, node.op == "passthrough") +} + +pub(super) fn out_port(node: &FunctionNode, bounds: Rect) -> Pos2 { + node_card::port(bounds, 0, 1, true, node.op == "passthrough") +} + +pub(super) fn preview_rect(app: &MaterialCraftApp, editor: &FunctionEditor, node: &FunctionNode, snap: bool, selected: bool) -> Rect { + let mut bounds = node_rect(node, app.ui.prefs.thumbnails); + if let Some(FunctionDrag::Node(d, delta)) = &editor.drag + && (*d == node.id || selected) + { + let position = materialcraft_engine::graph_grid::translate(node.pos, (*delta).into(), snap); + bounds = bounds.translate(vec2(position[0] - node.pos[0], position[1] - node.pos[1])); + } + if matches!(editor.target, FunctionTarget::Graph) { + bounds = bounds.translate(crate::graph::annotation_canvas::offset(app, |contents| contents.function_nodes.contains(&node.id))); + } + bounds +} diff --git a/crates/ui-egui/src/function/input.rs b/crates/ui-egui/src/function/input.rs new file mode 100644 index 0000000..0eb4144 --- /dev/null +++ b/crates/ui-egui/src/function/input.rs @@ -0,0 +1,125 @@ +use super::function_port::FunctionPort; +use super::{FunctionDrag, FunctionEditor}; +use crate::{MaterialCraftApp, graph::GraphCamera, theme::Tokens}; +use egui::{Pos2, Rect, Stroke, Ui}; +use materialcraft_engine::{FunctionEdit, core::NodeId}; + +pub(super) fn handle( + app: &mut MaterialCraftApp, + editor: &mut FunctionEditor, + ui: &mut Ui, + response: &egui::Response, + ports: &[FunctionPort], + rectangles: &[(NodeId, Rect)], + on_annotation: bool, +) { + let canvas_bounds = response.rect; + let pointer = ui.input(|input| input.pointer.hover_pos()); + let painter = ui.painter_at(canvas_bounds); + let tokens = Tokens::get(ui.ctx()); + let snap = app.ui.prefs.snap_to_grid; + if crate::graph::gesture::cancelled(ui) { + editor.drag = None; + return; + } + // Gestures: wires from output dots, panning + let near = |pointer: Pos2| crate::graph::port_hit::nearest_by(ports, pointer, |port| (port.position, port.radius)).map(|port| (port.node, port.slot)); + if editor.drag.is_none() && GraphCamera::pan_started(ui, canvas_bounds) { + editor.drag = Some(FunctionDrag::Pan(crate::graph::gesture::pan_button(ui))); + } else if ui.input(|input| input.pointer.primary_pressed()) + && editor.drag.is_none() + && !app.graph.is_dragging() + && let Some(pointer_position) = pointer + && ui.rect_contains_pointer(canvas_bounds) + && let Some((id, None)) = near(pointer_position) + { + editor.drag = Some(FunctionDrag::Wire(id)); + } + + if editor.drag.is_none() + && !app.graph.is_dragging() + && response.hovered() + && ui.input(|input| input.pointer.primary_pressed()) + && let Some(start) = pointer + && !on_annotation + { + if matches!(editor.target, super::FunctionTarget::Graph) && app.session.annotation_selection.is_some() { + app.run("graph.annotation.select", serde_json::json!({})); + } + editor.drag = Some(FunctionDrag::Box { start }); + } + + let delta = ui.input(|input| input.pointer.delta()); + match &mut editor.drag { + Some(FunctionDrag::Node(_, offset)) => *offset += delta / editor.zoom, + Some(FunctionDrag::Pan(_)) => editor.pan -= delta / editor.zoom, + Some(FunctionDrag::Wire(id)) => { + if let (Some(pointer_position), Some(source_id)) = (pointer, ports.iter().find(|port| port.node == *id && port.slot.is_none())) { + crate::graph::wire_geometry::bezier(&painter, source_id.position, pointer_position, Stroke::new(2.0, tokens.accent)); + } + } + Some(FunctionDrag::Box { start }) => { + if let Some(pointer) = pointer { + crate::graph::node_selection::paint_box(&painter, *start, pointer, tokens.accent); + } + } + None => {} + } + + let owner = match editor.drag { + Some(FunctionDrag::Pan(button)) => button, + _ => egui::PointerButton::Primary, + }; + if crate::graph::gesture::finished(ui, owner) { + match editor.drag.take() { + Some(FunctionDrag::Node(id, offset)) => { + if offset.length() > 0.5 { + let mut ids = editor.selection.clone(); + if !ids.contains(&id) { + ids.push(id); + } + editor.edit(app, FunctionEdit::Move { ids, by: offset.into(), snap }, false); + } + } + Some(FunctionDrag::Box { start }) => { + if let Some(pointer) = pointer { + let nodes = rectangles.iter().map(|(id, bounds)| (id.0 as u32, *bounds)); + crate::graph::node_selection::select_box(&mut editor.selection, nodes, start, pointer, ui.input(|input| input.modifiers)); + } + } + Some(FunctionDrag::Wire(from)) => { + if let Some(pointer) = pointer + && let Some((to, Some(input))) = near(pointer) + && from != to + { + editor.edit(app, FunctionEdit::Connect { from, to, input }, false); + } + } + _ => {} + } + } + + if response.clicked() && !ui.input(|input| input.modifiers.alt) { + crate::graph::node_selection::select(&mut editor.selection, None, ui.input(|input| input.modifiers)); + } + + let camera = GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom }; + + // Adding operations + if response.secondary_clicked() + && let Some(pointer_position) = pointer + { + editor.menu_at = camera.to_graph(pointer_position); + } + if response.hovered() + && !ui.ctx().egui_wants_keyboard_input() + && ui.input(|input| input.key_pressed(egui::Key::Space)) + && let Some(pointer_position) = pointer + { + editor.menu_at = camera.to_graph(pointer_position); + egui::Popup::open_id(ui.ctx(), response.id.with("menu")); + } + response.context_menu(|ui| { + super::context_menu::show(app, editor, ui); + }); +} diff --git a/crates/ui-egui/src/function/library.rs b/crates/ui-egui/src/function/library.rs index b41437b..56ea6a7 100644 --- a/crates/ui-egui/src/function/library.rs +++ b/crates/ui-egui/src/function/library.rs @@ -1,24 +1,21 @@ use crate::{MaterialCraftApp, i18n::tr}; use egui::Ui; -use materialcraft_engine::nodes::function::{FUNCTIONS, default_value}; -use serde_json::json; +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(); egui::ScrollArea::vertical().show(ui, |ui| { - for definition in FUNCTIONS.iter().filter(|definition| definition.label.to_ascii_lowercase().contains(&search)) { + for definition in operations.filter(|definition| definition.label.to_ascii_lowercase().contains(&search)) { if ui.selectable_label(false, tr(definition.label)).double_clicked() - && let Some(mut graph) = app.session.graph().ok().and_then(|graph| graph.function.clone()) + && let Some(mut editor) = app.function_editor.take() { - let id = graph.add(definition.id, &[], default_value(definition.id)); - if graph.output.is_none() { - graph.output = Some(id); - } - if let Some(node) = graph.nodes.iter_mut().find(|node| node.id == id) { - node.pos = materialcraft_engine::graph_grid::snap_position(node.pos, app.ui.prefs.snap_to_grid); - } - app.run("graph.function.set", json!({"function": graph})); + let at = editor.current(app).map_or([0.0; 2], |graph| [graph.nodes.len() as f32 * 140.0, 0.0]); + editor.edit(app, FunctionEdit::Add { operation: definition.id.into(), at, snap: app.ui.prefs.snap_to_grid }, false); + app.function_editor = Some(editor); } } }); diff --git a/crates/ui-egui/src/function/mod.rs b/crates/ui-egui/src/function/mod.rs index b8a0181..136b0db 100644 --- a/crates/ui-egui/src/function/mod.rs +++ b/crates/ui-egui/src/function/mod.rs @@ -6,9 +6,18 @@ mod function_target; pub(crate) mod library; mod port_label; pub(crate) mod properties; -mod selection; -pub(crate) use canvas::{enabled, invoke, show, show_graph}; +pub(crate) use actions::{enabled, invoke}; use function_drag::FunctionDrag; pub use function_editor::FunctionEditor; pub use function_target::FunctionTarget; +pub(crate) use panel::show_graph; + +mod actions; +mod geometry; +mod input; +mod panel; + +mod function_canvas; +mod function_port; +mod render; diff --git a/crates/ui-egui/src/function/panel.rs b/crates/ui-egui/src/function/panel.rs new file mode 100644 index 0000000..a4334b1 --- /dev/null +++ b/crates/ui-egui/src/function/panel.rs @@ -0,0 +1,13 @@ +use super::{FunctionEditor, FunctionTarget, canvas::canvas}; +use crate::MaterialCraftApp; +use egui::Ui; + +pub(crate) fn show_graph(app: &mut MaterialCraftApp, ui: &mut Ui) { + let index = app.session.graph; + let mut editor = app.function_editor.take().filter(|editor| editor.graph == index).unwrap_or_else(|| FunctionEditor::standalone(index)); + if editor.target == FunctionTarget::Graph { + editor.selection = app.session.selection.iter().filter_map(|id| u32::try_from(id.0).ok()).collect(); + } + canvas(app, &mut editor, ui); + app.function_editor = Some(editor); +} diff --git a/crates/ui-egui/src/function/properties.rs b/crates/ui-egui/src/function/properties.rs index 7a6eea1..52ab4ae 100644 --- a/crates/ui-egui/src/function/properties.rs +++ b/crates/ui-egui/src/function/properties.rs @@ -1,16 +1,11 @@ use egui::Ui; use materialcraft_engine::{core::FunctionGraph, nodes::function::definition}; -use super::{FunctionTarget, canvas}; use crate::{MaterialCraftApp, graph::node_selection, i18n::tr}; fn current(app: &MaterialCraftApp) -> Option<(&FunctionGraph, u32)> { let editor = app.function_editor.as_ref()?; - if editor.target != FunctionTarget::Graph(app.session.graph) { - return None; - } - - let graph = app.session.graph().ok()?.function.as_ref()?; + let graph = editor.current(app)?; let id = node_selection::inspected(&editor.selection, editor.inspected_node)?; graph.node(id)?; Some((graph, id)) @@ -25,8 +20,8 @@ pub(crate) fn title(app: &MaterialCraftApp) -> Option { pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) -> bool { let Some((graph, id)) = current(app) else { return false }; - let mut graph = graph.clone(); - let Some(node) = graph.nodes.iter_mut().find(|node| node.id == id) else { return false }; + + let Some(node) = graph.node(id) else { return false }; let label = definition(&node.op).map_or(node.op.as_str(), |definition| definition.label); ui.heading(tr(label)); @@ -34,10 +29,15 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) -> bool { ui.label(tr("Output node")); } - let changed = node.value.as_mut().is_some_and(|value| crate::value_editor::show(ui, value)); - if changed && let Some(editor) = app.function_editor.take() { - canvas::commit(app, &editor, &graph); + let mut value = node.value.clone(); + let changed = value.as_mut().is_some_and(|value| crate::value_editor::show(ui, value)); + if changed + && let Some(value) = value + && let Some(mut editor) = app.function_editor.take() + { + editor.edit(app, materialcraft_engine::FunctionEdit::Value { id, value }, true); app.function_editor = Some(editor); } + true } diff --git a/crates/ui-egui/src/function/render.rs b/crates/ui-egui/src/function/render.rs new file mode 100644 index 0000000..60a320b --- /dev/null +++ b/crates/ui-egui/src/function/render.rs @@ -0,0 +1,214 @@ +use super::geometry::{category_color, in_port, node_rect, out_port, preview_rect, visible_inputs}; +use super::{FunctionDrag, FunctionEditor, FunctionTarget, port_label::port_label}; +use super::{function_canvas::FunctionCanvas, function_port::FunctionPort}; +use crate::graph::canvas_geometry::CanvasGeometry; +use crate::{MaterialCraftApp, graph::node_card, theme::Tokens}; +use egui::{Align2, Color32, FontId, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2}; +use egui_phosphor::regular as icon; +use std::collections::{BTreeMap, BTreeSet}; + +pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) -> Option { + let graph = editor.current(app)?; + let snap = app.ui.prefs.snap_to_grid; + let selected: BTreeSet<_> = editor.selection.iter().copied().collect(); + let layouts: BTreeMap<_, _> = + graph.nodes.iter().map(|node| (node.id, (node, preview_rect(app, editor, node, snap, selected.contains(&node.id))))).collect(); + editor.selection.retain(|id| layouts.contains_key(id)); + editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node); + let standalone = matches!(editor.target, FunctionTarget::Graph); + let tokens = Tokens::get(ui.ctx()); + let (canvas_bounds, response) = ui.allocate_exact_size(ui.available_size().max(vec2(200.0, 200.0)), Sense::click_and_drag()); + crate::widgets::name(&response, egui::Role::Canvas, "Function Graph"); + let painter = ui.painter_at(canvas_bounds); + painter.rect_filled(canvas_bounds, 4.0, Color32::from_rgb(0x26, 0x28, 0x2c)); + let mut geometry = CanvasGeometry::default(); + let mut values = Vec::new(); + let mut nodes = Vec::new(); + let mut clear_annotation = false; + + let frame_key = crate::graph::GraphCamera::frame_key(ui, canvas_bounds); + if !editor.framed || app.ui.frame_all || frame_key { + editor.framed = true; + let selected_only = frame_key && !editor.selection.is_empty(); + let mut destination = graph + .nodes + .iter() + .filter(|node| !selected_only || selected.contains(&node.id)) + .map(|node| node_rect(node, app.ui.prefs.thumbnails)) + .fold(Rect::NOTHING, |combined, bounds| combined.union(bounds)); + if standalone + && !selected_only + && let Ok(document) = app.session.graph() + { + for frame in &document.frames { + destination = destination.union(Rect::from_min_size(pos2(frame.rect[0], frame.rect[1] - 32.0), vec2(frame.rect[2], frame.rect[3] + 32.0))); + } + } + let camera = crate::graph::GraphCamera::fit(canvas_bounds, destination); + editor.pan = camera.pan; + editor.zoom = camera.zoom; + } + + let mut camera = crate::graph::GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom }; + camera.zoom_from_input(ui, canvas_bounds); + editor.pan = camera.pan; + editor.zoom = camera.zoom; + let document = standalone.then(|| app.session.graph().ok()).flatten(); + let frame_hits = document.as_ref().map(|graph| crate::graph::annotation_canvas::frames(app, ui, &graph.frames, &camera)).unwrap_or_default(); + crate::graph::grid::paint(&painter, &camera, canvas_bounds); + + // Wires use the same prepared bounds as the cards + for node in &graph.nodes { + let Some((_, bounds)) = layouts.get(&node.id) else { continue }; + + for (input_index, source_id) in node.inputs.iter().enumerate() { + if let Some((source, source_bounds)) = source_id.and_then(|source| layouts.get(&source)) { + let source_position = camera.to_screen(out_port(source, *source_bounds)); + let destination = camera.to_screen(in_port(node, *bounds, input_index)); + let points = crate::graph::wire_geometry::bezier_points(source_position, destination); + geometry.wires.push(((materialcraft_engine::core::NodeId(u64::from(node.id)), input_index.to_string()), points)); + painter.add(egui::epaint::CubicBezierShape::from_points_stroke( + points, + false, + Color32::TRANSPARENT, + Stroke::new(2.0, Color32::from_gray(0xb4)), + )); + } + } + } + + // Nodes + let font = FontId::proportional((11.0 * editor.zoom).min(16.0)); + let mut ports = Vec::new(); + for node in &graph.nodes { + let id = node.id; + let Some((_, bounds)) = layouts.get(&id) else { continue }; + + let bounds = *bounds; + let screen_rect = Rect::from_min_max(camera.to_screen(bounds.min), camera.to_screen(bounds.max)); + geometry.rects.push((materialcraft_engine::core::NodeId(u64::from(id)), screen_rect)); + + let definition = materialcraft_engine::nodes::function::definition(&node.op); + let label = definition.map_or("?", |definition| definition.label); + let dot = node.op == "passthrough"; + let show_labels = crate::graph::port_label::visible(ui, screen_rect); + let is_output = graph.output == Some(id); + let selected = selected.contains(&id); + let outline = if selected { + tokens.accent + } else if dot { + Color32::from_gray(0xb4) + } else { + Color32::from_gray(0x10) + }; + + if dot { + node_card::paint_dot(&painter, screen_rect, outline); + } else { + node_card::paint(&painter, screen_rect, editor.zoom, label, category_color(definition.map_or("", |definition| definition.category))); + node_card::outline(&painter, screen_rect, editor.zoom, Stroke::new(if selected { 2.0 } else { 1.0 }, outline)); + let body = node_card::body(screen_rect, editor.zoom); + if node.value.is_none() { + painter.text(body.center(), Align2::CENTER_CENTER, icon::CODE, FontId::proportional(30.0 * editor.zoom), tokens.text_dim); + } + if is_output { + let header = node_card::header(screen_rect, editor.zoom); + painter.text(header.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, icon::STAR, font.clone(), Color32::GOLD); + } + } + + let port_radius = (4.5 * editor.zoom).clamp(2.5, 7.0); + let port_color = crate::graph::port_color(materialcraft_engine::nodes::PortKind::Value); + if let Some(definition) = definition { + for (input_index, identifier) in definition.inputs.iter().take(visible_inputs(node)).enumerate() { + let position = camera.to_screen(in_port(node, bounds, input_index)); + painter.circle(position, port_radius, port_color, Stroke::new(1.0, Color32::from_gray(0x18))); + if show_labels { + crate::graph::port_label::paint( + &painter, + position - vec2(10.0, 0.0), + Align2::RIGHT_CENTER, + port_label(identifier), + editor.zoom, + tokens.text_strong, + ); + } + ports.push(FunctionPort { + node: id, + slot: Some(input_index), + position, + radius: if dot { (3.5 * editor.zoom).max(2.0) } else { 9.0 }, + label: port_label(identifier), + }); + } + } + + let output_position = camera.to_screen(out_port(node, bounds)); + painter.circle(output_position, port_radius, port_color, Stroke::new(1.0, Color32::from_gray(0x18))); + if show_labels { + crate::graph::port_label::paint( + &painter, + output_position + vec2(10.0, 0.0), + Align2::LEFT_CENTER, + port_label("output"), + editor.zoom, + tokens.text_strong, + ); + } + ports.push(FunctionPort { + node: id, + slot: None, + position: output_position, + radius: if dot { (3.5 * editor.zoom).max(2.0) } else { 9.0 }, + label: port_label("output"), + }); + + let body = ui.interact(screen_rect, ui.scope_id().with(("fn-node", id)), Sense::click_and_drag()); + crate::widgets::name(&body, egui::Role::Button, label); + + if !dot && node.value.is_some() { + let content = node_card::body(screen_rect, editor.zoom).shrink(6.0 * editor.zoom); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(content)); + child.set_clip_rect(content.intersect(canvas_bounds)); + if let Some(mut value) = node.value.clone() + && crate::value_editor::show(&mut child, &mut value) + { + values.push((id, value)); + } + } + + if (body.contains_pointer() && ui.input(|input| input.pointer.primary_pressed() && !input.modifiers.alt)) || body.secondary_clicked() { + let modifiers = if body.secondary_clicked() { egui::Modifiers::NONE } else { ui.input(|input| input.modifiers) }; + + crate::graph::node_selection::select(&mut editor.selection, Some(id), modifiers); + if standalone && app.session.annotation_selection.is_some() { + clear_annotation = true; + } + } + + if body.drag_started() && !ui.input(|input| input.modifiers.alt) && editor.selection.contains(&id) && editor.drag.is_none() && !app.graph.is_dragging() + { + editor.drag = Some(FunctionDrag::Node(id, Vec2::ZERO)); + } + + nodes.push((id, body)); + } + + geometry.ports = ports + .iter() + .map(|port| crate::graph::PortHit { + node: materialcraft_engine::core::NodeId(u64::from(port.node)), + port: port.slot.map_or_else(|| "output".into(), |slot| slot.to_string()), + label: port.label.into(), + output: port.slot.is_none(), + kind: materialcraft_engine::nodes::PortKind::Value, + pos: port.position, + }) + .collect(); + + let comments = document.as_ref().map(|document| crate::graph::annotation_canvas::comments(app, ui, &document.comments, &camera)).unwrap_or_default(); + if let Some(document) = &document { + crate::graph::annotation_canvas::pins(app, ui, &document.pins, &camera); + } + Some(FunctionCanvas { response, camera, geometry, ports, nodes, values, frames: frame_hits, comments, clear_annotation }) +} diff --git a/crates/ui-egui/src/function/selection.rs b/crates/ui-egui/src/function/selection.rs deleted file mode 100644 index baf41e3..0000000 --- a/crates/ui-egui/src/function/selection.rs +++ /dev/null @@ -1,104 +0,0 @@ -use super::FunctionEditor; -use materialcraft_engine::core::{FunctionGraph, FunctionNode}; -use std::collections::{BTreeMap, BTreeSet}; - -pub(super) fn enabled(editor: &FunctionEditor, command: &str) -> Option { - Some(match command { - "edit.selectAll" | "edit.selectNone" => true, - "edit.paste" | "edit.pasteWithoutLinks" => !editor.clipboard.is_empty(), - "edit.copy" - | "edit.cut" - | "edit.delete" - | "edit.deleteRelink" - | "edit.duplicate" - | "edit.duplicateWithoutLinks" - | "graph.selectUpstream" - | "graph.selectDownstream" => !editor.selection.is_empty(), - "graph.node.disable" => false, - _ => return None, - }) -} - -pub(super) fn run(editor: &mut FunctionEditor, graph: &mut FunctionGraph, command: &str, snap: bool) -> bool { - match command { - "edit.selectAll" => editor.selection = graph.nodes.iter().map(|node| node.id).collect(), - "edit.selectNone" => editor.selection.clear(), - "edit.copy" | "edit.cut" => { - editor.clipboard = graph.nodes.iter().filter(|node| editor.selection.contains(&node.id)).cloned().collect(); - if command == "edit.cut" { - return remove(editor, graph, false); - } - } - "edit.delete" | "edit.deleteRelink" => return remove(editor, graph, command == "edit.deleteRelink"), - "edit.duplicate" | "edit.duplicateWithoutLinks" | "edit.paste" | "edit.pasteWithoutLinks" => { - let duplicate = command.starts_with("edit.duplicate"); - let nodes: Vec = - if duplicate { graph.nodes.iter().filter(|node| editor.selection.contains(&node.id)).cloned().collect() } else { editor.clipboard.clone() }; - let anchor = nodes.first().map_or([0.0; 2], |node| node.pos); - let offset = if duplicate { [32.0; 2] } else { [editor.menu_at.x - anchor[0], editor.menu_at.y - anchor[1]] }; - let mut ids = BTreeMap::new(); - for mut node in nodes { - let source = node.id; - node.id = graph.next_id(); - node.pos = materialcraft_engine::graph_grid::snap_position([node.pos[0] + offset[0], node.pos[1] + offset[1]], snap); - ids.insert(source, node.id); - graph.nodes.push(node); - } - editor.selection = ids.values().copied().collect(); - for node in graph.nodes.iter_mut().filter(|node| editor.selection.contains(&node.id)) { - for input in &mut node.inputs { - *input = input.and_then(|id| ids.get(&id).copied().or_else(|| (!command.ends_with("WithoutLinks")).then_some(id))); - } - } - return !ids.is_empty(); - } - "graph.selectUpstream" | "graph.selectDownstream" => { - let upstream = command == "graph.selectUpstream"; - let mut visited = BTreeSet::new(); - let mut pending = editor.selection.clone(); - while let Some(id) = pending.pop() { - if !visited.insert(id) { - continue; - } - if upstream { - if let Some(node) = graph.node(id) { - pending.extend(node.inputs.iter().flatten()); - } - } else { - pending.extend(graph.nodes.iter().filter(|node| node.inputs.contains(&Some(id))).map(|node| node.id)); - } - } - editor.selection = visited.into_iter().collect(); - } - _ => {} - } - false -} - -fn remove(editor: &mut FunctionEditor, graph: &mut FunctionGraph, relink: bool) -> bool { - let replacements: BTreeMap<_, _> = graph - .nodes - .iter() - .filter(|node| editor.selection.contains(&node.id)) - .map(|node| (node.id, if relink { node.inputs.first().copied().flatten() } else { None })) - .collect(); - graph.nodes.retain(|node| !editor.selection.contains(&node.id)); - for node in &mut graph.nodes { - for input in &mut node.inputs { - let mut seen = BTreeSet::new(); - while let Some(id) = *input { - let Some(replacement) = replacements.get(&id) else { break }; - if !seen.insert(id) { - *input = None; - break; - } - *input = *replacement; - } - } - } - if graph.output.is_some_and(|id| editor.selection.contains(&id)) { - graph.output = None; - } - editor.selection.clear(); - !replacements.is_empty() -} diff --git a/crates/ui-egui/src/graph/actions.rs b/crates/ui-egui/src/graph/actions.rs index 84d38ee..9c0ddde 100644 --- a/crates/ui-egui/src/graph/actions.rs +++ b/crates/ui-egui/src/graph/actions.rs @@ -2,6 +2,7 @@ use crate::{MaterialCraftApp, docking::Panel}; pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option { match command { + "ui.graph.viewOutputs" | "ui.graph.resetViewOutputs" => Some(app.session.graph().is_ok_and(|graph| graph.function.is_none())), "ui.graph.previousPin" | "ui.graph.nextPin" => Some(app.session.graph().is_ok_and(|graph| !graph.pins.is_empty())), command if command.starts_with("ui.graph.") => Some(app.session.graph().is_ok()), _ => None, @@ -18,18 +19,27 @@ pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool { let Some(result) = app.run(command, serde_json::Value::Null) else { return true }; let Some(node) = result.get("node").and_then(serde_json::Value::as_u64) else { return true }; - app.function_editor = None; - app.pattern_editor = Some(crate::pattern::PatternEditor::new(app.session.graph, materialcraft_engine::core::NodeId(node))); + let node = materialcraft_engine::core::NodeId(node); + match result.get("kind").and_then(serde_json::Value::as_str) { + Some("pattern") => { + app.function_editor = None; + app.pattern_editor = Some(crate::pattern::PatternEditor::new(app.session.graph, node)); + } + Some("function") => { + super::subgraph_navigation::open_function(app, node, crate::function::FunctionTarget::Parameter("function".into())); + } + Some("graph") => { + if let Some(index) = result.get("graph").and_then(serde_json::Value::as_u64).and_then(|index| usize::try_from(index).ok()) { + super::subgraph_navigation::open_instance(app, index); + } + } + _ => {} + } app.ui.dock.focus(Panel::Graph); } "ui.graph.snapToGrid" => app.ui.prefs.snap_to_grid = !app.ui.prefs.snap_to_grid, "ui.graph.viewOutputs" | "ui.graph.resetViewOutputs" => { - if command == "ui.graph.resetViewOutputs" { - app.run("view.3d.reset", serde_json::Value::Null); - } - - app.ui.dock.focus(Panel::View3d); - app.session.dirty = true; + app.run("view.3d.outputs", serde_json::json!({"reset": command == "ui.graph.resetViewOutputs"})); } "ui.graph.computeThumbnails" => { app.graph.thumbnails_cleared = false; @@ -68,4 +78,9 @@ fn navigate_pin(app: &mut MaterialCraftApp, forward: bool) { let Some(pin) = graph.pins.get(index) else { return }; camera.pan = [pin.pos[0] - app.graph.view.width() * 0.5 / zoom, pin.pos[1] - app.graph.view.height() * 0.5 / zoom]; + if let Some(editor) = &mut app.function_editor + && editor.target == crate::function::FunctionTarget::Graph + { + editor.set_camera(*camera); + } } diff --git a/crates/ui-egui/src/graph/annotation_canvas.rs b/crates/ui-egui/src/graph/annotation_canvas.rs index 0071f91..e37bb4d 100644 --- a/crates/ui-egui/src/graph/annotation_canvas.rs +++ b/crates/ui-egui/src/graph/annotation_canvas.rs @@ -1,16 +1,19 @@ use egui::{Align2, Color32, FontId, Rect, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; use egui_phosphor::regular as icon; -use materialcraft_engine::{AnnotationSelection, core::Graph}; +use materialcraft_engine::{ + AnnotationSelection, + core::{Comment, Frame, Pin}, +}; use super::{GraphCamera, GraphDrag, frame_hit::FrameHit}; use crate::{MaterialCraftApp, theme::Tokens}; -pub(crate) fn frames(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: &GraphCamera) -> Vec { +pub(crate) fn frames(app: &MaterialCraftApp, ui: &Ui, frames: &[Frame], camera: &GraphCamera) -> Vec { let painter = ui.painter_at(app.graph.view); let theme = Tokens::get(ui.ctx()); - let mut hits = Vec::with_capacity(graph.frames.len()); + let mut hits = Vec::with_capacity(frames.len()); - let mut frames: Vec<_> = graph.frames.iter().collect(); + let mut frames: Vec<_> = frames.iter().collect(); frames.sort_by(|first, second| (second.rect[2] * second.rect[3]).total_cmp(&(first.rect[2] * first.rect[3]))); for frame in frames { @@ -29,6 +32,7 @@ pub(crate) fn frames(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: &Gr let fill = Color32::from_rgba_unmultiplied(channel(color[0]), channel(color[1]), channel(color[2]), (color[3] * 255.0).round() as u8); let selected = app.session.annotation_selection == Some(AnnotationSelection::Frame(frame.id)); let outline = if selected { Stroke::new(2.0, theme.accent) } else { Stroke::new(1.0, Color32::from_black_alpha(180)) }; + painter.rect(rect, 0.0, fill, outline, StrokeKind::Outside); let title = if frame.title_visible { @@ -58,12 +62,12 @@ pub(crate) fn frames(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: &Gr hits } -pub(crate) fn comments(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: &GraphCamera) -> Vec<(u64, Rect)> { +pub(crate) fn comments(app: &MaterialCraftApp, ui: &Ui, comments: &[Comment], camera: &GraphCamera) -> Vec<(u64, Rect)> { let painter = ui.painter_at(app.graph.view); let theme = Tokens::get(ui.ctx()); - let mut hits = Vec::with_capacity(graph.comments.len()); + let mut hits = Vec::with_capacity(comments.len()); - for comment in &graph.comments { + for comment in comments { let mut position = pos2(comment.pos[0], comment.pos[1]) + offset(app, |contents| contents.comments.contains(&comment.id)); if let Some(GraphDrag::Comment { id, delta }) = &app.graph.drag && *id == comment.id @@ -73,6 +77,7 @@ pub(crate) fn comments(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: & let selected = app.session.annotation_selection == Some(AnnotationSelection::Comment(comment.id)); let color = if selected { theme.accent } else { theme.text }; + let text = painter.layout(comment.text.clone(), FontId::proportional((14.0 * camera.zoom).clamp(6.0, 36.0)), color, comment.size[0] * camera.zoom); let rect = Rect::from_min_size(camera.to_screen(position), text.size().max(vec2(24.0, 16.0))); painter.galley(rect.min, text, color); @@ -82,11 +87,11 @@ pub(crate) fn comments(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: & hits } -pub(crate) fn pins(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: &GraphCamera) { +pub(crate) fn pins(app: &MaterialCraftApp, ui: &Ui, pins: &[Pin], camera: &GraphCamera) { let painter = ui.painter_at(app.graph.view); let theme = Tokens::get(ui.ctx()); - for pin in &graph.pins { + for pin in pins { let position = pos2(pin.pos[0], pin.pos[1]) + offset(app, |contents| contents.pins.contains(&pin.id)); let position = camera.to_screen(position); painter.text(position, Align2::CENTER_BOTTOM, icon::MAP_PIN, FontId::proportional(18.0), theme.accent); diff --git a/crates/ui-egui/src/graph/annotation_input.rs b/crates/ui-egui/src/graph/annotation_input.rs index a6bae1e..565462a 100644 --- a/crates/ui-egui/src/graph/annotation_input.rs +++ b/crates/ui-egui/src/graph/annotation_input.rs @@ -4,23 +4,21 @@ use egui::{Rect, Ui, Vec2}; use serde_json::json; pub(crate) fn handle(app: &mut MaterialCraftApp, ui: &Ui, camera: &GraphCamera, frames: &[FrameHit], comments: &[(u64, Rect)]) { + if super::gesture::cancelled(ui) { + app.graph.drag = None; + return; + } + let Some(pointer) = ui.input(|input| input.pointer.interact_pos()) else { return }; + let pressed = ui.input(|input| input.pointer.primary_pressed()); let motion = ui.input(|input| input.pointer.delta()) / camera.zoom; if pressed && app.graph.view.contains(pointer) && app.graph.drag.is_none() && !app.graph.rects.iter().any(|(_, rect)| rect.contains(pointer)) { if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(pointer)) { - app.run("graph.annotation.select", json!({"kind": "comment", "id": id})); - app.graph.drag = Some(GraphDrag::Comment { id: *id, delta: Vec2::ZERO }); + begin_comment(app, *id); } else if let Some(hit) = frames.iter().rev().find(|hit| hit.contains(pointer)) { - let contents = app - .session - .graph() - .ok() - .and_then(|graph| graph.frames.iter().find(|frame| frame.id == hit.id).map(|frame| materialcraft_engine::FrameContents::capture(graph, frame))) - .unwrap_or_default(); - app.run("graph.annotation.select", json!({"kind": "frame", "id": hit.id})); - app.graph.drag = Some(GraphDrag::Frame { id: hit.id, delta: Vec2::ZERO, resize: hit.grip.contains(pointer), contents }); + begin_frame(app, hit.id, hit.grip.contains(pointer)); } else { app.run("graph.annotation.select", json!({})); } @@ -28,25 +26,47 @@ pub(crate) fn handle(app: &mut MaterialCraftApp, ui: &Ui, camera: &GraphCamera, *delta += motion; } - if ui.input(|input| input.pointer.primary_released()) { - match app.graph.drag.take() { - Some(GraphDrag::Frame { id, delta, resize, .. }) if delta.length() > 0.5 => { - if resize { - if let Some(frame) = app.session.graph().ok().and_then(|graph| graph.frames.iter().find(|frame| frame.id == id)) { - let rect = [frame.rect[0], frame.rect[1], frame.rect[2] + delta.x, frame.rect[3] + delta.y]; - app.run("graph.frame.edit", json!({"id": id, "rect": rect})); - } - } else { - app.run("graph.frame.move", json!({"id": id, "by": [delta.x, delta.y]})); + if super::gesture::finished(ui, egui::PointerButton::Primary) + && let Some(drag) = app.graph.drag.take() + { + finish(app, drag); + } +} + +pub(super) fn begin_comment(app: &mut MaterialCraftApp, id: u64) { + app.run("graph.annotation.select", json!({"kind": "comment", "id": id})); + app.graph.drag = Some(GraphDrag::Comment { id, delta: Vec2::ZERO }); +} + +pub(super) fn begin_frame(app: &mut MaterialCraftApp, id: u64, resize: bool) { + let contents = app + .session + .graph() + .ok() + .and_then(|graph| graph.frames.iter().find(|frame| frame.id == id).map(|frame| materialcraft_engine::FrameContents::capture(graph, frame))) + .unwrap_or_default(); + app.run("graph.annotation.select", json!({"kind": "frame", "id": id})); + app.graph.drag = Some(GraphDrag::Frame { id, delta: Vec2::ZERO, resize, contents }); +} + +pub(super) fn finish(app: &mut MaterialCraftApp, drag: GraphDrag) { + match drag { + GraphDrag::Frame { id, delta, resize, .. } if delta.length() > 0.5 => { + if resize { + if let Some(frame) = app.session.graph().ok().and_then(|graph| graph.frames.iter().find(|frame| frame.id == id)) { + let rect = [frame.rect[0], frame.rect[1], frame.rect[2] + delta.x, frame.rect[3] + delta.y]; + app.run("graph.frame.edit", json!({"id": id, "rect": rect})); } + } else { + app.run("graph.frame.move", json!({"id": id, "by": [delta.x, delta.y]})); } - Some(GraphDrag::Comment { id, delta }) if delta.length() > 0.5 => { - if let Some(comment) = app.session.graph().ok().and_then(|graph| graph.comments.iter().find(|comment| comment.id == id)) { - let position = [comment.pos[0] + delta.x, comment.pos[1] + delta.y]; - app.run("graph.comment.edit", json!({"id": id, "at": position})); - } + } + GraphDrag::Comment { id, delta } if delta.length() > 0.5 => { + if let Some(comment) = app.session.graph().ok().and_then(|graph| graph.comments.iter().find(|comment| comment.id == id)) { + let position = [comment.pos[0] + delta.x, comment.pos[1] + delta.y]; + app.run("graph.comment.edit", json!({"id": id, "at": position})); } - _ => {} } + _ => {} } } diff --git a/crates/ui-egui/src/graph/canvas.rs b/crates/ui-egui/src/graph/canvas.rs index 6efaf7a..c876e19 100644 --- a/crates/ui-egui/src/graph/canvas.rs +++ b/crates/ui-egui/src/graph/canvas.rs @@ -1,283 +1,46 @@ -use super::node_card; -use super::node_card::port as port_pos; -use super::node_layout::NodeLayout; -use super::{GraphCamera, GraphDrag, LibraryDrag, NodeSearch, PortHit, WireRef}; -use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; +use super::node_style::{PORT_RADIUS, header_color, node_label, node_rect, port_color}; +use super::{GraphCamera, GraphDrag, PortHit, WireRef}; +use super::{ + navigation::frame, + port_hit::nearest as nearest_port, + wire_geometry::{bezier, bezier_points, wire_at}, +}; +use super::{node_card, node_card::port as port_pos, node_layout::NodeLayout}; +use crate::{MaterialCraftApp, theme::Tokens}; +use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2}; use egui_phosphor::regular as icon; -use materialcraft_engine::core::{Node, NodeId, Value}; -use materialcraft_engine::nodes::PortKind; -use serde_json::json; - -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; - -pub const NODE_W: f32 = node_card::WIDTH; -const PORT_R: f32 = 4.5; - -/// Pointer distance (points) within which a wire is hit -const WIRE_HIT: f32 = 5.0; - -/// Header strip color of a node by its library category -pub fn header_color(def: &str) -> Color32 { - let cat = materialcraft_engine::nodes::find(def).map_or("", |d| d.category); - match def { - "output" => Color32::from_rgb(0x2c, 0x8f, 0x5e), - "input_color" | "input_grayscale" => Color32::from_rgb(0x6d, 0x52, 0xb5), - "graph_instance" => Color32::from_rgb(0x1e, 0x8a, 0xa0), - _ if cat.starts_with("Atomic") => Color32::from_rgb(0x5c, 0x62, 0x6e), - _ if cat.contains("Noises") => Color32::from_rgb(0xa8, 0x3c, 0x34), - _ if cat.contains("Patterns") => Color32::from_rgb(0xb3, 0x5a, 0x2c), - _ if cat.starts_with("Material") => Color32::from_rgb(0x3a, 0x66, 0xb0), - _ if cat.starts_with("Filters") => Color32::from_rgb(0x3b, 0x7f, 0x4c), - _ => Color32::from_rgb(0x5c, 0x62, 0x6e), - } -} - -pub fn port_color(kind: PortKind) -> Color32 { - match kind { - PortKind::Gray => Color32::from_rgb(0xc8, 0xc8, 0xc8), - PortKind::Color => Color32::from_rgb(0xe8, 0xa9, 0x3c), - PortKind::Value => Color32::from_rgb(0x8b, 0xc6, 0x74), - PortKind::Any => Color32::from_rgb(0x8c, 0xb4, 0xe0), - } -} - -/// A node's display label -pub fn node_label(n: &Node) -> String { - if !n.label.is_empty() { - return n.label.clone(); - } - match n.def.as_str() { - "graph_instance" => match n.params.get("graph") { - Some(Value::Text(g)) => g.clone(), - _ => tr("Graph instance").into(), - }, - "output" | "input_color" | "input_grayscale" => materialcraft_engine::eval::identifier(n), - d => materialcraft_engine::nodes::find(d).map_or(d, |d| d.label).to_string(), - } -} - -/// Graph-space rectangle of a node card -pub fn node_rect(node: &Node, inputs: usize, outputs: usize, previews: bool) -> Rect { - node_card::bounds(node.pos, inputs, outputs, previews, node.def == "dot") -} - -fn bezier_points(a: Pos2, b: Pos2) -> [Pos2; 4] { - let dx = ((b.x - a.x).abs() * 0.5).max(30.0); - [a, a + vec2(dx, 0.0), b - vec2(dx, 0.0), b] -} - -fn bezier(p: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke) { - p.add(egui::epaint::CubicBezierShape::from_points_stroke(bezier_points(a, b), false, Color32::TRANSPARENT, stroke)); -} - -/// The point at `t` (0..1) along a cubic bezier -fn bezier_at(c: &[Pos2; 4], t: f32) -> Pos2 { - let u = 1.0 - t; - let w = [u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t]; - pos2(c.iter().zip(w).map(|(p, w)| p.x * w).sum(), c.iter().zip(w).map(|(p, w)| p.y * w).sum()) -} - -/// Distance from `p` to a cubic bezier (sampled as a polyline) -fn bezier_distance(c: &[Pos2; 4], p: Pos2) -> f32 { - const N: usize = 32; - let mut best = f32::INFINITY; - let mut prev = c[0]; - for i in 1..=N { - let q = bezier_at(c, i as f32 / N as f32); - let (seg, rel) = (q - prev, p - prev); - let t = if seg.length_sq() > 0.0 { (rel.dot(seg) / seg.length_sq()).clamp(0.0, 1.0) } else { 0.0 }; - best = best.min((prev + seg * t).distance(p)); - prev = q; - } - best -} - -/// The wire nearest `p` within [`WIRE_HIT`] points -fn wire_at(wires: &[(WireRef, [Pos2; 4])], p: Pos2) -> Option<&WireRef> { - wires - .iter() - .filter(|(_, c)| Rect::from_points(c).expand(WIRE_HIT).contains(p)) - .map(|(w, c)| (w, bezier_distance(c, p))) - .filter(|(_, d)| *d <= WIRE_HIT) - .min_by(|a, b| a.1.total_cmp(&b.1)) - .map(|(w, _)| w) -} +use materialcraft_engine::core::NodeId; /// The graph panel: toolbar row and canvas pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + app.reconcile_editors(); + if !crate::pattern::active(app) { + app.pattern_editor = None; + if app.session.graph().is_ok_and(|graph| graph.function.is_some()) { + let target = crate::function::FunctionTarget::Graph; + if app.function_editor.as_ref().is_none_or(|editor| editor.target != target) { + app.function_editor = Some(crate::function::FunctionEditor::standalone(app.session.graph)); + } + } else if app.function_editor.as_ref().is_some_and(|editor| matches!(editor.target, crate::function::FunctionTarget::Graph)) { + app.function_editor = None; + } + } + + super::toolbar::show(app, ui); + if app.function_editor.is_some() { + crate::function::show_graph(app, ui); + return; + } if crate::pattern::active(app) { crate::pattern::show(app, ui); return; } - app.pattern_editor = None; - if app.session.graph().is_ok_and(|graph| graph.function.is_some()) { - crate::function::show_graph(app, ui); - return; - } - if app.function_editor.as_ref().is_some_and(|editor| matches!(editor.target, crate::function::FunctionTarget::Graph(_))) { - app.function_editor = None; - } - - toolbar(app, ui); canvas(app, ui); } -fn toolbar(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - egui::Frame::NONE.fill(tk.panel).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - let b = |ui: &mut Ui, ic: &str, tip: &str| crate::widgets::icon_button(ui, ic, tip, false, 22.0).clicked(); - if b(ui, icon::CORNERS_OUT, tr("Frame all (F)")) { - app.ui.frame_all = true; - } - for (ic, mode, tip) in [ - (icon::ALIGN_LEFT, "left", "Align left"), - (icon::ALIGN_TOP, "top", "Align top"), - (icon::ALIGN_CENTER_HORIZONTAL, "hcenter", "Align centers horizontally"), - (icon::ALIGN_CENTER_VERTICAL, "vcenter", "Align centers vertically"), - (icon::COLUMNS, "hdistribute", "Distribute horizontally"), - (icon::ROWS, "vdistribute", "Distribute vertically"), - ] { - if b(ui, ic, tr(tip)) { - app.run("graph.align", json!({"mode": mode})); - } - } - ui.separator(); - if b(ui, icon::SELECTION, tr("Add frame around the selection")) { - app.run("graph.frame.add", json!({})); - } - if b(ui, icon::NOTE, tr("Add comment")) { - app.run("graph.comment.add", json!({})); - } - if b(ui, icon::MAP_PIN, tr("Add navigation pin")) { - let c = view_center(app); - app.run("graph.pin.add", json!({"at": [c.x, c.y]})); - } - ui.separator(); - if crate::widgets::icon_button(ui, icon::GRID_FOUR, tr("Snap to grid"), app.ui.prefs.snap_to_grid, 22.0).clicked() { - crate::menus::invoke(app, ui.ctx(), "ui.graph.snapToGrid"); - } - - // Quick insert of the atomic nodes - for (ic, def) in [ - (icon::IMAGE, "bitmap"), - (icon::PALETTE, "uniform"), - (icon::STACK, "blend"), - (icon::DROP, "blur"), - (icon::SHUFFLE, "channels_shuffle"), - (icon::CHART_LINE, "curve"), - (icon::WIND, "directional_blur"), - (icon::ARROWS_OUT_LINE_HORIZONTAL, "directional_warp"), - (icon::RULER, "distance"), - (icon::MOUNTAINS, "emboss"), - (icon::GRADIENT, "gradient_map"), - (icon::CIRCLE_HALF, "grayscale_conversion"), - (icon::SWATCHES, "hsl"), - (icon::SLIDERS_HORIZONTAL, "levels"), - (icon::CUBE, "normal"), - (icon::CODE, "pixel_processor"), - (icon::DIAMOND, "sharpen"), - (icon::ARROWS_CLOCKWISE, "transformation"), - (icon::WAVES, "warp"), - (icon::SIGN_IN, "input_grayscale"), - (icon::SIGN_OUT, "output"), - ] { - let label = materialcraft_engine::nodes::find(def).map_or(def, |d| d.label); - if b(ui, ic, label) { - add_node_near_selection(app, def); - } - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let thumbs = app.ui.prefs.thumbnails; - if crate::widgets::icon_button(ui, icon::IMAGE, tr("Show node thumbnails"), thumbs, 22.0).clicked() { - app.ui.prefs.thumbnails = !thumbs; - } - parent_size(app, ui); - }); - }); - }); -} - -/// "Parent size: [1024 ▾] × [1024 ▾]" -fn parent_size(app: &mut MaterialCraftApp, ui: &mut Ui) { - let Ok(g) = app.session.graph() else { return }; - let [w, h] = g.size; - let mut nw = w; - let mut nh = h; - let combo = |ui: &mut Ui, id: &str, v: &mut u32| { - let r = egui::ComboBox::from_id_salt(id).width(64.0).selected_text(format!("{}", 1u32 << *v)).show_ui(ui, |ui| { - for l in 4..=13u32 { - ui.selectable_value(v, l, format!("{}", 1u32 << l)); - } - }); - crate::widgets::name(&r.response, egui::Role::ComboBox, if id == "parent-w" { "Parent width" } else { "Parent height" }); - }; - - combo(ui, "parent-h", &mut nh); - ui.label("x"); - combo(ui, "parent-w", &mut nw); - ui.label(egui::RichText::new(tr("Parent size:")).color(Tokens::get(ui.ctx()).text_dim)); - if (nw, nh) != (w, h) { - app.run("graph.size", json!({"log2": [nw, nh]})); - } -} - -fn view_center(app: &MaterialCraftApp) -> Pos2 { - let c = &app.ui.graph_camera; - let v = app.graph.view; - pos2(c.pan[0] + v.width() * 0.5 / c.zoom, c.pan[1] + v.height() * 0.5 / c.zoom) -} - -/// 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(); - let has_inputs = materialcraft_engine::nodes::find(def).is_some_and(|d| !d.inputs.is_empty()); - let params = match sel { - Some(id) if has_inputs && !app.session.output_ports(id).is_empty() => json!({"def": def, "connectFrom": {"node": id.0}}), - _ => { - let c = view_center(app); - json!({"def": def, "at": [c.x - NODE_W * 0.5, c.y - 60.0]}) - } - }; - - app.run("graph.node.add", params); -} - -/// Frame the graph (or the selection) in the view -fn frame(app: &mut MaterialCraftApp, view: Rect, only_selection: bool) { - let thumbs = app.ui.prefs.thumbnails; - let Ok(g) = app.session.graph() else { return }; - let mut r = Rect::NOTHING; - for n in &g.nodes { - if only_selection && !app.session.selection.contains(&n.id) { - continue; - } - - let (inputs, outputs) = materialcraft_engine::eval::ports(&app.session.pkg, g, n); - let visible = super::input_visibility::count(inputs.iter().map(|port| g.input_of(n.id, &port.id).is_some()), if n.def == "fx_map" { 2 } else { 1 }); - r = r.union(node_rect(n, visible, outputs.len(), thumbs)); - } - for f in &g.frames { - if !only_selection { - r = r.union(Rect::from_min_size(pos2(f.rect[0], f.rect[1] - 32.0), vec2(f.rect[2], f.rect[3] + 32.0))); - } - } - if !r.is_finite() || r.width() <= 0.0 { - app.ui.graph_camera = crate::state::GraphCamera::default(); - return; - } - let r = r.expand(40.0); - let zoom = (view.width() / r.width()).min(view.height() / r.height()).clamp(0.1, 1.5); - let pan = r.center().to_vec2() - vec2(view.width(), view.height()) * 0.5 / zoom; - app.ui.graph_camera = crate::state::GraphCamera { pan: [pan.x, pan.y], zoom }; -} - fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); + let theme = Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); let (rect, resp) = ui.allocate_exact_size(ui.available_size(), Sense::click_and_drag()); crate::widgets::name(&resp, egui::Role::Canvas, "Node graph"); @@ -291,31 +54,17 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let painter = ui.painter_at(rect); // Background and grid painter.rect_filled(rect, 0.0, Color32::from_rgb(0x2b, 0x2d, 0x31)); - let cam = GraphCamera { origin: rect.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom.clamp(0.08, 4.0) }; - grid(&painter, &cam, rect); + let mut camera = GraphCamera { origin: rect.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom }; + camera.zoom_from_input(ui, rect); + app.ui.graph_camera = camera.state(); + super::grid::paint(&painter, &camera, rect); + let pointer = ctx.input(|input| input.pointer.hover_pos()); - let pointer = ctx.input(|i| i.pointer.hover_pos()); - let hovered_canvas = pointer.is_some_and(|p| rect.contains(p)) && resp.hovered(); + let show_thumbnails = app.ui.prefs.thumbnails; + let Ok(graph) = app.session.graph() else { return }; - // Zoom around the pointer - if hovered_canvas || ui.rect_contains_pointer(rect) { - let scroll = ctx.input(|i| i.smooth_scroll_delta.y + i.zoom_delta().ln() * 200.0); - if scroll.abs() > 0.0 - && let Some(p) = pointer - && rect.contains(p) - { - let before = cam.to_graph(p); - let zoom = (cam.zoom * (scroll * 0.0025).exp()).clamp(0.08, 4.0); - let pan = before.to_vec2() - (p - rect.min) / zoom; - app.ui.graph_camera = crate::state::GraphCamera { pan: [pan.x, pan.y], zoom }; - } - } - let cam = GraphCamera { origin: rect.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom.clamp(0.08, 4.0) }; - - let thumbs_on = app.ui.prefs.thumbnails; - let Ok(g) = app.session.graph() else { return }; - let g = g.clone(); - let selection = app.session.selection.clone(); + let index = materialcraft_engine::core::GraphIndex::new(graph); + let selection: std::collections::BTreeSet<_> = app.session.selection.iter().copied().collect(); let node_delta = match &app.graph.drag { Some(GraphDrag::Nodes { delta }) => *delta, _ => Vec2::ZERO, @@ -323,40 +72,42 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { // Layout every node and its ports - let mut laid: Vec = Vec::with_capacity(g.nodes.len()); - for n in &g.nodes { - let (mut ins, outs) = materialcraft_engine::eval::ports(&app.session.pkg, &g, n); - let visible = super::input_visibility::count(ins.iter().map(|port| g.input_of(n.id, &port.id).is_some()), if n.def == "fx_map" { 2 } else { 1 }); + let mut layouts: Vec = Vec::with_capacity(graph.nodes.len()); + for node in &graph.nodes { + let (mut ins, outs) = materialcraft_engine::eval::ports_with_connections(&app.session.pkg, node, index.incoming(node.id).iter().copied()); + let visible = + super::input_visibility::count(ins.iter().map(|port| index.input_of(node.id, &port.id).is_some()), if node.def == "fx_map" { 2 } else { 1 }); ins.truncate(visible); - let mut r = node_rect(n, ins.len(), outs.len(), thumbs_on); - if selection.contains(&n.id) && node_delta.length() > 0.5 { - let position = materialcraft_engine::graph_grid::snap_position([n.pos[0] + node_delta.x, n.pos[1] + node_delta.y], app.ui.prefs.snap_to_grid); - r = r.translate(vec2(position[0] - n.pos[0], position[1] - n.pos[1])); + let mut r = node_rect(node, ins.len(), outs.len(), show_thumbnails); + if selection.contains(&node.id) && node_delta.length() > 0.5 { + let position = materialcraft_engine::graph_grid::translate(node.pos, node_delta.into(), app.ui.prefs.snap_to_grid); + r = r.translate(vec2(position[0] - node.pos[0], position[1] - node.pos[1])); } - r = r.translate(super::annotation_canvas::offset(app, |contents| contents.nodes.contains(&n.id))); - let dot = n.def == "dot"; - let pi = |i: usize, output: bool, total: usize| port_pos(r, i, total, output, dot); - laid.push(NodeLayout { - id: n.id, + r = r.translate(super::annotation_canvas::offset(app, |contents| contents.nodes.contains(&node.id))); + let dot = node.def == "dot"; + let port_position = |i: usize, output: bool, total: usize| port_pos(r, i, total, output, dot); + layouts.push(NodeLayout { + id: node.id, rect: r, - ins: ins.iter().enumerate().map(|(i, p)| (p.id.clone(), p.label.clone(), p.kind, pi(i, false, ins.len()))).collect(), - outs: outs.iter().enumerate().map(|(i, p)| (p.id.clone(), p.label.clone(), p.kind, pi(i, true, outs.len()))).collect(), + ins: ins.iter().enumerate().map(|(i, p)| (p.id.clone(), p.label.clone(), p.kind, port_position(i, false, ins.len()))).collect(), + outs: outs.iter().enumerate().map(|(i, p)| (p.id.clone(), p.label.clone(), p.kind, port_position(i, true, outs.len()))).collect(), }); } - app.graph.rects = laid.iter().map(|l| (l.id, Rect::from_min_max(cam.to_screen(l.rect.min), cam.to_screen(l.rect.max)))).collect(); - app.graph.ports = laid + app.graph.rects = + layouts.iter().map(|layout| (layout.id, Rect::from_min_max(camera.to_screen(layout.rect.min), camera.to_screen(layout.rect.max)))).collect(); + app.graph.ports = layouts .iter() - .flat_map(|l| { - let ins = l.ins.iter().map(move |(id, label, kind, p)| PortHit { - node: l.id, + .flat_map(|layout| { + let ins = layout.ins.iter().map(move |(id, label, kind, p)| PortHit { + node: layout.id, output: false, port: id.clone(), label: label.clone(), pos: *p, kind: *kind, }); - let outs = l.outs.iter().map(move |(id, label, kind, p)| PortHit { - node: l.id, + let outs = layout.outs.iter().map(move |(id, label, kind, p)| PortHit { + node: layout.id, output: true, port: id.clone(), label: label.clone(), @@ -366,14 +117,19 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { ins.chain(outs) }) .map(|mut h| { - h.pos = cam.to_screen(h.pos); + h.pos = camera.to_screen(h.pos); h }) .collect(); - let frame_hits = super::annotation_canvas::frames(app, ui, &g, &cam); + let frame_hits = super::annotation_canvas::frames(app, ui, &graph.frames, &camera); app.graph.frames = frame_hits.iter().map(|frame| (frame.id, frame.rect)).collect(); + let mut layout_indices = std::collections::BTreeMap::new(); + for (index, layout) in layouts.iter().enumerate() { + layout_indices.entry(layout.id).or_insert(index); + } + // Wires let cooked = &app.session.cooked; let detached = match &app.graph.drag { @@ -381,15 +137,15 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { _ => None, }; - let mut wires: Vec<(WireRef, [Pos2; 4])> = Vec::with_capacity(g.connections.len()); - for c in &g.connections { - if detached.as_ref().is_some_and(|(n, p)| *n == c.to && *p == c.to_port) { + let mut wires: Vec<(WireRef, [Pos2; 4])> = Vec::with_capacity(graph.connections.len()); + for c in &graph.connections { + if detached.as_ref().is_some_and(|(node, p)| *node == c.to && *p == c.to_port) { continue; } - let a = laid.iter().find(|l| l.id == c.from).and_then(|l| l.outs.iter().find(|p| p.0 == c.from_port)); - let b = laid.iter().find(|l| l.id == c.to).and_then(|l| l.ins.iter().find(|p| p.0 == c.to_port)); + let a = layout_indices.get(&c.from).and_then(|index| layouts.get(*index)).and_then(|layout| layout.outs.iter().find(|p| p.0 == c.from_port)); + let b = layout_indices.get(&c.to).and_then(|index| layouts.get(*index)).and_then(|layout| layout.ins.iter().find(|p| p.0 == c.to_port)); if let (Some(a), Some(b)) = (a, b) { - wires.push(((c.to, c.to_port.clone()), bezier_points(cam.to_screen(a.3), cam.to_screen(b.3)))); + wires.push(((c.to, c.to_port.clone()), bezier_points(camera.to_screen(a.3), camera.to_screen(b.3)))); } } // Hover: not where a node card or a port sits on top of the wire @@ -401,17 +157,18 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { }; for (w, ctrl) in &wires { - let Some(c) = g.input_of(w.0, &w.1) else { continue }; + let Some(c) = index.input_of(w.0, &w.1) else { continue }; + let hot = selection.contains(&c.from) || selection.contains(&c.to); let picked = app.graph.selected_wires.contains(w); let hovered = wire_hover.as_ref() == Some(w); - let base = (2.0 * cam.zoom).clamp(1.0, 3.0); + let base = (2.0 * camera.zoom).clamp(1.0, 3.0); let stroke = if picked { - Stroke::new(base + 2.0, tk.accent) + Stroke::new(base + 2.0, theme.accent) } else if hovered { Stroke::new(base + 1.0, Color32::WHITE) } else { - Stroke::new(base, if hot { tk.accent } else { Color32::from_gray(0xb4) }) + Stroke::new(base, if hot { theme.accent } else { Color32::from_gray(0xb4) }) }; painter.add(egui::epaint::CubicBezierShape::from_points_stroke(*ctrl, false, Color32::TRANSPARENT, stroke)); @@ -419,80 +176,82 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { app.graph.wires = wires; // Nodes - let font = FontId::proportional((10.5 * cam.zoom).clamp(6.0, 16.0)); - let small = FontId::proportional((9.0 * cam.zoom).clamp(5.5, 13.0)); - let mut node_resps: Vec<(NodeId, egui::Response)> = Vec::new(); - for l in &laid { - let Ok(n) = g.node(l.id) else { continue }; - let sr = Rect::from_min_max(cam.to_screen(l.rect.min), cam.to_screen(l.rect.max)); - if !sr.intersects(rect) { + let font = FontId::proportional((10.5 * camera.zoom).clamp(6.0, 16.0)); + let small = FontId::proportional((9.0 * camera.zoom).clamp(5.5, 13.0)); + let mut node_responses: Vec<(NodeId, egui::Response)> = Vec::new(); + for layout in &layouts { + let Some(node) = index.node(layout.id) else { continue }; + + let screen_rect = Rect::from_min_max(camera.to_screen(layout.rect.min), camera.to_screen(layout.rect.max)); + if !screen_rect.intersects(rect) { continue; } - let selected = selection.contains(&n.id); - let result = cooked.nodes.get(&n.id); - let error = result.and_then(|r| r.error.clone()); - let resp = ui.interact(sr, ui.scope_id().with(("node", n.id.0)), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Button, &node_label(n)); - if n.def == "dot" { - node_card::paint_dot(&painter, sr, if selected { tk.accent } else { Color32::from_gray(0xb4) }); + let selected = selection.contains(&node.id); + let result = cooked.nodes.get(&node.id); + let error = result.and_then(|r| r.error.as_ref()); + let resp = ui.interact(screen_rect, ui.scope_id().with(("node", node.id.0)), Sense::click_and_drag()); + crate::widgets::name(&resp, egui::Role::Button, &node_label(node)); + if node.def == "dot" { + node_card::paint_dot(&painter, screen_rect, if selected { theme.accent } else { Color32::from_gray(0xb4) }); } else { - node_card::paint(&painter, sr, cam.zoom, &node_label(n), header_color(&n.def)); - let header = node_card::header(sr, cam.zoom); - let body = node_card::body(sr, cam.zoom); + node_card::paint(&painter, screen_rect, camera.zoom, &node_label(node), header_color(&node.def)); + let header = node_card::header(screen_rect, camera.zoom); + let body = node_card::body(screen_rect, camera.zoom); if let Some(r0) = result && let Some(img) = r0.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image) - && thumbs_on + && show_thumbnails && !app.graph.thumbnails_cleared { - let side = body.width().min(body.height()) - 6.0 * cam.zoom; + let side = body.width().min(body.height()) - 6.0 * camera.zoom; let tr_ = Rect::from_center_size(body.center(), vec2(side, side)); let tex = app.thumbs.node(&ctx, r0.key, 0, img); - painter.image(tex, tr_, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), if n.disabled { Color32::from_gray(90) } else { Color32::WHITE }); + painter.image(tex, tr_, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), if node.disabled { Color32::from_gray(90) } else { Color32::WHITE }); } else if let Some(value) = result.and_then(|result| result.outputs.first()).and_then(materialcraft_engine::eval::NodeOutput::as_value) { let text = match value { materialcraft_engine::core::Value::Float(value) => value.to_string(), _ => serde_json::to_value(value).ok().and_then(|value| value.get("v").map(ToString::to_string)).unwrap_or_default(), }; - let text = crate::widgets::elided(&painter, text, font.size, tk.text, body.width() - 8.0); - painter.galley(body.center() - text.size() * 0.5, text, tk.text); + let text = crate::widgets::elided(&painter, text, font.size, theme.text, body.width() - 8.0); + painter.galley(body.center() - text.size() * 0.5, text, theme.text); } else if result.is_none() { - painter.text(body.center(), Align2::CENTER_CENTER, icon::HOURGLASS_MEDIUM, small.clone(), tk.text_dim); + painter.text(body.center(), Align2::CENTER_CENTER, icon::HOURGLASS_MEDIUM, small.clone(), theme.text_dim); } // Footer: size and format - let footer = Rect::from_min_max(pos2(sr.left(), body.bottom()), sr.max); + let footer = Rect::from_min_max(pos2(screen_rect.left(), body.bottom()), screen_rect.max); if let Some(img) = result.and_then(|r| r.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image)) { - let bits = if n.base.format == materialcraft_engine::core::OutputFormat::Inherit { g.format.bits() } else { n.base.format.bits() }; + let bits = if node.base.format == materialcraft_engine::core::OutputFormat::Inherit { graph.format.bits() } else { node.base.format.bits() }; + let txt = format!("{}x{} - {}{}", img.w, img.h, if img.is_gray() { "L" } else { "C" }, bits); - painter.text(footer.center(), Align2::CENTER_CENTER, txt, small.clone(), tk.text_dim); + painter.text(footer.center(), Align2::CENTER_CENTER, txt, small.clone(), theme.text_dim); } - if n.def == "output" { + if node.def == "output" { painter.text(header.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, icon::SIGN_OUT, small.clone(), Color32::WHITE); } let outline = if error.is_some() { Stroke::new(2.0, Color32::from_rgb(0xff, 0x30, 0xd0)) } else if selected { - Stroke::new(2.0, tk.accent) + Stroke::new(2.0, theme.accent) } else if resp.hovered() { Stroke::new(1.0, Color32::from_gray(0x90)) } else { Stroke::new(1.0, Color32::from_gray(0x10)) }; - node_card::outline(&painter, sr, cam.zoom, outline); - if n.disabled { - painter.line_segment([sr.left_top(), sr.right_bottom()], Stroke::new(1.5, tk.danger)); + node_card::outline(&painter, screen_rect, camera.zoom, outline); + if node.disabled { + painter.line_segment([screen_rect.left_top(), screen_rect.right_bottom()], Stroke::new(1.5, theme.danger)); } - if let Some(e) = &error { + if let Some(e) = error { resp.clone().on_hover_text(e); } } - node_resps.push((n.id, resp)); + node_responses.push((node.id, resp)); } - let comment_hits = super::annotation_canvas::comments(app, ui, &g, &cam); + let comment_hits = super::annotation_canvas::comments(app, ui, &graph.comments, &camera); app.graph.comments = comment_hits.clone(); - super::annotation_canvas::pins(app, ui, &g, &cam); + super::annotation_canvas::pins(app, ui, &graph.pins, &camera); // Ports (drawn last, interactable over the node cards) let port_hover = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 9.0)).cloned(); @@ -501,7 +260,8 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { continue; } let hot = port_hover.as_ref().is_some_and(|x| x.node == h.node && x.port == h.port && x.output == h.output); - let r = (PORT_R * cam.zoom).clamp(2.5, 7.0) * if hot { 1.4 } else { 1.0 }; + let r = (PORT_RADIUS * camera.zoom).clamp(2.5, 7.0) * if hot { 1.4 } else { 1.0 }; + painter.circle(h.pos, r, port_color(h.kind), Stroke::new(1.0, Color32::from_gray(0x18))); } let hovered_node = app.graph.rects.iter().rev().find(|(_, bounds)| super::port_label::visible(ui, *bounds)).map(|(id, _)| *id); @@ -511,8 +271,10 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { } let anchor = if port.output { Align2::LEFT_CENTER } else { Align2::RIGHT_CENTER }; + let offset = if port.output { vec2(10.0, 0.0) } else { vec2(-10.0, 0.0) }; - super::port_label::paint(&painter, port.pos + offset, anchor, &port.label, cam.zoom, tk.text_strong); + + super::port_label::paint(&painter, port.pos + offset, anchor, &port.label, camera.zoom, theme.text_strong); } // A wire under a comment is not hit @@ -521,706 +283,34 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { ctx.set_cursor_icon(egui::CursorIcon::PointingHand); } app.graph.inspected_node = super::node_selection::inspected(&app.session.selection, app.graph.inspected_node); - handle_input(app, ui, &resp, rect, &cam, &node_resps, &frame_hits, &comment_hits, port_hover, wire_hover); + super::input::handle(app, ui, &resp, rect, &camera, &node_responses, &frame_hits, &comment_hits, port_hover, wire_hover); app.graph.inspected_node = super::node_selection::inspected(&app.session.selection, app.graph.inspected_node); // GraphDrag previews match &app.graph.drag { Some(GraphDrag::Box { start }) => { if let Some(p) = pointer { - let r = Rect::from_two_pos(*start, p); - painter.rect(r, 0.0, tk.accent.gamma_multiply(0.12), Stroke::new(1.0, tk.accent), StrokeKind::Inside); + super::node_selection::paint_box(&painter, *start, p, theme.accent); } } Some(GraphDrag::Wire { from, .. }) => { if let (Some(p), Some(src)) = (pointer, app.graph.ports.iter().find(|h| h.output && h.node == from.0 && h.port == from.1)) { - bezier(&painter, src.pos, p, Stroke::new(2.0, tk.accent)); + bezier(&painter, src.pos, p, Stroke::new(2.0, theme.accent)); } } _ => {} } - search_popup(app, ui, &cam); + super::search::show(app, ui, &camera); let (failed, placeholders) = app.session.cook_failures(); let mut at = rect.right_bottom() - vec2(8.0, 8.0); if !failed.is_empty() { let text = format!("{} {} node(s) failed", icon::WARNING, failed.len()); - at.y = painter.text(at, Align2::RIGHT_BOTTOM, text, FontId::proportional(11.0), tk.danger).top() - 2.0; + at.y = painter.text(at, Align2::RIGHT_BOTTOM, text, FontId::proportional(11.0), theme.danger).top() - 2.0; } // Placeholders for missing SBS nodes are a soft warning, not a failure if placeholders > 0 { let text = format!("{} {placeholders} missing node(s), see the Console", icon::WARNING); - painter.text(at, Align2::RIGHT_BOTTOM, text, FontId::proportional(11.0), tk.warning); - } -} - -pub(crate) fn grid(p: &egui::Painter, cam: &GraphCamera, rect: Rect) { - for (step, alpha) in [(materialcraft_engine::graph_grid::GRID_SPACING, 10u8), (256.0, 22)] { - let s = step * cam.zoom; - if s < 8.0 { - continue; - } - let col = Color32::from_white_alpha(alpha); - let x0 = cam.pan.x - (cam.pan.x.rem_euclid(step)); - let mut x = x0; - while cam.to_screen(pos2(x, 0.0)).x < rect.right() { - let sx = cam.to_screen(pos2(x, 0.0)).x; - p.line_segment([pos2(sx, rect.top()), pos2(sx, rect.bottom())], Stroke::new(1.0, col)); - x += step; - } - let y0 = cam.pan.y - (cam.pan.y.rem_euclid(step)); - let mut y = y0; - while cam.to_screen(pos2(0.0, y)).y < rect.bottom() { - let sy = cam.to_screen(pos2(0.0, y)).y; - p.line_segment([pos2(rect.left(), sy), pos2(rect.right(), sy)], Stroke::new(1.0, col)); - y += step; - } - } -} - -fn nearest_port(ports: &[PortHit], p: Pos2, radius: f32) -> Option<&PortHit> { - ports.iter().filter(|h| h.pos.distance(p) <= radius).min_by(|a, b| a.pos.distance(p).total_cmp(&b.pos.distance(p))) -} - -#[allow(clippy::too_many_arguments)] -fn handle_input( - app: &mut MaterialCraftApp, - ui: &mut Ui, - canvas: &egui::Response, - rect: Rect, - cam: &GraphCamera, - nodes: &[(NodeId, egui::Response)], - frames: &[super::frame_hit::FrameHit], - comments: &[(u64, Rect)], - port_hover: Option, - wire_hover: Option, -) { - let ctx = ui.ctx().clone(); - let (pointer, mods, primary_pressed, primary_down, middle_down, released) = ctx.input(|i| { - (i.pointer.interact_pos(), i.modifiers, i.pointer.primary_pressed(), i.pointer.primary_down(), i.pointer.middle_down(), i.pointer.any_released()) - }); - let zoom = cam.zoom; - let motion = ctx.input(|i| i.pointer.delta()) / zoom; - - // Starting gestures (only on a press inside the canvas, with no gesture running) - if app.graph.drag.is_none() - && let Some(p) = pointer - && rect.contains(p) - && app.graph.search.is_none() - { - if middle_down || (primary_pressed && mods.alt) { - app.graph.drag = Some(GraphDrag::Pan); - } else if primary_pressed { - if app.session.annotation_selection.is_some() { - app.run("graph.annotation.select", json!({})); - } - - let on_card = nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p)); - let wire = wire_hover.as_ref().filter(|_| port_hover.is_none() && !on_card); - // Any press other than on a wire drops the wire selection - if wire.is_none() { - app.graph.selected_wires.clear(); - } - if let Some(w) = wire { - app.graph.drag = Some(GraphDrag::WirePress { wire: w.clone(), start: p }); - } else if let Some(h) = &port_hover { - if h.output { - app.graph.drag = Some(GraphDrag::Wire { from: (h.node, h.port.clone()), detached: None }); - } else if let Some(c) = app.session.graph().ok().and_then(|g| g.input_of(h.node, &h.port).cloned()) { - app.graph.drag = Some(GraphDrag::Wire { from: (c.from, c.from_port.clone()), detached: Some((h.node, h.port.clone())) }); - } - } else if let Some((id, _)) = comments.iter().rev().find(|(_, r)| r.contains(p)) { - app.run("graph.annotation.select", json!({"kind": "comment", "id": id})); - app.graph.drag = Some(GraphDrag::Comment { id: *id, delta: Vec2::ZERO }); - } else if let Some((id, _)) = nodes.iter().rev().find(|(_, r)| r.rect.contains(p)) { - super::node_selection::select(&mut app.session.selection, Some(*id), mods); - app.graph.drag = Some(GraphDrag::Nodes { delta: Vec2::ZERO }); - } else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(p)) { - let resize = hit.grip.contains(p); - let contents = app - .session - .graph() - .ok() - .and_then(|graph| { - graph.frames.iter().find(|frame| frame.id == hit.id).map(|frame| materialcraft_engine::FrameContents::capture(graph, frame)) - }) - .unwrap_or_default(); - app.run("graph.annotation.select", json!({"kind": "frame", "id": hit.id})); - app.graph.drag = Some(GraphDrag::Frame { id: hit.id, delta: Vec2::ZERO, resize, contents }); - } else { - app.graph.drag = Some(GraphDrag::Box { start: p }); - } - } - } - - // Continuing gestures - match &mut app.graph.drag { - Some(GraphDrag::Pan) => { - let d = ctx.input(|i| i.pointer.delta()) / zoom; - app.ui.graph_camera.pan = [app.ui.graph_camera.pan[0] - d.x, app.ui.graph_camera.pan[1] - d.y]; - } - Some(GraphDrag::Nodes { delta }) | Some(GraphDrag::Frame { delta, .. }) | Some(GraphDrag::Comment { delta, .. }) => *delta += motion, - Some(GraphDrag::WirePress { wire, start }) => { - // Dragged far enough: a reroute dot where the press was, carried by the pointer - if let Some(p) = pointer - && p.distance(*start) > 4.0 - { - let (wire, start) = (wire.clone(), *start); - let at = cam.to_graph(start); - app.graph.drag = None; - if app.run("graph.wire.insertDot", json!({"to": wire.0.0, "toPort": wire.1, "at": [at.x, at.y]})).is_some() { - app.graph.drag = Some(GraphDrag::Nodes { delta: (p - start) / zoom }); - } - } - } - _ => {} - } - - // Ending gestures - let ended = released && !primary_down && !middle_down; - if ended && let Some(drag) = app.graph.drag.take() { - match drag { - GraphDrag::Pan => {} - GraphDrag::WirePress { wire, .. } => { - app.session.selection.clear(); - let sel = &mut app.graph.selected_wires; - if mods.ctrl && sel.contains(&wire) { - // Ctrl+click toggles a wire out of the selection - sel.retain(|w| *w != wire); - } else if mods.ctrl || mods.shift { - if !sel.contains(&wire) { - sel.push(wire); - } - } else { - *sel = vec![wire]; - } - } - GraphDrag::Nodes { delta } => { - if delta.length() > 0.5 { - app.run("graph.node.move", json!({"by": [delta.x, delta.y]})); - } - } - GraphDrag::Box { start } => { - if let Some(p) = pointer { - let r = Rect::from_two_pos(start, p); - if r.width() > 3.0 || r.height() > 3.0 { - let hit: Vec = app.graph.rects.iter().filter(|(_, nr)| r.intersects(*nr)).map(|(id, _)| *id).collect(); - if mods.ctrl || mods.shift { - for id in hit { - if !app.session.selection.contains(&id) { - app.session.selection.push(id); - } - } - } else { - app.session.selection = hit; - } - } else { - super::node_selection::select(&mut app.session.selection, None, mods); - } - } - } - GraphDrag::Wire { from, detached } => { - let target = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 12.0)).filter(|h| !h.output).cloned(); - match target { - Some(t) => { - let mut parameters = json!({"from": from.0.0, "fromPort": from.1, "to": t.node.0, "toPort": t.port}); - if let Some((node, port)) = detached { - parameters["detach"] = json!({"to": node.0, "toPort": port}); - } - - app.run("graph.connect", parameters); - } - None => { - if let Some((n, p)) = &detached { - app.run("graph.disconnect", json!({"to": n.0, "toPort": p})); - } else if let Some(p) = pointer - && rect.contains(p) - { - open_search(app, cam.to_graph(p), Some(from)); - } - } - } - } - GraphDrag::Frame { id, delta, resize, .. } => { - if delta.length() > 0.5 { - if resize { - if let Some(frame) = app.session.graph().ok().and_then(|graph| graph.frames.iter().find(|frame| frame.id == id)) { - let rect = [frame.rect[0], frame.rect[1], frame.rect[2] + delta.x, frame.rect[3] + delta.y]; - app.run("graph.frame.edit", json!({"id": id, "rect": rect})); - } - } else { - app.run("graph.frame.move", json!({"id": id, "by": [delta.x, delta.y]})); - } - } - } - GraphDrag::Comment { id, delta } => { - if delta.length() > 0.5 - && let Some(c) = app.session.graph().ok().and_then(|g| g.comments.iter().find(|c| c.id == id)).cloned() - { - app.run("graph.comment.edit", json!({"id": id, "at": [c.pos[0] + delta.x, c.pos[1] + delta.y]})); - } - } - } - } - - // Clicks - for (id, r) in nodes { - if r.double_clicked() { - let def = app.session.graph().ok().and_then(|g| g.node(*id).ok()).map(|n| (n.def.clone(), n.params.get("graph").cloned())); - match def { - Some((d, Some(Value::Text(name)))) if d == "graph_instance" => { - app.run("graph.open", json!({"graph": name})); - } - Some((d, _)) if d == "pixel_processor" || d == "value_processor" => { - app.run("view.2d", json!({"node": id.0, "port": 0})); - app.function_editor = Some(crate::function::FunctionEditor::new(*id, crate::function::FunctionTarget::Parameter("function".into()))); - } - _ => { - app.run("view.2d", json!({"node": id.0, "port": 0})); - } - } - } else if r.clicked() && app.session.selection.contains(id) && app.session.view2d.node != Some(*id) { - // Keep the current output when deselecting or clicking the node already shown - app.run("view.2d", json!({"node": id.0})); - } - if r.secondary_clicked() - && let Some(pointer) = pointer - { - app.graph.menu_at = cam.to_graph(pointer); - } - - let at = app.graph.menu_at; - r.context_menu(|ui| super::context_menu::show(app, ui, at, Some(*id))); - } - if let Some(h) = &port_hover - && h.output - && ctx.input(|i| i.pointer.primary_clicked()) - { - let idx = app.session.output_ports(h.node).iter().position(|p| *p == h.port).unwrap_or(0); - app.run("view.2d", json!({"node": h.node.0, "port": idx})); - } - let on_node = pointer.is_some_and(|p| { - nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p)) || frames.iter().any(|frame| frame.contains(p)) - }); - if canvas.double_clicked() - && !on_node - && let Some(p) = pointer - { - match &wire_hover { - // Double-click a wire: a reroute dot there - Some(w) => { - let at = cam.to_graph(p); - app.run("graph.wire.insertDot", json!({"to": w.0.0, "toPort": w.1, "at": [at.x, at.y]})); - app.graph.selected_wires.clear(); - } - None => open_search(app, cam.to_graph(p), None), - } - } - if canvas.secondary_clicked() - && let Some(p) = pointer - { - app.graph.menu_at = cam.to_graph(p); - if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(p)) { - app.run("graph.annotation.select", json!({"kind": "comment", "id": id})); - } else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(p)) { - app.run("graph.annotation.select", json!({"kind": "frame", "id": hit.id})); - } - app.graph.menu_wire = wire_hover.clone().filter(|_| !on_node); - // Right-clicking a selected wire keeps the selection (to swap or delete them all) - if let Some(w) = &app.graph.menu_wire - && !app.graph.selected_wires.contains(w) - { - app.session.selection.clear(); - app.graph.selected_wires = vec![w.clone()]; - } - } - let at = app.graph.menu_at; - canvas.context_menu(|ui| match app.graph.menu_wire.clone() { - Some(w) => wire_menu(app, ui, w, at), - None => super::context_menu::show(app, ui, at, None), - }); - - // Library drops - if let Some(payload) = canvas.dnd_release_payload::() - && let Some(p) = pointer - { - let gp = cam.to_graph(p); - let at = [gp.x - NODE_W * 0.5, gp.y - 20.0]; - match payload.0.strip_prefix('@') { - Some(graph) => app.run("graph.node.add", json!({"def": "graph_instance", "at": at, "params": {"graph": graph}})), - None => app.run("graph.node.add", json!({"def": payload.0, "at": at})), - }; - } - - // Keys over the canvas - let hovered = pointer.is_some_and(|p| rect.contains(p)); - if hovered && app.graph.search.is_none() { - let space = !ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::Space)); - let tab = !app.graph.keyboard_was_focused && !ctx.text_edit_focused() && ctx.input(|i| i.key_pressed(egui::Key::Tab)); - if (space || tab) - && let Some(p) = pointer - { - open_search(app, cam.to_graph(p), None); - } - if !ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::F) && i.modifiers.is_none()) { - let sel = !app.session.selection.is_empty(); - frame(app, rect, sel); - } - } -} - -fn open_search(app: &mut MaterialCraftApp, at: Pos2, connect: Option<(NodeId, String)>) { - app.graph.search = Some(NodeSearch { at, text: String::new(), sel: 0, connect, focus: true }); -} - -/// Catalog entries matching `text` (label or id contains every word) -fn matches(text: &str) -> Vec<&'static materialcraft_engine::nodes::NodeDefinition> { - let words: Vec = text.split_whitespace().map(str::to_ascii_lowercase).collect(); - let mut v: Vec<_> = materialcraft_engine::nodes::catalog() - .iter() - .filter(|d| d.id != "graph_instance") - .filter(|d| { - let hay = format!("{} {} {}", d.label.to_ascii_lowercase(), d.id, d.category.to_ascii_lowercase()); - words.iter().all(|w| hay.contains(w.as_str())) - }) - .collect(); - if let Some(w) = words.first() { - v.sort_by_key(|d| !d.label.to_ascii_lowercase().starts_with(w.as_str())); - } - v -} - -fn search_popup(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &GraphCamera) { - let Some(s) = app.graph.search.as_mut() else { return }; - let tk = Tokens::get(ui.ctx()); - let screen = cam.to_screen(s.at); - let mut close = false; - let mut pick: Option<&'static str> = None; - egui::Area::new(egui::Id::unique("node-search")).fixed_pos(screen).order(egui::Order::Foreground).show(ui.ctx(), |ui| { - egui::Frame::popup(ui.style()).show(ui, |ui| { - ui.set_width(260.0); - ui.horizontal(|ui| { - ui.label(egui::RichText::new(icon::MAGNIFYING_GLASS).color(tk.text_dim)); - let r = ui.add(egui::TextEdit::singleline(&mut s.text).hint_text(tr("Search nodes...")).desired_width(220.0)); - crate::widgets::name(&r, egui::Role::SearchInput, "Search nodes"); - if s.focus { - r.request_focus(); - s.focus = false; - } - if r.changed() { - s.sel = 0; - } - }); - let list = matches(&s.text); - let (up, down, enter, esc) = ui.input(|i| { - (i.key_pressed(egui::Key::ArrowUp), i.key_pressed(egui::Key::ArrowDown), i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape)) - }); - if down { - s.sel = (s.sel + 1).min(list.len().saturating_sub(1)); - } - if up { - s.sel = s.sel.saturating_sub(1); - } - if esc { - close = true; - } - if enter && let Some(d) = list.get(s.sel) { - pick = Some(d.id); - } - egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| { - for (i, d) in list.iter().enumerate().take(60) { - let r = ui.add( - egui::Button::selectable(i == s.sel, format!("{} ", d.label)) - .right_text(egui::RichText::new(d.group()).size(10.0).color(tk.text_dim)), - ); - if i == s.sel && (up || down) { - r.scroll_to_me(None); - } - if r.clicked() { - pick = Some(d.id); - } - } - if list.is_empty() { - ui.label(egui::RichText::new(tr("No matching node")).color(tk.text_dim)); - } - }); - }); - }); - let clicked_out = ui.input(|i| i.pointer.any_pressed()) - && ui.ctx().pointer_interact_pos().is_some_and(|p| !ui.ctx().layer_id_at(p).is_some_and(|l| l.id == egui::Id::unique("node-search"))); - if let Some(def) = pick { - let s = app.graph.search.take(); - if let Some(s) = s { - let mut p = json!({"def": def, "at": [s.at.x, s.at.y - 20.0]}); - if let Some((n, port)) = s.connect { - p["connectFrom"] = json!({"node": n.0, "port": port}); - } - app.run("graph.node.add", p); - } - } else if close || clicked_out { - app.graph.search = None; - } -} - -/// `wires` as the `{wires: [{to, toPort}, ...]}` parameter of the wire commands -fn wires_json(wires: &[WireRef]) -> serde_json::Value { - json!({"wires": wires.iter().map(|(to, port)| json!({"to": to.0, "toPort": port})).collect::>()}) -} - -/// Delete the selected wires in one undo step (the Delete and Backspace keys); `false` when none is selected -pub fn delete_selected_wires(app: &mut MaterialCraftApp) -> bool { - let wires = std::mem::take(&mut app.graph.selected_wires); - if wires.is_empty() { - return false; - } - app.run("graph.wire.delete", wires_json(&wires)); - true -} - -/// Reverse the sources of selected wires so pressing X again restores them -pub fn swap_selected_wires(app: &mut MaterialCraftApp) -> bool { - if app.graph.selected_wires.is_empty() { - return false; - } - let params = wires_json(&app.graph.selected_wires); - app.run("graph.wire.swap", params); - true -} - -fn wire_menu(app: &mut MaterialCraftApp, ui: &mut Ui, (to, port): WireRef, at: Pos2) { - let n = app.graph.selected_wires.len(); - if ui.button(format!("{} {}", icon::DOT_OUTLINE, tr("Insert reroute dot"))).clicked() { - app.run("graph.wire.insertDot", json!({"to": to.0, "toPort": port, "at": [at.x, at.y]})); - app.graph.selected_wires.clear(); - ui.close(); - } - if n >= 2 && ui.button(format!("{} {} (X)", icon::ARROWS_LEFT_RIGHT, tr("Swap selected links"))).clicked() { - swap_selected_wires(app); - ui.close(); - } - let label = if n >= 2 { tr("Delete selected links") } else { tr("Delete link") }; - if ui.button(format!("{} {label}", icon::TRASH)).clicked() { - if n < 2 { - app.graph.selected_wires = vec![(to, port)]; - } - delete_selected_wires(app); - ui.close(); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - use super::super::frames::Frames; - - /// Three primitive nodes framed on screen - fn three_nodes() -> (Frames, [NodeId; 3]) { - let mut s = materialcraft_engine::sample_session(); - materialcraft_engine::execute(&mut s, "file.new", &json!({"template": "empty", "size": 256})).unwrap(); - let ids = ["uniform", "uniform", "channels_shuffle"].iter().enumerate().map(|(i, def)| { - let added = materialcraft_engine::execute(&mut s, "graph.node.add", &json!({"def": def, "at": [i as f32 * 300.0, 0.0]})).unwrap(); - NodeId(added["id"].as_u64().unwrap()) - }); - let ids: [NodeId; 3] = ids.collect::>().try_into().unwrap(); - s.selection.clear(); - (Frames::new(s), ids) - } - - #[test] - fn clicking_a_node_shows_it_in_the_2d_view() { - let (mut f, [noise, checker, _]) = three_nodes(); - // Shown explicitly first (a double-click, an output port or "View in 2D view") - f.app.run("view.2d", json!({"node": noise.0})); - assert_eq!(f.shown(), Some(noise)); - let at = f.center(checker); - f.click(at, egui::Modifiers::NONE); - assert_eq!(f.app.session.selection, vec![checker]); - assert_eq!(f.app.session.view2d.node, Some(checker)); - assert_eq!(f.shown(), Some(checker)); - // And back - let at = f.center(noise); - f.click(at, egui::Modifiers::NONE); - assert_eq!(f.app.session.view2d.node, Some(noise)); - assert_eq!(f.shown(), Some(noise)); - // Ctrl+click adds a node to the selection and shows it too - let at = f.center(checker); - f.click(at, egui::Modifiers::CTRL); - assert_eq!(f.app.session.selection, vec![noise, checker]); - assert_eq!(f.shown(), Some(checker)); - } - - #[test] - fn ctrl_click_that_deselects_a_node_does_not_show_it() { - let (mut f, [noise, checker, _]) = three_nodes(); - f.app.session.selection = vec![noise, checker]; - f.app.run("view.2d", json!({"node": checker.0})); - let at = f.center(noise); - f.click(at, egui::Modifiers::CTRL); - assert_eq!(f.app.session.selection, vec![checker]); - assert_eq!(f.shown(), Some(checker)); - } - - #[test] - fn dragging_a_node_keeps_the_2d_view() { - let (mut f, [noise, checker, _]) = three_nodes(); - f.app.run("view.2d", json!({"node": noise.0})); - let before = f.app.session.graph().unwrap().node(checker).unwrap().pos; - let from = f.center(checker); - let none = egui::Modifiers::NONE; - f.run(vec![egui::Event::PointerMoved(from)], none); - f.run(vec![egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: none }], none); - for step in 1..=8 { - f.run(vec![egui::Event::PointerMoved(from + vec2(5.0 * step as f32, 0.0))], none); - } - let to = from + vec2(40.0, 0.0); - f.run(vec![egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: none }], none); - let after = f.app.session.graph().unwrap().node(checker).unwrap().pos; - let moved = 40.0 / f.app.ui.graph_camera.zoom; - assert_eq!(after, materialcraft_engine::graph_grid::snap_position([before[0] + moved, before[1]], true)); - assert_eq!(f.app.session.selection, vec![checker]); - assert_eq!(f.shown(), Some(noise)); - } - - #[test] - fn clicking_the_shown_node_keeps_its_port() { - let (mut f, [_, _, split]) = three_nodes(); - f.app.run("view.2d", json!({"node": split.0, "port": 2})); - let at = f.center(split); - f.click(at, egui::Modifiers::NONE); - assert_eq!(f.app.session.selection, vec![split]); - assert_eq!((f.app.session.view2d.node, f.app.session.view2d.port), (Some(split), 2)); - } - - #[test] - fn tab_opens_search_in_the_full_workspace() { - let mut f = Frames::new(materialcraft_engine::sample_session()); - let pointer = f.app.graph.view.center(); - let tab = egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - f.run(vec![egui::Event::PointerMoved(pointer), tab], egui::Modifiers::NONE); - assert!(f.app.graph.search.is_some()); - } - - #[test] - fn clicked_wires_swap_with_x_and_delete_together() { - let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); - app.run("file.new", json!({"template": "empty"})); - let id = |v: Option| v.and_then(|v| v["id"].as_u64()).unwrap(); - let a = id(app.run("graph.node.add", json!({"def": "uniform", "at": [0, -150]}))); - let b = id(app.run("graph.node.add", json!({"def": "uniform", "at": [0, 150]}))); - let blend = id(app.run("graph.node.add", json!({"def": "blend", "at": [450, 0]}))); - app.run("graph.connect", json!({"from": a, "to": blend, "toPort": "foreground"})); - app.run("graph.connect", json!({"from": b, "to": blend, "toPort": "background"})); - let ctx = egui::Context::default(); - let mut frame = |app: &mut MaterialCraftApp, mut events: Vec, modifiers: egui::Modifiers| { - events.insert(0, egui::Event::ModifiersChanged(modifiers)); - let input = egui::RawInput { events, ..Default::default() }; - ctx.run_ui(input, |ui| { - app.step(&ui.ctx().clone()); - app.draw(ui); - }) - .textures_delta - .clear(); - }; - - for _ in 0..3 { - frame(&mut app, Vec::new(), egui::Modifiers::NONE); - } - let mid = - |app: &MaterialCraftApp, port: &str| app.graph.wires.iter().find(|(w, _)| w.0.0 == blend && w.1 == port).map(|(_, c)| bezier_at(c, 0.5)).unwrap(); - let click = - |app: &mut MaterialCraftApp, frame: &mut dyn FnMut(&mut MaterialCraftApp, Vec, egui::Modifiers), port: &str, m: egui::Modifiers| { - let p = mid(app, port); - let button = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: m }; - frame(app, vec![egui::Event::PointerMoved(p)], m); - frame(app, vec![button(true)], m); - frame(app, vec![button(false)], m); - }; - - click(&mut app, &mut frame, "foreground", egui::Modifiers::NONE); - click(&mut app, &mut frame, "background", egui::Modifiers::SHIFT); - assert_eq!(app.graph.selected_wires.len(), 2, "{:?}", app.graph.selected_wires); - let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - let src = |app: &MaterialCraftApp, port: &str| app.session.graph().unwrap().input_of(NodeId(blend), port).unwrap().from.0; - frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE); - assert_eq!((src(&app, "foreground"), src(&app, "background")), (b, a)); - // Still selected: X again swaps back - frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE); - assert_eq!((src(&app, "foreground"), src(&app, "background")), (a, b)); - frame(&mut app, vec![key(egui::Key::Delete)], egui::Modifiers::NONE); - assert!(app.session.graph().unwrap().connections.is_empty()); - assert!(app.graph.selected_wires.is_empty()); - } - - #[test] - fn node_search_shortcuts_respect_hover_and_keyboard_focus() { - for key in [egui::Key::Space, egui::Key::Tab] { - for (hovered, editing) in [(true, false), (false, false), (true, true)] { - let ctx = egui::Context::default(); - let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); - let mut text = String::new(); - let mut draw = |ui: &mut Ui| { - if editing { - ui.text_edit_singleline(&mut text).request_focus(); - } - app.graph.keyboard_was_focused = ui.ctx().egui_wants_keyboard_input(); - show(&mut app, ui); - }; - - ctx.run_ui(egui::RawInput::default(), &mut draw).textures_delta.clear(); - let pointer = if hovered { pos2(200.0, 200.0) } else { pos2(-10.0, -10.0) }; - let input = egui::RawInput { - events: vec![ - egui::Event::PointerMoved(pointer), - egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }, - ], - ..Default::default() - }; - - ctx.run_ui(input, &mut draw).textures_delta.clear(); - assert_eq!(app.graph.search.is_some(), hovered && !editing, "{key:?}: hovered={hovered}, editing={editing}"); - if let Some(search) = &app.graph.search { - let cam = GraphCamera { origin: app.graph.view.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom }; - assert_eq!(search.at, cam.to_graph(pointer)); - assert!(search.text.is_empty()); - } - } - } - } - - #[test] - fn search_finds_by_label_and_category() { - assert!(matches("uniform").iter().any(|d| d.id == "uniform")); - assert!(matches("blur").first().is_some_and(|d| d.label.to_ascii_lowercase().starts_with("blur"))); - assert!(matches("noises cells").iter().all(|d| d.category.contains("Noises"))); - assert!(matches("zzzz").is_empty()); - } - - #[test] - fn wires_are_hit_near_their_curve_only() { - let a = (NodeId(1), "input".to_string()); - let b = (NodeId(2), "input".to_string()); - let wires = vec![(a.clone(), bezier_points(pos2(0.0, 0.0), pos2(200.0, 100.0))), (b.clone(), bezier_points(pos2(0.0, 300.0), pos2(200.0, 300.0)))]; - // The midpoint of a symmetric wire lies on the line between its ends - let mid = bezier_at(&wires[0].1, 0.5); - assert!((mid - pos2(100.0, 50.0)).length() < 1e-3, "{mid:?}"); - assert_eq!(wire_at(&wires, mid + vec2(0.0, 3.0)), Some(&a)); - assert_eq!(wire_at(&wires, pos2(100.0, 302.0)), Some(&b)); - assert_eq!(wire_at(&wires, pos2(100.0, 200.0)), None); - assert_eq!(wire_at(&wires, mid + vec2(0.0, WIRE_HIT * 3.0)), None); - // The ends are on the wire - assert!(bezier_distance(&wires[0].1, pos2(0.0, 0.0)) < 1e-3); - assert!(bezier_distance(&wires[0].1, pos2(200.0, 100.0)) < 1e-3); - } - - #[test] - fn port_positions_stay_on_the_card() { - let n = Node::new(NodeId(1), "blend", [0.0, 0.0]); - let r = node_rect(&n, 3, 1, true); - for i in 0..3 { - let p = port_pos(r, i, 3, false, false); - assert!(r.contains(p) || (p.x - r.left()).abs() < 1e-3); - assert!(p.y > r.top() + node_card::HEADER_HEIGHT && p.y < r.bottom() - node_card::FOOTER_HEIGHT); - } + painter.text(at, Align2::RIGHT_BOTTOM, text, FontId::proportional(11.0), theme.warning); } } diff --git a/crates/ui-egui/src/graph/canvas_geometry.rs b/crates/ui-egui/src/graph/canvas_geometry.rs new file mode 100644 index 0000000..c5a88ef --- /dev/null +++ b/crates/ui-egui/src/graph/canvas_geometry.rs @@ -0,0 +1,19 @@ +use super::{GraphView, PortHit, WireRef}; +use egui::{Pos2, Rect}; +use materialcraft_engine::core::NodeId; + +#[derive(Default)] +pub(crate) struct CanvasGeometry { + pub rects: Vec<(NodeId, Rect)>, + pub ports: Vec, + pub wires: Vec<(WireRef, [Pos2; 4])>, +} + +impl CanvasGeometry { + pub fn publish(self, view: &mut GraphView, bounds: Rect) { + view.view = bounds; + view.rects = self.rects; + view.ports = self.ports; + view.wires = self.wires; + } +} diff --git a/crates/ui-egui/src/graph/canvas_tests.rs b/crates/ui-egui/src/graph/canvas_tests.rs new file mode 100644 index 0000000..5462b88 --- /dev/null +++ b/crates/ui-egui/src/graph/canvas_tests.rs @@ -0,0 +1,221 @@ +use super::canvas::*; +use super::node_card::port as port_pos; +use super::search::matches; +use super::wire_geometry::{WIRE_HIT, bezier_at, bezier_distance, bezier_points, wire_at}; +use super::{GraphCamera, node_card, node_rect}; +use crate::MaterialCraftApp; +use egui::{Ui, Vec2, pos2, vec2}; +use materialcraft_engine::core::{Node, NodeId}; +use serde_json::json; + +use super::frames::Frames; + +/// Three primitive nodes framed on screen +fn three_nodes() -> (Frames, [NodeId; 3]) { + let mut s = materialcraft_engine::sample_session(); + materialcraft_engine::execute(&mut s, "file.new", &json!({"template": "empty", "size": 256})).unwrap(); + let ids = ["uniform", "uniform", "channels_shuffle"].iter().enumerate().map(|(i, def)| { + let added = materialcraft_engine::execute(&mut s, "graph.node.add", &json!({"def": def, "at": [i as f32 * 300.0, 0.0]})).unwrap(); + NodeId(added["id"].as_u64().unwrap()) + }); + let ids: [NodeId; 3] = ids.collect::>().try_into().unwrap(); + s.selection.clear(); + (Frames::new(s), ids) +} + +#[test] +fn clicking_a_node_shows_it_in_the_2d_view() { + let (mut f, [noise, checker, _]) = three_nodes(); + // Shown explicitly first (a double-click, an output port or "View in 2D view") + f.app.run("view.2d", json!({"node": noise.0})); + assert_eq!(f.shown(), Some(noise)); + let at = f.center(checker); + f.click(at, egui::Modifiers::NONE); + assert_eq!(f.app.session.selection, vec![checker]); + assert_eq!(f.app.session.view2d.node, Some(checker)); + assert_eq!(f.shown(), Some(checker)); + // And back + let at = f.center(noise); + f.click(at, egui::Modifiers::NONE); + assert_eq!(f.app.session.view2d.node, Some(noise)); + assert_eq!(f.shown(), Some(noise)); + // Ctrl+click adds a node to the selection and shows it too + let at = f.center(checker); + f.click(at, egui::Modifiers::CTRL); + assert_eq!(f.app.session.selection, vec![noise, checker]); + assert_eq!(f.shown(), Some(checker)); +} + +#[test] +fn ctrl_click_that_deselects_a_node_does_not_show_it() { + let (mut f, [noise, checker, _]) = three_nodes(); + f.app.session.selection = vec![noise, checker]; + f.app.run("view.2d", json!({"node": checker.0})); + let at = f.center(noise); + f.click(at, egui::Modifiers::CTRL); + assert_eq!(f.app.session.selection, vec![checker]); + assert_eq!(f.shown(), Some(checker)); +} + +#[test] +fn dragging_a_node_keeps_the_2d_view() { + let (mut f, [noise, checker, _]) = three_nodes(); + f.app.run("view.2d", json!({"node": noise.0})); + let before = f.app.session.graph().unwrap().node(checker).unwrap().pos; + let from = f.center(checker); + let none = egui::Modifiers::NONE; + f.run(vec![egui::Event::PointerMoved(from)], none); + f.run(vec![egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: none }], none); + for step in 1..=8 { + f.run(vec![egui::Event::PointerMoved(from + vec2(5.0 * step as f32, 0.0))], none); + } + let to = from + vec2(40.0, 0.0); + f.run(vec![egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: none }], none); + let after = f.app.session.graph().unwrap().node(checker).unwrap().pos; + let moved = 40.0 / f.app.ui.graph_camera.zoom; + assert_eq!(after, materialcraft_engine::graph_grid::snap_position([before[0] + moved, before[1]], true)); + assert_eq!(f.app.session.selection, vec![checker]); + assert_eq!(f.shown(), Some(noise)); +} + +#[test] +fn clicking_the_shown_node_keeps_its_port() { + let (mut f, [_, _, split]) = three_nodes(); + f.app.run("view.2d", json!({"node": split.0, "port": 2})); + let at = f.center(split); + f.click(at, egui::Modifiers::NONE); + assert_eq!(f.app.session.selection, vec![split]); + assert_eq!((f.app.session.view2d.node, f.app.session.view2d.port), (Some(split), 2)); +} + +#[test] +fn tab_opens_search_in_the_full_workspace() { + let mut f = Frames::new(materialcraft_engine::sample_session()); + let pointer = f.app.graph.view.center(); + let tab = egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + f.run(vec![egui::Event::PointerMoved(pointer), tab], egui::Modifiers::NONE); + assert!(f.app.graph.search.is_some()); +} + +#[test] +fn clicked_wires_swap_with_x_and_delete_together() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); + app.run("file.new", json!({"template": "empty"})); + let id = |v: Option| v.and_then(|v| v["id"].as_u64()).unwrap(); + let a = id(app.run("graph.node.add", json!({"def": "uniform", "at": [0, -150]}))); + let b = id(app.run("graph.node.add", json!({"def": "uniform", "at": [0, 150]}))); + let blend = id(app.run("graph.node.add", json!({"def": "blend", "at": [450, 0]}))); + app.run("graph.connect", json!({"from": a, "to": blend, "toPort": "foreground"})); + app.run("graph.connect", json!({"from": b, "to": blend, "toPort": "background"})); + let ctx = egui::Context::default(); + let mut frame = |app: &mut MaterialCraftApp, mut events: Vec, modifiers: egui::Modifiers| { + events.insert(0, egui::Event::ModifiersChanged(modifiers)); + let input = egui::RawInput { events, ..Default::default() }; + ctx.run_ui(input, |ui| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }) + .textures_delta + .clear(); + }; + + for _ in 0..3 { + frame(&mut app, Vec::new(), egui::Modifiers::NONE); + } + let mid = |app: &MaterialCraftApp, port: &str| app.graph.wires.iter().find(|(w, _)| w.0.0 == blend && w.1 == port).map(|(_, c)| bezier_at(c, 0.5)).unwrap(); + let click = + |app: &mut MaterialCraftApp, frame: &mut dyn FnMut(&mut MaterialCraftApp, Vec, egui::Modifiers), port: &str, m: egui::Modifiers| { + let p = mid(app, port); + let button = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: m }; + frame(app, vec![egui::Event::PointerMoved(p)], m); + frame(app, vec![button(true)], m); + frame(app, vec![button(false)], m); + }; + + click(&mut app, &mut frame, "foreground", egui::Modifiers::NONE); + click(&mut app, &mut frame, "background", egui::Modifiers::SHIFT); + assert_eq!(app.graph.selected_wires.len(), 2, "{:?}", app.graph.selected_wires); + let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let src = |app: &MaterialCraftApp, port: &str| app.session.graph().unwrap().input_of(NodeId(blend), port).unwrap().from.0; + frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE); + assert_eq!((src(&app, "foreground"), src(&app, "background")), (b, a)); + // Still selected: X again swaps back + frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE); + assert_eq!((src(&app, "foreground"), src(&app, "background")), (a, b)); + frame(&mut app, vec![key(egui::Key::Delete)], egui::Modifiers::NONE); + assert!(app.session.graph().unwrap().connections.is_empty()); + assert!(app.graph.selected_wires.is_empty()); +} + +#[test] +fn node_search_shortcuts_respect_hover_and_keyboard_focus() { + for key in [egui::Key::Space, egui::Key::Tab] { + for (hovered, editing) in [(true, false), (false, false), (true, true)] { + let ctx = egui::Context::default(); + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); + let mut text = String::new(); + let mut draw = |ui: &mut Ui| { + if editing { + ui.text_edit_singleline(&mut text).request_focus(); + } + app.graph.keyboard_was_focused = ui.ctx().egui_wants_keyboard_input(); + show(&mut app, ui); + }; + + ctx.run_ui(egui::RawInput::default(), &mut draw).textures_delta.clear(); + let pointer = if hovered { pos2(200.0, 200.0) } else { pos2(-10.0, -10.0) }; + + let input = egui::RawInput { + events: vec![ + egui::Event::PointerMoved(pointer), + egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }, + ], + ..Default::default() + }; + + ctx.run_ui(input, &mut draw).textures_delta.clear(); + assert_eq!(app.graph.search.is_some(), hovered && !editing, "{key:?}: hovered={hovered}, editing={editing}"); + if let Some(search) = &app.graph.search { + let cam = GraphCamera { origin: app.graph.view.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom }; + assert_eq!(search.at, cam.to_graph(pointer)); + assert!(search.text.is_empty()); + } + } + } +} + +#[test] +fn search_finds_by_label_and_category() { + assert!(matches("uniform").iter().any(|d| d.id == "uniform")); + assert!(matches("blur").first().is_some_and(|d| d.label.to_ascii_lowercase().starts_with("blur"))); + assert!(matches("noises cells").iter().all(|d| d.category.contains("Noises"))); + assert!(matches("zzzz").is_empty()); +} + +#[test] +fn wires_are_hit_near_their_curve_only() { + let a = (NodeId(1), "input".to_string()); + let b = (NodeId(2), "input".to_string()); + let wires = vec![(a.clone(), bezier_points(pos2(0.0, 0.0), pos2(200.0, 100.0))), (b.clone(), bezier_points(pos2(0.0, 300.0), pos2(200.0, 300.0)))]; + // The midpoint of a symmetric wire lies on the line between its ends + let mid = bezier_at(&wires[0].1, 0.5); + assert!((mid - pos2(100.0, 50.0)).length() < 1e-3, "{mid:?}"); + assert_eq!(wire_at(&wires, mid + vec2(0.0, 3.0)), Some(&a)); + assert_eq!(wire_at(&wires, pos2(100.0, 302.0)), Some(&b)); + assert_eq!(wire_at(&wires, pos2(100.0, 200.0)), None); + assert_eq!(wire_at(&wires, mid + vec2(0.0, WIRE_HIT * 3.0)), None); + // The ends are on the wire + assert!(bezier_distance(&wires[0].1, pos2(0.0, 0.0)) < 1e-3); + assert!(bezier_distance(&wires[0].1, pos2(200.0, 100.0)) < 1e-3); +} + +#[test] +fn port_positions_stay_on_the_card() { + let n = Node::new(NodeId(1), "blend", [0.0, 0.0]); + let r = node_rect(&n, 3, 1, true); + for i in 0..3 { + let p = port_pos(r, i, 3, false, false); + assert!(r.contains(p) || (p.x - r.left()).abs() < 1e-3); + assert!(p.y > r.top() + node_card::HEADER_HEIGHT && p.y < r.bottom() - node_card::FOOTER_HEIGHT); + } +} diff --git a/crates/ui-egui/src/graph/context_menu.rs b/crates/ui-egui/src/graph/context_menu.rs index ab305ff..194d040 100644 --- a/crates/ui-egui/src/graph/context_menu.rs +++ b/crates/ui-egui/src/graph/context_menu.rs @@ -31,31 +31,24 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2, node: Opti action(app, ui, "Add Dot node", "graph.node.add", json!({"def": "dot", "at": [at.x, at.y]})); ui.separator(); - action(app, ui, "View outputs in 3D view", "ui.graph.viewOutputs", Value::Null); - action(app, ui, "Reset and view outputs in 3D view", "ui.graph.resetViewOutputs", Value::Null); + if let Some(node) = node { + if let Some(parameters) = crate::material_preview_menu::show(ui, &app.session, app.session.graph, node) { + app.run("view.3d.assign", parameters); + } + } else { + action(app, ui, "View outputs in 3D view", "ui.graph.viewOutputs", Value::Null); + action(app, ui, "Reset and view outputs in 3D view", "ui.graph.resetViewOutputs", Value::Null); + } outputs(app, ui, node); action(app, ui, "Compute nodes thumbnails", "ui.graph.computeThumbnails", Value::Null); action(app, ui, "Clear nodes thumbnails", "ui.graph.clearThumbnails", Value::Null); action(app, ui, "Save package", "file.save", Value::Null); - action(app, ui, "Paste", "edit.paste", json!({"at": [at.x, at.y]})); - action(app, ui, "Paste without link", "edit.pasteWithoutLinks", json!({"at": [at.x, at.y]})); - action(app, ui, "Select all", "edit.selectAll", Value::Null); + if let Some(command) = super::edit_menu::selection(ui, |command| menus::enabled(app, command)) { + let parameters = if matches!(command, "edit.paste" | "edit.pasteWithoutLinks") { json!({"at": [at.x, at.y]}) } else { Value::Null }; + app.run(command, parameters); + } action(app, ui, "Previous pin", "ui.graph.previousPin", Value::Null); action(app, ui, "Next pin", "ui.graph.nextPin", Value::Null); - ui.separator(); - - for (label, command) in [ - ("Copy selection", "edit.copy"), - ("Delete selection", "edit.delete"), - ("Delete and relink", "edit.deleteRelink"), - ("Duplicate selection", "edit.duplicate"), - ("Duplicate selection without link", "edit.duplicateWithoutLinks"), - ("Select upstream nodes", "graph.selectUpstream"), - ("Select downstream nodes", "graph.selectDownstream"), - ("Disable selection", "graph.node.disable"), - ] { - action(app, ui, label, command, Value::Null); - } } fn add_nodes(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2) { @@ -101,12 +94,7 @@ fn outputs(app: &mut MaterialCraftApp, ui: &mut Ui, node: Option) { } fn action(app: &mut MaterialCraftApp, ui: &mut Ui, label: &str, command: &str, parameters: Value) { - let mut button = egui::Button::new(tr(label)); - if let Some(shortcut) = menus::shortcut_of(command) { - button = button.shortcut_text(shortcut); - } - - if ui.add_enabled(menus::enabled(app, command), button).clicked() { + if super::edit_menu::button(ui, label, command, menus::enabled(app, command)) { if command.starts_with("ui.") || matches!(command, "file.save" | "graph.node.edit") { menus::invoke(app, ui.ctx(), command); } else { diff --git a/crates/ui-egui/src/graph/edit_menu.rs b/crates/ui-egui/src/graph/edit_menu.rs new file mode 100644 index 0000000..b419bc8 --- /dev/null +++ b/crates/ui-egui/src/graph/edit_menu.rs @@ -0,0 +1,40 @@ +use crate::{i18n::tr, menus}; +use egui::Ui; + +pub(crate) fn button(ui: &mut Ui, label: &str, command: &str, enabled: bool) -> bool { + let mut button = egui::Button::new(tr(label)); + if let Some(shortcut) = menus::shortcut_of(command) { + button = button.shortcut_text(shortcut); + } + let clicked = ui.add_enabled(enabled, button).clicked(); + if clicked { + ui.close(); + } + clicked +} + +pub(crate) fn selection(ui: &mut Ui, enabled: impl Fn(&str) -> bool) -> Option<&'static str> { + let mut chosen = None; + for (label, command) in [ + ("Paste", "edit.paste"), + ("Paste without link", "edit.pasteWithoutLinks"), + ("Select all", "edit.selectAll"), + ("Copy selection", "edit.copy"), + ("Cut selection", "edit.cut"), + ("Delete selection", "edit.delete"), + ("Delete and relink", "edit.deleteRelink"), + ("Duplicate selection", "edit.duplicate"), + ("Duplicate selection without link", "edit.duplicateWithoutLinks"), + ("Select upstream nodes", "graph.selectUpstream"), + ("Select downstream nodes", "graph.selectDownstream"), + ("Disable selection", "graph.node.disable"), + ] { + if command == "edit.copy" { + ui.separator(); + } + if button(ui, label, command, enabled(command)) { + chosen = Some(command); + } + } + chosen +} diff --git a/crates/ui-egui/src/graph/editor_actions.rs b/crates/ui-egui/src/graph/editor_actions.rs new file mode 100644 index 0000000..d1ffcc3 --- /dev/null +++ b/crates/ui-egui/src/graph/editor_actions.rs @@ -0,0 +1,25 @@ +use super::editor_target::EditorTarget; +use crate::MaterialCraftApp; + +pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option { + if command == "ui.graph.parent" { + return Some(super::subgraph_navigation::can_return(app)); + } + match EditorTarget::resolve(app) { + EditorTarget::Function => crate::function::enabled(app, command), + EditorTarget::Pattern => crate::pattern::enabled(app, command), + EditorTarget::Material => None, + } +} + +pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool { + if command == "ui.graph.parent" { + super::subgraph_navigation::parent(app); + return true; + } + match EditorTarget::resolve(app) { + EditorTarget::Function => crate::function::invoke(app, command), + EditorTarget::Pattern => crate::pattern::invoke(app, command), + EditorTarget::Material => false, + } +} diff --git a/crates/ui-egui/src/graph/editor_target.rs b/crates/ui-egui/src/graph/editor_target.rs new file mode 100644 index 0000000..18f7b31 --- /dev/null +++ b/crates/ui-egui/src/graph/editor_target.rs @@ -0,0 +1,31 @@ +use crate::{MaterialCraftApp, function::FunctionTarget}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum EditorTarget { + Material, + Function, + Pattern, +} + +impl EditorTarget { + pub(crate) fn annotation_active(app: &MaterialCraftApp) -> bool { + app.session.annotation_selection.is_some() + && match Self::resolve(app) { + Self::Material => true, + Self::Function => app.function_editor.as_ref().is_some_and(|editor| matches!(editor.target, FunctionTarget::Graph)), + Self::Pattern => false, + } + } + + pub(crate) fn resolve(app: &MaterialCraftApp) -> Self { + if app.function_editor.as_ref().is_some_and(|editor| editor.current(app).is_some()) { + Self::Function + } else if crate::pattern::active(app) { + Self::Pattern + } else if app.session.graph().is_ok_and(|graph| graph.function.is_some()) { + Self::Function + } else { + Self::Material + } + } +} diff --git a/crates/ui-egui/src/graph/gesture.rs b/crates/ui-egui/src/graph/gesture.rs new file mode 100644 index 0000000..94d1868 --- /dev/null +++ b/crates/ui-egui/src/graph/gesture.rs @@ -0,0 +1,13 @@ +use egui::{PointerButton, Ui}; + +pub(crate) fn pan_button(ui: &Ui) -> PointerButton { + if ui.input(|input| input.pointer.button_pressed(PointerButton::Middle)) { PointerButton::Middle } else { PointerButton::Primary } +} + +pub(crate) fn finished(ui: &Ui, owner: PointerButton) -> bool { + ui.input(|input| input.pointer.button_released(owner)) +} + +pub(crate) fn cancelled(ui: &Ui) -> bool { + ui.input(|input| !input.focused || input.key_pressed(egui::Key::Escape)) +} diff --git a/crates/ui-egui/src/graph/graph_camera.rs b/crates/ui-egui/src/graph/graph_camera.rs index 7ce3c3f..cbc75a0 100644 --- a/crates/ui-egui/src/graph/graph_camera.rs +++ b/crates/ui-egui/src/graph/graph_camera.rs @@ -1,4 +1,4 @@ -use egui::{Pos2, Vec2}; +use egui::{Pos2, Rect, Ui, Vec2}; pub(crate) struct GraphCamera { pub(crate) origin: Pos2, @@ -7,10 +7,54 @@ pub(crate) struct GraphCamera { } impl GraphCamera { - pub(crate) fn to_screen(&self, p: Pos2) -> Pos2 { - self.origin + (p.to_vec2() - self.pan) * self.zoom + pub(crate) fn to_screen(&self, position: Pos2) -> Pos2 { + self.origin + (position.to_vec2() - self.pan) * self.zoom } - pub(crate) fn to_graph(&self, s: Pos2) -> Pos2 { - ((s - self.origin) / self.zoom + self.pan).to_pos2() + + pub(crate) fn to_graph(&self, position: Pos2) -> Pos2 { + ((position - self.origin) / self.zoom + self.pan).to_pos2() + } + + pub(crate) fn state(&self) -> crate::state::GraphCamera { + crate::state::GraphCamera { pan: self.pan.into(), zoom: self.zoom } + } + + pub(crate) fn fit(view: Rect, destination: Rect) -> Self { + if !destination.is_finite() || destination.width() <= 0.0 { + let state = crate::state::GraphCamera::default(); + return Self { origin: view.min, pan: state.pan.into(), zoom: state.zoom }; + } + + let destination = destination.expand(40.0); + let zoom = (view.width() / destination.width()).min(view.height() / destination.height()).clamp(0.1, 1.5); + let pan = destination.center().to_vec2() - view.size() * 0.5 / zoom; + Self { origin: view.min, pan, zoom } + } + + pub(crate) fn zoom_from_input(&mut self, ui: &Ui, view: Rect) { + self.zoom = self.zoom.clamp(0.08, 4.0); + if !ui.rect_contains_pointer(view) { + return; + } + + let Some(pointer) = ui.input(|input| input.pointer.hover_pos()).filter(|pointer| view.contains(*pointer)) else { return }; + + let scroll = ui.input(|input| input.smooth_scroll_delta.y + input.zoom_delta().ln() * 200.0); + if scroll.is_finite() && scroll != 0.0 { + let before = self.to_graph(pointer); + self.zoom = (self.zoom * (scroll * 0.0025).exp()).clamp(0.08, 4.0); + self.pan = before.to_vec2() - (pointer - self.origin) / self.zoom; + } + } + + pub(crate) fn pan_started(ui: &Ui, view: Rect) -> bool { + ui.rect_contains_pointer(view) + && ui.input(|input| input.pointer.button_pressed(egui::PointerButton::Middle) || input.pointer.primary_pressed() && input.modifiers.alt) + } + + pub(crate) fn frame_key(ui: &Ui, view: Rect) -> bool { + ui.rect_contains_pointer(view) + && !ui.ctx().egui_wants_keyboard_input() + && ui.input(|input| input.key_pressed(egui::Key::F) && input.modifiers.is_none()) } } diff --git a/crates/ui-egui/src/graph/graph_drag.rs b/crates/ui-egui/src/graph/graph_drag.rs index a2db925..d2e73bb 100644 --- a/crates/ui-egui/src/graph/graph_drag.rs +++ b/crates/ui-egui/src/graph/graph_drag.rs @@ -19,7 +19,7 @@ pub(super) enum GraphDrag { wire: WireRef, start: Pos2, }, - Pan, + Pan(egui::PointerButton), Frame { id: u64, delta: Vec2, diff --git a/crates/ui-egui/src/graph/graph_parent.rs b/crates/ui-egui/src/graph/graph_parent.rs new file mode 100644 index 0000000..99fbf1d --- /dev/null +++ b/crates/ui-egui/src/graph/graph_parent.rs @@ -0,0 +1,7 @@ +use materialcraft_engine::core::NodeId; + +pub(crate) struct GraphParent { + pub graph: usize, + pub selection: Vec, + pub camera: crate::state::GraphCamera, +} diff --git a/crates/ui-egui/src/graph/grid.rs b/crates/ui-egui/src/graph/grid.rs new file mode 100644 index 0000000..b722fc7 --- /dev/null +++ b/crates/ui-egui/src/graph/grid.rs @@ -0,0 +1,26 @@ +use super::GraphCamera; +use egui::{Color32, Rect, Stroke, pos2}; + +pub(crate) fn paint(p: &egui::Painter, cam: &GraphCamera, rect: Rect) { + for (step, alpha) in [(materialcraft_engine::graph_grid::GRID_SPACING, 10u8), (256.0, 22)] { + let s = step * cam.zoom; + if s < 8.0 { + continue; + } + let col = Color32::from_white_alpha(alpha); + let x0 = cam.pan.x - (cam.pan.x.rem_euclid(step)); + let mut x = x0; + while cam.to_screen(pos2(x, 0.0)).x < rect.right() { + let sx = cam.to_screen(pos2(x, 0.0)).x; + p.line_segment([pos2(sx, rect.top()), pos2(sx, rect.bottom())], Stroke::new(1.0, col)); + x += step; + } + let y0 = cam.pan.y - (cam.pan.y.rem_euclid(step)); + let mut y = y0; + while cam.to_screen(pos2(0.0, y)).y < rect.bottom() { + let sy = cam.to_screen(pos2(0.0, y)).y; + p.line_segment([pos2(rect.left(), sy), pos2(rect.right(), sy)], Stroke::new(1.0, col)); + y += step; + } + } +} diff --git a/crates/ui-egui/src/graph/input.rs b/crates/ui-egui/src/graph/input.rs new file mode 100644 index 0000000..9092987 --- /dev/null +++ b/crates/ui-egui/src/graph/input.rs @@ -0,0 +1,249 @@ +use super::{GraphCamera, GraphDrag, LibraryDrag, NODE_W, PortHit, WireRef}; +use super::{navigation::frame, port_hit::nearest as nearest_port, search::open_search, wire_actions::wire_menu}; +use crate::MaterialCraftApp; +use egui::{Rect, Ui, Vec2}; +use materialcraft_engine::core::NodeId; +use serde_json::json; + +#[allow(clippy::too_many_arguments)] +pub(super) fn handle( + app: &mut MaterialCraftApp, + ui: &mut Ui, + canvas: &egui::Response, + rect: Rect, + cam: &GraphCamera, + nodes: &[(NodeId, egui::Response)], + frames: &[super::frame_hit::FrameHit], + comments: &[(u64, Rect)], + port_hover: Option, + wire_hover: Option, +) { + let ctx = ui.ctx().clone(); + if super::gesture::cancelled(ui) { + app.graph.drag = None; + return; + } + let (pointer, mods, primary_pressed) = ctx.input(|input| (input.pointer.interact_pos(), input.modifiers, input.pointer.primary_pressed())); + let zoom = cam.zoom; + let motion = ctx.input(|i| i.pointer.delta()) / zoom; + + // Starting gestures (only on a press inside the canvas, with no gesture running) + if app.graph.drag.is_none() + && let Some(p) = pointer + && rect.contains(p) + && ui.rect_contains_pointer(rect) + && app.graph.search.is_none() + { + if GraphCamera::pan_started(ui, rect) { + app.graph.drag = Some(GraphDrag::Pan(super::gesture::pan_button(ui))); + } else if primary_pressed { + if app.session.annotation_selection.is_some() { + app.run("graph.annotation.select", json!({})); + } + + let on_card = nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p)); + let wire = wire_hover.as_ref().filter(|_| port_hover.is_none() && !on_card); + // Any press other than on a wire drops the wire selection + if wire.is_none() { + app.graph.selected_wires.clear(); + } + if let Some(w) = wire { + app.graph.drag = Some(GraphDrag::WirePress { wire: w.clone(), start: p }); + } else if let Some(h) = &port_hover { + if h.output { + app.graph.drag = Some(GraphDrag::Wire { from: (h.node, h.port.clone()), detached: None }); + } else if let Some(c) = app.session.graph().ok().and_then(|g| g.input_of(h.node, &h.port).cloned()) { + app.graph.drag = Some(GraphDrag::Wire { from: (c.from, c.from_port.clone()), detached: Some((h.node, h.port.clone())) }); + } + } else if let Some((id, _)) = comments.iter().rev().find(|(_, r)| r.contains(p)) { + super::annotation_input::begin_comment(app, *id); + } else if let Some((id, _)) = nodes.iter().rev().find(|(_, r)| r.rect.contains(p)) { + super::node_selection::select(&mut app.session.selection, Some(*id), mods); + app.graph.drag = Some(GraphDrag::Nodes { delta: Vec2::ZERO }); + } else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(p)) { + super::annotation_input::begin_frame(app, hit.id, hit.grip.contains(p)); + } else { + app.graph.drag = Some(GraphDrag::Box { start: p }); + } + } + } + + // Continuing gestures + match &mut app.graph.drag { + Some(GraphDrag::Pan(_)) => { + let d = ctx.input(|i| i.pointer.delta()) / zoom; + app.ui.graph_camera.pan = [app.ui.graph_camera.pan[0] - d.x, app.ui.graph_camera.pan[1] - d.y]; + } + Some(GraphDrag::Nodes { delta }) | Some(GraphDrag::Frame { delta, .. }) | Some(GraphDrag::Comment { delta, .. }) => *delta += motion, + Some(GraphDrag::WirePress { wire, start }) => { + // Dragged far enough: a reroute dot where the press was, carried by the pointer + if let Some(p) = pointer + && p.distance(*start) > 4.0 + { + let (wire, start) = (wire.clone(), *start); + let at = cam.to_graph(start); + app.graph.drag = None; + if app.run("graph.wire.insertDot", json!({"to": wire.0.0, "toPort": wire.1, "at": [at.x, at.y]})).is_some() { + app.graph.drag = Some(GraphDrag::Nodes { delta: (p - start) / zoom }); + } + } + } + _ => {} + } + + // Ending gestures + let owner = match app.graph.drag { + Some(GraphDrag::Pan(button)) => button, + _ => egui::PointerButton::Primary, + }; + let ended = super::gesture::finished(ui, owner); + if ended && let Some(drag) = app.graph.drag.take() { + match drag { + GraphDrag::Pan(_) => {} + GraphDrag::WirePress { wire, .. } => { + app.session.selection.clear(); + let sel = &mut app.graph.selected_wires; + if mods.ctrl && sel.contains(&wire) { + // Ctrl+click toggles a wire out of the selection + sel.retain(|w| *w != wire); + } else if mods.ctrl || mods.shift { + if !sel.contains(&wire) { + sel.push(wire); + } + } else { + *sel = vec![wire]; + } + } + GraphDrag::Nodes { delta } => { + if delta.length() > 0.5 { + app.run("graph.node.move", json!({"by": [delta.x, delta.y]})); + } + } + GraphDrag::Box { start } => { + if let Some(p) = pointer { + super::node_selection::select_box(&mut app.session.selection, app.graph.rects.iter().copied(), start, p, mods); + } + } + GraphDrag::Wire { from, detached } => { + let target = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 12.0)).filter(|h| !h.output).cloned(); + match target { + Some(t) => { + let mut parameters = json!({"from": from.0.0, "fromPort": from.1, "to": t.node.0, "toPort": t.port}); + if let Some((node, port)) = detached { + parameters["detach"] = json!({"to": node.0, "toPort": port}); + } + + app.run("graph.connect", parameters); + } + None => { + if let Some((n, p)) = &detached { + app.run("graph.disconnect", json!({"to": n.0, "toPort": p})); + } else if let Some(p) = pointer + && rect.contains(p) + { + open_search(app, cam.to_graph(p), Some(from)); + } + } + } + } + GraphDrag::Frame { .. } | GraphDrag::Comment { .. } => super::annotation_input::finish(app, drag), + } + } + + // Clicks + for (id, r) in nodes { + if r.double_clicked() { + app.run("view.2d", json!({"node": id.0, "port": 0})); + if crate::menus::enabled(app, "graph.node.edit") { + crate::menus::invoke(app, ui.ctx(), "graph.node.edit"); + } + } else if r.clicked() && app.session.selection.contains(id) && app.session.view2d.node != Some(*id) { + // Keep the current output when deselecting or clicking the node already shown + app.run("view.2d", json!({"node": id.0})); + } + if r.secondary_clicked() + && let Some(pointer) = pointer + { + app.graph.menu_at = cam.to_graph(pointer); + } + + let at = app.graph.menu_at; + r.context_menu(|ui| super::context_menu::show(app, ui, at, Some(*id))); + } + if let Some(h) = &port_hover + && h.output + && ui.rect_contains_pointer(rect) + && ctx.input(|i| i.pointer.primary_clicked()) + { + let idx = app.session.output_ports(h.node).iter().position(|p| *p == h.port).unwrap_or(0); + app.run("view.2d", json!({"node": h.node.0, "port": idx})); + } + let on_node = pointer.is_some_and(|p| { + nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p)) || frames.iter().any(|frame| frame.contains(p)) + }); + if canvas.double_clicked() + && !on_node + && let Some(p) = pointer + { + match &wire_hover { + // Double-click a wire: a reroute dot there + Some(w) => { + let at = cam.to_graph(p); + app.run("graph.wire.insertDot", json!({"to": w.0.0, "toPort": w.1, "at": [at.x, at.y]})); + app.graph.selected_wires.clear(); + } + None => open_search(app, cam.to_graph(p), None), + } + } + if canvas.secondary_clicked() + && let Some(p) = pointer + { + app.graph.menu_at = cam.to_graph(p); + if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(p)) { + app.run("graph.annotation.select", json!({"kind": "comment", "id": id})); + } else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(p)) { + app.run("graph.annotation.select", json!({"kind": "frame", "id": hit.id})); + } + app.graph.menu_wire = wire_hover.clone().filter(|_| !on_node); + // Right-clicking a selected wire keeps the selection (to swap or delete them all) + if let Some(w) = &app.graph.menu_wire + && !app.graph.selected_wires.contains(w) + { + app.session.selection.clear(); + app.graph.selected_wires = vec![w.clone()]; + } + } + let at = app.graph.menu_at; + canvas.context_menu(|ui| match app.graph.menu_wire.clone() { + Some(w) => wire_menu(app, ui, w, at), + None => super::context_menu::show(app, ui, at, None), + }); + + // Library drops + if let Some(payload) = crate::widgets::dnd_release::(canvas) + && let Some(p) = pointer + { + let gp = cam.to_graph(p); + let at = [gp.x - NODE_W * 0.5, gp.y - 20.0]; + match payload.0.strip_prefix('@') { + Some(graph) => app.run("graph.node.add", json!({"def": "graph_instance", "at": at, "params": {"graph": graph}})), + None => app.run("graph.node.add", json!({"def": payload.0, "at": at})), + }; + } + + // Keys over the canvas + let hovered = pointer.is_some_and(|p| rect.contains(p)); + if hovered && app.graph.search.is_none() { + let space = !ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::Space)); + let tab = !app.graph.keyboard_was_focused && !ctx.text_edit_focused() && ctx.input(|i| i.key_pressed(egui::Key::Tab)); + if (space || tab) + && let Some(p) = pointer + { + open_search(app, cam.to_graph(p), None); + } + if GraphCamera::frame_key(ui, rect) { + let sel = !app.session.selection.is_empty(); + frame(app, rect, sel); + } + } +} diff --git a/crates/ui-egui/src/graph/interaction_tests.rs b/crates/ui-egui/src/graph/interaction_tests.rs index f3d9327..7cf5cd2 100644 --- a/crates/ui-egui/src/graph/interaction_tests.rs +++ b/crates/ui-egui/src/graph/interaction_tests.rs @@ -468,3 +468,65 @@ fn every_canvas_keeps_properties_after_deselection() { } } } + +#[test] +fn box_selection_and_alt_panning_are_shared_by_every_canvas() { + use materialcraft_engine::core::{FunctionGraph, PatternGraph, PatternNodeKind, Value}; + + for kind in ["material", "function", "pattern"] { + let mut frames = Frames::new(new_session()); + match kind { + "function" => { + frames.app.run("file.new", json!({"kind": "function"})).unwrap(); + let mut graph = FunctionGraph::default(); + for x in [0.0, 320.0] { + graph.add("get_float1", &[], Some(Value::Text("value".into()))); + graph.nodes.last_mut().unwrap().pos = [x, 0.0]; + } + frames.app.run("graph.function.set", json!({"function": graph})).unwrap(); + } + "pattern" => { + let owner = NodeId(frames.app.run("graph.node.add", json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + let mut graph = PatternGraph::default(); + for x in [0.0, 320.0] { + graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes.last_mut().unwrap().position = [x, 0.0]; + } + frames.app.run("graph.pattern.set", json!({"id": owner.0, "pattern": graph})).unwrap(); + frames.app.pattern_editor = Some(crate::pattern::PatternEditor::new(frames.app.session.graph, owner)); + } + _ => { + for x in [0, 320] { + frames.app.run("graph.node.add", json!({"def": "uniform", "at": [x, 0]})).unwrap(); + } + } + } + if kind == "function" { + frames.app.run("graph.frame.add", json!({"rect": [-256, 256, 240, 100]})).unwrap(); + } + frames.app.ui.frame_all = true; + frames.run(Vec::new(), Modifiers::NONE); + frames.run(Vec::new(), Modifiers::NONE); + let original = frames.app.session.pkg.clone(); + let bounds = frames.app.graph.rects.iter().fold(egui::Rect::NOTHING, |bounds, (_, rect)| bounds.union(*rect)).expand(12.0); + drag(&mut frames, bounds.min, bounds.max); + let selection_count = match kind { + "function" => frames.app.function_editor.as_ref().unwrap().selection.len(), + "pattern" => frames.app.pattern_editor.as_ref().unwrap().selection.len(), + _ => frames.app.session.selection.len(), + }; + assert_eq!(selection_count, 2, "{kind} box selection"); + + let before = frames.app.graph.rects[0].1.center(); + let from = frames.app.graph.view.left_bottom() + vec2(20.0, -20.0); + let to = from + vec2(30.0, -20.0); + frames.run(vec![Event::PointerMoved(from)], Modifiers::ALT); + frames.run(vec![Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::ALT }], Modifiers::ALT); + frames.run(vec![Event::PointerMoved(to)], Modifiers::ALT); + frames.run(vec![Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::ALT }], Modifiers::ALT); + frames.run(Vec::new(), Modifiers::NONE); + let after = frames.app.graph.rects[0].1.center(); + assert!((after - before - (to - from)).length() < 0.01, "{kind} pan: {before:?} -> {after:?}"); + assert_eq!(frames.app.session.pkg, original, "{kind} navigation edited the document"); + } +} diff --git a/crates/ui-egui/src/graph/mod.rs b/crates/ui-egui/src/graph/mod.rs index 3b37ae1..6464299 100644 --- a/crates/ui-egui/src/graph/mod.rs +++ b/crates/ui-egui/src/graph/mod.rs @@ -4,11 +4,12 @@ pub(crate) mod annotation_canvas; pub(crate) mod annotation_input; pub(crate) mod canvas; mod context_menu; -mod frame_hit; +pub(crate) mod frame_hit; #[cfg(test)] mod frames; mod graph_camera; mod graph_drag; +pub(crate) mod graph_parent; mod graph_view; pub(crate) mod input_visibility; #[cfg(test)] @@ -18,14 +19,40 @@ pub(crate) mod node_card; mod node_layout; mod node_search; pub(crate) mod node_selection; -mod port_hit; +pub(crate) mod port_hit; pub(crate) mod port_label; +pub(crate) mod subgraph_navigation; -pub use canvas::{NODE_W, add_node_near_selection, delete_selected_wires, header_color, node_label, node_rect, port_color, show, swap_selected_wires}; +pub use canvas::show; 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; use node_search::NodeSearch; +pub use node_style::{NODE_W, header_color, node_label, node_rect, port_color}; pub use port_hit::PortHit; +pub use wire_actions::{delete_selected_wires, swap_selected_wires}; pub type WireRef = (materialcraft_engine::core::NodeId, String); + +#[cfg(test)] +mod canvas_tests; +pub(crate) mod grid; +mod input; +mod navigation; +mod node_style; +mod search; +pub(crate) mod selection_commands; +pub(crate) mod toolbar; +mod wire_actions; +pub(crate) mod wire_geometry; + +#[cfg(test)] +mod review_tests; + +pub(crate) mod edit_menu; +pub(crate) mod editor_actions; +pub(crate) mod editor_target; +pub(crate) mod gesture; + +pub(crate) mod canvas_geometry; diff --git a/crates/ui-egui/src/graph/navigation.rs b/crates/ui-egui/src/graph/navigation.rs new file mode 100644 index 0000000..46bf08f --- /dev/null +++ b/crates/ui-egui/src/graph/navigation.rs @@ -0,0 +1,48 @@ +use super::{NODE_W, node_rect}; +use crate::MaterialCraftApp; +use egui::{Pos2, Rect, pos2, vec2}; +use serde_json::json; + +pub(super) fn view_center(app: &MaterialCraftApp) -> Pos2 { + let c = &app.ui.graph_camera; + let v = app.graph.view; + pos2(c.pan[0] + v.width() * 0.5 / c.zoom, c.pan[1] + v.height() * 0.5 / c.zoom) +} + +/// 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(); + let has_inputs = materialcraft_engine::nodes::find(def).is_some_and(|d| !d.inputs.is_empty()); + let params = match sel { + Some(id) if has_inputs && !app.session.output_ports(id).is_empty() => json!({"def": def, "connectFrom": {"node": id.0}}), + _ => { + let c = view_center(app); + json!({"def": def, "at": [c.x - NODE_W * 0.5, c.y - 60.0]}) + } + }; + + app.run("graph.node.add", params); +} + +/// Frame the graph (or the selection) in the view +pub(super) fn frame(app: &mut MaterialCraftApp, view: Rect, only_selection: bool) { + let thumbs = app.ui.prefs.thumbnails; + let Ok(g) = app.session.graph() else { return }; + + let mut r = Rect::NOTHING; + for n in &g.nodes { + if only_selection && !app.session.selection.contains(&n.id) { + continue; + } + + let (inputs, outputs) = materialcraft_engine::eval::ports(&app.session.pkg, g, n); + let visible = super::input_visibility::count(inputs.iter().map(|port| g.input_of(n.id, &port.id).is_some()), if n.def == "fx_map" { 2 } else { 1 }); + r = r.union(node_rect(n, visible, outputs.len(), thumbs)); + } + for f in &g.frames { + if !only_selection { + r = r.union(Rect::from_min_size(pos2(f.rect[0], f.rect[1] - 32.0), vec2(f.rect[2], f.rect[3] + 32.0))); + } + } + app.ui.graph_camera = super::GraphCamera::fit(view, r).state(); +} diff --git a/crates/ui-egui/src/graph/node_selection.rs b/crates/ui-egui/src/graph/node_selection.rs index 35a1d98..eaacf56 100644 --- a/crates/ui-egui/src/graph/node_selection.rs +++ b/crates/ui-egui/src/graph/node_selection.rs @@ -25,3 +25,27 @@ pub(crate) fn select(selection: &mut Vec, node: Option, modi pub(crate) fn inspected(selection: &[T], previous: Option) -> Option { selection.last().copied().or(previous) } + +pub(crate) fn select_box( + selection: &mut Vec, + nodes: impl IntoIterator, + start: egui::Pos2, + end: egui::Pos2, + modifiers: Modifiers, +) { + let bounds = egui::Rect::from_two_pos(start, end); + select(selection, None, modifiers); + if bounds.width() <= 3.0 && bounds.height() <= 3.0 { + return; + } + + for (id, rect) in nodes { + if bounds.intersects(rect) && !selection.contains(&id) { + selection.push(id); + } + } +} + +pub(crate) fn paint_box(painter: &egui::Painter, start: egui::Pos2, end: egui::Pos2, color: egui::Color32) { + painter.rect(egui::Rect::from_two_pos(start, end), 0.0, color.gamma_multiply(0.12), egui::Stroke::new(1.0, color), egui::StrokeKind::Inside); +} diff --git a/crates/ui-egui/src/graph/node_style.rs b/crates/ui-egui/src/graph/node_style.rs new file mode 100644 index 0000000..b9104c5 --- /dev/null +++ b/crates/ui-egui/src/graph/node_style.rs @@ -0,0 +1,85 @@ +use super::node_card; +use crate::i18n::tr; +use egui::{Color32, Rect}; +use materialcraft_engine::{ + core::{Node, Value}, + nodes::PortKind, +}; +pub const NODE_W: f32 = node_card::WIDTH; +pub(super) const PORT_RADIUS: f32 = 4.5; + +/// Header strip color of a node by its library category +pub fn header_color(def: &str) -> Color32 { + let cat = materialcraft_engine::nodes::find(def).map_or("", |d| d.category); + match def { + "output" => Color32::from_rgb(0x2c, 0x8f, 0x5e), + "input_color" | "input_grayscale" | "input_value" => Color32::from_rgb(0x6d, 0x52, 0xb5), + "graph_instance" => Color32::from_rgb(0x1e, 0x8a, 0xa0), + _ if cat.starts_with("Atomic") => Color32::from_rgb(0x5c, 0x62, 0x6e), + _ if cat.contains("Noises") => Color32::from_rgb(0xa8, 0x3c, 0x34), + _ if cat.contains("Patterns") => Color32::from_rgb(0xb3, 0x5a, 0x2c), + _ if cat.starts_with("Material") => Color32::from_rgb(0x3a, 0x66, 0xb0), + _ if cat.starts_with("Filters") => Color32::from_rgb(0x3b, 0x7f, 0x4c), + _ => Color32::from_rgb(0x5c, 0x62, 0x6e), + } +} + +pub fn port_color(kind: PortKind) -> Color32 { + match kind { + PortKind::Gray => Color32::from_rgb(0xc8, 0xc8, 0xc8), + PortKind::Color => Color32::from_rgb(0xe8, 0xa9, 0x3c), + PortKind::Value => Color32::from_rgb(0x8b, 0xc6, 0x74), + PortKind::Any => Color32::from_rgb(0x8c, 0xb4, 0xe0), + } +} + +/// A node's display label +pub fn node_label(n: &Node) -> String { + if !n.label.is_empty() { + return n.label.clone(); + } + let label = match n.def.as_str() { + "graph_instance" => match n.params.get("graph") { + Some(Value::Text(g)) => g.clone(), + _ => tr("Graph instance").into(), + }, + "output" | "input_color" | "input_grayscale" | "input_value" => materialcraft_engine::eval::identifier(n), + d => materialcraft_engine::nodes::find(d).map_or(d, |d| d.label).to_string(), + }; + label.split(['_', ' ']).filter(|word| !word.is_empty()).fold(String::with_capacity(label.len()), |mut display, word| { + if !display.is_empty() { + display.push(' '); + } + let mut letters = word.chars(); + if let Some(first) = letters.next() { + display.extend(first.to_uppercase()); + display.extend(letters); + } + display + }) +} + +/// Graph-space rectangle of a node card +pub fn node_rect(node: &Node, inputs: usize, outputs: usize, previews: bool) -> Rect { + node_card::bounds(node.pos, inputs, outputs, previews, node.def == "dot") +} + +#[cfg(test)] +mod tests { + use super::*; + use materialcraft_engine::core::NodeId; + + #[test] + fn default_labels_are_capitalized_without_changing_identifiers_or_custom_labels() { + for definition in ["input_color", "input_grayscale", "input_value", "output"] { + let mut node = Node::new(NodeId(1), definition, [0.0; 2]); + node.params.insert("identifier".into(), Value::Text("échantillon_value".into())); + assert_eq!(node_label(&node), "Échantillon Value"); + assert_eq!(materialcraft_engine::eval::identifier(&node), "échantillon_value"); + node.label = "my exact_label".into(); + assert_eq!(node_label(&node), "my exact_label"); + } + let node = Node::new(NodeId(2), "unknown_primitive", [0.0; 2]); + assert_eq!(node_label(&node), "Unknown Primitive"); + } +} diff --git a/crates/ui-egui/src/graph/port_hit.rs b/crates/ui-egui/src/graph/port_hit.rs index e2ef8bb..268f541 100644 --- a/crates/ui-egui/src/graph/port_hit.rs +++ b/crates/ui-egui/src/graph/port_hit.rs @@ -12,3 +12,19 @@ pub struct PortHit { pub pos: Pos2, pub kind: PortKind, } + +pub(super) fn nearest(ports: &[PortHit], pointer: Pos2, radius: f32) -> Option<&PortHit> { + nearest_by(ports, pointer, |port| (port.pos, radius)) +} + +pub(crate) fn nearest_by(items: &[T], pointer: Pos2, hit_area: impl Fn(&T) -> (Pos2, f32)) -> Option<&T> { + items + .iter() + .filter_map(|item| { + let (position, radius) = hit_area(item); + let distance = position.distance_sq(pointer); + (distance <= radius * radius).then_some((item, distance)) + }) + .min_by(|left, right| left.1.total_cmp(&right.1)) + .map(|(item, _)| item) +} diff --git a/crates/ui-egui/src/graph/review_tests.rs b/crates/ui-egui/src/graph/review_tests.rs new file mode 100644 index 0000000..98de7f9 --- /dev/null +++ b/crates/ui-egui/src/graph/review_tests.rs @@ -0,0 +1,343 @@ +use crate::{ + MaterialCraftApp, UiState, + function::{FunctionEditor, FunctionTarget}, + menus, +}; +use materialcraft_engine::{ + core::{FunctionGraph, NodeId, PatternGraph, PatternNodeKind, Value}, + new_session, +}; +use serde_json::json; + +#[test] +fn embedded_function_commands_do_not_edit_the_parent_selection() { + let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); + let owner = NodeId(app.run("graph.node.add", json!({"def": "pixel_processor"})).unwrap()["id"].as_u64().unwrap()); + app.function_editor = Some(FunctionEditor::new(app.session.graph, owner, FunctionTarget::Parameter("function".into()))); + app.session.selection = vec![owner]; + let context = egui::Context::default(); + menus::invoke(&mut app, &context, "edit.selectAll"); + menus::invoke(&mut app, &context, "edit.delete"); + let node = app.session.graph().unwrap().node(owner).expect("Delete must stay in the Function editor"); + let Value::Function(function) = &node.params["function"] else { panic!("missing function") }; + assert!(function.nodes.is_empty()); +} + +#[test] +fn nested_function_commands_take_priority_over_fx_map_selection() { + let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); + let owner = NodeId(app.run("graph.node.add", json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); + let node = graph.nodes[0].id; + graph.nodes[0].parameters.insert("patternrotation".into(), Value::Function(Box::new(FunctionGraph::constant(Value::Float(0.0))))); + app.run("graph.pattern.set", json!({"id": owner.0, "pattern": graph})).unwrap(); + app.pattern_editor = Some(crate::pattern::PatternEditor::new(app.session.graph, owner)); + let context = egui::Context::default(); + menus::invoke(&mut app, &context, "edit.selectAll"); + app.function_editor = Some(FunctionEditor::new(app.session.graph, owner, FunctionTarget::Pattern { node, parameter: "patternrotation".into() })); + menus::invoke(&mut app, &context, "edit.selectAll"); + let inspected = crate::control::handle(&mut app, &context, "ui.inspect", &json!({})); + assert_eq!(inspected["result"]["subgraph"]["kind"], "function"); + menus::invoke(&mut app, &context, "edit.delete"); + let Value::PatternGraph(graph) = &app.session.graph().unwrap().node(owner).unwrap().params["pattern"] else { panic!("missing pattern") }; + assert_eq!(graph.nodes.len(), 1); + let Value::Function(function) = &graph.nodes[0].parameters["patternrotation"] else { panic!("missing function") }; + assert!(function.nodes.is_empty()); + menus::invoke(&mut app, &context, "ui.graph.parent"); + assert!(app.function_editor.is_none()); + assert_eq!(app.pattern_editor.as_ref().unwrap().selection, vec![node]); + menus::invoke(&mut app, &context, "ui.graph.parent"); + assert!(app.pattern_editor.is_none()); + assert_eq!(app.session.selection, vec![owner]); +} + +#[test] +fn graph_gestures_ignore_other_button_releases_and_escape_cancels() { + use super::frames::Frames; + use egui::{Event, Key, Modifiers, PointerButton, vec2}; + for kind in ["material", "function", "pattern"] { + let mut frames = Frames::new(new_session()); + frames.app.ui.prefs.snap_to_grid = false; + match kind { + "function" => { + frames.app.run("file.new", json!({"kind": "function"})).unwrap(); + let mut graph = FunctionGraph::default(); + graph.add("mul", &[], None); + frames.app.run("graph.function.set", json!({"function": graph})).unwrap(); + } + "pattern" => { + let owner = NodeId(frames.app.run("graph.node.add", json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + frames.app.run("graph.pattern.set", json!({"id": owner.0, "pattern": PatternGraph::with_root(PatternNodeKind::Quadrant)})).unwrap(); + frames.app.pattern_editor = Some(crate::pattern::PatternEditor::new(frames.app.session.graph, owner)); + } + _ => { + frames.app.run("graph.node.add", json!({"def": "uniform"})).unwrap(); + } + } + frames.app.ui.frame_all = true; + frames.run(Vec::new(), Modifiers::NONE); + for cancel in [false, true] { + frames.run(Vec::new(), Modifiers::NONE); + let original = frames.app.session.pkg.clone(); + let from = frames.app.graph.rects[0].1.center(); + let middle = from + vec2(20.0, 0.0); + let to = from + vec2(60.0, 0.0); + let button = |pos, button, pressed| Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE }; + frames.run(vec![Event::PointerMoved(from)], Modifiers::NONE); + frames.run(vec![button(from, PointerButton::Primary, true)], Modifiers::NONE); + frames.run(vec![Event::PointerMoved(middle)], Modifiers::NONE); + for pressed in [true, false] { + frames.run(vec![button(middle, PointerButton::Middle, pressed)], Modifiers::NONE); + } + assert_eq!(frames.app.session.pkg, original, "{kind}: unrelated release committed movement"); + frames.run(vec![Event::PointerMoved(to)], Modifiers::NONE); + if cancel { + frames + .run(vec![Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }], Modifiers::NONE); + } + frames.run(vec![button(to, PointerButton::Primary, false)], Modifiers::NONE); + frames.run(Vec::new(), Modifiers::NONE); + if cancel { + assert_eq!(frames.app.session.pkg, original, "{kind}: cancelled movement committed"); + } else { + assert!((frames.app.graph.rects[0].1.center().x - from.x - 60.0).abs() < 0.1, "{kind}: gesture ended early"); + } + } + } +} + +#[test] +fn processors_edit_inline_and_return_to_the_parent_without_document_changes() { + use super::{editor_target::EditorTarget, frames::Frames}; + for definition in ["pixel_processor", "value_processor"] { + let mut frames = Frames::new(new_session()); + let owner = NodeId(frames.app.run("graph.node.add", json!({"def": definition})).unwrap()["id"].as_u64().unwrap()); + frames.run(Vec::new(), egui::Modifiers::NONE); + let parent_camera = frames.app.ui.graph_camera; + let original = frames.app.session.pkg.clone(); + let history = frames.app.session.history(); + menus::invoke(&mut frames.app, &frames.ctx, "graph.node.edit"); + for _ in 0..3 { + frames.run(Vec::new(), egui::Modifiers::NONE); + } + assert_eq!(EditorTarget::resolve(&frames.app), EditorTarget::Function); + let inspected = crate::control::handle(&mut frames.app, &frames.ctx, "ui.inspect", &json!({})); + assert_eq!(inspected["result"]["graphView"][0], json!(frames.app.graph.view.min.x)); + assert_eq!(inspected["result"]["subgraph"]["kind"], "function"); + let point = frames.app.graph.view.left_bottom() + egui::vec2(20.0, -20.0); + frames.click(point, egui::Modifiers::NONE); + assert_eq!(EditorTarget::resolve(&frames.app), EditorTarget::Function); + menus::invoke(&mut frames.app, &frames.ctx, "ui.graph.parent"); + frames.run(Vec::new(), egui::Modifiers::NONE); + assert_eq!(EditorTarget::resolve(&frames.app), EditorTarget::Material); + assert_eq!(frames.app.ui.graph_camera, parent_camera); + assert_eq!(frames.app.session.selection, vec![owner]); + assert_eq!(frames.app.session.pkg, original); + assert_eq!(frames.app.session.history(), history); + } +} + +#[test] +fn instance_navigation_preserves_parent_view_and_material_across_renames() { + use materialcraft_engine::core::Graph; + let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); + let owner = app.session.graph_mut().unwrap().add_node("graph_instance", [0.0; 2]); + app.session.graph_mut().unwrap().node_mut(owner).unwrap().params.insert("graph".into(), Value::Text("Child".into())); + app.session.pkg.graphs.push(Graph::new("Child")); + app.session.selection = vec![owner]; + app.ui.graph_camera = crate::state::GraphCamera { pan: [123.0, -456.0], zoom: 1.5 }; + let camera = app.ui.graph_camera; + let material = app.session.material_preview.clone(); + let context = egui::Context::default(); + menus::invoke(&mut app, &context, "graph.node.edit"); + assert_eq!(app.session.graph, 1); + assert_eq!(app.session.material_preview, material); + assert!(menus::enabled(&app, "ui.graph.parent")); + app.run("graph.rename", json!({"graph": 0, "name": "Renamed parent"})).unwrap(); + assert!(super::subgraph_navigation::breadcrumb(&app).starts_with("Renamed parent / Child")); + menus::invoke(&mut app, &context, "ui.graph.parent"); + assert_eq!(app.session.graph, 0); + assert_eq!(app.session.selection, vec![owner]); + assert_eq!(app.ui.graph_camera, camera); + assert_eq!(app.session.material_preview, material); + assert!(!menus::enabled(&app, "ui.graph.parent")); + menus::invoke(&mut app, &context, "graph.node.edit"); + app.run("graph.open", json!({"graph": 0})).unwrap(); + assert!(!menus::enabled(&app, "ui.graph.parent")); +} + +#[test] +fn dynamic_parameter_functions_return_to_the_owning_node() { + let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); + let owner = NodeId(app.run("graph.node.add", json!({"def": "blur"})).unwrap()["id"].as_u64().unwrap()); + app.run("graph.node.function", json!({"id": owner, "param": "intensity"})).unwrap(); + super::subgraph_navigation::open_function(&mut app, owner, FunctionTarget::Dynamic("intensity".into())); + assert!(super::subgraph_navigation::breadcrumb(&app).ends_with("Blur / intensity")); + let context = egui::Context::default(); + menus::invoke(&mut app, &context, "edit.selectAll"); + menus::invoke(&mut app, &context, "edit.delete"); + assert!(app.session.graph().unwrap().node(owner).unwrap().functions["intensity"].nodes.is_empty()); + menus::invoke(&mut app, &context, "ui.graph.parent"); + assert_eq!(app.session.selection, vec![owner]); + assert!(app.function_editor.is_none()); +} + +#[test] +fn idle_ui_frames_preserve_explicit_automation_undo_groups() { + use super::frames::Frames; + use egui::{Event, Modifiers, PointerButton}; + let mut frames = Frames::new(new_session()); + frames.app.run("file.new", json!({"kind": "function"})).unwrap(); + let added = frames.app.run("graph.function.edit", json!({"edit": {"action": "add", "operation": "const_float1", "at": [0, 0]}})).unwrap(); + let id = added["id"].as_u64().unwrap(); + frames.run(Vec::new(), Modifiers::NONE); + frames.app.session.reset_history(); + for value in [1.0, 2.0, 3.0] { + frames.app.run("graph.function.edit", json!({"merge": true, "edit": {"action": "value", "id": id, "value": Value::Float(value)}})).unwrap(); + frames.run(Vec::new(), Modifiers::NONE); + } + assert_eq!(frames.app.session.history().len(), 1); + frames.app.run("edit.finish", json!({})).unwrap(); + let position = frames.app.graph.view.left_bottom() + egui::vec2(20.0, -20.0); + frames.run( + vec![Event::PointerMoved(position), Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }], + Modifiers::NONE, + ); + frames.app.run("graph.function.edit", json!({"merge": true, "edit": {"action": "value", "id": id, "value": Value::Float(4.0)}})).unwrap(); + frames.run(vec![Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }], Modifiers::NONE); + frames.app.run("graph.function.edit", json!({"merge": true, "edit": {"action": "value", "id": id, "value": Value::Float(5.0)}})).unwrap(); + assert_eq!(frames.app.session.history().len(), 3); +} + +#[test] +#[ignore = "release canvas timing, run with --nocapture"] +fn canvas_frame_cost() { + for count in [128, 4096] { + for kind in ["function", "pattern"] { + let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); + if kind == "function" { + app.run("file.new", json!({"kind": "function"})).unwrap(); + let mut graph = FunctionGraph::default(); + let mut previous = None; + for index in 0..count { + let id = graph.add("passthrough", &previous.into_iter().collect::>(), None); + graph.nodes.last_mut().unwrap().pos = [(index % 64) as f32 * 200.0, (index / 64) as f32 * 180.0]; + previous = Some(id); + } + app.session.graph_mut().unwrap().function = Some(graph); + } else { + let owner = NodeId(app.run("graph.node.add", json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + let mut graph = PatternGraph::default(); + for index in 0..count { + graph.add(PatternNodeKind::Quadrant).unwrap(); + let node = graph.nodes.last_mut().unwrap(); + node.position = [(index % 64) as f32 * 200.0, (index / 64) as f32 * 180.0]; + node.parameters.insert("rotation".into(), Value::Function(Box::new(FunctionGraph::constant(Value::Float(0.0))))); + } + app.session.graph_mut().unwrap().node_mut(owner).unwrap().params.insert("pattern".into(), Value::PatternGraph(Box::new(graph))); + app.pattern_editor = Some(crate::pattern::PatternEditor::new(app.session.graph, owner)); + } + let context = egui::Context::default(); + crate::theme::install(&context); + let mut frame = || { + let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))), ..Default::default() }; + std::hint::black_box(context.run_ui(input, |ui| super::show(&mut app, ui))); + }; + for _ in 0..3 { + frame(); + } + let mut samples = Vec::new(); + for _ in 0..3 { + let start = std::time::Instant::now(); + for _ in 0..8 { + frame(); + } + samples.push(start.elapsed().as_secs_f64() * 1000.0 / 8.0); + } + samples.sort_by(f64::total_cmp); + println!("{kind} {count} nodes: {:.3} ms/frame", samples[1]); + } + } +} + +#[test] +fn undo_closes_an_embedded_editor_when_its_owning_graph_changes() { + let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); + let owner = NodeId(app.run("graph.node.add", json!({"def": "pixel_processor"})).unwrap()["id"].as_u64().unwrap()); + app.run("graph.duplicate", json!({})).unwrap(); + app.session.reset_history(); + app.run("graph.open", json!({"graph": 0})).unwrap(); + app.run("graph.size", json!({"log2": [8, 8]})).unwrap(); + app.run("graph.open", json!({"graph": 1})).unwrap(); + app.function_editor = Some(FunctionEditor::new(app.session.graph, owner, FunctionTarget::Parameter("function".into()))); + let context = egui::Context::default(); + menus::invoke(&mut app, &context, "edit.selectAll"); + menus::invoke(&mut app, &context, "edit.undo"); + assert_eq!(app.session.graph, 0); + assert!(app.function_editor.is_none()); + for graph in &app.session.pkg.graphs { + let node = graph.node(owner).unwrap(); + assert!(!matches!(node.params.get("function"), Some(Value::Function(graph)) if graph.nodes.is_empty())); + } +} + +#[test] +fn rejected_duplicate_keeps_the_function_editor_selection() { + let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); + app.run("file.new", json!({"kind": "function"})).unwrap(); + let mut graph = FunctionGraph::default(); + for _ in 0..2049 { + graph.add("passthrough", &[], None); + } + app.run("graph.function.set", json!({"function": graph})).unwrap(); + app.function_editor = Some(FunctionEditor::standalone(app.session.graph)); + let context = egui::Context::default(); + menus::invoke(&mut app, &context, "edit.selectAll"); + let before = app.function_editor.as_ref().unwrap().selection.clone(); + menus::invoke(&mut app, &context, "edit.duplicate"); + assert_eq!(app.function_editor.as_ref().unwrap().selection, before); + assert_eq!(app.session.graph().unwrap().function.as_ref().unwrap().nodes.len(), 2049); +} + +#[test] +fn properties_and_library_follow_the_active_embedded_function() { + use super::{editor_target::EditorTarget, frames::Frames}; + let mut frames = Frames::new(new_session()); + let owner = NodeId(frames.app.run("graph.node.add", json!({"def": "pixel_processor"})).unwrap()["id"].as_u64().unwrap()); + let target = materialcraft_engine::FunctionGraphTarget::Parameter { node: owner, parameter: "function".into() }; + frames.app.run("graph.function.set", json!({"target": target, "function": FunctionGraph::constant(Value::Float(0.5))})).unwrap(); + frames.app.function_editor = Some(FunctionEditor::new(frames.app.session.graph, owner, FunctionTarget::Parameter("function".into()))); + menus::invoke(&mut frames.app, &frames.ctx, "edit.selectAll"); + assert_eq!(EditorTarget::resolve(&frames.app), EditorTarget::Function); + let label = materialcraft_engine::nodes::function::definition("const_float1").unwrap().label; + assert!(crate::properties::title(&frames.app).starts_with(label)); + frames.app.ui.library_search.clear(); + let output = frames + .ctx + .run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 800.0))), ..Default::default() }, |ui| { + crate::library::show(&mut frames.app, ui) + }); + assert!(output.shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.job.text.contains("Search functions")))); + menus::invoke(&mut frames.app, &frames.ctx, "ui.graph.parent"); + assert_eq!(EditorTarget::resolve(&frames.app), EditorTarget::Material); + assert!(crate::properties::title(&frames.app).starts_with("Pixel Processor")); +} + +#[test] +fn standalone_function_creation_keeps_selection_after_the_next_frame() { + use super::frames::Frames; + let mut frames = Frames::new(new_session()); + frames.app.run("file.new", json!({"kind": "function"})).unwrap(); + frames.run(Vec::new(), egui::Modifiers::NONE); + let mut editor = frames.app.function_editor.take().unwrap(); + editor.edit(&mut frames.app, materialcraft_engine::FunctionEdit::Add { operation: "const_float1".into(), at: [0.0; 2], snap: false }, false); + let selected = editor.selection.clone(); + frames.app.function_editor = Some(editor); + frames.run(Vec::new(), egui::Modifiers::NONE); + assert!(!selected.is_empty()); + assert_eq!(frames.app.function_editor.as_ref().unwrap().selection, selected); + menus::invoke(&mut frames.app, &frames.ctx, "edit.delete"); + menus::invoke(&mut frames.app, &frames.ctx, "edit.undo"); + frames.run(Vec::new(), egui::Modifiers::NONE); + assert_eq!(frames.app.function_editor.as_ref().unwrap().selection, selected); +} diff --git a/crates/ui-egui/src/graph/search.rs b/crates/ui-egui/src/graph/search.rs new file mode 100644 index 0000000..3ce3d58 --- /dev/null +++ b/crates/ui-egui/src/graph/search.rs @@ -0,0 +1,100 @@ +use super::{GraphCamera, NodeSearch}; +use crate::{MaterialCraftApp, i18n::tr, theme::Tokens}; +use egui::{Pos2, Ui}; +use egui_phosphor::regular as icon; +use materialcraft_engine::core::NodeId; +use serde_json::json; + +pub(super) fn open_search(app: &mut MaterialCraftApp, at: Pos2, connect: Option<(NodeId, String)>) { + app.graph.search = Some(NodeSearch { at, text: String::new(), sel: 0, connect, focus: true }); +} + +/// Catalog entries matching `text` (label or id contains every word) +pub(super) fn matches(text: &str) -> Vec<&'static materialcraft_engine::nodes::NodeDefinition> { + let words: Vec = text.split_whitespace().map(str::to_ascii_lowercase).collect(); + let mut v: Vec<_> = materialcraft_engine::nodes::catalog() + .iter() + .filter(|d| d.id != "graph_instance") + .filter(|d| { + let hay = format!("{} {} {}", d.label.to_ascii_lowercase(), d.id, d.category.to_ascii_lowercase()); + words.iter().all(|w| hay.contains(w.as_str())) + }) + .collect(); + if let Some(w) = words.first() { + v.sort_by_key(|d| !d.label.to_ascii_lowercase().starts_with(w.as_str())); + } + v +} + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &GraphCamera) { + let Some(s) = app.graph.search.as_mut() else { return }; + + let tk = Tokens::get(ui.ctx()); + let screen = cam.to_screen(s.at); + let mut close = false; + let mut pick: Option<&'static str> = None; + egui::Area::new(egui::Id::unique("node-search")).fixed_pos(screen).order(egui::Order::Foreground).show(ui.ctx(), |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + ui.set_width(260.0); + ui.horizontal(|ui| { + ui.label(egui::RichText::new(icon::MAGNIFYING_GLASS).color(tk.text_dim)); + let r = ui.add(egui::TextEdit::singleline(&mut s.text).hint_text(tr("Search nodes...")).desired_width(220.0)); + crate::widgets::name(&r, egui::Role::SearchInput, "Search nodes"); + if s.focus { + r.request_focus(); + s.focus = false; + } + if r.changed() { + s.sel = 0; + } + }); + let list = matches(&s.text); + let (up, down, enter, esc) = ui.input(|i| { + (i.key_pressed(egui::Key::ArrowUp), i.key_pressed(egui::Key::ArrowDown), i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape)) + }); + if down { + s.sel = (s.sel + 1).min(list.len().saturating_sub(1)); + } + if up { + s.sel = s.sel.saturating_sub(1); + } + if esc { + close = true; + } + if enter && let Some(d) = list.get(s.sel) { + pick = Some(d.id); + } + egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| { + for (i, d) in list.iter().enumerate().take(60) { + let r = ui.add( + egui::Button::selectable(i == s.sel, format!("{} ", d.label)) + .right_text(egui::RichText::new(d.group()).size(10.0).color(tk.text_dim)), + ); + if i == s.sel && (up || down) { + r.scroll_to_me(None); + } + if r.clicked() { + pick = Some(d.id); + } + } + if list.is_empty() { + ui.label(egui::RichText::new(tr("No matching node")).color(tk.text_dim)); + } + }); + }); + }); + let clicked_out = ui.input(|i| i.pointer.any_pressed()) + && ui.ctx().pointer_interact_pos().is_some_and(|p| !ui.ctx().layer_id_at(p).is_some_and(|l| l.id == egui::Id::unique("node-search"))); + if let Some(def) = pick { + let s = app.graph.search.take(); + if let Some(s) = s { + let mut p = json!({"def": def, "at": [s.at.x, s.at.y - 20.0]}); + if let Some((n, port)) = s.connect { + p["connectFrom"] = json!({"node": n.0, "port": port}); + } + app.run("graph.node.add", p); + } + } else if close || clicked_out { + app.graph.search = None; + } +} diff --git a/crates/ui-egui/src/graph/selection_commands.rs b/crates/ui-egui/src/graph/selection_commands.rs new file mode 100644 index 0000000..736492e --- /dev/null +++ b/crates/ui-egui/src/graph/selection_commands.rs @@ -0,0 +1,11 @@ +use crate::MaterialCraftApp; +use serde_json::Value; + +pub(crate) fn invoke(app: &mut MaterialCraftApp, selection: &mut Vec, command: &str, parameters: Value) { + if let Some(mut result) = app.run(command, parameters) + && let Some(ids) = result.get_mut("ids") + && let Ok(updated) = serde_json::from_value(ids.take()) + { + *selection = updated; + } +} diff --git a/crates/ui-egui/src/graph/subgraph_navigation.rs b/crates/ui-egui/src/graph/subgraph_navigation.rs new file mode 100644 index 0000000..f9e1eec --- /dev/null +++ b/crates/ui-egui/src/graph/subgraph_navigation.rs @@ -0,0 +1,86 @@ +use crate::{ + MaterialCraftApp, + docking::Panel, + function::{FunctionEditor, FunctionTarget}, +}; +use serde_json::json; + +use super::graph_parent::GraphParent; + +pub(crate) fn can_return(app: &MaterialCraftApp) -> bool { + app.function_editor.as_ref().is_some_and(|editor| editor.target != FunctionTarget::Graph) || crate::pattern::active(app) || !app.graph_parents.is_empty() +} + +pub(crate) fn parent(app: &mut MaterialCraftApp) { + if app.function_editor.as_ref().is_some_and(|editor| editor.target != FunctionTarget::Graph) { + app.function_editor = None; + } else if crate::pattern::active(app) { + app.pattern_editor = None; + } else if let Some(parent) = app.graph_parents.pop() + && open_graph(app, parent.graph) + { + app.session.selection = parent.selection.into_iter().filter(|id| app.session.graph().is_ok_and(|graph| graph.node(*id).is_ok())).collect(); + app.ui.graph_camera = parent.camera; + app.graph.framed_graph = Some(parent.graph); + app.ui.frame_all = false; + } + app.ui.dock.focus(Panel::Graph); +} + +pub(crate) fn open_function(app: &mut MaterialCraftApp, node: materialcraft_engine::core::NodeId, target: FunctionTarget) { + if !matches!(target, FunctionTarget::Pattern { .. }) { + app.pattern_editor = None; + } + app.graph.drag = None; + app.function_editor = Some(FunctionEditor::new(app.session.graph, node, target)); + app.ui.dock.focus(Panel::Graph); +} + +pub(crate) fn open_instance(app: &mut MaterialCraftApp, graph: usize) { + let parent = GraphParent { graph: app.session.graph, selection: app.session.selection.clone(), camera: app.ui.graph_camera }; + if open_graph(app, graph) { + app.graph_parents.push(parent); + app.ui.dock.focus(Panel::Graph); + } +} + +fn open_graph(app: &mut MaterialCraftApp, index: usize) -> bool { + let parents = std::mem::take(&mut app.graph_parents); + let material = app.session.material_preview.clone(); + let opened = app.run("graph.open", json!({"graph": index})).is_some(); + app.graph_parents = parents; + app.session.material_preview = material; + opened +} + +pub(crate) fn breadcrumb(app: &MaterialCraftApp) -> String { + let mut path: Vec = + app.graph_parents.iter().filter_map(|parent| app.session.pkg.graphs.get(parent.graph).map(|graph| graph.name.clone())).collect(); + if let Ok(graph) = app.session.graph() { + path.push(graph.name.clone()); + let owner = app.function_editor.as_ref().and_then(|editor| editor.node).or_else(|| app.pattern_editor.as_ref().map(|editor| editor.node)); + if let Some(node) = owner.and_then(|id| graph.node(id).ok()) { + path.push(super::node_label(node)); + } + } + if let Some(editor) = &app.function_editor { + match &editor.target { + FunctionTarget::Pattern { node, parameter } => { + let label = app + .pattern_editor + .as_ref() + .and_then(|editor| editor.current(app)) + .and_then(|graph| graph.nodes.iter().find(|item| item.id == *node)) + .map(|node| node.kind.label()); + if let Some(label) = label { + path.push(label.into()); + } + path.push(parameter.clone()); + } + FunctionTarget::Dynamic(parameter) => path.push(parameter.clone()), + FunctionTarget::Parameter(parameter) if parameter != "function" => path.push(parameter.clone()), + _ => {} + } + } + path.join(" / ") +} diff --git a/crates/ui-egui/src/graph/toolbar.rs b/crates/ui-egui/src/graph/toolbar.rs new file mode 100644 index 0000000..086c66f --- /dev/null +++ b/crates/ui-egui/src/graph/toolbar.rs @@ -0,0 +1,186 @@ +use super::navigation::{add_node_near_selection, view_center}; +use crate::{MaterialCraftApp, i18n::tr, theme::Tokens}; +use egui::Ui; +use egui_phosphor::regular as icon; +use serde_json::json; + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + let function = app.function_editor.is_some(); + let pattern = !function && crate::pattern::active(app); + let embedded_function = app.function_editor.as_ref().is_some_and(|editor| editor.target != crate::function::FunctionTarget::Graph); + let function_target = app.function_editor.as_ref().and_then(|editor| editor.command_target()); + let selection: Vec = if pattern { + app.pattern_editor.as_ref().map(|editor| editor.selection.iter().copied().map(u64::from).collect()).unwrap_or_default() + } else if function { + app.function_editor.as_ref().map(|editor| editor.selection.iter().copied().map(u64::from).collect()).unwrap_or_default() + } else { + app.session.selection.iter().map(|id| id.0).collect() + }; + let graph = app.session.graph; + let owner = pattern.then(|| app.pattern_editor.as_ref().map(|editor| editor.node.0)).flatten(); + row(ui, |ui| { + let b = button; + if common(app, ui, selection.len(), || { + let mut parameters = json!({"graph": graph, "ids": selection}); + if let Some(owner) = owner { + parameters["pattern"] = json!(owner); + } + if let Some(target) = &function_target { + parameters["function"] = json!(target); + } + parameters + }) { + app.ui.frame_all = true; + } + if !pattern && !embedded_function { + ui.separator(); + if b(ui, icon::SELECTION, tr("Add frame around the selection")) { + let parameters = if function { function_frame(app, &selection) } else { json!({}) }; + app.run("graph.frame.add", parameters); + } + if b(ui, icon::NOTE, tr("Add comment")) { + app.run("graph.comment.add", json!({})); + } + if b(ui, icon::MAP_PIN, tr("Add navigation pin")) { + let center = view_center(app); + app.run("graph.pin.add", json!({"at": [center.x, center.y]})); + } + } + + if !pattern && !function { + // Quick insert of the atomic nodes + for (ic, def) in [ + (icon::IMAGE, "bitmap"), + (icon::PALETTE, "uniform"), + (icon::STACK, "blend"), + (icon::DROP, "blur"), + (icon::SHUFFLE, "channels_shuffle"), + (icon::CHART_LINE, "curve"), + (icon::WIND, "directional_blur"), + (icon::ARROWS_OUT_LINE_HORIZONTAL, "directional_warp"), + (icon::RULER, "distance"), + (icon::MOUNTAINS, "emboss"), + (icon::GRADIENT, "gradient_map"), + (icon::CIRCLE_HALF, "grayscale_conversion"), + (icon::SWATCHES, "hsl"), + (icon::SLIDERS_HORIZONTAL, "levels"), + (icon::CUBE, "normal"), + (icon::CODE, "pixel_processor"), + (icon::DIAMOND, "sharpen"), + (icon::ARROWS_CLOCKWISE, "transformation"), + (icon::WAVES, "warp"), + (icon::SIGN_IN, "input_grayscale"), + (icon::SIGN_OUT, "output"), + ] { + let label = materialcraft_engine::nodes::find(def).map_or(def, |d| d.label); + if b(ui, ic, label) { + add_node_near_selection(app, def); + } + } + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if super::subgraph_navigation::can_return(app) { + if b(ui, icon::ARROW_BEND_UP_LEFT, tr("Return to parent graph")) { + crate::menus::invoke(app, ui.ctx(), "ui.graph.parent"); + } + ui.label(super::subgraph_navigation::breadcrumb(app)); + } + if pattern { + if app.pattern_editor.as_ref().and_then(|editor| editor.current(app)).is_some_and(|graph| graph.root.is_none()) { + ui.label(tr("Set a node as the root")); + } + } else { + thumbnails(app, ui); + if function { + if app.function_editor.as_ref().and_then(|editor| editor.current(app)).is_some_and(|graph| graph.output.is_none()) { + ui.label(tr("Set a node as the output")); + } + } else { + parent_size(app, ui); + } + } + }); + }); +} + +fn row(ui: &mut Ui, draw: impl FnOnce(&mut Ui)) { + let tokens = Tokens::get(ui.ctx()); + egui::Frame::NONE.fill(tokens.panel).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + draw(ui); + }); + }); +} + +fn button(ui: &mut Ui, icon: &str, tooltip: &str) -> bool { + crate::widgets::icon_button(ui, icon, tooltip, false, 22.0).clicked() +} + +fn common(app: &mut MaterialCraftApp, ui: &mut Ui, selection_count: usize, parameters: impl Fn() -> serde_json::Value) -> bool { + let frame = button(ui, icon::CORNERS_OUT, tr("Frame all (F)")); + let can_align = selection_count > 1; + for (icon, mode, tooltip) in [ + (icon::ALIGN_LEFT, "left", "Align left"), + (icon::ALIGN_TOP, "top", "Align top"), + (icon::ALIGN_CENTER_HORIZONTAL, "hcenter", "Align centers horizontally"), + (icon::ALIGN_CENTER_VERTICAL, "vcenter", "Align centers vertically"), + (icon::COLUMNS, "hdistribute", "Distribute horizontally"), + (icon::ROWS, "vdistribute", "Distribute vertically"), + ] { + if ui.add_enabled_ui(can_align, |ui| button(ui, icon, tr(tooltip))).inner { + let mut parameters = parameters(); + parameters["mode"] = json!(mode); + app.run("graph.align", parameters); + } + } + ui.separator(); + if crate::widgets::icon_button(ui, icon::GRID_FOUR, tr("Snap to grid"), app.ui.prefs.snap_to_grid, 22.0).clicked() { + crate::menus::invoke(app, ui.ctx(), "ui.graph.snapToGrid"); + } + frame +} + +fn thumbnails(app: &mut MaterialCraftApp, ui: &mut Ui) { + let thumbnails = app.ui.prefs.thumbnails; + if crate::widgets::icon_button(ui, icon::IMAGE, tr("Show node thumbnails"), thumbnails, 22.0).clicked() { + app.ui.prefs.thumbnails = !thumbnails; + } +} + +/// "Parent size: [1024 ▾] × [1024 ▾]" +fn parent_size(app: &mut MaterialCraftApp, ui: &mut Ui) { + let Ok(g) = app.session.graph() else { return }; + + let [w, h] = g.size; + let mut nw = w; + let mut nh = h; + let combo = |ui: &mut Ui, id: &str, v: &mut u32| { + let r = egui::ComboBox::from_id_salt(id).width(64.0).selected_text(format!("{}", 1u32 << *v)).show_ui(ui, |ui| { + for l in 4..=13u32 { + ui.selectable_value(v, l, format!("{}", 1u32 << l)); + } + }); + crate::widgets::name(&r.response, egui::Role::ComboBox, if id == "parent-w" { "Parent width" } else { "Parent height" }); + }; + + combo(ui, "parent-h", &mut nh); + ui.label("x"); + combo(ui, "parent-w", &mut nw); + ui.label(egui::RichText::new(tr("Parent size:")).color(Tokens::get(ui.ctx()).text_dim)); + if (nw, nh) != (w, h) { + app.run("graph.size", json!({"log2": [nw, nh]})); + } +} + +fn function_frame(app: &MaterialCraftApp, selection: &[u64]) -> serde_json::Value { + let camera = super::GraphCamera { origin: app.graph.view.min, pan: app.ui.graph_camera.pan.into(), zoom: app.ui.graph_camera.zoom }; + let bounds = app.graph.rects.iter().filter(|(id, _)| selection.contains(&id.0)).fold(egui::Rect::NOTHING, |bounds, (_, rect)| bounds.union(*rect)); + if !bounds.is_finite() { + return json!({}); + } + + let start = camera.to_graph(bounds.min); + let size = bounds.size() / camera.zoom; + json!({"rect": [start.x - 24.0, start.y - 44.0, size.x + 48.0, size.y + 68.0]}) +} diff --git a/crates/ui-egui/src/graph/wire_actions.rs b/crates/ui-egui/src/graph/wire_actions.rs new file mode 100644 index 0000000..7483458 --- /dev/null +++ b/crates/ui-egui/src/graph/wire_actions.rs @@ -0,0 +1,52 @@ +use super::WireRef; +use crate::{MaterialCraftApp, i18n::tr}; +use egui::{Pos2, Ui}; +use egui_phosphor::regular as icon; +use serde_json::json; + +/// `wires` as the `{wires: [{to, toPort}, ...]}` parameter of the wire commands +fn wires_json(wires: &[WireRef]) -> serde_json::Value { + json!({"wires": wires.iter().map(|(to, port)| json!({"to": to.0, "toPort": port})).collect::>()}) +} + +/// Delete the selected wires in one undo step (the Delete and Backspace keys); `false` when none is selected +pub fn delete_selected_wires(app: &mut MaterialCraftApp) -> bool { + let wires = std::mem::take(&mut app.graph.selected_wires); + if wires.is_empty() { + return false; + } + app.run("graph.wire.delete", wires_json(&wires)); + true +} + +/// Reverse the sources of selected wires so pressing X again restores them +pub fn swap_selected_wires(app: &mut MaterialCraftApp) -> bool { + if app.graph.selected_wires.is_empty() { + return false; + } + let params = wires_json(&app.graph.selected_wires); + app.run("graph.wire.swap", params); + true +} + +pub(super) fn wire_menu(app: &mut MaterialCraftApp, ui: &mut Ui, (to, port): WireRef, at: Pos2) { + let n = app.graph.selected_wires.len(); + if ui.button(format!("{} {}", icon::DOT_OUTLINE, tr("Insert reroute dot"))).clicked() { + app.run("graph.wire.insertDot", json!({"to": to.0, "toPort": port, "at": [at.x, at.y]})); + app.graph.selected_wires.clear(); + ui.close(); + } + if n >= 2 && ui.button(format!("{} {} (X)", icon::ARROWS_LEFT_RIGHT, tr("Swap selected links"))).clicked() { + swap_selected_wires(app); + ui.close(); + } + let label = if n >= 2 { tr("Delete selected links") } else { tr("Delete link") }; + + if ui.button(format!("{} {label}", icon::TRASH)).clicked() { + if n < 2 { + app.graph.selected_wires = vec![(to, port)]; + } + delete_selected_wires(app); + ui.close(); + } +} diff --git a/crates/ui-egui/src/graph/wire_geometry.rs b/crates/ui-egui/src/graph/wire_geometry.rs new file mode 100644 index 0000000..7bfb10a --- /dev/null +++ b/crates/ui-egui/src/graph/wire_geometry.rs @@ -0,0 +1,52 @@ +use super::WireRef; +use egui::{Color32, Pos2, Rect, Stroke, pos2}; + +/// Pointer distance in points within which a wire is hit +pub(super) const WIRE_HIT: f32 = 5.0; + +pub(crate) fn bezier_points(a: Pos2, b: Pos2) -> [Pos2; 4] { + curve_points(a, b, egui::Vec2::X) +} + +pub(crate) fn curve_points(source: Pos2, destination: Pos2, axis: egui::Vec2) -> [Pos2; 4] { + let offset = axis * ((destination - source).dot(axis).abs() * 0.5).max(30.0); + [source, source + offset, destination - offset, destination] +} + +pub(crate) fn bezier(p: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke) { + p.add(egui::epaint::CubicBezierShape::from_points_stroke(bezier_points(a, b), false, Color32::TRANSPARENT, stroke)); +} + +/// The point at `t` (0..1) along a cubic bezier +pub(super) fn bezier_at(c: &[Pos2; 4], t: f32) -> Pos2 { + let u = 1.0 - t; + let w = [u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t]; + pos2(c.iter().zip(w).map(|(p, w)| p.x * w).sum(), c.iter().zip(w).map(|(p, w)| p.y * w).sum()) +} + +/// Distance from `p` to a cubic bezier (sampled as a polyline) +pub(super) fn bezier_distance(c: &[Pos2; 4], p: Pos2) -> f32 { + const N: usize = 32; + let mut best = f32::INFINITY; + let mut prev = c[0]; + for i in 1..=N { + let q = bezier_at(c, i as f32 / N as f32); + let (seg, rel) = (q - prev, p - prev); + let t = if seg.length_sq() > 0.0 { (rel.dot(seg) / seg.length_sq()).clamp(0.0, 1.0) } else { 0.0 }; + + best = best.min((prev + seg * t).distance(p)); + prev = q; + } + best +} + +/// The wire nearest `p` within [`WIRE_HIT`] points +pub(super) fn wire_at(wires: &[(WireRef, [Pos2; 4])], p: Pos2) -> Option<&WireRef> { + wires + .iter() + .filter(|(_, c)| Rect::from_points(c).expand(WIRE_HIT).contains(p)) + .map(|(w, c)| (w, bezier_distance(c, p))) + .filter(|(_, d)| *d <= WIRE_HIT) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(w, _)| w) +} diff --git a/crates/ui-egui/src/graph_drag_payload.rs b/crates/ui-egui/src/graph_drag_payload.rs new file mode 100644 index 0000000..c4cc3da --- /dev/null +++ b/crates/ui-egui/src/graph_drag_payload.rs @@ -0,0 +1,4 @@ +/// A graph resource dragged from Explorer to a material preview +pub(crate) struct GraphDragPayload { + pub name: String, +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7937e5c..9b6eaa2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -9,11 +9,14 @@ pub mod explorer; pub mod fonts; pub mod function; pub mod graph; +mod graph_drag_payload; pub mod i18n; pub mod levels_editor; pub mod library; +mod material_preview_menu; mod menu_item; pub mod menus; +#[path = "property/mod.rs"] pub mod properties; pub mod state; pub mod theme; diff --git a/crates/ui-egui/src/library.rs b/crates/ui-egui/src/library.rs index 639eee8..7815eba 100644 --- a/crates/ui-egui/src/library.rs +++ b/crates/ui-egui/src/library.rs @@ -39,14 +39,16 @@ fn category_icon(top: &str) -> &'static str { } pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - if crate::pattern::active(app) { - crate::pattern::library::show(app, ui); - return; - } - - if app.session.graph().is_ok_and(|graph| graph.function.is_some()) { - crate::function::library::show(app, ui); - return; + 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()); diff --git a/crates/ui-egui/src/material_craft_app.rs b/crates/ui-egui/src/material_craft_app.rs index 85ba045..8739b83 100644 --- a/crates/ui-egui/src/material_craft_app.rs +++ b/crates/ui-egui/src/material_craft_app.rs @@ -19,9 +19,10 @@ pub struct MaterialCraftApp { pub graph: graph::GraphView, pub view3d: view3d::View3dState, pub view2d: view2d::View2dState, - /// The function graph editor window, when open + /// Embedded graph editors in the main graph panel pub pattern_editor: Option, pub function_editor: Option, + pub(crate) graph_parents: Vec, /// Synthetic input from the control channel, fed to egui on the next frames pub input_queue: VecDeque, /// Replies waiting for the next window capture (`ui.screenshot`) @@ -39,6 +40,7 @@ pub struct MaterialCraftApp { pub fonts: fonts::UiFonts, /// The icon font is installed (it takes effect on the frame after `set_fonts`) fonts_ready: bool, + ui_gesture_active: bool, } impl MaterialCraftApp { @@ -68,6 +70,7 @@ impl MaterialCraftApp { view3d: view3d::View3dState::default(), view2d: view2d::View2dState::default(), function_editor: None, + graph_parents: Vec::new(), pattern_editor: None, input_queue: VecDeque::new(), pending_screenshots: Vec::new(), @@ -79,6 +82,7 @@ impl MaterialCraftApp { styled: None, fonts: fonts::UiFonts::default(), fonts_ready: false, + ui_gesture_active: false, }; i18n::set_language(&app.ui.prefs.language); app.apply_prefs(); @@ -122,6 +126,9 @@ impl MaterialCraftApp { match materialcraft_engine::execute(&mut self.session, id, ¶ms) { Ok(v) => { self.close_subgraph_after(id); + if matches!(id, "view.3d.assign" | "view.3d.outputs") { + self.ui.dock.focus(docking::Panel::View3d); + } Some(v) } Err(e) => { @@ -134,9 +141,26 @@ impl MaterialCraftApp { pub(crate) fn close_subgraph_after(&mut self, command: &str) { if command.starts_with("file.new") || matches!(command, "file.open" | "graph.open" | "graph.delete" | "graph.duplicate") { self.graph.inspected_node = None; + self.graph_parents.clear(); self.pattern_editor = None; self.function_editor = None; } + self.reconcile_editors(); + if (materialcraft_engine::selection_commands::supports(command) || matches!(command, "edit.undo" | "edit.redo")) + && let Some(editor) = &mut self.function_editor + && matches!(editor.target, function::FunctionTarget::Graph) + { + editor.selection = self.session.selection.iter().filter_map(|id| u32::try_from(id.0).ok()).collect(); + } + } + + pub(crate) fn reconcile_editors(&mut self) { + if self.function_editor.as_ref().is_some_and(|editor| editor.current(self).is_none()) { + self.function_editor = None; + } + if self.pattern_editor.as_ref().is_some_and(|editor| editor.current(self).is_none()) { + self.pattern_editor = None; + } } pub fn toast(&mut self, text: impl Into, error: bool) { @@ -224,6 +248,9 @@ impl MaterialCraftApp { if (ctx.zoom_factor() - scale).abs() > 1e-3 { ctx.set_zoom_factor(scale); } + if ctx.input(|input| input.pointer.any_pressed()) { + self.session.finish_edit(); + } control::poll(self, ctx); web_files::poll(self); for f in ctx.input(|i| i.raw.dropped_files.clone()) { @@ -233,6 +260,7 @@ impl MaterialCraftApp { cook::drive(self, ctx); #[cfg(not(target_arch = "wasm32"))] self.autosave(now); + self.reconcile_editors(); menus::shortcuts(self, ctx); self.toasts.retain(|t| t.until > now); if !self.input_queue.is_empty() { @@ -255,7 +283,11 @@ impl MaterialCraftApp { toolbar::status_bar(self, ui); egui::CentralPanel::default().frame(egui::Frame::NONE.fill(theme::Tokens::get(&ctx).chrome)).show(ui, |ui| docking::show(self, ui)); windows::show(self, &ctx); - function::show(self, &ctx); + let gesture_active = ctx.input(|input| input.pointer.any_down()) || ctx.egui_wants_keyboard_input(); + if !gesture_active && (self.ui_gesture_active || ctx.input(|input| input.pointer.any_released())) { + self.session.finish_edit(); + } + self.ui_gesture_active = gesture_active; crate::toast::show(self, &ctx); control::request_screenshots(self, &ctx); let dt = (now_ms() - t0) as f32; diff --git a/crates/ui-egui/src/material_preview_menu.rs b/crates/ui-egui/src/material_preview_menu.rs new file mode 100644 index 0000000..539486b --- /dev/null +++ b/crates/ui-egui/src/material_preview_menu.rs @@ -0,0 +1,44 @@ +use egui::Ui; +use materialcraft_engine::{ + MaterialSource, Session, + core::{MaterialChannel, NodeId}, +}; +use serde_json::{Value, json}; + +use crate::i18n::tr; + +/// Shared node/output assignment menu for the canvas and Explorer +pub(crate) fn show(ui: &mut Ui, session: &Session, graph_index: usize, node_id: NodeId) -> Option { + let graph = session.pkg.graphs.get(graph_index)?; + let node = graph.node(node_id).ok()?; + let ports = if node.def == "output" { + vec![("output".to_string(), materialcraft_engine::eval::identifier(node))] + } else { + materialcraft_engine::eval::ports(&session.pkg, graph, node).1.into_iter().map(|port| (port.id, port.label)).collect() + }; + let ports: Vec<_> = + ports.into_iter().filter(|(port, _)| MaterialSource { graph: graph_index, node: node_id, port: port.clone() }.is_image(&session.pkg)).collect(); + let mut action = None; + ui.add_enabled_ui(!ports.is_empty(), |ui| { + for (label, reset) in [("View in 3D view", false), ("Reset and view in 3D view", true)] { + ui.menu_button(tr(label), |ui| { + for (port, label) in &ports { + let mut channels = |ui: &mut Ui| { + for channel in MaterialChannel::ALL { + if ui.button(tr(channel.label())).clicked() { + action = Some(json!({"graph": graph_index, "node": node_id.0, "port": port, "channel": channel.id(), "reset": reset})); + ui.close(); + } + } + }; + if ports.len() == 1 { + channels(ui); + } else { + ui.menu_button(label, channels); + } + } + }); + } + }); + action +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 99bf687..cecf492 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -97,11 +97,7 @@ fn is_ui(id: &str) -> bool { /// Whether an item can run now pub fn enabled(app: &MaterialCraftApp, id: &str) -> bool { - if let Some(enabled) = crate::pattern::enabled(app, id) { - return enabled; - } - - if let Some(enabled) = crate::function::enabled(app, id) { + if let Some(enabled) = crate::graph::editor_actions::enabled(app, id) { return enabled; } @@ -126,11 +122,7 @@ pub fn implemented(id: &str) -> bool { /// Invoke a menu item (menus, shortcuts, the control channel's `ui.menu.invoke`) pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) { - if crate::pattern::invoke(app, id) { - return; - } - - if crate::function::invoke(app, id) { + if crate::graph::editor_actions::invoke(app, id) { return; } @@ -288,7 +280,7 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { } // Selected wires handle deletion and swapping before nodes - if !crate::pattern::active(app) && !app.graph.selected_wires.is_empty() { + if crate::graph::editor_target::EditorTarget::resolve(app) == crate::graph::editor_target::EditorTarget::Material && !app.graph.selected_wires.is_empty() { if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Delete) | i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace)) { crate::graph::delete_selected_wires(app); } else if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::X)) { diff --git a/crates/ui-egui/src/pattern/actions.rs b/crates/ui-egui/src/pattern/actions.rs index a8aa13d..65b1ea0 100644 --- a/crates/ui-egui/src/pattern/actions.rs +++ b/crates/ui-egui/src/pattern/actions.rs @@ -1,4 +1,4 @@ -use super::selection; +use super::PatternEditor; use crate::MaterialCraftApp; pub(crate) fn active(app: &MaterialCraftApp) -> bool { @@ -8,18 +8,15 @@ pub(crate) fn active(app: &MaterialCraftApp) -> bool { } pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option { - if command == "ui.graph.parent" { - return Some(active(app)); - } if !active(app) { return None; } - if let Some(enabled) = selection::enabled(app.pattern_editor.as_ref()?, command) { + if let Some(enabled) = editor_enabled(app, app.pattern_editor.as_ref()?, command) { return Some(enabled); } match command { - "ui.graph.snapToGrid" | "graph.cook" => None, + "ui.graph.snapToGrid" | "graph.cook" | "edit.finish" => None, command if command.starts_with("graph.") || command.starts_with("ui.graph.") @@ -32,24 +29,33 @@ pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option { } pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool { - if command == "ui.graph.parent" { - app.pattern_editor = None; - app.function_editor = None; - return true; - } let Some(allowed) = enabled(app, command) else { return false }; + if !allowed { return true; } let Some(mut editor) = app.pattern_editor.take() else { return true }; - if let Some(mut graph) = editor.current(app) { - match selection::run(&mut editor, &mut graph, command, app.ui.prefs.snap_to_grid) { - Ok(true) => editor.commit(app, graph), - Ok(false) => {} - Err(error) => app.toast(error, true), - } - } + + invoke_editor(app, &mut editor, command); app.pattern_editor = Some(editor); true } + +pub(super) fn invoke_editor(app: &mut MaterialCraftApp, editor: &mut PatternEditor, command: &str) { + if editor_enabled(app, editor, command) != Some(true) { + return; + } + let parameters = editor.selection_parameters(command); + crate::graph::selection_commands::invoke(app, &mut editor.selection, command, parameters); +} + +pub(super) fn editor_enabled(app: &MaterialCraftApp, editor: &PatternEditor, command: &str) -> Option { + materialcraft_engine::selection_commands::enabled_for( + &app.session, + &materialcraft_engine::SelectionTarget::Pattern(editor.node), + &editor.selection, + command, + ) + .map(|enabled| enabled && editor.current(app).is_some()) +} diff --git a/crates/ui-egui/src/pattern/canvas.rs b/crates/ui-egui/src/pattern/canvas.rs index 41e6e6a..296eb3a 100644 --- a/crates/ui-egui/src/pattern/canvas.rs +++ b/crates/ui-egui/src/pattern/canvas.rs @@ -1,5 +1,6 @@ +use crate::graph::canvas_geometry::CanvasGeometry; use egui::{Color32, Rect, Sense, Stroke, Ui, vec2}; -use materialcraft_engine::core::{NodeId, PatternGraph}; +use materialcraft_engine::core::NodeId; use materialcraft_engine::nodes::PortKind; use std::collections::BTreeMap; @@ -15,94 +16,79 @@ const PORT_COLOR: Color32 = Color32::from_rgb(165, 157, 215); pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let Some(mut editor) = app.pattern_editor.take() else { return }; - let Some(mut graph) = editor.current(app) else { return }; - editor.selection.retain(|id| graph.nodes.iter().any(|node| node.id == *id)); - let parent = app.session.graph().map(|graph| graph.name.clone()).unwrap_or_default(); - let label = app.session.graph().ok().and_then(|graph| graph.node(editor.node).ok()).map(crate::graph::node_label).unwrap_or_default(); - let mut back = false; - ui.horizontal(|ui| { - back = ui.button(&parent).on_hover_text(tr("Return to parent graph")).clicked(); - ui.label("›"); - ui.label(label); - }); - ui.horizontal(|ui| { - if ui.button(tr("Frame all")).clicked() { - editor.framed = false; - } - ui.checkbox(&mut app.ui.prefs.snap_to_grid, tr("Snap to grid")); - if graph.root.is_none() { - ui.label(tr("Set a node as the root")); - } - }); + if let Some(graph) = editor.current(app) { + let present: std::collections::BTreeSet<_> = graph.nodes.iter().map(|node| node.id).collect(); + editor.selection.retain(|id| present.contains(id)); + } + let Some((geometry, response, camera)) = paint(app, &mut editor, ui) else { return }; + + app.ui.frame_all = false; + geometry.publish(&mut app.graph, response.rect); + app.graph.frames.clear(); + app.graph.comments.clear(); + super::input::handle(app, &mut editor, ui, &response, &camera); + if let Some(PatternDrag::Wire { node, slot }) = editor.drag + && let Some(source) = app.graph.ports.iter().find(|port| { + port.node.0 == u64::from(node) + && port.output == slot.is_some() + && slot.is_none_or(|slot| port.port == format!("output{slot}") || slot == 0 && port.port == "output") + }) + && let Some(pointer) = ui.input(|input| input.pointer.hover_pos()) + { + let points = if slot.is_some() { geometry::wire(source.pos, pointer) } else { geometry::wire(pointer, source.pos) }; + ui.painter_at(response.rect).add(egui::epaint::CubicBezierShape::from_points_stroke(points, false, Color32::TRANSPARENT, Stroke::new(2.0, PORT_COLOR))); + } + response.context_menu(|ui| super::context_menu::show(app, &mut editor, ui)); editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node); - let changed = canvas(app, &mut editor, &mut graph, ui); - editor.inspected_node = - crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node).filter(|id| graph.nodes.iter().any(|node| node.id == *id)); - if changed { - editor.commit(app, graph); - } - if back { - app.function_editor = None; - } else { - app.pattern_editor = Some(editor); - } + app.pattern_editor = Some(editor); } -fn canvas(app: &mut MaterialCraftApp, editor: &mut PatternEditor, graph: &mut PatternGraph, ui: &mut Ui) -> bool { +fn paint(app: &MaterialCraftApp, editor: &mut PatternEditor, ui: &mut Ui) -> Option<(CanvasGeometry, egui::Response, GraphCamera)> { + let graph = editor.current(app)?; + let selected: std::collections::BTreeSet<_> = editor.selection.iter().copied().collect(); + let mut geometry = CanvasGeometry::default(); let (bounds, response) = ui.allocate_exact_size(ui.available_size().max(vec2(100.0, 100.0)), Sense::click_and_drag()); crate::widgets::name(&response, egui::Role::Canvas, "FX-Map graph"); let painter = ui.painter_at(bounds); painter.rect_filled(bounds, 0.0, Color32::from_rgb(0x26, 0x28, 0x2c)); let snap = app.ui.prefs.snap_to_grid; - let frame_key = response.hovered() && !ui.ctx().egui_wants_keyboard_input() && ui.input(|input| input.key_pressed(egui::Key::F)); + let frame_key = GraphCamera::frame_key(ui, bounds); if !editor.framed || app.ui.frame_all || frame_key { - let destination = graph.nodes.iter().map(|node| geometry::bounds(node, editor, snap)).fold(Rect::NOTHING, |all, node| all.union(node)); - if destination.is_finite() { - let destination = destination.expand(48.0); - editor.zoom = (bounds.width() / destination.width()).min(bounds.height() / destination.height()).clamp(0.15, 1.2); - editor.pan = destination.center().to_vec2() - bounds.size() * 0.5 / editor.zoom; - } + let selected_only = frame_key && !editor.selection.is_empty(); + let destination = graph + .nodes + .iter() + .filter(|node| !selected_only || selected.contains(&node.id)) + .map(|node| geometry::bounds(node, editor, snap, selected.contains(&node.id))) + .fold(Rect::NOTHING, |all, node| all.union(node)); + let camera = GraphCamera::fit(bounds, destination); + editor.pan = camera.pan; + editor.zoom = camera.zoom; editor.framed = true; - app.ui.frame_all = false; } let mut camera = GraphCamera { origin: bounds.min, pan: editor.pan, zoom: editor.zoom }; - if response.hovered() - && let Some(pointer) = ui.input(|input| input.pointer.hover_pos()) - { - let scroll = ui.input(|input| input.smooth_scroll_delta.y); - if scroll != 0.0 { - let before = camera.to_graph(pointer); - editor.zoom = (editor.zoom * (scroll * 0.0025).exp()).clamp(0.15, 3.0); - editor.pan = before.to_vec2() - (pointer - bounds.min) / editor.zoom; - camera.pan = editor.pan; - camera.zoom = editor.zoom; - } - } - crate::graph::canvas::grid(&painter, &camera, bounds); - app.graph.view = bounds; - app.graph.rects.clear(); - app.graph.ports.clear(); - app.graph.wires.clear(); - app.graph.frames.clear(); - app.graph.comments.clear(); - + camera.zoom_from_input(ui, bounds); + editor.pan = camera.pan; + editor.zoom = camera.zoom; + crate::graph::grid::paint(&painter, &camera, bounds); let rectangles: BTreeMap<_, _> = graph .nodes .iter() .map(|node| { - let bounds = geometry::bounds(node, editor, snap); + let bounds = geometry::bounds(node, editor, snap, selected.contains(&node.id)); (node.id, Rect::from_min_max(camera.to_screen(bounds.min), camera.to_screen(bounds.max))) }) .collect(); for node in &graph.nodes { let Some(bounds) = rectangles.get(&node.id) else { continue }; + for (slot, child) in node.children.iter().enumerate() { if let Some(child_bounds) = child.and_then(|id| rectangles.get(&id)) { let points = geometry::wire(geometry::port(*bounds, Some(slot), node.children.len()), child_bounds.center_top()); painter.add(egui::epaint::CubicBezierShape::from_points_stroke(points, false, Color32::TRANSPARENT, Stroke::new(2.0, PORT_COLOR))); - app.graph.wires.push(((NodeId(u64::from(node.id)), node.kind.child_port(slot).unwrap_or_default().to_string()), points)); + geometry.wires.push(((NodeId(u64::from(node.id)), node.kind.child_port(slot).unwrap_or_default().to_string()), points)); } } } @@ -110,8 +96,10 @@ fn canvas(app: &mut MaterialCraftApp, editor: &mut PatternEditor, graph: &mut Pa let tokens = Tokens::get(ui.ctx()); for node in &graph.nodes { let Some(bounds) = rectangles.get(&node.id).copied() else { continue }; - app.graph.rects.push((NodeId(u64::from(node.id)), bounds)); - let outline = if editor.selection.contains(&node.id) { tokens.accent } else { Color32::from_gray(30) }; + + geometry.rects.push((NodeId(u64::from(node.id)), bounds)); + let outline = if selected.contains(&node.id) { tokens.accent } else { Color32::from_gray(30) }; + super::node_canvas::paint(&painter, bounds, node.kind, editor.zoom, outline); if graph.root == Some(node.id) { painter.text( @@ -132,7 +120,7 @@ fn canvas(app: &mut MaterialCraftApp, editor: &mut PatternEditor, graph: &mut Pa painter.circle_stroke(position, 5.0 * editor.zoom, Stroke::new(1.5, Color32::from_gray(30))); ui.interact(Rect::from_center_size(position, vec2(16.0, 16.0)), response.id.with((node.id, slot)), Sense::hover()) .on_hover_text(tr("Drag to connect; Alt-click to disconnect")); - app.graph.ports.push(PortHit { + geometry.ports.push(PortHit { node: NodeId(u64::from(node.id)), output: slot.is_some(), port: slot.map_or_else(|| "input".into(), |slot| node.kind.child_port(slot).unwrap_or_default().to_string()), @@ -143,16 +131,5 @@ fn canvas(app: &mut MaterialCraftApp, editor: &mut PatternEditor, graph: &mut Pa } } - let mut changed = super::input::handle(app, editor, graph, ui, &response, &camera); - if let Some(PatternDrag::Wire { node, slot }) = editor.drag - && let Some(bounds) = rectangles.get(&node) - && let Some(pointer) = ui.input(|input| input.pointer.hover_pos()) - { - let count = graph.nodes.iter().find(|candidate| candidate.id == node).map_or(0, |node| node.children.len()); - let source = geometry::port(*bounds, slot, count); - let points = if slot.is_some() { geometry::wire(source, pointer) } else { geometry::wire(pointer, source) }; - painter.add(egui::epaint::CubicBezierShape::from_points_stroke(points, false, Color32::TRANSPARENT, Stroke::new(2.0, PORT_COLOR))); - } - response.context_menu(|ui| changed |= super::context_menu::show(app, editor, graph, ui)); - changed + Some((geometry, response, camera)) } diff --git a/crates/ui-egui/src/pattern/context_menu.rs b/crates/ui-egui/src/pattern/context_menu.rs index eb960e7..b0a4b54 100644 --- a/crates/ui-egui/src/pattern/context_menu.rs +++ b/crates/ui-egui/src/pattern/context_menu.rs @@ -1,71 +1,39 @@ +use super::PatternEditor; +use crate::{MaterialCraftApp, graph::edit_menu, i18n::tr, menus}; use egui::Ui; -use materialcraft_engine::core::{PatternGraph, PatternNodeKind}; +use materialcraft_engine::{PatternEdit, core::PatternNodeKind}; -use super::{PatternEditor, selection}; -use crate::{MaterialCraftApp, i18n::tr, menus}; - -pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut PatternEditor, graph: &mut PatternGraph, ui: &mut Ui) -> bool { - let mut changed = false; +pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: &mut Ui) { + let mut add = None; ui.menu_button(tr("Add node"), |ui| { - let kinds = PatternNodeKind::ALL.into_iter().filter(|kind| *kind != PatternNodeKind::Dot); - let entries = kinds.map(|kind| (kind.native_id(), kind.label(), "FX-Map")); - if let Some(id) = crate::graph::add_node_menu::show(ui, entries) - && let Some(kind) = PatternNodeKind::ALL.into_iter().find(|kind| kind.native_id() == id) - { - match editor.add(graph, kind, app.ui.prefs.snap_to_grid) { - Ok(()) => changed = true, - Err(error) => app.toast(error, true), - } + let entries = PatternNodeKind::ALL.into_iter().filter(|kind| *kind != PatternNodeKind::Dot).map(|kind| (kind.native_id(), kind.label(), "FX-Map")); + if let Some(id) = crate::graph::add_node_menu::show(ui, entries) { + add = PatternNodeKind::ALL.into_iter().find(|kind| kind.native_id() == id); } }); if ui.button(tr("Add Dot node")).clicked() { - match editor.add(graph, PatternNodeKind::Dot, app.ui.prefs.snap_to_grid) { - Ok(()) => changed = true, - Err(error) => app.toast(error, true), - } + add = Some(PatternNodeKind::Dot); ui.close(); } + if let Some(kind) = add { + editor.edit(app, PatternEdit::Add { kind, at: editor.menu_at.into(), snap: app.ui.prefs.snap_to_grid }, false); + } if let Some(id) = editor.selection.last().copied() && ui.button(tr("Set as root")).clicked() { - graph.root = Some(id); - changed = true; + editor.edit(app, PatternEdit::Root { id }, false); ui.close(); } ui.separator(); - - for (label, command) in [ - ("Copy selection", "edit.copy"), - ("Cut selection", "edit.cut"), - ("Paste", "edit.paste"), - ("Paste without link", "edit.pasteWithoutLinks"), - ("Duplicate selection", "edit.duplicate"), - ("Duplicate selection without link", "edit.duplicateWithoutLinks"), - ("Delete selection", "edit.delete"), - ("Select all", "edit.selectAll"), - ("Select upstream nodes", "graph.selectUpstream"), - ("Select downstream nodes", "graph.selectDownstream"), - ] { - let mut button = egui::Button::new(tr(label)); - if let Some(shortcut) = menus::shortcut_of(command) { - button = button.shortcut_text(shortcut); - } - if ui.add_enabled(selection::enabled(editor, command).unwrap_or(false), button).clicked() { - match selection::run(editor, graph, command, app.ui.prefs.snap_to_grid) { - Ok(edit) => changed |= edit, - Err(error) => app.toast(error, true), - } - ui.close(); - } + if edit_menu::button(ui, "Save package", "file.save", menus::enabled(app, "file.save")) { + menus::invoke(app, ui.ctx(), "file.save"); + } + if let Some(command) = edit_menu::selection(ui, |command| super::actions::editor_enabled(app, editor, command).unwrap_or(false)) { + super::actions::invoke_editor(app, editor, command); } ui.separator(); if ui.button(tr("Frame all")).clicked() { editor.framed = false; ui.close(); } - if ui.add(egui::Button::new(tr("Save package")).shortcut_text("Ctrl+S")).clicked() { - menus::invoke(app, ui.ctx(), "file.save"); - ui.close(); - } - changed } diff --git a/crates/ui-egui/src/pattern/geometry.rs b/crates/ui-egui/src/pattern/geometry.rs index 01eba35..21e98d6 100644 --- a/crates/ui-egui/src/pattern/geometry.rs +++ b/crates/ui-egui/src/pattern/geometry.rs @@ -6,12 +6,12 @@ use super::{PatternDrag, PatternEditor}; pub(super) const NODE_SIZE: f32 = 96.0; pub(super) const HEADER_HEIGHT: f32 = 18.0; -pub(super) fn bounds(node: &PatternNode, editor: &PatternEditor, snap: bool) -> Rect { +pub(super) fn bounds(node: &PatternNode, editor: &PatternEditor, snap: bool, selected: bool) -> Rect { let mut position = materialcraft_engine::graph_grid::snap_position(node.position, false); if let Some(PatternDrag::Nodes { delta, .. }) = editor.drag - && editor.selection.contains(&node.id) + && selected { - position = materialcraft_engine::graph_grid::snap_position([position[0] + delta.x, position[1] + delta.y], snap); + position = materialcraft_engine::graph_grid::translate(position, delta.into(), snap); } let position = pos2(position[0], position[1]); if node.kind == PatternNodeKind::Dot { @@ -39,6 +39,5 @@ pub(super) fn port_label(kind: PatternNodeKind, slot: usize) -> &'static str { } pub(super) fn wire(source: Pos2, destination: Pos2) -> [Pos2; 4] { - let offset = vec2(0.0, ((destination.y - source.y).abs() * 0.5).max(24.0)); - [source, source + offset, destination - offset, destination] + crate::graph::wire_geometry::curve_points(source, destination, egui::Vec2::Y) } diff --git a/crates/ui-egui/src/pattern/input.rs b/crates/ui-egui/src/pattern/input.rs index dea849c..89a0ed0 100644 --- a/crates/ui-egui/src/pattern/input.rs +++ b/crates/ui-egui/src/pattern/input.rs @@ -1,42 +1,35 @@ -use egui::{PointerButton, Rect, Response, Ui}; -use materialcraft_engine::core::PatternGraph; +use egui::{PointerButton, Response, Ui}; +use materialcraft_engine::PatternEdit; use super::{PatternDrag, PatternEditor}; use crate::{MaterialCraftApp, graph::GraphCamera}; -pub(super) fn handle( - app: &mut MaterialCraftApp, - editor: &mut PatternEditor, - graph: &mut PatternGraph, - ui: &Ui, - response: &Response, - camera: &GraphCamera, -) -> bool { - let Some(pointer) = ui.input(|input| input.pointer.interact_pos()) else { return false }; +pub(super) fn handle(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: &Ui, response: &Response, camera: &GraphCamera) { + if crate::graph::gesture::cancelled(ui) { + editor.drag = None; + return; + } + let Some(pointer) = ui.input(|input| input.pointer.interact_pos()) else { return }; + let position = camera.to_graph(pointer); - let port = app - .graph - .ports - .iter() - .filter(|port| port.pos.distance(pointer) < (6.0 * editor.zoom).clamp(1.5, 8.0)) - .min_by(|left, right| left.pos.distance_sq(pointer).total_cmp(&right.pos.distance_sq(pointer))) - .map(|port| { - ( - port.node.0 as u32, - port.output - .then(|| port.port.strip_prefix("output").and_then(|slot| if slot.is_empty() { Some(0) } else { slot.parse::().ok() })) - .flatten(), - ) - }); + let port = crate::graph::port_hit::nearest_by(&app.graph.ports, pointer, |port| (port.pos, (6.0 * editor.zoom).clamp(1.5, 8.0))).map(|port| { + ( + port.node.0 as u32, + port.output.then(|| port.port.strip_prefix("output").and_then(|slot| if slot.is_empty() { Some(0) } else { slot.parse::().ok() })).flatten(), + ) + }); let node = app.graph.rects.iter().rev().find(|(_, bounds)| bounds.contains(pointer)).map(|(id, _)| id.0 as u32); let modifiers = ui.input(|input| input.modifiers); - let mut changed = false; - if response.hovered() && ui.input(|input| input.pointer.button_pressed(PointerButton::Primary)) { + if editor.drag.is_none() + && GraphCamera::pan_started(ui, response.rect) + && !(port.is_some() && modifiers.alt && ui.input(|input| input.pointer.primary_pressed())) + { + editor.drag = Some(PatternDrag::Pan(crate::graph::gesture::pan_button(ui))); + } else if editor.drag.is_none() && response.hovered() && ui.input(|input| input.pointer.button_pressed(PointerButton::Primary)) { if let Some((id, slot)) = port { if modifiers.alt { - disconnect(graph, id, slot); - changed = true; + editor.edit(app, PatternEdit::Disconnect { node: id, slot }, false); } else { editor.drag = Some(PatternDrag::Wire { node: id, slot }); } @@ -46,36 +39,27 @@ pub(super) fn handle( editor.drag = Some(PatternDrag::Nodes { start: position, delta: egui::Vec2::ZERO }); } } else { - let additive = modifiers.shift || modifiers.ctrl || modifiers.command; crate::graph::node_selection::select(&mut editor.selection, None, modifiers); - editor.drag = Some(PatternDrag::Box { start: pointer, additive }); + editor.drag = Some(PatternDrag::Box { start: pointer }); } } - if response.drag_started_by(PointerButton::Middle) { - editor.drag = Some(PatternDrag::Pan); - } match &mut editor.drag { Some(PatternDrag::Nodes { start, delta }) => *delta = position - *start, - Some(PatternDrag::Pan) => editor.pan -= ui.input(|input| input.pointer.delta()) / editor.zoom, + Some(PatternDrag::Pan(_)) => editor.pan -= ui.input(|input| input.pointer.delta()) / editor.zoom, Some(PatternDrag::Box { start, .. }) => { - ui.painter().rect_stroke( - Rect::from_two_pos(*start, pointer), - 0.0, - egui::Stroke::new(1.0, crate::theme::Tokens::get(ui.ctx()).accent), - egui::StrokeKind::Inside, - ); + crate::graph::node_selection::paint_box(ui.painter(), *start, pointer, crate::theme::Tokens::get(ui.ctx()).accent); } _ => {} } - if ui.input(|input| input.pointer.button_released(PointerButton::Primary)) { + let owner = match editor.drag { + Some(PatternDrag::Pan(button)) => button, + _ => PointerButton::Primary, + }; + if crate::graph::gesture::finished(ui, owner) { match editor.drag.take() { - Some(PatternDrag::Nodes { delta, .. }) if delta.length_sq() > 0.01 => { - for node in graph.nodes.iter_mut().filter(|node| editor.selection.contains(&node.id)) { - node.position = - materialcraft_engine::graph_grid::snap_position([node.position[0] + delta.x, node.position[1] + delta.y], app.ui.prefs.snap_to_grid); - } - changed = true; + Some(PatternDrag::Nodes { delta, .. }) if delta.length() > 0.5 => { + editor.edit(app, PatternEdit::Move { ids: editor.selection.clone(), by: delta.into(), snap: app.ui.prefs.snap_to_grid }, false); } Some(PatternDrag::Wire { node, slot }) => { if let Some((target, target_slot)) = port { @@ -84,32 +68,18 @@ pub(super) fn handle( (None, Some(slot)) => Some((target, slot, node)), _ => None, }; - if let Some((parent, slot, child)) = connection - && let Some(destination) = graph.nodes.iter_mut().find(|node| node.id == parent).and_then(|node| node.children.get_mut(slot)) - { - *destination = Some(child); - changed = true; + if let Some((parent, slot, child)) = connection { + editor.edit(app, PatternEdit::Connect { parent, slot, child }, false); } } } - Some(PatternDrag::Box { start, additive }) => { - if !additive { - editor.selection.clear(); - } - let bounds = Rect::from_two_pos(start, pointer); - for (id, rectangle) in &app.graph.rects { - let id = id.0 as u32; - if bounds.intersects(*rectangle) && !editor.selection.contains(&id) { - editor.selection.push(id); - } - } + Some(PatternDrag::Box { start }) => { + let nodes = app.graph.rects.iter().map(|(id, rect)| (id.0 as u32, *rect)); + crate::graph::node_selection::select_box(&mut editor.selection, nodes, start, pointer, modifiers); } _ => {} } } - if ui.input(|input| input.pointer.button_released(PointerButton::Middle)) { - editor.drag = None; - } if response.secondary_clicked() { editor.menu_at = position; if let Some(id) = node @@ -118,23 +88,8 @@ pub(super) fn handle( crate::graph::node_selection::select(&mut editor.selection, Some(id), egui::Modifiers::NONE); } } - if response.hovered() && ui.input(|input| input.key_pressed(egui::Key::Space)) { + if response.hovered() && !ui.ctx().egui_wants_keyboard_input() && ui.input(|input| input.key_pressed(egui::Key::Space)) { editor.menu_at = position; egui::Popup::open_id(ui.ctx(), response.id.with("menu")); } - changed -} - -fn disconnect(graph: &mut PatternGraph, id: u32, slot: Option) { - if let Some(slot) = slot { - if let Some(child) = graph.nodes.iter_mut().find(|node| node.id == id).and_then(|node| node.children.get_mut(slot)) { - *child = None; - } - } else { - for child in graph.nodes.iter_mut().flat_map(|node| &mut node.children) { - if *child == Some(id) { - *child = None; - } - } - } } diff --git a/crates/ui-egui/src/pattern/library.rs b/crates/ui-egui/src/pattern/library.rs index 945e3d3..b7b1d1e 100644 --- a/crates/ui-egui/src/pattern/library.rs +++ b/crates/ui-egui/src/pattern/library.rs @@ -9,13 +9,8 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { if ui.selectable_label(false, tr(kind.label())).double_clicked() && let Some(mut editor) = app.pattern_editor.take() { - if let Some(mut graph) = editor.current(app) { - editor.menu_at = (editor.pan + app.graph.view.size() * 0.5 / editor.zoom).to_pos2(); - match editor.add(&mut graph, kind, app.ui.prefs.snap_to_grid) { - Ok(()) => editor.commit(app, graph), - Err(error) => app.toast(error, true), - } - } + 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/pattern/mod.rs b/crates/ui-egui/src/pattern/mod.rs index 7a16369..dc56d04 100644 --- a/crates/ui-egui/src/pattern/mod.rs +++ b/crates/ui-egui/src/pattern/mod.rs @@ -9,7 +9,6 @@ mod parameter_value; mod pattern_drag; mod pattern_editor; pub(crate) mod properties; -mod selection; pub(crate) use actions::{active, enabled, invoke}; pub(crate) use canvas::show; diff --git a/crates/ui-egui/src/pattern/pattern_drag.rs b/crates/ui-egui/src/pattern/pattern_drag.rs index 89623ba..71a66eb 100644 --- a/crates/ui-egui/src/pattern/pattern_drag.rs +++ b/crates/ui-egui/src/pattern/pattern_drag.rs @@ -3,6 +3,6 @@ use egui::{Pos2, Vec2}; pub(super) enum PatternDrag { Nodes { start: Pos2, delta: Vec2 }, Wire { node: u32, slot: Option }, - Box { start: Pos2, additive: bool }, - Pan, + Box { start: Pos2 }, + Pan(egui::PointerButton), } diff --git a/crates/ui-egui/src/pattern/pattern_editor.rs b/crates/ui-egui/src/pattern/pattern_editor.rs index 08a5967..772ccfe 100644 --- a/crates/ui-egui/src/pattern/pattern_editor.rs +++ b/crates/ui-egui/src/pattern/pattern_editor.rs @@ -1,5 +1,5 @@ use egui::{Pos2, Vec2}; -use materialcraft_engine::core::{NodeId, PatternGraph, PatternNode, PatternNodeKind, Value}; +use materialcraft_engine::core::{NodeId, PatternGraph, Value}; use serde_json::json; use super::PatternDrag; @@ -10,7 +10,6 @@ pub struct PatternEditor { pub graph: usize, pub(crate) selection: Vec, pub(crate) inspected_node: Option, - pub(super) clipboard: Vec, pub(super) pan: Vec2, pub(super) zoom: f32, pub(super) framed: bool, @@ -20,21 +19,10 @@ pub struct PatternEditor { impl PatternEditor { pub fn new(graph: usize, node: NodeId) -> Self { - Self { - node, - graph, - selection: Vec::new(), - inspected_node: None, - clipboard: Vec::new(), - pan: Vec2::ZERO, - zoom: 1.0, - framed: false, - drag: None, - menu_at: Pos2::ZERO, - } + Self { node, graph, selection: Vec::new(), inspected_node: None, pan: Vec2::ZERO, zoom: 1.0, framed: false, drag: None, menu_at: Pos2::ZERO } } - pub(super) fn current(&self, app: &MaterialCraftApp) -> Option { + pub(crate) fn current<'a>(&self, app: &'a MaterialCraftApp) -> Option<&'a PatternGraph> { if app.session.graph != self.graph { return None; } @@ -46,22 +34,29 @@ impl PatternEditor { let default = materialcraft_engine::nodes::find(&node.def)?.param("pattern"); match node.params.get("pattern").or_else(|| default.map(|parameter| ¶meter.default)) { - Some(Value::PatternGraph(graph)) => Some((**graph).clone()), - None => Some(PatternGraph::default()), + Some(Value::PatternGraph(graph)) => Some(graph.as_ref()), + None => { + static EMPTY: std::sync::OnceLock = std::sync::OnceLock::new(); + Some(EMPTY.get_or_init(PatternGraph::default)) + } _ => None, } } - pub(super) fn commit(&self, app: &mut MaterialCraftApp, graph: PatternGraph) { - app.run("graph.pattern.set", json!({"id": self.node.0, "pattern": graph})); + pub(crate) fn selection_parameters(&self, command: &str) -> serde_json::Value { + let selection = if matches!(command, "edit.selectAll" | "edit.selectNone") { &[][..] } else { self.selection.as_slice() }; + json!({"graph": self.graph, "pattern": self.node.0, "ids": selection, "at": [self.menu_at.x, self.menu_at.y]}) } - pub(super) fn add(&mut self, graph: &mut PatternGraph, kind: PatternNodeKind, snap: bool) -> Result<(), String> { - let id = graph.add(kind)?; - if let Some(node) = graph.nodes.iter_mut().find(|node| node.id == id) { - node.position = materialcraft_engine::graph_grid::snap_position([self.menu_at.x, self.menu_at.y], snap); + pub(super) fn edit(&mut self, app: &mut MaterialCraftApp, edit: materialcraft_engine::PatternEdit, merge: bool) { + if self.current(app).is_none() { + return; + } + + if let Some(result) = app.run("graph.pattern.edit", json!({"id": self.node.0, "edit": edit, "merge": merge})) + && let Some(id) = result.get("id").and_then(serde_json::Value::as_u64).and_then(|id| u32::try_from(id).ok()) + { + self.selection = vec![id]; } - self.selection = vec![id]; - Ok(()) } } diff --git a/crates/ui-egui/src/pattern/properties.rs b/crates/ui-egui/src/pattern/properties.rs index 5dd8de8..4942dc5 100644 --- a/crates/ui-egui/src/pattern/properties.rs +++ b/crates/ui-egui/src/pattern/properties.rs @@ -1,11 +1,7 @@ use egui::Ui; use materialcraft_engine::core::{FunctionGraph, Value}; -use crate::{ - MaterialCraftApp, - function::{FunctionEditor, FunctionTarget}, - i18n::tr, -}; +use crate::{MaterialCraftApp, function::FunctionTarget, i18n::tr}; pub(crate) fn title(app: &MaterialCraftApp) -> String { let kind = app.pattern_editor.as_ref().and_then(|editor| { @@ -17,13 +13,15 @@ pub(crate) fn title(app: &MaterialCraftApp) -> String { } pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - let Some(editor) = app.pattern_editor.take() else { return }; - let Some(mut graph) = editor.current(app) else { return }; - let mut changed = false; + let Some(mut editor) = app.pattern_editor.take() else { return }; + + let Some(graph) = editor.current(app) else { return }; + + let mut edits = Vec::new(); let mut function_target = None; let inspected = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node); - if let Some(node) = graph.nodes.iter_mut().find(|node| Some(node.id) == inspected) { + if let Some(node) = graph.nodes.iter().find(|node| Some(node.id) == inspected) { ui.heading(tr(node.kind.label())); if graph.root == Some(node.id) { ui.label(tr("Root node")); @@ -32,25 +30,33 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { for parameter in &definition.params { ui.push_id(parameter.id, |ui| { ui.label(tr(parameter.label)); - let mut value = node.parameters.get(parameter.id).unwrap_or(¶meter.default).clone(); ui.horizontal_wrapped(|ui| { + let value = node.parameters.get(parameter.id).unwrap_or(¶meter.default); if matches!(value, Value::Function(_)) { if ui.small_button(tr("Edit function")).clicked() { function_target = Some(FunctionTarget::Pattern { node: node.id, parameter: parameter.id.to_string() }); } if ui.small_button(tr("Reset")).clicked() { - node.parameters.remove(parameter.id); - changed = true; + edits.push((materialcraft_engine::PatternEdit::Value { id: node.id, parameter: parameter.id.into(), value: None }, false)); } } else { + let mut value = value.clone(); if super::parameter_value::show(ui, parameter.id, &mut value) { - node.parameters.insert(parameter.id.to_string(), value.clone()); - changed = true; + edits.push(( + materialcraft_engine::PatternEdit::Value { id: node.id, parameter: parameter.id.into(), value: Some(value.clone()) }, + true, + )); } if ui.small_button(tr("Function")).clicked() { - node.parameters.insert(parameter.id.to_string(), Value::Function(Box::new(FunctionGraph::constant(value)))); + edits.push(( + materialcraft_engine::PatternEdit::Value { + id: node.id, + parameter: parameter.id.into(), + value: Some(Value::Function(Box::new(FunctionGraph::constant(value)))), + }, + false, + )); function_target = Some(FunctionTarget::Pattern { node: node.id, parameter: parameter.id.to_string() }); - changed = true; } } }); @@ -62,11 +68,11 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { ui.heading(tr("FX-Map")); ui.label(tr("Select a node to edit its parameters")); } - if changed { - editor.commit(app, graph); + for (edit, merge) in edits { + editor.edit(app, edit, merge); } if let Some(target) = function_target { - app.function_editor = Some(FunctionEditor::new(editor.node, target)); + crate::graph::subgraph_navigation::open_function(app, editor.node, target); } app.pattern_editor = Some(editor); } diff --git a/crates/ui-egui/src/pattern/selection.rs b/crates/ui-egui/src/pattern/selection.rs deleted file mode 100644 index 226a129..0000000 --- a/crates/ui-egui/src/pattern/selection.rs +++ /dev/null @@ -1,88 +0,0 @@ -use materialcraft_engine::core::PatternGraph; -use std::collections::{BTreeMap, BTreeSet}; - -use super::PatternEditor; - -pub(super) fn enabled(editor: &PatternEditor, command: &str) -> Option { - Some(match command { - "edit.selectAll" | "edit.selectNone" => true, - "edit.paste" | "edit.pasteWithoutLinks" => !editor.clipboard.is_empty(), - "edit.copy" | "edit.cut" | "edit.delete" | "edit.duplicate" | "edit.duplicateWithoutLinks" | "graph.selectUpstream" | "graph.selectDownstream" => { - !editor.selection.is_empty() - } - _ => return None, - }) -} - -pub(super) fn run(editor: &mut PatternEditor, graph: &mut PatternGraph, command: &str, snap: bool) -> Result { - match command { - "edit.selectAll" => editor.selection = graph.nodes.iter().map(|node| node.id).collect(), - "edit.selectNone" => editor.selection.clear(), - "edit.copy" | "edit.cut" => { - editor.clipboard = graph.nodes.iter().filter(|node| editor.selection.contains(&node.id)).cloned().collect(); - if command == "edit.cut" { - return Ok(remove(editor, graph)); - } - } - "edit.delete" => return Ok(remove(editor, graph)), - "edit.duplicate" | "edit.duplicateWithoutLinks" | "edit.paste" | "edit.pasteWithoutLinks" => { - let duplicate = command.starts_with("edit.duplicate"); - let nodes = - if duplicate { graph.nodes.iter().filter(|node| editor.selection.contains(&node.id)).cloned().collect() } else { editor.clipboard.clone() }; - let anchor = nodes.first().map_or([0.0; 2], |node| node.position); - let offset = if duplicate { [32.0; 2] } else { [editor.menu_at.x - anchor[0], editor.menu_at.y - anchor[1]] }; - let present: BTreeSet<_> = graph.nodes.iter().map(|node| node.id).collect(); - let mut ids = BTreeMap::new(); - for mut node in nodes { - let original = node.id; - node.id = graph.add(node.kind)?; - node.position = materialcraft_engine::graph_grid::snap_position([node.position[0] + offset[0], node.position[1] + offset[1]], snap); - ids.insert(original, node.id); - if let Some(destination) = graph.nodes.last_mut() { - *destination = node; - } - } - editor.selection = ids.values().copied().collect(); - for node in graph.nodes.iter_mut().filter(|node| editor.selection.contains(&node.id)) { - for child in &mut node.children { - *child = child.and_then(|id| ids.get(&id).copied().or_else(|| (!command.ends_with("WithoutLinks") && present.contains(&id)).then_some(id))); - } - } - return Ok(!ids.is_empty()); - } - "graph.selectUpstream" | "graph.selectDownstream" => { - let mut visited = BTreeSet::new(); - let mut pending = editor.selection.clone(); - while let Some(id) = pending.pop() { - if !visited.insert(id) { - continue; - } - if command == "graph.selectDownstream" { - if let Some(node) = graph.nodes.iter().find(|node| node.id == id) { - pending.extend(node.children.iter().flatten()); - } - } else { - pending.extend(graph.nodes.iter().filter(|node| node.children.contains(&Some(id))).map(|node| node.id)); - } - } - editor.selection = visited.into_iter().collect(); - } - _ => {} - } - Ok(false) -} - -fn remove(editor: &mut PatternEditor, graph: &mut PatternGraph) -> bool { - let before = graph.nodes.len(); - graph.nodes.retain(|node| !editor.selection.contains(&node.id)); - for child in graph.nodes.iter_mut().flat_map(|node| &mut node.children) { - if child.is_some_and(|id| editor.selection.contains(&id)) { - *child = None; - } - } - if graph.root.is_some_and(|id| editor.selection.contains(&id)) { - graph.root = None; - } - editor.selection.clear(); - graph.nodes.len() != before -} diff --git a/crates/ui-egui/src/properties.rs b/crates/ui-egui/src/properties.rs deleted file mode 100644 index 5046718..0000000 --- a/crates/ui-egui/src/properties.rs +++ /dev/null @@ -1,810 +0,0 @@ -use egui::{Color32, Pos2, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; -use egui_phosphor::regular as icon; -use materialcraft_engine::core::{Curve, Gradient, NodeId, OutputFormat, SizeMode, Value}; -use materialcraft_engine::nodes::ParameterDefinition; -use serde_json::{Value as J, json}; - -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; - -/// The panel title: " - Properties" or " - Properties" -pub fn title(app: &MaterialCraftApp) -> String { - if crate::pattern::active(app) { - return crate::pattern::properties::title(app); - } - - if let Some(selection) = app.session.annotation_selection { - let name = match selection { - materialcraft_engine::AnnotationSelection::Frame(_) => tr("Frame"), - materialcraft_engine::AnnotationSelection::Comment(_) => tr("Comment"), - }; - return format!("{name} - {}", tr("Properties")); - } - - if let Some(title) = crate::function::properties::title(app) { - return title; - } - - let sel = crate::graph::node_selection::inspected(&app.session.selection, app.graph.inspected_node) - .and_then(|id| app.session.graph().ok()?.node(id).ok().map(crate::graph::node_label)); - let name = sel.or_else(|| app.session.graph().ok().map(|g| g.name.clone())).unwrap_or_default(); - format!("{name} - {}", tr("Properties")) -} - -pub(crate) fn section(ui: &mut Ui, id: &str, title: &str, body: impl FnOnce(&mut Ui)) { - let tk = Tokens::get(ui.ctx()); - let id = ui.make_persistent_id(id); - let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true); - let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click()); - crate::widgets::name(&resp, egui::Role::Button, title); - ui.painter().rect_filled(r, 3.0, tk.row); - let chev = if state.is_open() { icon::CARET_DOWN } else { icon::CARET_RIGHT }; - ui.painter().text(r.left_center() + vec2(6.0, 0.0), egui::Align2::LEFT_CENTER, chev, egui::FontId::proportional(10.0), tk.text_dim); - ui.painter().text(r.left_center() + vec2(20.0, 0.0), egui::Align2::LEFT_CENTER, title.to_uppercase(), egui::FontId::proportional(10.5), tk.text_strong); - if resp.clicked() { - state.toggle(ui); - } - state.show_body_unindented(ui, |ui| { - ui.add_space(3.0); - body(ui); - ui.add_space(6.0); - }); -} - -pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - ui.set_width(ui.available_width()); - if crate::pattern::active(app) { - crate::pattern::properties::show(app, ui); - return; - } - - if let Some(selection) = app.session.annotation_selection { - ui.push_id((app.session.graph, format!("{selection:?}")), |ui| crate::annotation::show(app, ui, selection)); - return; - } - - if crate::function::properties::show(app, ui) { - return; - } - - let node = crate::graph::node_selection::inspected(&app.session.selection, app.graph.inspected_node) - .and_then(|id| app.session.graph().ok()?.node(id).ok().cloned()); - ui.push_id((app.session.graph, node.as_ref().map(|n| n.id)), |ui| match node { - Some(n) => node_props(app, ui, &n), - None => graph_props(app, ui), - }); - }); -} - -fn node_props(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine::core::Node) { - let tk = Tokens::get(ui.ctx()); - let def = materialcraft_engine::nodes::find(&n.def); - // Header: label (renamable) and description - ui.horizontal(|ui| { - ui.painter().rect_filled(Rect::from_min_size(ui.cursor().min + vec2(0.0, 2.0), vec2(4.0, 16.0)), 1.0, crate::graph::header_color(&n.def)); - ui.add_space(8.0); - let mut label = if n.label.is_empty() { crate::graph::node_label(n) } else { n.label.clone() }; - let r = ui.add(egui::TextEdit::singleline(&mut label).desired_width(ui.available_width() - 4.0).font(egui::TextStyle::Heading)); - crate::widgets::name(&r, egui::Role::TextInput, "Node label"); - if r.changed() { - app.run("graph.node.rename", json!({"id": n.id.0, "label": label})); - } - }); - if let Some(d) = def - && !d.description.is_empty() - { - ui.label(RichText::new(d.description).size(11.0).color(tk.text_dim)); - } - if let Some(r) = app.session.cooked.nodes.get(&n.id) - && let Some(e) = &r.error - { - ui.label(RichText::new(format!("{} {e}", icon::WARNING)).color(tk.danger)); - } - ui.add_space(4.0); - section(ui, "base", tr("Base parameters"), |ui| base_params(app, ui, n)); - crate::value_input_editor::show(app, ui, n); - if n.def == "input_value" { - crate::value_input_editor::default_value(app, ui, n); - } - if n.def == "graph_instance" { - section(ui, "instance", tr("Instance parameters"), |ui| instance_params(app, ui, n)); - return; - } - let Some(def) = def else { return }; - if def.params.is_empty() { - return; - } - section(ui, "specific", tr("Specific parameters"), |ui| { - if n.def == "levels" { - crate::levels_editor::show(app, ui, n); - ui.add_space(6.0); - } - let exposed: Vec<(String, String)> = - app.session.graph().map(|g| g.exposed.iter().map(|e| (e.id.clone(), e.label.clone())).collect()).unwrap_or_default(); - for p in &def.params { - if n.def == "input_value" && p.id == "default" { - continue; - } - let cur = n.params.get(p.id).cloned().unwrap_or_else(|| p.default.clone()); - if n.functions.contains_key(p.id) { - function_row(app, ui, n.id, p.id, p.label); - continue; - } - let bound = n.bindings.get(p.id).cloned(); - param_row(app, ui, n.id, p, cur, bound, &exposed); - } - }); -} - -fn base_params(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine::core::Node) { - let b = &n.base; - let id = n.id.0; - let modes = [(SizeMode::RelativeToInput, "Relative to input"), (SizeMode::RelativeToParent, "Relative to parent"), (SizeMode::Absolute, "Absolute")]; - let cur = modes.iter().find(|m| m.0 == b.size_mode).map_or("", |m| m.1); - crate::widgets::combo(ui, tr("Output size"), tr(cur), |ui| { - for (m, label) in modes { - if ui.selectable_label(b.size_mode == m, tr(label)).clicked() { - let key = match m { - SizeMode::RelativeToInput => "relativeToInput", - SizeMode::RelativeToParent => "relativeToParent", - SizeMode::Absolute => "absolute", - }; - - let size = if m == SizeMode::Absolute { json!([10, 10]) } else { json!([0, 0]) }; - app.run("graph.node.base", json!({"id": id, "sizeMode": key, "size": size})); - } - } - }); - let (lo, hi) = if b.size_mode == SizeMode::Absolute { (4.0, 13.0) } else { (-6.0, 6.0) }; - for (axis, label) in [(0usize, "Width"), (1, "Height")] { - let mut v = b.size[axis] as f32; - let caption = if b.size_mode == SizeMode::Absolute { - format!("{label} {} px", 1u32 << b.size[axis].clamp(4, 13)) - } else { - format!("{label} x {}", 2f32.powi(b.size[axis])) - }; - - if crate::widgets::slider(ui, &caption, &mut v, lo..=hi, 0).changed() { - let mut size = b.size; - size[axis] = v.round() as i32; - app.run("graph.node.base", json!({"id": id, "size": size})); - } - } - crate::widgets::combo(ui, tr("Output format"), tr(b.format.label()), |ui| { - for f in OutputFormat::ALL { - if ui.selectable_label(b.format == f, tr(f.label())).clicked() { - let key = match f { - OutputFormat::Inherit => "inherit", - OutputFormat::U8 => "u8", - OutputFormat::U16 => "u16", - OutputFormat::F16 => "f16", - OutputFormat::F32 => "f32", - }; - - app.run("graph.node.base", json!({"id": id, "format": key})); - } - } - }); - let mut seed = b.seed as f32; - if crate::widgets::slider(ui, tr("Random seed"), &mut seed, 0.0..=1000.0, 0).changed() { - app.run("graph.node.base", json!({"id": id, "seed": seed.round() as i64})); - } - if ui.button(format!("{} {}", icon::SHUFFLE, tr("New random seed"))).clicked() { - let s = (crate::now_ms() as u64 ^ id).wrapping_mul(2654435761) % 1000; - app.run("graph.node.base", json!({"id": id, "seed": s})); - } - let mut tiling = b.tiling[0] && b.tiling[1]; - if ui.checkbox(&mut tiling, tr("Tiling (H and V)")).changed() { - app.run("graph.node.base", json!({"id": id, "tiling": tiling})); - } -} - -fn set(app: &mut MaterialCraftApp, node: NodeId, param: &str, value: J) { - app.run("graph.node.param", json!({"id": node.0, "param": param, "value": value})); -} - -fn typed(v: &Value) -> J { - serde_json::to_value(v).unwrap_or(J::Null) -} - -/// One parameter: its editor, plus the expose/bind menu -fn param_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, p: &ParameterDefinition, cur: Value, bound: Option, exposed: &[(String, String)]) { - let tk = Tokens::get(ui.ctx()); - if let Some(input) = &bound { - ui.horizontal(|ui| { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - ui.label(RichText::new(format!("{} {input}", icon::LINK)).color(tk.accent)); - if crate::widgets::icon_button(ui, icon::LINK_BREAK, tr("Unbind"), false, 18.0).clicked() { - app.run("graph.node.bind", json!({"id": node.0, "param": p.id, "input": J::Null})); - } - }); - return; - } - let resp_menu = |app: &mut MaterialCraftApp, resp: &egui::Response| { - resp.context_menu(|ui| { - if ui.button(tr("Reset to default")).clicked() { - app.run("graph.node.reset", json!({"id": node.0, "param": p.id})); - ui.close(); - } - let dynamic = !matches!(p.default, Value::Text(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_) | Value::PatternGraph(_)); - if dynamic && ui.button(tr("Set function...")).clicked() { - if app.run("graph.node.function", json!({"id": node.0, "param": p.id})).is_some() { - app.function_editor = Some(crate::function::FunctionEditor::new(node, crate::function::FunctionTarget::Dynamic(p.id.to_string()))); - } - ui.close(); - } - if ui.button(tr("Expose as graph input")).clicked() { - app.run("graph.exposed.add", json!({"id": p.id, "label": p.label, "bind": {"node": node.0, "param": p.id}})); - ui.close(); - } - if !exposed.is_empty() { - ui.menu_button(tr("Bind to input"), |ui| { - for (id, label) in exposed { - if ui.button(label).clicked() { - app.run("graph.node.bind", json!({"id": node.0, "param": p.id, "input": id})); - ui.close(); - } - } - }); - } - }); - }; - - match cur { - Value::Float(mut v) => { - if p.angle { - let mut deg = v * 360.0; - let r = crate::widgets::slider(ui, tr(p.label), &mut deg, -360.0..=360.0, 1); - if r.changed() { - v = deg / 360.0; - set(app, node, p.id, json!(v)); - } - resp_menu(app, &r); - } else { - let (lo, hi) = (p.min.min(v), p.max.max(v)); - let r = crate::widgets::slider(ui, tr(p.label), &mut v, lo..=hi, if hi - lo > 20.0 { 1 } else { 3 }); - if r.changed() { - set(app, node, p.id, json!(v)); - } - resp_menu(app, &r); - } - } - Value::Int(i) => { - let mut v = i as f32; - let range = p.min.min(v)..=p.max.max(v); - let r = crate::widgets::slider(ui, tr(p.label), &mut v, range, 0); - if r.changed() && v.round() as i32 != i { - set(app, node, p.id, json!(v.round() as i32)); - } - resp_menu(app, &r); - } - Value::Float2(v) => { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - let mut nv = v; - for (k, axis) in ["X", "Y"].iter().enumerate() { - let range = p.min.min(nv[k])..=p.max.max(nv[k]); - let r = crate::widgets::slider(ui, axis, &mut nv[k], range, 3); - if r.changed() { - set(app, node, p.id, json!(nv)); - } - resp_menu(app, &r); - } - } - Value::Int2(v) => { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - for k in 0..2 { - let mut f = v[k] as f32; - if crate::widgets::slider(ui, ["X", "Y"][k], &mut f, p.min..=p.max, 0).changed() { - let mut nv = v; - nv[k] = f.round() as i32; - set(app, node, p.id, json!(nv)); - } - } - } - Value::Bool(b) => { - let mut v = b; - let r = ui.checkbox(&mut v, tr(p.label)); - if r.changed() { - set(app, node, p.id, json!(v)); - } - resp_menu(app, &r); - } - Value::Float3(_) | Value::Float4(_) | Value::Int3(_) | Value::Int4(_) => { - ui.label(tr(p.label)); - let mut value = cur.clone(); - if crate::value_editor::show(ui, &mut value) { - set(app, node, p.id, serde_json::to_value(value).unwrap_or_default()); - } - } - Value::Color(c) => { - ui.horizontal(|ui| { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mut rgb = [c[0], c[1], c[2]]; - if crate::widgets::color_swatch(ui, &format!("{}-{}", node.0, p.id), &mut rgb, 90.0) { - set(app, node, p.id, json!([rgb[0], rgb[1], rgb[2], c[3]])); - } - }); - }); - } - Value::Enum(i) => { - let cur = p.options.get(i as usize).copied().unwrap_or("?"); - crate::widgets::combo(ui, tr(p.label), tr(cur), |ui| { - for (k, o) in p.options.iter().enumerate() { - if ui.selectable_label(k as u32 == i, tr(o)).clicked() { - set(app, node, p.id, json!(k)); - } - } - }); - } - Value::Text(t) if p.resource => { - let names: Vec = app.session.pkg.resources.iter().map(|r| r.name.clone()).collect(); - crate::widgets::combo(ui, tr(p.label), if t.is_empty() { tr("(checker)").to_string() } else { t.clone() }, |ui| { - for n in &names { - if ui.selectable_label(*n == t, n).clicked() { - set(app, node, p.id, json!(n)); - } - } - }); - if ui.button(format!("{} {}", icon::IMAGE, tr("Import bitmap..."))).clicked() { - crate::menus::invoke(app, ui.ctx(), "file.importBitmap"); - } - } - Value::Text(t) => { - ui.horizontal(|ui| { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - let mut s = t.clone(); - let r = ui.add(egui::TextEdit::singleline(&mut s).desired_width(ui.available_width())); - crate::widgets::name(&r, egui::Role::TextInput, p.label); - if r.changed() { - set(app, node, p.id, json!(s)); - } - }); - } - Value::Curve(c) => { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - if let Some(nc) = curve_editor(ui, &format!("curve-{}-{}", node.0, p.id), &c) { - set(app, node, p.id, json!(nc.points.iter().map(|q| [q.x, q.y]).collect::>())); - } - } - Value::Gradient(g) => { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - if let Some(ng) = gradient_editor(ui, &format!("grad-{}-{}", node.0, p.id), &g) { - set(app, node, p.id, typed(&Value::Gradient(ng))); - } - } - Value::PatternGraph(graph) => { - ui.label(format!("{}: {} nodes", p.label, graph.nodes.len())); - } - Value::Function(f) => { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - crate::windows::function_summary(app, ui, node, p.id, &f); - } - } -} - -/// A parameter driven by a function: its label, Edit and Remove -fn function_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, param: &str, label: &str) { - let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.label(RichText::new(tr(label)).color(tk.text)); - ui.label(RichText::new(format!("{} {}", icon::FUNCTION, tr("function"))).color(tk.accent)); - if ui.small_button(tr("Edit")).clicked() { - app.function_editor = Some(crate::function::FunctionEditor::new(node, crate::function::FunctionTarget::Dynamic(param.to_string()))); - } - if crate::widgets::icon_button(ui, icon::X, tr("Remove function"), false, 18.0).clicked() { - app.run("graph.node.function", json!({"id": node.0, "param": param, "remove": true})); - } - }); -} - -fn instance_params(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine::core::Node) { - let tk = Tokens::get(ui.ctx()); - let Some((gi, sub)) = materialcraft_engine::eval::instance_graph(&app.session.pkg, n) else { - ui.label(RichText::new(tr("The instanced graph is missing")).color(tk.danger)); - return; - }; - - let exposed = sub.exposed.clone(); - if ui.button(format!("{} {}", icon::ARROW_SQUARE_OUT, tr("Open graph"))).clicked() { - app.run("graph.open", json!({"graph": gi})); - return; - } - if exposed.is_empty() { - ui.label(RichText::new(tr("This graph exposes no inputs")).color(tk.text_dim)); - } - for e in exposed { - let cur = n.params.get(&e.id).cloned().unwrap_or_else(|| e.default.clone()); - if let Some(v) = input_editor(ui, &e, &cur) { - app.run("graph.node.param", json!({"id": n.id.0, "param": e.id, "value": v})); - } - } -} - -/// The editor for one exposed input's value; returns the new value as JSON when it changed -fn input_editor(ui: &mut Ui, e: &materialcraft_engine::core::ExposedParameter, cur: &Value) -> Option { - match *cur { - Value::Float(mut f) => { - let v0 = f; - crate::widgets::slider(ui, &e.label, &mut f, e.min.min(v0)..=e.max.max(v0), 3).changed().then(|| json!(f)) - } - Value::Int(i) => { - let mut f = i as f32; - let v0 = f; - crate::widgets::slider(ui, &e.label, &mut f, e.min.min(v0)..=e.max.max(v0), 0).changed().then(|| json!(f.round())) - } - Value::Bool(mut b) => ui.checkbox(&mut b, &e.label).changed().then(|| json!(b)), - Value::Enum(i) => { - let mut out = None; - crate::widgets::combo(ui, &e.label, e.options.get(i as usize).cloned().unwrap_or_default(), |ui| { - for (k, o) in e.options.iter().enumerate() { - if ui.selectable_label(k as u32 == i, o).clicked() { - out = Some(json!(k)); - } - } - }); - out - } - Value::Color(c) => { - let mut rgb = [c[0], c[1], c[2]]; - let mut out = None; - ui.horizontal(|ui| { - ui.label(&e.label); - if crate::widgets::color_swatch(ui, &format!("exp-{}", e.id), &mut rgb, 80.0) { - out = Some(json!([rgb[0], rgb[1], rgb[2], c[3]])); - } - }); - out - } - ref other => { - ui.label(format!("{}: {}", e.label, other.type_name())); - None - } - } -} - -fn graph_props(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let Ok(g) = app.session.graph() else { - ui.label(tr("No graph is open")); - return; - }; - - let g = g.clone(); - section(ui, "graph-base", tr("Base parameters"), |ui| { - ui.horizontal(|ui| { - ui.label(tr("Name")); - let mut name = g.name.clone(); - let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(ui.available_width())); - crate::widgets::name(&r, egui::Role::TextInput, "Graph name"); - if r.lost_focus() && name != g.name { - app.run("graph.rename", json!({"name": name})); - } - }); - if g.function.is_some() { - return; - } - - for (axis, label) in [(0usize, "Width"), (1, "Height")] { - let mut v = g.size[axis] as f32; - if crate::widgets::slider(ui, &format!("{} {} px", tr(label), 1u32 << g.size[axis]), &mut v, 4.0..=13.0, 0).changed() { - let mut s = g.size; - s[axis] = v.round() as u32; - app.run("graph.size", json!({"log2": s})); - } - } - crate::widgets::combo(ui, tr("Output format"), tr(g.format.label()), |ui| { - for (f, key) in [(OutputFormat::U8, "u8"), (OutputFormat::U16, "u16"), (OutputFormat::F16, "f16"), (OutputFormat::F32, "f32")] { - if ui.selectable_label(g.format == f, tr(f.label())).clicked() { - app.run("graph.format", json!({"format": key})); - } - } - }); - let mut seed = g.seed as f32; - if crate::widgets::slider(ui, tr("Random seed"), &mut seed, 0.0..=1000.0, 0).changed() { - app.run("graph.seed", json!({"seed": seed.round() as i64})); - } - }); - section(ui, "graph-attr", tr("Attributes"), |ui| { - for (key, label, cur) in [ - ("category", "Category", &g.attributes.category), - ("description", "Description", &g.attributes.description), - ("author", "Author", &g.attributes.author), - ("tags", "Tags", &g.attributes.tags), - ] { - ui.horizontal(|ui| { - ui.label(tr(label)); - let mut s = cur.clone(); - let r = ui.add(egui::TextEdit::singleline(&mut s).desired_width(ui.available_width())); - crate::widgets::name(&r, egui::Role::TextInput, label); - if r.lost_focus() && s != *cur { - app.run("graph.attributes", json!({key: s})); - } - }); - } - }); - section(ui, "graph-inputs", tr("Input parameters"), |ui| { - if g.exposed.is_empty() { - ui.label(RichText::new(tr("Right-click a node parameter > Expose as graph input")).size(11.0).color(tk.text_dim)); - } else { - presets_bar(app, ui, &g); - } - let mut groups: Vec<&str> = Vec::new(); - for e in &g.exposed { - if !groups.contains(&e.group.as_str()) { - groups.push(&e.group); - } - } - let mut last_group: Option<&str> = None; - let mut order: Vec<&materialcraft_engine::core::ExposedParameter> = Vec::new(); - for grp in &groups { - order.extend(g.exposed.iter().filter(|e| e.group == *grp)); - } - for e in order { - if last_group != Some(e.group.as_str()) && !e.group.is_empty() { - ui.label(RichText::new(e.group.to_uppercase()).size(10.5).strong().color(tk.text_dim)); - } - last_group = Some(e.group.as_str()); - let cur = g.input_value(&e.id).cloned().unwrap_or_else(|| e.default.clone()); - ui.horizontal(|ui| { - if crate::widgets::icon_button(ui, icon::X, tr("Delete input"), false, 18.0).clicked() { - app.run("graph.exposed.delete", json!({"id": e.id})); - } - ui.vertical(|ui| { - if let Some(v) = input_editor(ui, e, &cur) { - app.run("graph.exposed.set", json!({"id": e.id, "value": v})); - } - }); - }); - } - }); - input_previews(app, ui, &g); - section(ui, "graph-outputs", tr("Outputs"), |ui| { - for n in g.nodes.iter().filter(|n| n.def == "output") { - let usage = n.params.get("usage").and_then(Value::as_i32).unwrap_or(0) as usize; - let label = format!( - "{} {} | {}", - icon::SIGN_OUT, - materialcraft_engine::nodes::atomic::USAGES.get(usage).copied().unwrap_or("Any"), - materialcraft_engine::eval::identifier(n) - ); - if ui.add(egui::Button::selectable(app.session.view2d.node == Some(n.id), label)).clicked() { - app.run("view.2d", json!({"node": n.id.0})); - } - } - }); -} - -/// Preview images of the graph's input nodes: a bitmap resource, or (desktop) an image file such as a mesh map baked in TextureCraft -fn input_previews(app: &mut MaterialCraftApp, ui: &mut Ui, g: &materialcraft_engine::core::Graph) { - let inputs = materialcraft_engine::material_cmds::image_inputs(g); - if inputs.is_empty() { - return; - } - let resources: Vec = app.session.pkg.resources.iter().map(|r| r.name.clone()).collect(); - section(ui, "graph-input-images", tr("Input previews"), |ui| { - for i in &inputs { - let id = &i.identifier; - let bound = g.input_images.get(id); - ui.horizontal(|ui| { - ui.label(id); - egui::ComboBox::from_id_salt(("input-preview", id)).width(120.0).selected_text(bound.map_or(tr("None"), String::as_str)).show_ui(ui, |ui| { - if ui.selectable_label(bound.is_none(), tr("None")).clicked() { - app.run("graph.input.unbind", json!({"identifier": id})); - } - for r in &resources { - if ui.selectable_label(bound == Some(r), r).clicked() { - app.run("graph.input.bind", json!({"identifier": id, "resource": r})); - } - } - }); - #[cfg(not(target_arch = "wasm32"))] - if crate::widgets::icon_button(ui, icon::FOLDER_OPEN, tr("Pick an image file (a mesh map baked in TextureCraft)"), false, 18.0).clicked() - && let Some(p) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() - { - app.run("graph.input.bind", json!({"identifier": id, "path": p.display().to_string()})); - } - }); - } - }); -} - -/// Presets: apply one, save the current inputs under a name, delete one -fn presets_bar(app: &mut MaterialCraftApp, ui: &mut Ui, g: &materialcraft_engine::core::Graph) { - let name_id = ui.make_persistent_id("preset-name"); - let mut name: String = ui.data(|d| d.get_temp(name_id)).unwrap_or_default(); - ui.horizontal(|ui| { - let names: Vec = g.presets.iter().map(|p| p.name.clone()).collect(); - let r = egui::ComboBox::from_id_salt("presets").width(110.0).selected_text(tr("Presets")).show_ui(ui, |ui| { - for n in &names { - if ui.button(n).clicked() { - app.run("graph.preset.apply", json!({"name": n})); - } - } - if names.is_empty() { - ui.label(tr("No presets yet")); - } - }); - crate::widgets::name(&r.response, egui::Role::ComboBox, "Presets"); - let t = ui.add(egui::TextEdit::singleline(&mut name).hint_text(tr("Preset name")).desired_width(90.0)); - crate::widgets::name(&t, egui::Role::TextInput, "Preset name"); - if crate::widgets::icon_button(ui, icon::FLOPPY_DISK, tr("Save preset"), false, 20.0).clicked() && !name.trim().is_empty() { - app.run("graph.preset.save", json!({"name": name})); - } - if crate::widgets::icon_button(ui, icon::X, tr("Delete preset"), false, 20.0).clicked() && !name.trim().is_empty() { - app.run("graph.preset.delete", json!({"name": name})); - } - }); - ui.data_mut(|d| d.insert_temp(name_id, name)); -} - -/// A tone curve editor: drag points, double-click to add one, right-click a point to remove it. Returns the new curve when it changed -pub fn curve_editor(ui: &mut Ui, id: &str, c: &Curve) -> Option { - let tk = Tokens::get(ui.ctx()); - let w = ui.available_width().min(240.0); - let (rect, resp) = ui.allocate_exact_size(vec2(w, w * 0.75), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Canvas, "Curve editor"); - let p = ui.painter_at(rect); - p.rect_filled(rect, 4.0, tk.field); - for i in 1..4 { - let t = i as f32 / 4.0; - p.line_segment([pos2(rect.left() + rect.width() * t, rect.top()), pos2(rect.left() + rect.width() * t, rect.bottom())], Stroke::new(1.0, tk.separator)); - p.line_segment([pos2(rect.left(), rect.top() + rect.height() * t), pos2(rect.right(), rect.top() + rect.height() * t)], Stroke::new(1.0, tk.separator)); - } - let to_s = |x: f32, y: f32| pos2(rect.left() + x * rect.width(), rect.bottom() - y * rect.height()); - let from_s = |s: Pos2| (((s.x - rect.left()) / rect.width()).clamp(0.0, 1.0), ((rect.bottom() - s.y) / rect.height()).clamp(0.0, 1.0)); - let pts: Vec = (0..=64).map(|i| i as f32 / 64.0).map(|x| to_s(x, c.eval(x).clamp(0.0, 1.0))).collect(); - p.add(egui::Shape::line(pts, Stroke::new(2.0, tk.accent))); - let drag_id = ui.make_persistent_id(id).with("drag"); - let mut dragging: Option = ui.data(|d| d.get_temp(drag_id)); - let pointer = resp.interact_pointer_pos().or(resp.hover_pos()); - let nearest = pointer.and_then(|q| { - c.points - .iter() - .enumerate() - .map(|(i, pt)| (i, to_s(pt.x, pt.y).distance(q))) - .filter(|(_, d)| *d < 10.0) - .min_by(|a, b| a.1.total_cmp(&b.1)) - .map(|(i, _)| i) - }); - for (i, pt) in c.points.iter().enumerate() { - let hot = Some(i) == nearest || Some(i) == dragging; - p.circle(to_s(pt.x, pt.y), if hot { 5.0 } else { 4.0 }, tk.panel, Stroke::new(1.5, if hot { tk.text_strong } else { tk.text })); - } - let mut out: Option = None; - if resp.drag_started() { - dragging = nearest; - } - if resp.dragged() - && let (Some(i), Some(q)) = (dragging, pointer) - { - let (x, y) = from_s(q); - let mut nc = c.clone(); - let last = nc.points.len().saturating_sub(1); - if let Some(pt) = nc.points.get_mut(i) { - // End points keep their x - if i != 0 && i != last { - pt.x = x; - } - pt.y = y; - } - nc.points.sort_by(|a, b| a.x.total_cmp(&b.x)); - out = Some(nc); - } - if resp.drag_stopped() { - dragging = None; - } - ui.data_mut(|d| d.insert_temp(drag_id, dragging)); - if resp.double_clicked() - && let Some(q) = pointer - { - let (x, _) = from_s(q); - let mut nc = c.clone(); - nc.points.push(materialcraft_engine::core::CurvePoint::new(x, c.eval(x))); - nc.points.sort_by(|a, b| a.x.total_cmp(&b.x)); - out = Some(nc); - } - if resp.secondary_clicked() - && let Some(i) = nearest - && i != 0 - && i + 1 != c.points.len() - { - let mut nc = c.clone(); - nc.points.remove(i); - out = Some(nc); - } - out -} - -/// A gradient editor: the ramp with its keys below; drag keys, click the ramp to add one, pick a key's color, right-click a key to remove it -pub fn gradient_editor(ui: &mut Ui, id: &str, g: &Gradient) -> Option { - let tk = Tokens::get(ui.ctx()); - let w = ui.available_width().min(260.0); - let (rect, resp) = ui.allocate_exact_size(vec2(w, 30.0), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Canvas, "Gradient editor"); - let p = ui.painter_at(rect.expand(6.0)); - let bar = Rect::from_min_size(rect.min, vec2(w, 18.0)); - let n = 64; - for i in 0..n { - let t0 = i as f32 / n as f32; - let c = g.eval(t0 + 0.5 / n as f32); - let q = |v: f32| (materialcraft_engine::image::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0) as u8; - let r = Rect::from_min_max(pos2(bar.left() + bar.width() * t0, bar.top()), pos2(bar.left() + bar.width() * (t0 + 1.0 / n as f32) + 0.5, bar.bottom())); - p.rect_filled(r, 0.0, Color32::from_rgb(q(c[0]), q(c[1]), q(c[2]))); - } - p.rect_stroke(bar, 2.0, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside); - let sel_id = ui.make_persistent_id(id).with("sel"); - let mut sel: usize = ui.data(|d| d.get_temp(sel_id)).unwrap_or(0); - let key_x = |pos: f32| bar.left() + pos * bar.width(); - let pointer = resp.interact_pointer_pos().or(resp.hover_pos()); - let nearest = pointer.and_then(|q| { - g.keys.iter().enumerate().map(|(i, k)| (i, (key_x(k.pos) - q.x).abs())).filter(|(_, d)| *d < 7.0).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i) - }); - for (i, k) in g.keys.iter().enumerate() { - let x = key_x(k.pos); - let tri = vec![pos2(x, bar.bottom() + 1.0), pos2(x - 5.0, bar.bottom() + 10.0), pos2(x + 5.0, bar.bottom() + 10.0)]; - p.add(egui::Shape::convex_polygon(tri, if i == sel { tk.accent } else { tk.text }, Stroke::NONE)); - } - let mut out: Option = None; - if resp.drag_started() - && let Some(i) = nearest - { - sel = i; - } - if resp.dragged() - && let Some(q) = pointer - && nearest.is_some() - { - let mut ng = g.clone(); - if let Some(k) = ng.keys.get_mut(sel) { - k.pos = ((q.x - bar.left()) / bar.width()).clamp(0.0, 1.0); - } - let moved = ng.keys.get(sel).copied(); - ng.sort(); - if let Some(m) = moved { - sel = ng.keys.iter().position(|k| k.pos == m.pos && k.color == m.color).unwrap_or(sel); - } - out = Some(ng); - } - if resp.clicked() - && let Some(q) = pointer - { - match nearest { - Some(i) => sel = i, - None => { - let t = ((q.x - bar.left()) / bar.width()).clamp(0.0, 1.0); - let mut ng = g.clone(); - ng.keys.push(materialcraft_engine::core::GradientKey::new(t, g.eval(t))); - ng.sort(); - sel = ng.keys.iter().position(|k| k.pos == t).unwrap_or(0); - out = Some(ng); - } - } - } - if resp.secondary_clicked() - && let Some(i) = nearest - && g.keys.len() > 1 - { - let mut ng = g.clone(); - ng.keys.remove(i); - sel = 0; - out = Some(ng); - } - ui.data_mut(|d| d.insert_temp(sel_id, sel)); - if let Some(k) = g.keys.get(sel) { - ui.horizontal(|ui| { - ui.label(RichText::new(format!("{} {:.2}", tr("Key at"), k.pos)).size(11.0).color(tk.text_dim)); - let mut rgb = [k.color[0], k.color[1], k.color[2]]; - if crate::widgets::color_swatch(ui, &format!("{id}-key"), &mut rgb, 60.0) { - let mut ng = out.clone().unwrap_or_else(|| g.clone()); - if let Some(kk) = ng.keys.get_mut(sel) { - kk.color = [rgb[0], rgb[1], rgb[2], kk.color[3]]; - } - out = Some(ng); - } - }); - } - out -} diff --git a/crates/ui-egui/src/property/curve.rs b/crates/ui-egui/src/property/curve.rs new file mode 100644 index 0000000..888c2f1 --- /dev/null +++ b/crates/ui-egui/src/property/curve.rs @@ -0,0 +1,93 @@ +use crate::theme::Tokens; +use egui::{Pos2, Sense, Stroke, Ui, pos2, vec2}; +use materialcraft_engine::core::Curve; + +/// A tone curve editor: drag points, double-click to add one, right-click a point to remove it. Returns the new curve when it changed +pub fn curve_editor(ui: &mut Ui, id: &str, curve: &Curve) -> Option { + let tokens = Tokens::get(ui.ctx()); + let width = ui.available_width().min(240.0); + let (rect, response) = ui.allocate_exact_size(vec2(width, width * 0.75), Sense::click_and_drag()); + crate::widgets::name(&response, egui::Role::Canvas, "Curve editor"); + let painter = ui.painter_at(rect); + painter.rect_filled(rect, 4.0, tokens.field); + for i in 1..4 { + let t = i as f32 / 4.0; + painter.line_segment( + [pos2(rect.left() + rect.width() * t, rect.top()), pos2(rect.left() + rect.width() * t, rect.bottom())], + Stroke::new(1.0, tokens.separator), + ); + painter.line_segment( + [pos2(rect.left(), rect.top() + rect.height() * t), pos2(rect.right(), rect.top() + rect.height() * t)], + Stroke::new(1.0, tokens.separator), + ); + } + let to_screen = |x: f32, y: f32| pos2(rect.left() + x * rect.width(), rect.bottom() - y * rect.height()); + let from_screen = |s: Pos2| (((s.x - rect.left()) / rect.width()).clamp(0.0, 1.0), ((rect.bottom() - s.y) / rect.height()).clamp(0.0, 1.0)); + let curve_points: Vec = (0..=64).map(|i| i as f32 / 64.0).map(|x| to_screen(x, curve.eval(x).clamp(0.0, 1.0))).collect(); + painter.add(egui::Shape::line(curve_points, Stroke::new(2.0, tokens.accent))); + let drag_id = ui.make_persistent_id(id).with("drag"); + let mut dragging: Option = ui.data(|d| d.get_temp(drag_id)); + let pointer = response.interact_pointer_pos().or(response.hover_pos()); + let nearest = pointer.and_then(|pointer_position| { + curve + .points + .iter() + .enumerate() + .map(|(i, point)| (i, to_screen(point.x, point.y).distance(pointer_position))) + .filter(|(_, d)| *d < 10.0) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(i, _)| i) + }); + for (i, point) in curve.points.iter().enumerate() { + let hot = Some(i) == nearest || Some(i) == dragging; + painter.circle( + to_screen(point.x, point.y), + if hot { 5.0 } else { 4.0 }, + tokens.panel, + Stroke::new(1.5, if hot { tokens.text_strong } else { tokens.text }), + ); + } + let mut edited_curve: Option = None; + if response.drag_started() { + dragging = nearest; + } + if response.dragged() + && let (Some(i), Some(pointer_position)) = (dragging, pointer) + { + let (x, y) = from_screen(pointer_position); + let mut updated_curve = curve.clone(); + let last = updated_curve.points.len().saturating_sub(1); + if let Some(point) = updated_curve.points.get_mut(i) { + // End points keep their x + if i != 0 && i != last { + point.x = x; + } + point.y = y; + } + updated_curve.points.sort_by(|a, b| a.x.total_cmp(&b.x)); + edited_curve = Some(updated_curve); + } + if response.drag_stopped() { + dragging = None; + } + ui.data_mut(|d| d.insert_temp(drag_id, dragging)); + if response.double_clicked() + && let Some(pointer_position) = pointer + { + let (x, _) = from_screen(pointer_position); + let mut updated_curve = curve.clone(); + updated_curve.points.push(materialcraft_engine::core::CurvePoint::new(x, curve.eval(x))); + updated_curve.points.sort_by(|a, b| a.x.total_cmp(&b.x)); + edited_curve = Some(updated_curve); + } + if response.secondary_clicked() + && let Some(i) = nearest + && i != 0 + && i + 1 != curve.points.len() + { + let mut updated_curve = curve.clone(); + updated_curve.points.remove(i); + edited_curve = Some(updated_curve); + } + edited_curve +} diff --git a/crates/ui-egui/src/property/gradient.rs b/crates/ui-egui/src/property/gradient.rs new file mode 100644 index 0000000..dd61ece --- /dev/null +++ b/crates/ui-egui/src/property/gradient.rs @@ -0,0 +1,101 @@ +use crate::{i18n::tr, theme::Tokens}; +use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; +use materialcraft_engine::core::Gradient; + +/// A gradient editor: the ramp with its keys below; drag keys, click the ramp to add one, pick a key's color, right-click a key to remove it +pub fn gradient_editor(ui: &mut Ui, id: &str, gradient: &Gradient) -> Option { + let tokens = Tokens::get(ui.ctx()); + let width = ui.available_width().min(260.0); + let (rect, response) = ui.allocate_exact_size(vec2(width, 30.0), Sense::click_and_drag()); + crate::widgets::name(&response, egui::Role::Canvas, "Gradient editor"); + let painter = ui.painter_at(rect.expand(6.0)); + let bar = Rect::from_min_size(rect.min, vec2(width, 18.0)); + let n = 64; + for i in 0..n { + let t0 = i as f32 / n as f32; + let c = gradient.eval(t0 + 0.5 / n as f32); + let q = |v: f32| (materialcraft_engine::image::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0) as u8; + let r = Rect::from_min_max(pos2(bar.left() + bar.width() * t0, bar.top()), pos2(bar.left() + bar.width() * (t0 + 1.0 / n as f32) + 0.5, bar.bottom())); + painter.rect_filled(r, 0.0, Color32::from_rgb(q(c[0]), q(c[1]), q(c[2]))); + } + painter.rect_stroke(bar, 2.0, Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); + let selection_id = ui.make_persistent_id(id).with("sel"); + let mut selected: usize = ui.data(|d| d.get_temp(selection_id)).unwrap_or(0); + let key_x = |pos: f32| bar.left() + pos * bar.width(); + let pointer = response.interact_pointer_pos().or(response.hover_pos()); + let nearest = pointer.and_then(|q| { + gradient + .keys + .iter() + .enumerate() + .map(|(i, k)| (i, (key_x(k.pos) - q.x).abs())) + .filter(|(_, d)| *d < 7.0) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(i, _)| i) + }); + for (i, k) in gradient.keys.iter().enumerate() { + let x = key_x(k.pos); + let triangle = vec![pos2(x, bar.bottom() + 1.0), pos2(x - 5.0, bar.bottom() + 10.0), pos2(x + 5.0, bar.bottom() + 10.0)]; + painter.add(egui::Shape::convex_polygon(triangle, if i == selected { tokens.accent } else { tokens.text }, Stroke::NONE)); + } + let mut edited_gradient: Option = None; + if response.drag_started() + && let Some(i) = nearest + { + selected = i; + } + if response.dragged() + && let Some(q) = pointer + && nearest.is_some() + { + let mut updated_gradient = gradient.clone(); + if let Some(k) = updated_gradient.keys.get_mut(selected) { + k.pos = ((q.x - bar.left()) / bar.width()).clamp(0.0, 1.0); + } + let moved = updated_gradient.keys.get(selected).copied(); + updated_gradient.sort(); + if let Some(m) = moved { + selected = updated_gradient.keys.iter().position(|k| k.pos == m.pos && k.color == m.color).unwrap_or(selected); + } + edited_gradient = Some(updated_gradient); + } + if response.clicked() + && let Some(q) = pointer + { + match nearest { + Some(i) => selected = i, + None => { + let t = ((q.x - bar.left()) / bar.width()).clamp(0.0, 1.0); + let mut updated_gradient = gradient.clone(); + updated_gradient.keys.push(materialcraft_engine::core::GradientKey::new(t, gradient.eval(t))); + updated_gradient.sort(); + selected = updated_gradient.keys.iter().position(|k| k.pos == t).unwrap_or(0); + edited_gradient = Some(updated_gradient); + } + } + } + if response.secondary_clicked() + && let Some(i) = nearest + && gradient.keys.len() > 1 + { + let mut updated_gradient = gradient.clone(); + updated_gradient.keys.remove(i); + selected = 0; + edited_gradient = Some(updated_gradient); + } + ui.data_mut(|d| d.insert_temp(selection_id, selected)); + if let Some(k) = gradient.keys.get(selected) { + ui.horizontal(|ui| { + ui.label(RichText::new(format!("{} {:.2}", tr("Key at"), k.pos)).size(11.0).color(tokens.text_dim)); + let mut rgb = [k.color[0], k.color[1], k.color[2]]; + if crate::widgets::color_swatch(ui, &format!("{id}-key"), &mut rgb, 60.0) { + let mut updated_gradient = edited_gradient.clone().unwrap_or_else(|| gradient.clone()); + if let Some(selected_key) = updated_gradient.keys.get_mut(selected) { + selected_key.color = [rgb[0], rgb[1], rgb[2], selected_key.color[3]]; + } + edited_gradient = Some(updated_gradient); + } + }); + } + edited_gradient +} diff --git a/crates/ui-egui/src/property/graph.rs b/crates/ui-egui/src/property/graph.rs new file mode 100644 index 0000000..166b627 --- /dev/null +++ b/crates/ui-egui/src/property/graph.rs @@ -0,0 +1,184 @@ +use super::{input::input_editor, section}; +use crate::{MaterialCraftApp, i18n::tr, theme::Tokens}; +use egui::{RichText, Ui}; +use egui_phosphor::regular as icon; +use materialcraft_engine::core::{Graph, OutputFormat, Resource, Value}; +use serde_json::{Value as JsonValue, json}; + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let Ok(graph) = app.session.graph() else { + ui.label(tr("No graph is open")); + return; + }; + + let mut commands = Vec::new(); + let mut emit = |id: &'static str, parameters| commands.push((id, parameters)); + section(ui, "graph-base", tr("Base parameters"), |ui| { + ui.horizontal(|ui| { + ui.label(tr("Name")); + let mut name = graph.name.clone(); + let response = ui.add(egui::TextEdit::singleline(&mut name).desired_width(ui.available_width())); + crate::widgets::name(&response, egui::Role::TextInput, "Graph name"); + if response.lost_focus() && name != graph.name { + emit("graph.rename", json!({"name": name})); + } + }); + if graph.function.is_some() { + return; + } + + for (axis, label) in [(0usize, "Width"), (1, "Height")] { + let mut value = graph.size[axis] as f32; + if crate::widgets::slider(ui, &format!("{} {} px", tr(label), 1u32 << graph.size[axis]), &mut value, 4.0..=13.0, 0).changed() { + let mut edited = graph.size; + edited[axis] = value.round() as u32; + emit("graph.size", json!({"log2": edited})); + } + } + crate::widgets::combo(ui, tr("Output format"), tr(graph.format.label()), |ui| { + for (format, key) in [(OutputFormat::U8, "u8"), (OutputFormat::U16, "u16"), (OutputFormat::F16, "f16"), (OutputFormat::F32, "f32")] { + if ui.selectable_label(graph.format == format, tr(format.label())).clicked() { + emit("graph.format", json!({"format": key})); + } + } + }); + let mut seed = graph.seed as f32; + if crate::widgets::slider(ui, tr("Random seed"), &mut seed, 0.0..=1000.0, 0).changed() { + emit("graph.seed", json!({"seed": seed.round() as i64})); + } + }); + section(ui, "graph-attr", tr("Attributes"), |ui| { + for (key, label, current) in [ + ("category", "Category", &graph.attributes.category), + ("description", "Description", &graph.attributes.description), + ("author", "Author", &graph.attributes.author), + ("tags", "Tags", &graph.attributes.tags), + ] { + ui.horizontal(|ui| { + ui.label(tr(label)); + let mut edited = current.clone(); + let response = ui.add(egui::TextEdit::singleline(&mut edited).desired_width(ui.available_width())); + crate::widgets::name(&response, egui::Role::TextInput, label); + if response.lost_focus() && edited != *current { + emit("graph.attributes", json!({key: edited})); + } + }); + } + }); + section(ui, "graph-inputs", tr("Input parameters"), |ui| { + if graph.exposed.is_empty() { + ui.label(RichText::new(tr("Right-click a node parameter > Expose as graph input")).size(11.0).color(tokens.text_dim)); + } else { + presets_bar(ui, graph, &mut emit); + } + let mut groups: Vec<&str> = Vec::new(); + for exposed in &graph.exposed { + if !groups.contains(&exposed.group.as_str()) { + groups.push(&exposed.group); + } + } + let mut last_group: Option<&str> = None; + let mut order: Vec<&materialcraft_engine::core::ExposedParameter> = Vec::new(); + for group in &groups { + order.extend(graph.exposed.iter().filter(|exposed| exposed.group == *group)); + } + for exposed in order { + if last_group != Some(exposed.group.as_str()) && !exposed.group.is_empty() { + ui.label(RichText::new(exposed.group.to_uppercase()).size(10.5).strong().color(tokens.text_dim)); + } + last_group = Some(exposed.group.as_str()); + let current = graph.input_value(&exposed.id).cloned().unwrap_or_else(|| exposed.default.clone()); + ui.horizontal(|ui| { + if crate::widgets::icon_button(ui, icon::X, tr("Delete input"), false, 18.0).clicked() { + emit("graph.exposed.delete", json!({"id": exposed.id})); + } + ui.vertical(|ui| { + if let Some(value) = input_editor(ui, exposed, ¤t) { + emit("graph.exposed.set", json!({"id": exposed.id, "value": value})); + } + }); + }); + } + }); + input_previews(ui, graph, &app.session.pkg.resources, &mut emit); + section(ui, "graph-outputs", tr("Outputs"), |ui| { + for node in graph.nodes.iter().filter(|node| node.def == "output") { + let usage = node.params.get("usage").and_then(Value::as_i32).unwrap_or(0) as usize; + let label = format!( + "{} {} | {}", + icon::SIGN_OUT, + materialcraft_engine::core::ComponentUsage::from_index(usage as u32).label, + materialcraft_engine::eval::identifier(node) + ); + if ui.add(egui::Button::selectable(app.session.view2d.node == Some(node.id), label)).clicked() { + emit("view.2d", json!({"node": node.id.0})); + } + } + }); + + for (id, parameters) in commands { + app.run(id, parameters); + } +} + +/// Preview images of the graph's input nodes: a bitmap resource, or (desktop) an image file such as a mesh map baked in TextureCraft +fn input_previews(ui: &mut Ui, graph: &Graph, resources: &[Resource], emit: &mut impl FnMut(&'static str, JsonValue)) { + let inputs = materialcraft_engine::material_cmds::image_inputs(graph); + if inputs.is_empty() { + return; + } + section(ui, "graph-input-images", tr("Input previews"), |ui| { + for input in &inputs { + let id = &input.identifier; + let bound = graph.input_images.get(id); + ui.horizontal(|ui| { + ui.label(id); + egui::ComboBox::from_id_salt(("input-preview", id)).width(120.0).selected_text(bound.map_or(tr("None"), String::as_str)).show_ui(ui, |ui| { + if ui.selectable_label(bound.is_none(), tr("None")).clicked() { + emit("graph.input.unbind", json!({"identifier": id})); + } + for resource in resources { + if ui.selectable_label(bound == Some(&resource.name), &resource.name).clicked() { + emit("graph.input.bind", json!({"identifier": id, "resource": resource.name})); + } + } + }); + #[cfg(not(target_arch = "wasm32"))] + if crate::widgets::icon_button(ui, icon::FOLDER_OPEN, tr("Pick an image file (a mesh map baked in TextureCraft)"), false, 18.0).clicked() + && let Some(path) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() + { + emit("graph.input.bind", json!({"identifier": id, "path": path.display().to_string()})); + } + }); + } + }); +} + +/// Presets: apply one, save the current inputs under a name, delete one +fn presets_bar(ui: &mut Ui, graph: &Graph, emit: &mut impl FnMut(&'static str, JsonValue)) { + let name_id = ui.make_persistent_id("preset-name"); + let mut name: String = ui.data(|data| data.get_temp(name_id)).unwrap_or_default(); + ui.horizontal(|ui| { + let response = egui::ComboBox::from_id_salt("presets").width(110.0).selected_text(tr("Presets")).show_ui(ui, |ui| { + for preset in &graph.presets { + if ui.button(&preset.name).clicked() { + emit("graph.preset.apply", json!({"name": preset.name})); + } + } + if graph.presets.is_empty() { + ui.label(tr("No presets yet")); + } + }); + crate::widgets::name(&response.response, egui::Role::ComboBox, "Presets"); + let text_response = ui.add(egui::TextEdit::singleline(&mut name).hint_text(tr("Preset name")).desired_width(90.0)); + crate::widgets::name(&text_response, egui::Role::TextInput, "Preset name"); + if crate::widgets::icon_button(ui, icon::FLOPPY_DISK, tr("Save preset"), false, 20.0).clicked() && !name.trim().is_empty() { + emit("graph.preset.save", json!({"name": name})); + } + if crate::widgets::icon_button(ui, icon::X, tr("Delete preset"), false, 20.0).clicked() && !name.trim().is_empty() { + emit("graph.preset.delete", json!({"name": name})); + } + }); + ui.data_mut(|data| data.insert_temp(name_id, name)); +} diff --git a/crates/ui-egui/src/property/input.rs b/crates/ui-egui/src/property/input.rs new file mode 100644 index 0000000..e6d49f4 --- /dev/null +++ b/crates/ui-egui/src/property/input.rs @@ -0,0 +1,45 @@ +use egui::Ui; +use materialcraft_engine::core::Value; +use serde_json::{Value as JsonValue, json}; + +/// The editor for one exposed input's value; returns the new value as JSON when it changed +pub(super) fn input_editor(ui: &mut Ui, exposed: &materialcraft_engine::core::ExposedParameter, current: &Value) -> Option { + match *current { + Value::Float(mut f) => { + let initial = f; + crate::widgets::slider(ui, &exposed.label, &mut f, exposed.min.min(initial)..=exposed.max.max(initial), 3).changed().then(|| json!(f)) + } + Value::Int(i) => { + let mut f = i as f32; + let initial = f; + crate::widgets::slider(ui, &exposed.label, &mut f, exposed.min.min(initial)..=exposed.max.max(initial), 0).changed().then(|| json!(f.round())) + } + Value::Bool(mut b) => ui.checkbox(&mut b, &exposed.label).changed().then(|| json!(b)), + Value::Enum(i) => { + let mut out = None; + crate::widgets::combo(ui, &exposed.label, exposed.options.get(i as usize).cloned().unwrap_or_default(), |ui| { + for (k, o) in exposed.options.iter().enumerate() { + if ui.selectable_label(k as u32 == i, o).clicked() { + out = Some(json!(k)); + } + } + }); + out + } + Value::Color(c) => { + let mut rgb = [c[0], c[1], c[2]]; + let mut out = None; + ui.horizontal(|ui| { + ui.label(&exposed.label); + if crate::widgets::color_swatch(ui, &format!("exp-{}", exposed.id), &mut rgb, 80.0) { + out = Some(json!([rgb[0], rgb[1], rgb[2], c[3]])); + } + }); + out + } + ref other => { + ui.label(format!("{}: {}", exposed.label, other.type_name())); + None + } + } +} diff --git a/crates/ui-egui/src/property/mod.rs b/crates/ui-egui/src/property/mod.rs new file mode 100644 index 0000000..89e6720 --- /dev/null +++ b/crates/ui-egui/src/property/mod.rs @@ -0,0 +1,69 @@ +mod curve; +mod gradient; +mod graph; +mod input; +mod node; +mod parameter; +mod section; + +pub use curve::curve_editor; +pub use gradient::gradient_editor; +pub(crate) use section::section; + +use crate::{MaterialCraftApp, graph::editor_target::EditorTarget, i18n::tr}; +use egui::Ui; + +/// The panel title: " - Properties" or " - Properties" +pub fn title(app: &MaterialCraftApp) -> String { + match EditorTarget::resolve(app) { + EditorTarget::Pattern => return crate::pattern::properties::title(app), + EditorTarget::Function if !EditorTarget::annotation_active(app) => { + return crate::function::properties::title(app).unwrap_or_else(|| format!("{} - {}", tr("Function Graph"), tr("Properties"))); + } + _ => {} + } + + if let Some(selection) = app.session.annotation_selection { + let name = match selection { + materialcraft_engine::AnnotationSelection::Frame(_) => tr("Frame"), + materialcraft_engine::AnnotationSelection::Comment(_) => tr("Comment"), + }; + return format!("{name} - {}", tr("Properties")); + } + + let sel = crate::graph::node_selection::inspected(&app.session.selection, app.graph.inspected_node) + .and_then(|id| app.session.graph().ok()?.node(id).ok().map(crate::graph::node_label)); + let name = sel.or_else(|| app.session.graph().ok().map(|g| g.name.clone())).unwrap_or_default(); + format!("{name} - {}", tr("Properties")) +} + +pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + ui.set_width(ui.available_width()); + match EditorTarget::resolve(app) { + EditorTarget::Pattern => { + crate::pattern::properties::show(app, ui); + return; + } + EditorTarget::Function if !EditorTarget::annotation_active(app) => { + if !crate::function::properties::show(app, ui) { + ui.label(tr("Select a node")); + } + return; + } + _ => {} + } + + if let Some(selection) = app.session.annotation_selection { + ui.push_id((app.session.graph, format!("{selection:?}")), |ui| crate::annotation::show(app, ui, selection)); + return; + } + + let node = crate::graph::node_selection::inspected(&app.session.selection, app.graph.inspected_node) + .and_then(|id| app.session.graph().ok()?.node(id).ok().cloned()); + ui.push_id((app.session.graph, node.as_ref().map(|n| n.id)), |ui| match node { + Some(n) => node::show(app, ui, &n), + None => graph::show(app, ui), + }); + }); +} diff --git a/crates/ui-egui/src/property/node.rs b/crates/ui-egui/src/property/node.rs new file mode 100644 index 0000000..d66ab94 --- /dev/null +++ b/crates/ui-egui/src/property/node.rs @@ -0,0 +1,157 @@ +use super::{ + input::input_editor, + parameter::{function_row, param_row}, + section, +}; +use crate::{MaterialCraftApp, i18n::tr, theme::Tokens}; +use egui::{Rect, RichText, Ui, vec2}; +use egui_phosphor::regular as icon; +use materialcraft_engine::core::{OutputFormat, SizeMode}; +use serde_json::json; + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, node: &materialcraft_engine::core::Node) { + let tokens = Tokens::get(ui.ctx()); + let definition = materialcraft_engine::nodes::find(&node.def); + // Header: label (renamable) and description + ui.horizontal(|ui| { + ui.painter().rect_filled(Rect::from_min_size(ui.cursor().min + vec2(0.0, 2.0), vec2(4.0, 16.0)), 1.0, crate::graph::header_color(&node.def)); + ui.add_space(8.0); + let mut label = if node.label.is_empty() { crate::graph::node_label(node) } else { node.label.clone() }; + let response = ui.add(egui::TextEdit::singleline(&mut label).desired_width(ui.available_width() - 4.0).font(egui::TextStyle::Heading)); + crate::widgets::name(&response, egui::Role::TextInput, "Node label"); + if response.changed() { + app.run("graph.node.rename", json!({"id": node.id.0, "label": label})); + } + }); + if let Some(definition) = definition + && !definition.description.is_empty() + { + ui.label(RichText::new(definition.description).size(11.0).color(tokens.text_dim)); + } + if let Some(response) = app.session.cooked.nodes.get(&node.id) + && let Some(entry) = &response.error + { + ui.label(RichText::new(format!("{} {entry}", icon::WARNING)).color(tokens.danger)); + } + ui.add_space(4.0); + section(ui, "base", tr("Base parameters"), |ui| base_params(app, ui, node)); + crate::value_input_editor::show(app, ui, node); + if node.def == "input_value" { + crate::value_input_editor::default_value(app, ui, node); + } + if node.def == "graph_instance" { + section(ui, "instance", tr("Instance parameters"), |ui| instance_params(app, ui, node)); + return; + } + let Some(definition) = definition else { return }; + + if definition.params.is_empty() { + return; + } + section(ui, "specific", tr("Specific parameters"), |ui| { + if node.def == "levels" { + crate::levels_editor::show(app, ui, node); + ui.add_space(6.0); + } + let exposed: Vec<(String, String)> = + app.session.graph().map(|g| g.exposed.iter().map(|entry| (entry.id.clone(), entry.label.clone())).collect()).unwrap_or_default(); + for parameter in &definition.params { + if node.def == "input_value" && parameter.id == "default" { + continue; + } + let current = node.params.get(parameter.id).cloned().unwrap_or_else(|| parameter.default.clone()); + if node.functions.contains_key(parameter.id) { + function_row(app, ui, node.id, parameter.id, parameter.label); + continue; + } + let bound = node.bindings.get(parameter.id).cloned(); + param_row(app, ui, node.id, parameter, current, bound, &exposed); + } + }); +} + +fn base_params(app: &mut MaterialCraftApp, ui: &mut Ui, node: &materialcraft_engine::core::Node) { + let base = &node.base; + let id = node.id.0; + let modes = [(SizeMode::RelativeToInput, "Relative to input"), (SizeMode::RelativeToParent, "Relative to parent"), (SizeMode::Absolute, "Absolute")]; + let current = modes.iter().find(|mode| mode.0 == base.size_mode).map_or("", |mode| mode.1); + crate::widgets::combo(ui, tr("Output size"), tr(current), |ui| { + for (mode, label) in modes { + if ui.selectable_label(base.size_mode == mode, tr(label)).clicked() { + let key = match mode { + SizeMode::RelativeToInput => "relativeToInput", + SizeMode::RelativeToParent => "relativeToParent", + SizeMode::Absolute => "absolute", + }; + + let size = if mode == SizeMode::Absolute { json!([10, 10]) } else { json!([0, 0]) }; + app.run("graph.node.base", json!({"id": id, "sizeMode": key, "size": size})); + } + } + }); + let (minimum, maximum) = if base.size_mode == SizeMode::Absolute { (4.0, 13.0) } else { (-6.0, 6.0) }; + for (axis, label) in [(0usize, "Width"), (1, "Height")] { + let mut value = base.size[axis] as f32; + let caption = if base.size_mode == SizeMode::Absolute { + format!("{label} {} px", 1u32 << base.size[axis].clamp(4, 13)) + } else { + format!("{label} x {}", 2f32.powi(base.size[axis])) + }; + + if crate::widgets::slider(ui, &caption, &mut value, minimum..=maximum, 0).changed() { + let mut size = base.size; + size[axis] = value.round() as i32; + app.run("graph.node.base", json!({"id": id, "size": size})); + } + } + crate::widgets::combo(ui, tr("Output format"), tr(base.format.label()), |ui| { + for format in OutputFormat::ALL { + if ui.selectable_label(base.format == format, tr(format.label())).clicked() { + let key = match format { + OutputFormat::Inherit => "inherit", + OutputFormat::U8 => "u8", + OutputFormat::U16 => "u16", + OutputFormat::F16 => "f16", + OutputFormat::F32 => "f32", + }; + + app.run("graph.node.base", json!({"id": id, "format": key})); + } + } + }); + let mut seed = base.seed as f32; + if crate::widgets::slider(ui, tr("Random seed"), &mut seed, 0.0..=1000.0, 0).changed() { + app.run("graph.node.base", json!({"id": id, "seed": seed.round() as i64})); + } + if ui.button(format!("{} {}", icon::SHUFFLE, tr("New random seed"))).clicked() { + let seed = (crate::now_ms() as u64 ^ id).wrapping_mul(2654435761) % 1000; + app.run("graph.node.base", json!({"id": id, "seed": seed})); + } + let mut tiling = base.tiling[0] && base.tiling[1]; + if ui.checkbox(&mut tiling, tr("Tiling (H and V)")).changed() { + app.run("graph.node.base", json!({"id": id, "tiling": tiling})); + } +} + +fn instance_params(app: &mut MaterialCraftApp, ui: &mut Ui, node: &materialcraft_engine::core::Node) { + let tokens = Tokens::get(ui.ctx()); + let Some((graph_index, subgraph)) = materialcraft_engine::eval::instance_graph(&app.session.pkg, node) else { + ui.label(RichText::new(tr("The instanced graph is missing")).color(tokens.danger)); + return; + }; + + let exposed = subgraph.exposed.clone(); + if ui.button(format!("{} {}", icon::ARROW_SQUARE_OUT, tr("Open graph"))).clicked() { + crate::graph::subgraph_navigation::open_instance(app, graph_index); + return; + } + if exposed.is_empty() { + ui.label(RichText::new(tr("This graph exposes no inputs")).color(tokens.text_dim)); + } + for entry in exposed { + let current = node.params.get(&entry.id).cloned().unwrap_or_else(|| entry.default.clone()); + if let Some(value) = input_editor(ui, &entry, ¤t) { + app.run("graph.node.param", json!({"id": node.id.0, "param": entry.id, "value": value})); + } + } +} diff --git a/crates/ui-egui/src/property/parameter.rs b/crates/ui-egui/src/property/parameter.rs new file mode 100644 index 0000000..f0ce608 --- /dev/null +++ b/crates/ui-egui/src/property/parameter.rs @@ -0,0 +1,214 @@ +use super::{curve_editor, gradient_editor}; +use crate::{MaterialCraftApp, i18n::tr, theme::Tokens}; +use egui::{RichText, Ui}; +use egui_phosphor::regular as icon; +use materialcraft_engine::core::{NodeId, Value}; +use materialcraft_engine::nodes::ParameterDefinition; +use serde_json::{Value as JsonValue, json}; + +fn set(app: &mut MaterialCraftApp, node: NodeId, param: &str, value: JsonValue) { + app.run("graph.node.param", json!({"id": node.0, "param": param, "value": value})); +} + +fn typed(v: &Value) -> JsonValue { + serde_json::to_value(v).unwrap_or(JsonValue::Null) +} + +/// One parameter: its editor, plus the expose/bind menu +pub(super) fn param_row( + app: &mut MaterialCraftApp, + ui: &mut Ui, + node: NodeId, + parameter: &ParameterDefinition, + current: Value, + bound: Option, + exposed: &[(String, String)], +) { + let tokens = Tokens::get(ui.ctx()); + if let Some(input) = &bound { + ui.horizontal(|ui| { + ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); + ui.label(RichText::new(format!("{} {input}", icon::LINK)).color(tokens.accent)); + if crate::widgets::icon_button(ui, icon::LINK_BREAK, tr("Unbind"), false, 18.0).clicked() { + app.run("graph.node.bind", json!({"id": node.0, "param": parameter.id, "input": JsonValue::Null})); + } + }); + return; + } + let show_menu = |app: &mut MaterialCraftApp, resp: &egui::Response| { + resp.context_menu(|ui| { + if ui.button(tr("Reset to default")).clicked() { + app.run("graph.node.reset", json!({"id": node.0, "param": parameter.id})); + ui.close(); + } + let dynamic = !matches!(parameter.default, Value::Text(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_) | Value::PatternGraph(_)); + if dynamic && ui.button(tr("Set function...")).clicked() { + if app.run("graph.node.function", json!({"id": node.0, "param": parameter.id})).is_some() { + crate::graph::subgraph_navigation::open_function(app, node, crate::function::FunctionTarget::Dynamic(parameter.id.to_string())); + } + ui.close(); + } + if ui.button(tr("Expose as graph input")).clicked() { + app.run("graph.exposed.add", json!({"id": parameter.id, "label": parameter.label, "bind": {"node": node.0, "param": parameter.id}})); + ui.close(); + } + if !exposed.is_empty() { + ui.menu_button(tr("Bind to input"), |ui| { + for (id, label) in exposed { + if ui.button(label).clicked() { + app.run("graph.node.bind", json!({"id": node.0, "param": parameter.id, "input": id})); + ui.close(); + } + } + }); + } + }); + }; + + match current { + Value::Float(mut v) => { + if parameter.angle { + let mut degrees = v * 360.0; + let response = crate::widgets::slider(ui, tr(parameter.label), &mut degrees, -360.0..=360.0, 1); + if response.changed() { + v = degrees / 360.0; + set(app, node, parameter.id, json!(v)); + } + show_menu(app, &response); + } else { + let (minimum, maximum) = (parameter.min.min(v), parameter.max.max(v)); + let response = crate::widgets::slider(ui, tr(parameter.label), &mut v, minimum..=maximum, if maximum - minimum > 20.0 { 1 } else { 3 }); + if response.changed() { + set(app, node, parameter.id, json!(v)); + } + show_menu(app, &response); + } + } + Value::Int(i) => { + let mut v = i as f32; + let range = parameter.min.min(v)..=parameter.max.max(v); + let response = crate::widgets::slider(ui, tr(parameter.label), &mut v, range, 0); + if response.changed() && v.round() as i32 != i { + set(app, node, parameter.id, json!(v.round() as i32)); + } + show_menu(app, &response); + } + Value::Float2(v) => { + ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); + let mut nv = v; + for (k, axis) in ["X", "Y"].iter().enumerate() { + let range = parameter.min.min(nv[k])..=parameter.max.max(nv[k]); + let response = crate::widgets::slider(ui, axis, &mut nv[k], range, 3); + if response.changed() { + set(app, node, parameter.id, json!(nv)); + } + show_menu(app, &response); + } + } + Value::Int2(v) => { + ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); + for k in 0..2 { + let mut f = v[k] as f32; + if crate::widgets::slider(ui, ["X", "Y"][k], &mut f, parameter.min..=parameter.max, 0).changed() { + let mut nv = v; + nv[k] = f.round() as i32; + set(app, node, parameter.id, json!(nv)); + } + } + } + Value::Bool(b) => { + let mut v = b; + let response = ui.checkbox(&mut v, tr(parameter.label)); + if response.changed() { + set(app, node, parameter.id, json!(v)); + } + show_menu(app, &response); + } + Value::Float3(_) | Value::Float4(_) | Value::Int3(_) | Value::Int4(_) => { + ui.label(tr(parameter.label)); + let mut value = current.clone(); + if crate::value_editor::show(ui, &mut value) { + set(app, node, parameter.id, serde_json::to_value(value).unwrap_or_default()); + } + } + Value::Color(c) => { + ui.horizontal(|ui| { + ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mut rgb = [c[0], c[1], c[2]]; + if crate::widgets::color_swatch(ui, &format!("{}-{}", node.0, parameter.id), &mut rgb, 90.0) { + set(app, node, parameter.id, json!([rgb[0], rgb[1], rgb[2], c[3]])); + } + }); + }); + } + Value::Enum(i) => { + let current = parameter.options.get(i as usize).copied().unwrap_or("?"); + crate::widgets::combo(ui, tr(parameter.label), tr(current), |ui| { + for (k, o) in parameter.options.iter().enumerate() { + if ui.selectable_label(k as u32 == i, tr(o)).clicked() { + set(app, node, parameter.id, json!(k)); + } + } + }); + } + Value::Text(t) if parameter.resource => { + let names: Vec = app.session.pkg.resources.iter().map(|response| response.name.clone()).collect(); + crate::widgets::combo(ui, tr(parameter.label), if t.is_empty() { tr("(checker)").to_string() } else { t.clone() }, |ui| { + for n in &names { + if ui.selectable_label(*n == t, n).clicked() { + set(app, node, parameter.id, json!(n)); + } + } + }); + if ui.button(format!("{} {}", icon::IMAGE, tr("Import bitmap..."))).clicked() { + crate::menus::invoke(app, ui.ctx(), "file.importBitmap"); + } + } + Value::Text(t) => { + ui.horizontal(|ui| { + ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); + let mut s = t.clone(); + let response = ui.add(egui::TextEdit::singleline(&mut s).desired_width(ui.available_width())); + crate::widgets::name(&response, egui::Role::TextInput, parameter.label); + if response.changed() { + set(app, node, parameter.id, json!(s)); + } + }); + } + Value::Curve(c) => { + ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); + if let Some(nc) = curve_editor(ui, &format!("curve-{}-{}", node.0, parameter.id), &c) { + set(app, node, parameter.id, json!(nc.points.iter().map(|q| [q.x, q.y]).collect::>())); + } + } + Value::Gradient(g) => { + ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); + if let Some(ng) = gradient_editor(ui, &format!("grad-{}-{}", node.0, parameter.id), &g) { + set(app, node, parameter.id, typed(&Value::Gradient(ng))); + } + } + Value::PatternGraph(graph) => { + ui.label(format!("{}: {} nodes", parameter.label, graph.nodes.len())); + } + Value::Function(f) => { + ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); + crate::windows::function_summary(app, ui, node, parameter.id, &f); + } + } +} + +/// A parameter driven by a function: its label, Edit and Remove +pub(super) fn function_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, param: &str, label: &str) { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.label(RichText::new(tr(label)).color(tokens.text)); + ui.label(RichText::new(format!("{} {}", icon::FUNCTION, tr("function"))).color(tokens.accent)); + if ui.small_button(tr("Edit")).clicked() { + crate::graph::subgraph_navigation::open_function(app, node, crate::function::FunctionTarget::Dynamic(param.to_string())); + } + if crate::widgets::icon_button(ui, icon::X, tr("Remove function"), false, 18.0).clicked() { + app.run("graph.node.function", json!({"id": node.0, "param": param, "remove": true})); + } + }); +} diff --git a/crates/ui-egui/src/property/section.rs b/crates/ui-egui/src/property/section.rs new file mode 100644 index 0000000..c6bc3ba --- /dev/null +++ b/crates/ui-egui/src/property/section.rs @@ -0,0 +1,29 @@ +use crate::theme::Tokens; +use egui::{Sense, Ui, vec2}; +use egui_phosphor::regular as icon; + +pub(crate) fn section(ui: &mut Ui, id: &str, title: &str, body: impl FnOnce(&mut Ui)) { + let tokens = Tokens::get(ui.ctx()); + let id = ui.make_persistent_id(id); + let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click()); + crate::widgets::name(&response, egui::Role::Button, title); + ui.painter().rect_filled(rect, 3.0, tokens.row); + let chevron = if state.is_open() { icon::CARET_DOWN } else { icon::CARET_RIGHT }; + ui.painter().text(rect.left_center() + vec2(6.0, 0.0), egui::Align2::LEFT_CENTER, chevron, egui::FontId::proportional(10.0), tokens.text_dim); + ui.painter().text( + rect.left_center() + vec2(20.0, 0.0), + egui::Align2::LEFT_CENTER, + title.to_uppercase(), + egui::FontId::proportional(10.5), + tokens.text_strong, + ); + if response.clicked() { + state.toggle(ui); + } + state.show_body_unindented(ui, |ui| { + ui.add_space(3.0); + body(ui); + ui.add_space(6.0); + }); +} diff --git a/crates/ui-egui/src/view3d.rs b/crates/ui-egui/src/view3d.rs index 3b51724..adce9d1 100644 --- a/crates/ui-egui/src/view3d.rs +++ b/crates/ui-egui/src/view3d.rs @@ -1,4 +1,4 @@ -//! The 3D view: the open graph's material on a built-in scene, rendered by +//! The 3D view: assigned material channels on a built-in scene, rendered by //! `materialcraft-render` (one ray per pixel at half resolution while the camera moves, 2×2 //! supersampled when it rests). Left-drag orbits, Alt+drag or middle-drag pans, the wheel zooms, //! Shift+drag turns the light and a double-click resets the camera. @@ -93,6 +93,25 @@ fn menus(app: &mut MaterialCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); egui::Frame::NONE.fill(tk.panel).inner_margin(egui::Margin::symmetric(4, 1)).show(ui, |ui| { egui::MenuBar::new().ui(ui, |ui| { + ui.menu_button(tr("Material"), |ui| { + let sources = app.session.material_preview.sources(&app.session.pkg); + for channel in materialcraft_engine::core::MaterialChannel::ALL { + let source = sources.get(&channel); + let label = source + .and_then(|source| { + let graph = app.session.pkg.graphs.get(source.graph)?; + let node = graph.node(source.node).ok()?; + Some(format!("{} / {}", graph.name, crate::graph::node_label(node))) + }) + .unwrap_or_else(|| tr("Unassigned").to_string()); + ui.label(format!("{}: {label}", tr(channel.label()))); + } + ui.separator(); + if ui.button(tr("Clear material assignments")).clicked() { + app.run("view.3d.clear", json!({})); + ui.close(); + } + }); ui.menu_button(tr("Scene"), |ui| { for (id, label) in SCENES { if ui.selectable_label(app.session.view3d.scene == *id, tr(label)).clicked() { @@ -172,7 +191,12 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let avail = ui.available_size(); let (rect, resp) = ui.allocate_exact_size(vec2(avail.x, (avail.y - 22.0).max(40.0)), Sense::click_and_drag()); crate::widgets::name(&resp, egui::Role::Image, "3D view"); - // Camera gestures. + let graph_hover = resp.dnd_hover_payload::().is_some(); + if let Some(graph) = crate::widgets::dnd_release::(&resp) { + app.run("view.3d.outputs", json!({"graph": graph.name})); + } + + // Camera gestures let mut moving = false; if resp.dragged() { let d = resp.drag_delta(); @@ -217,7 +241,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { p.text( rect.center_top() + vec2(0.0, 18.0), egui::Align2::CENTER_TOP, - tr("Add Output nodes with usages (base color, normal, ...) to see the material"), + tr("Assign an image with View in 3D view, or connect Output nodes with material usages"), egui::FontId::proportional(11.0), tk.viewport_text, ); @@ -229,7 +253,18 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { egui::FontId::proportional(10.5), tk.viewport_text, ); - // Bottom bar. + if graph_hover { + p.rect_stroke(rect.shrink(2.0), 4.0, egui::Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); + p.text( + rect.center_top() + vec2(0.0, 38.0), + egui::Align2::CENTER_TOP, + tr("Drop to apply graph outputs"), + egui::FontId::proportional(13.0), + tk.viewport_text, + ); + } + + // Bottom bar let bar = Rect::from_min_size(pos2(rect.left(), rect.bottom()), vec2(rect.width(), 22.0)); ui.scope_builder(egui::UiBuilder::new().max_rect(bar), |ui| { ui.painter().rect_filled(bar, 0.0, tk.panel); @@ -281,11 +316,7 @@ fn content_key(app: &MaterialCraftApp, w: u32, h: u32, show_env: bool) -> u64 { for f in [v.yaw, v.pitch, v.distance, v.target[0], v.target[1], v.target[2], v.tiling, v.exposure, v.env_rotation, v.height_scale] { f.to_bits().hash(&mut hs); } - if let Ok(g) = app.session.graph() { - for (id, usage, _, _) in materialcraft_engine::eval::outputs(g, &app.session.cooked) { - (usage, app.session.cooked.nodes.get(&id).map(|r| r.key)).hash(&mut hs); - } - } + app.session.material_key().hash(&mut hs); hs.finish() } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index b5c356f..8e2c489 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -484,7 +484,7 @@ pub fn history(app: &mut MaterialCraftApp, ui: &mut Ui) { pub fn function_summary(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, param: &str, f: &FunctionGraph) { let tk = Tokens::get(ui.ctx()); if ui.add(crate::widgets::primary_button(ui, &format!("{} {}", icon::FLOW_ARROW, tr("Edit function graph...")))).clicked() { - app.function_editor = Some(crate::function::FunctionEditor::new(node, crate::function::FunctionTarget::Parameter(param.to_string()))); + crate::graph::subgraph_navigation::open_function(app, node, crate::function::FunctionTarget::Parameter(param.to_string())); } ui.label(RichText::new(format!("{} {}", f.nodes.len(), tr("function nodes"))).size(10.5).color(tk.text_dim)); let id = egui::Id::unique(("fn-edit", node.0, param)); diff --git a/crates/ui-egui/tests/snapshot.rs b/crates/ui-egui/tests/snapshot.rs index e910889..b1327e9 100644 --- a/crates/ui-egui/tests/snapshot.rs +++ b/crates/ui-egui/tests/snapshot.rs @@ -58,26 +58,28 @@ fn explorer_export_opens_the_clicked_graph() { #[ignore = "requires an offscreen GPU; run explicitly with --ignored"] fn empty_startup_can_create_a_template() { let app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); - let mut h = harness(app, 1600.0, 960.0); - settle(&mut h, 40); - assert_eq!(h.state().session.pkg.graphs.len(), 1); - assert!(h.state().session.graph().unwrap().nodes.is_empty()); - assert!(h.state().graph.rects.is_empty()); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 40); + assert_eq!(harness.state().session.pkg.graphs.len(), 1); + assert!(harness.state().session.graph().unwrap().nodes.is_empty()); + assert!(harness.state().graph.rects.is_empty()); if let Some(dir) = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from) { std::fs::create_dir_all(&dir).unwrap(); - save(&mut h, &dir, "empty-startup"); + save(&mut harness, &dir, "empty-startup"); } - h.get_by_label("New graph...").click(); - settle(&mut h, 4); - h.get_by_label("Atomic sample").click(); - settle(&mut h, 4); - h.get_by_label("Create").click(); - settle(&mut h, 40); - assert_eq!(h.state().session.pkg.graphs.len(), 2); - assert!(!h.state().session.graph().unwrap().nodes.is_empty()); - assert!(!h.state().graph.rects.is_empty()); + harness.get_by_label("New graph...").click(); + settle(&mut harness, 4); + harness.get(By::new().role(egui::accesskit::Role::ComboBox).label("Template")).click(); + settle(&mut harness, 2); + harness.get_by_label("Atomic sample").click(); + settle(&mut harness, 4); + harness.get_by_label("Create").click(); + settle(&mut harness, 40); + assert_eq!(harness.state().session.pkg.graphs.len(), 2); + assert!(!harness.state().session.graph().unwrap().nodes.is_empty()); + assert!(!harness.state().graph.rects.is_empty()); if let Some(dir) = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from) { - save(&mut h, &dir, "chosen-template"); + save(&mut harness, &dir, "chosen-template"); } } @@ -144,6 +146,7 @@ fn snapshots() { h.state_mut().run("graph.select", json!({"ids": [id]})); h.state_mut().run("view.2d", json!({"node": id})); h.state_mut().function_editor = Some(materialcraft_ui_egui::function::FunctionEditor::new( + h.state().session.graph, materialcraft_engine::core::NodeId(id), materialcraft_ui_egui::function::FunctionTarget::Parameter("function".into()), )); @@ -205,7 +208,7 @@ fn graph_context_menu_has_flat_node_list() { let app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); let mut harness = harness(app, 1600.0, 960.0); settle(&mut harness, 8); - harness.get(By::new().role(egui::accesskit::Role::Button).label("Input Value")).click_secondary(); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Brightness")).click_secondary(); settle(&mut harness, 3); let directory = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from); if let Some(directory) = &directory { @@ -218,8 +221,8 @@ fn graph_context_menu_has_flat_node_list() { "Add Frame", "Add Navigation pin", "Add Dot node", - "View outputs in 3D view", - "Reset and view outputs in 3D view", + "View in 3D view", + "Reset and view in 3D view", "View output in 2D view", "Compute nodes thumbnails", "Clear nodes thumbnails", @@ -312,8 +315,7 @@ fn graph_context_menu_has_flat_node_list() { if let Some(directory) = &directory { save(&mut harness, directory, "pattern-graph-editor"); } - let parent = harness.state().session.graph().unwrap().name.clone(); - harness.get(By::new().role(egui::accesskit::Role::Button).label(&parent)).click(); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Return to parent graph")).click(); settle(&mut harness, 3); assert!(harness.state().pattern_editor.is_none()); @@ -553,7 +555,7 @@ fn named_outputs_open_properties_and_preview_only_on_double_click() { let view3d = serde_json::to_value(&app.session.view3d).unwrap(); let mut harness = harness(app, 1600.0, 960.0); settle(&mut harness, 5); - let query = By::new().role(egui::accesskit::Role::TreeItem).label("base_color"); + let query = By::new().role(egui::accesskit::Role::TreeItem).label("Base Color"); let position = harness.get(query.clone()).rect().center(); click_canvas(&mut harness, position); assert_eq!(harness.state().session.selection, vec![materialcraft_engine::core::NodeId(output)]); @@ -577,3 +579,317 @@ fn named_outputs_open_properties_and_preview_only_on_double_click() { assert_eq!(current, material); save(&mut harness, &directory, "named-output-preview"); } + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn shared_toolbar_targets_each_graph_and_preserves_undo() { + use materialcraft_engine::core::{FunctionGraph, NodeId, PatternGraph, PatternNodeKind, Value}; + + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + let mut common_controls = None; + for kind in ["material", "function", "pattern"] { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + let mut owner = 0; + match kind { + "function" => { + app.run("file.new", json!({"kind": "function"})).unwrap(); + let mut graph = FunctionGraph::default(); + for position in [[0.0, 0.0], [256.0, 160.0]] { + graph.add_constant(Value::Float(1.0)); + graph.nodes.last_mut().unwrap().pos = position; + } + graph.output = Some(2); + app.run("graph.function.set", json!({"function": graph})).unwrap(); + } + "pattern" => { + owner = app.run("graph.node.add", json!({"def": "fx_map", "at": [700, 800]})).unwrap()["id"].as_u64().unwrap(); + let mut graph = PatternGraph::default(); + for position in [[0.0, 0.0], [256.0, 160.0]] { + graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes.last_mut().unwrap().position = position; + } + app.run("graph.pattern.set", json!({"id": owner, "pattern": graph})).unwrap(); + app.pattern_editor = Some(materialcraft_ui_egui::pattern::PatternEditor::new(app.session.graph, NodeId(owner))); + } + _ => { + for position in [[0, 0], [256, 160]] { + app.run("graph.node.add", json!({"def": "uniform", "at": position})).unwrap(); + } + } + } + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 4); + let query = |label| By::new().role(egui::accesskit::Role::Button).label(label); + let controls = ["Frame all (F)", "Align left", "Distribute horizontally", "Snap to grid"].map(|label| harness.get(query(label)).rect()); + if let Some(expected) = common_controls { + assert_eq!(controls, expected, "{kind} toolbar drift"); + } + common_controls = Some(controls); + let context = harness.ctx.clone(); + materialcraft_ui_egui::menus::invoke(harness.state_mut(), &context, "edit.selectAll"); + settle(&mut harness, 2); + let original = harness.state().session.pkg.clone(); + harness.get(query("Align left")).click(); + settle(&mut harness, 3); + let graph = harness.state().session.graph().unwrap(); + let positions: Vec<_> = match kind { + "function" => graph.function.as_ref().unwrap().nodes.iter().map(|node| node.pos).collect(), + "pattern" => { + let Value::PatternGraph(pattern) = &graph.node(NodeId(owner)).unwrap().params["pattern"] else { panic!("missing pattern") }; + assert_eq!(graph.node(NodeId(owner)).unwrap().pos, [704.0, 800.0]); + pattern.nodes.iter().map(|node| node.position).collect() + } + _ => graph.nodes.iter().map(|node| node.pos).collect(), + }; + assert_eq!(positions, vec![[0.0, 0.0], [0.0, 160.0]], "{kind} alignment"); + harness.state_mut().session.undo().unwrap(); + assert_eq!(harness.state().session.pkg, original); + let snap = harness.state().ui.prefs.snap_to_grid; + harness.get(query("Snap to grid")).click(); + settle(&mut harness, 2); + assert_eq!(harness.state().ui.prefs.snap_to_grid, !snap); + assert_eq!(harness.state().session.pkg, original); + harness.get(query("Frame all (F)")).click(); + settle(&mut harness, 2); + save(&mut harness, &directory, &format!("shared-toolbar-{kind}")); + if kind == "pattern" { + materialcraft_ui_egui::menus::invoke(harness.state_mut(), &context, "edit.delete"); + settle(&mut harness, 2); + assert!(harness.query_all(By::new().label("Set a node as the root")).next().is_some()); + harness.state_mut().session.undo().unwrap(); + harness.get(query("Return to parent graph")).click(); + settle(&mut harness, 2); + assert!(harness.state().pattern_editor.is_none()); + assert_eq!(harness.state().session.pkg, original); + } else if kind == "function" { + harness.get(query("Add frame around the selection")).click(); + settle(&mut harness, 2); + assert_eq!(harness.state().session.graph().unwrap().frames.len(), 1); + assert_eq!(harness.state().session.graph().unwrap().function, original.graphs[harness.state().session.graph].function); + save(&mut harness, &directory, "shared-toolbar-function-frame"); + } + } +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn embedded_function_toolbar_and_panels_share_the_active_target() { + use materialcraft_engine::{ + FunctionGraphTarget, + core::{FunctionGraph, NodeId, Value}, + }; + for definition in ["pixel_processor", "value_processor"] { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + let owner = NodeId(app.run("graph.node.add", json!({"def": definition, "at": [700, 800]})).unwrap()["id"].as_u64().unwrap()); + let target = FunctionGraphTarget::Parameter { node: owner, parameter: "function".into() }; + let mut graph = FunctionGraph::default(); + for position in [[0.0, 0.0], [256.0, 160.0]] { + graph.add_constant(Value::Float(0.5)); + graph.nodes.last_mut().unwrap().pos = position; + } + app.run("graph.function.set", json!({"target": target, "function": graph})).unwrap(); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 4); + let context = harness.ctx.clone(); + materialcraft_ui_egui::menus::invoke(harness.state_mut(), &context, "graph.node.edit"); + materialcraft_ui_egui::menus::invoke(harness.state_mut(), &context, "edit.selectAll"); + settle(&mut harness, 2); + assert!(harness.query_all(By::new().role(egui::accesskit::Role::Window)).next().is_none()); + assert_eq!(harness.query_all(By::new().role(egui::accesskit::Role::Canvas).label("Function Graph")).count(), 1); + let query = |label| By::new().role(egui::accesskit::Role::Button).label(label); + for label in ["Frame all (F)", "Align left", "Distribute horizontally", "Snap to grid", "Show node thumbnails"] { + assert_eq!(harness.query_all(query(label)).count(), 1, "shared control {label}"); + } + let original = harness.state().session.pkg.clone(); + harness.get(query("Align left")).click(); + settle(&mut harness, 2); + let function = target.current(&harness.state().session).unwrap(); + assert_eq!(function.nodes.iter().map(|node| node.pos).collect::>(), vec![[0.0, 0.0], [0.0, 160.0]]); + assert_eq!(harness.state().session.graph().unwrap().node(owner).unwrap().pos, [704.0, 800.0]); + materialcraft_ui_egui::menus::invoke(harness.state_mut(), &context, "edit.undo"); + settle(&mut harness, 2); + assert_eq!(harness.state().session.pkg, original); + let snap = harness.state().ui.prefs.snap_to_grid; + harness.get(query("Snap to grid")).click(); + settle(&mut harness, 2); + assert_eq!(harness.state().ui.prefs.snap_to_grid, !snap); + assert!(harness.query_all(By::new().label("Get Float")).next().is_some()); + assert!(materialcraft_ui_egui::properties::title(harness.state()).starts_with("Float")); + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + save(&mut harness, &directory, &format!("{definition}-inline-function")); + harness.state_mut().ui.library_search = "Sample".into(); + settle(&mut harness, 2); + for label in ["Sample grayscale", "Sample color"] { + assert_eq!(harness.query_all(By::new().label(label)).next().is_some(), definition == "pixel_processor"); + } + harness.get(By::new().role(egui::accesskit::Role::Canvas).label("Function Graph")).click_secondary(); + settle(&mut harness, 2); + harness.get_by_label("Add node").click(); + settle(&mut harness, 2); + for label in ["Sample grayscale", "Sample color"] { + assert_eq!(harness.query_all(query(label)).next().is_some(), definition == "pixel_processor"); + } + save(&mut harness, &directory, &format!("{definition}-node-menu")); + harness.key_press(egui::Key::Escape); + harness.key_press(egui::Key::Escape); + settle(&mut harness, 2); + harness.get(query("Return to parent graph")).click(); + settle(&mut harness, 3); + assert!(harness.state().function_editor.is_none()); + assert_eq!(harness.state().session.selection, vec![owner]); + assert_eq!(harness.state().session.pkg, original); + } +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn material_assignment_previews_outputs_and_survives_function_editing() { + use materialcraft_engine::core::NodeId; + + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.session.preview_size = Some(64); + app.ui.prefs.preview_size = 64; + let source = + app.run("graph.node.add", json!({"def": "uniform", "at": [0, 0], "params": {"color_mode": true, "color": [0.8, 0.04, 0.02, 1.0]}})).unwrap()["id"] + .as_u64() + .unwrap(); + let output = app + .run("graph.node.add", json!({"def": "output", "at": [224, 0], "connectFrom": {"node": source}, "params": {"identifier": "preview_image", "usage": 9}})) + .unwrap()["id"] + .as_u64() + .unwrap(); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 45); + assert!(harness.state().session.material_maps().is_empty()); + let before = harness.state().view3d.shown.clone().unwrap(); + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + save(&mut harness, &directory, "material-unassigned"); + + let selection = harness.state().session.selection.clone(); + harness.get(By::new().role(egui::accesskit::Role::TreeItem).label("Preview Image")).click_secondary(); + settle(&mut harness, 3); + harness.get_by_label("View in 3D view").click(); + settle(&mut harness, 3); + save(&mut harness, &directory, "material-channel-menu"); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Base color")).click(); + settle(&mut harness, 45); + assert_eq!(harness.state().session.selection, selection, "channel menu clicks must not reach the graph beneath them"); + assert_eq!(harness.state().session.material_maps()[0].0, "baseColor"); + let red_frame = harness.state().view3d.shown.clone().unwrap(); + assert_ne!(before.2, red_frame.2, "assignment must invalidate the rendered frame"); + let red_pixels = red_frame.2.chunks_exact(4).filter(|pixel| u16::from(pixel[0]) > u16::from(pixel[1]) + 30).count(); + assert!(red_pixels > 100, "the rendered mesh must show the assigned red image"); + save(&mut harness, &directory, "material-assigned-red"); + + harness.state_mut().run("graph.node.param", json!({"id": source, "param": "color", "value": [0.02, 0.04, 0.8, 1.0]})).unwrap(); + settle(&mut harness, 45); + let blue_frame = harness.state().view3d.shown.clone().unwrap(); + let blue_pixels = blue_frame.2.chunks_exact(4).filter(|pixel| u16::from(pixel[2]) > u16::from(pixel[0]) + 30).count(); + assert!(blue_pixels > 100, "edits must refresh the assigned material"); + assert_ne!(red_frame.2, blue_frame.2); + save(&mut harness, &directory, "material-assigned-blue"); + + harness.state_mut().run("file.new", json!({"kind": "function", "name": "Function preview"})).unwrap(); + settle(&mut harness, 45); + let maps = harness.state().session.material_maps(); + assert_eq!(maps[0].1.get(0, 0, false), [0.02, 0.04, 0.8, 1.0]); + assert_eq!(harness.state().session.material_preview.channels[&materialcraft_engine::core::MaterialChannel::BaseColor].node, NodeId(output)); + save(&mut harness, &directory, "material-retained-in-function"); +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn explorer_inputs_and_graph_drop_share_labels_and_material_assignment() { + use materialcraft_engine::core::{ComponentUsage, MaterialChannel, NodeId}; + + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.session.pkg.graphs[0].name = "Atomic_sample".into(); + app.ui.prefs.preview_size = 64; + let mut inputs = Vec::new(); + for (definition, identifier, label) in [ + ("input_color", "color_input", "Color Input"), + ("input_grayscale", "gray_input", "Gray Input"), + ("input_value", "brightness_value", "Brightness Value"), + ] { + let id = app.run("graph.node.add", json!({"def": definition, "at": [0, inputs.len() * 192], "params": {"identifier": identifier}})).unwrap()["id"] + .as_u64() + .unwrap(); + inputs.push((NodeId(id), label)); + } + let source = app.run("graph.node.add", json!({"def": "uniform", "at": [224, 0], "params": {"color_mode": true, "color": [0.8, 0.04, 0.02, 1.0]}})).unwrap() + ["id"] + .as_u64() + .unwrap(); + let output = app.run("graph.node.add", json!({"def": "output", "at": [448, 0], "connectFrom": {"node": source}, "params": {"identifier": "base_color", "usage": ComponentUsage::index("diffuse")}})).unwrap()["id"].as_u64().unwrap(); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 8); + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + let graph_row = harness.get(By::new().role(egui::accesskit::Role::TreeItem).label("Atomic_sample")).rect(); + for (id, label) in inputs { + let row = harness.get(By::new().role(egui::accesskit::Role::TreeItem).label(label)); + assert!(row.rect().left() > graph_row.left()); + row.click(); + settle(&mut harness, 3); + assert_eq!(harness.state().session.selection, vec![id]); + assert_eq!(harness.get(By::new().role(egui::accesskit::Role::TextInput).label("Node label")).value().as_deref(), Some(label)); + assert!(harness.query_all(By::new().label("Identifier")).next().is_some()); + let before = harness.state().session.graph().unwrap().node(id).unwrap().clone(); + let default = &materialcraft_engine::nodes::find(&before.def).unwrap().param("usage").unwrap().default; + assert_eq!(before.params.get("usage").unwrap_or(default), &materialcraft_engine::core::Value::Enum(ComponentUsage::ANY_INDEX)); + harness.get(By::new().role(egui::accesskit::Role::ComboBox).label("Component Usage")).click(); + settle(&mut harness, 2); + harness.get_by_label("Base color").scroll_to_me(); + settle(&mut harness, 2); + harness.get_by_label("Base color").click(); + settle(&mut harness, 2); + assert_eq!(harness.state().session.graph().unwrap().node(id).unwrap().params.get("usage"), Some(&materialcraft_engine::core::Value::Enum(0))); + save(&mut harness, &directory, &format!("component-usage-{}", before.def)); + harness.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(harness.state().session.graph().unwrap().node(id).unwrap(), &before); + } + harness.get(By::new().role(egui::accesskit::Role::TreeItem).label("Base Color")).click(); + settle(&mut harness, 3); + harness.get(By::new().role(egui::accesskit::Role::ComboBox).label("Component Usage")).click(); + settle(&mut harness, 3); + harness.get_by_label("Glossiness").scroll_to_me(); + settle(&mut harness, 3); + harness.get_by_label("Glossiness").click(); + settle(&mut harness, 3); + let node = harness.state().session.graph().unwrap().node(NodeId(output)).unwrap(); + assert_eq!(materialcraft_engine::eval::output_usage(node), "glossiness"); + harness.state_mut().run("graph.node.param", json!({"id": output, "param": "usage", "value": ComponentUsage::index("diffuse")})).unwrap(); + + settle(&mut harness, 3); + save(&mut harness, &directory, "explorer-inputs-and-usages"); + harness.state_mut().run("file.new", json!({"kind": "function", "name": "Function editing"})).unwrap(); + harness.state_mut().run("view.3d.clear", json!({})).unwrap(); + settle(&mut harness, 8); + let graph = harness.state().session.graph; + let camera = harness.state().session.view3d.clone(); + let package = harness.state().session.pkg.clone(); + let start = harness.get(By::new().role(egui::accesskit::Role::TreeItem).label("Atomic_sample")).rect().center(); + let end = harness.get(By::new().role(egui::accesskit::Role::Image).label("3D view")).rect().center(); + 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(); + } + save(&mut harness, &directory, "graph-drop-target"); + harness.event(egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + settle(&mut harness, 45); + assert_eq!(harness.state().session.graph, graph, "dropping a graph must not open it"); + assert_eq!(harness.state().session.view3d, camera, "dropping must not orbit the camera"); + assert_eq!(harness.state().session.pkg, package); + let binding = &harness.state().session.material_preview.channels[&MaterialChannel::BaseColor]; + assert_eq!((binding.graph, binding.node), (0, NodeId(output))); + let frame = &harness.state().view3d.shown.as_ref().unwrap().2; + assert!(frame.chunks_exact(4).filter(|pixel| u16::from(pixel[0]) > u16::from(pixel[1]) + 30).count() > 100); + save(&mut harness, &directory, "graph-dropped-on-material"); +} diff --git a/docs/architecture.md b/docs/architecture.md index b6b05ed..a27f13a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (portable materials and TextureCraft) · **Target:** the professional node-based material workflow +> **Last reviewed:** 2026-11-05 · **Last updated:** 2026-11-05 · **Change:** evaluator and editor organization · **Target:** the professional node-based material workflow MaterialCraft is a Cargo workspace of small crates in strict layers (`cargo xtask layers` enforces them). Everything below the UI is plain Rust with no UI toolkit and builds for @@ -32,7 +32,7 @@ apps materialcraft (desktop), materialcraft-cli, materialcraft-web ## Cooking -A node's cook is a pure function `fn(&Ctx) -> Result, String>`: `Ctx` carries the output +A node's cook is a pure function `fn(&CookContext) -> Result, String>`: `CookContext` carries the output size, the seed, tiling, the inputs (by port order, `None` when unconnected), the resolved parameters, a resource decoder and the graph's exposed values. `eval::cook` walks the graph in dependency order. For each node it hashes the definition id, resolved parameters, size, seed, tiling, the keys of its @@ -40,6 +40,15 @@ input images, resource bytes and (for instances) the sub-graph: equal keys hit t re-cooks only the nodes downstream of it, and undo finds earlier results again. A failing node shows a magenta image and its error; nodes after it still cook. +Each cook builds a borrowed `core::GraphIndex` for node and connection lookups. `PreparedGraph` +resolves the needed nodes' ports once; `graph_execution` schedules them and `node_execution` handles +a single node. Parameter resolution, graph instances, value execution, output collection and cache +keys have separate modules. The index lives only for the cook, so it needs no invalidation protocol. + +Function execution shares one interpreter. Pixel Processor borrows the caller's variables and keeps +only assignments in its per-pixel state; ordinary function evaluation retains the full environment +for callers such as FX-Map that read the resulting variables. + Sizes: generators take the graph ("parent") size; filters take their main input's size; both can be offset by powers of two or set absolutely. While editing, outputs are capped at the preview size (512 px by default), with pixel-based parameters scaled by `w / 256` so previews and full-size @@ -66,12 +75,76 @@ against the curve, so wires can be selected, deleted, swapped or split with a re gestures into commands only when they complete. See [wires-and-alpha.md](wires-and-alpha.md). The 3D view renders with `materialcraft-render` on the CPU: half resolution while the camera moves, 2×2 supersampled when it rests. +The 3D material has its own `MaterialPreview` assignment state. Automatic graph output usages and +explicit `MaterialSource` overrides resolve to channels from `core::MaterialChannel`, shared with the +renderer and menus. A source records its graph, node and named port; selection and 2D preview do not +change it. `PreviewCook` publishes the editor cook and any other assigned graphs together through +the existing worker/cache, so opening a Function Graph preserves the material. Render invalidation +includes both source assignments and cooked content. Snapshot undo and graph deletion retain or +adjust source ownership; package replacement clears old assignments. + +`core::ComponentUsage` defines output metadata once for node properties, SBS and exports. Its +indices stay stable as choices are added; renderable channels remain a separate capability. +Explorer and canvas node labels share display formatting without rewriting identifiers. Explorer +lists every graph input/output, and graph drops dispatch the existing material assignment command. + `crates/ui-egui/tests/snapshot.rs` renders the real UI offscreen with egui_kittest + wgpu for visual checks and README screenshots. +The regular and function canvases separate drawing, geometry, navigation and input handling. +Shared modules own node cards, selection and annotation gestures. The regular canvas borrows the +document while drawing, then dispatches edits. Graph Properties follows the same pattern; its +`property/` modules separate panel routing, node and graph settings, parameter controls, curves +and gradients. Function and pattern Properties dispatch value edits without cloning graphs in the UI. + The properties panel builds every parameter editor from the node catalog; the Levels node adds a histogram editor with range handles on top of its sliders ([levels-editor.md](levels-editor.md)). +### Shared graph editing + +The graph panel renders one toolbar before dispatching to the material, Function Graph or FX-Map +canvas. Framing, alignment, distribution and snapping occupy the same positions. Image inserts, +parent texture size, annotations and parent-graph navigation appear only where the graph supports +them. Alignment uses the same engine command for all three models, with explicit embedded node IDs +and an explicit Function target or FX-Map owner ID, so overlapping IDs cannot move the parent material nodes. +Pixel Processor, Value Processor and parameter functions use that same main panel and function node +catalog, with one target-aware availability rule shared by node creation, Library and Add node. +Value Processor omits the two sampler entries; saved functions retain their existing operations. +A breadcrumb and parent action return from nested functions, FX-Maps and local graph instances +while retaining the parent view and material preview. + +`ui-egui/graph/graph_camera.rs` owns framing, pointer-centered scroll/pinch zoom and navigation +shortcuts. `node_selection.rs` owns click and box selection; `port_hit.rs` owns nearest-port picking; +`wire_geometry.rs` owns curve construction. Node movement uses the engine's `graph_grid::translate` +for both previews and commits. + +`engine/graph_edit/` owns Function/FX-Map selection commands, clipboard remapping, deletion and +connected-node traversal. Its small model adapters supply node fields, link direction, ID allocation +and result/root handling. Material clipboard commands retain their named-port connections and +cross-graph clipboard rules. Rendering and connection validation remain specific to each model; +all document changes still pass through engine commands and snapshot undo. `selection_commands.rs` +routes the existing selection and clipboard command IDs to these adapters, including headless calls. +Read-only selection actions borrow the graph. Document, selection and clipboard updates are published +only after validation succeeds; clipboard provenance prevents external links crossing graph targets. +`graph_validation.rs` supplies the same checks to creation, legacy setters and targeted edits. + +`graph/editor_target.rs` resolves command ownership for the material canvas, standalone Function +Graphs, FX-Map canvases and embedded Function Graphs. Menus, keyboard shortcuts and +`ui.menu.invoke`, Library and Properties use that resolver; `ui.inspect` reports the same editor and +its canvas coordinates. Embedded editors record their owning graph and close when undo or another +command makes that owner unavailable. +Common context-menu entries live in `graph/edit_menu.rs`. Pointer gestures finish only when their +initiating button is released; Escape or focus loss cancels pending canvas movement. + +Function and FX-Map rendering borrow the document, prepare screen geometry, and dispatch edits +after painting. Function wires reuse one node-layout index instead of scanning the graph for each +endpoint. The engine's `graph.function.edit` and `graph.pattern.edit` commands own creation, +movement, connections, values and result/root changes. Function targets identify standalone, +parameter, dynamic-parameter or nested FX-Map functions explicitly. Value updates may request +`merge: true`; `edit.finish` closes that undo group. The UI closes groups at gesture boundaries, +while discrete edits always receive their own undo entry. + + ## Files SBS is the project format. The codec writes native filters, ports, parameters, function graphs, @@ -79,6 +152,10 @@ pattern graphs and resources directly, without a private payload. Unsupported im warnings; unknown nodes remain placeholders. Library reference loading is not part of the current primitive workflow. `.mcraft` is no longer supported. +The SBS `read` and `write` modules expose codec entry points. `SbsReader` and `SbsWriter` own +serialization state; focused helpers handle values, functions, patterns and canvas annotations. +Native value type codes come from `core::ValueType` rather than a second scalar type table. + See [atomic-workflow.md](atomic-workflow.md) for the tested scope and remaining limitations. ## Other apps diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1c09d6c..10d12ae 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -68,7 +68,7 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg | Command | Params | |---|---| | `file.new` | `{template?, name?, size?}`; templates from `graph.templates` (`empty`, `pbr`, `bricks`, `stone_tiles`, `wood`, `rusty_metal`, `fabric`, `ground`) | -| `graph.node.edit` | `{}` resolves the selected FX-Map to `{node, parameter}`; use `ui.menu.invoke` to enter its subgraph in the graph panel | +| `graph.node.edit` | `{}` resolves the selected FX-Map, processor or local graph instance to `{kind, node, parameter?, graph?}`; use `ui.menu.invoke` to enter it in the graph panel | | `graph.pattern.set` | `{id, pattern}` replaces an FX-Map subgraph with cycle validation and undo | | `graph.node.add` | `{def, at?, params?, connectFrom?: {node, port?}, label?}` | | `graph.connect` / `graph.disconnect` | `{from, fromPort?, to, toPort?}` / `{to, toPort}` | @@ -84,11 +84,70 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg | `view.3d.loadMesh` | `{path}` shows an OBJ, glTF or GLB mesh (scene `custom`) | | `library.list` | `{filter?, category?}`: every node with ports and parameters | +## 3D material assignment + +`view.3d.outputs {graph?, reset?}` applies a material graph's image outputs by their usage. +`graph` accepts an index or name and defaults to the open graph. Ordinary application preserves +unmatched channel assignments; `reset: true` clears them while preserving the scene, camera and lighting. +Outputs with unsupported usages or scalar/vector results cannot supply material textures. + +`view.3d.assign {graph?, node?, port?, channel, reset?}` assigns an individual image to `baseColor`, +`normal`, `roughness`, `metallic`, `height`, `ambientOcclusion`, `emissive` or `opacity`. +The node defaults to the selection only in the open graph. The port accepts an identifier or index; +terminal Output nodes use `output` or index 0. Assignments refer to their source graph and named port, +update when that source changes, and remain active while editing a Function Graph. +`view.3d.clear {}` removes assignments without resetting the scene. + +Opening a material graph automatically previews its output usages. Selecting or previewing a node +in 2D does not reassign the 3D material. Dragging a graph from Explorer onto the 3D view applies its outputs without opening the graph. +Canvas and Explorer context menus use the same assignment +commands; the 3D View's Material menu lists its channel sources. A Height-only output affects height +sampling, not Base Color; assign that image to `baseColor` to inspect its grayscale pattern on the mesh. + +`session.inspect.material3d` reports assignments and resolved channels, including source graph/node/port, +image dimensions and mean values. Assignment commands leave the package and document undo history +unchanged. Document undo restores the associated source references; replacing a package clears them. + ## Function graphs `file.new {"kind": "function", "name": "Calculation"}` creates a standalone Function Graph. Omit `kind`, or use `"material"`, for a Graph. `graph.function.set {"function": {...}}` replaces the active standalone function through one validated, undoable command. +Both `graph.function.set` and `graph.function.edit` accept an optional `target`: `{"kind":"graph"}` +(the default), `{"kind":"parameter","node":12,"parameter":"function"}`, +`{"kind":"dynamic","node":12,"parameter":"opacity"}`, or +`{"kind":"pattern","owner":12,"node":3,"parameter":"patternrotation"}`. + +`graph.function.edit` accepts `edit: {action: add|move|connect|value|output, ...}`. +For example, `{"edit":{"action":"add","operation":"mul","at":[256,0],"snap":true}}` +creates and returns a node ID using the same defaults as library and context-menu insertion. +`graph.pattern.edit` accepts the FX-Map owner `id` and +`edit: {action: add|move|connect|disconnect|root|value, ...}`. +Use `command.list` for command descriptions and the serialized `FunctionEdit`/`PatternEdit` types +in `crates/engine/src/` for the action fields. Value edits are individual undo steps by default; +`merge: true` groups repeated updates to the same target and value until `edit.finish` or another +edit ends the group. Idle UI frames preserve explicitly requested automation groups. + +`ui.menu.invoke` sends selection actions to the focused editor, including embedded Function +windows. `ui.inspect.subgraph.target` identifies that Function target; its canvas rectangles and +ports correspond to the same editor. Raw `command.run` calls retain their explicit command targets. + + +Selection and clipboard commands (`graph.select`, `edit.selectAll`, `edit.copy`, `edit.cut`, +`edit.paste`, `edit.duplicate`, `edit.delete`, their without-link/relink variants and upstream/downstream +selection) also work without a UI. They infer the active standalone Function Graph. To address an +embedded graph, pass `function: ` or `pattern: ` and explicit +`ids` for selection-dependent operations. `edit.selectAll` returns those IDs. An optional numeric +`graph` guards against the owning graph no longer being active. `graph.align` accepts the same +Function and FX-Map targets with explicit IDs. + +Results include `ids` and `selected`; copy/cut also return `copied` and a typed `clip` accepted by +paste. The session retains the most recent embedded clipboard. Cross-target paste keeps internal +links and drops external links. Standalone commands update the session selection; embedded commands +return their selection without changing the parent selection. Invalid operations preserve the +document, clipboard, selection and undo history. Creation and all function/pattern setters share +cycle, capacity, ID and position validation. + A function has `nodes` and an optional `output` node id. Each node has `id`, native `op`, `inputs` (source ids or null for unwired ports), optional `value`, `type_code` and `pos`. @@ -121,10 +180,13 @@ each has its own reader and writer (`crates/formats/src/material.rs` here), so k "source": "source.sbs" } ``` -- Usages: `baseColor`, `normal`, `roughness`, `metallic`, `height`, `ambientOcclusion`, `emissive`, - `opacity`, `specular` (the first output of each). Color usages (`baseColor`, `emissive`, - `specular`) are 8-bit sRGB PNGs, the rest 16-bit linear. Normals are tangent space, OpenGL (Y+); - height is 0..1 with 0.5 at the surface. +- Usages come from the shared `ComponentUsage` catalog (the first output of each, excluding + `any`). The catalog includes PBR, diffuse/specular, coat, sheen, scattering and user channels. + Color maps are 8-bit sRGB PNGs; data maps are 16-bit linear. Each map records its color space. + Additional usage identifiers do not change the manifest version; consumers may ignore usages + they do not support. Normals are tangent space, OpenGL (Y+); height is 0..1 with 0.5 at the surface. + The 3D preview supports base color (including `diffuse`), normal, roughness, metallic, height, + ambient occlusion, emissive and opacity; other usages remain available for SBS and exports. - Parameters are the exposed inputs other apps can set (float, float2-4, int, int2, bool, color, enum), values in the typed form `{"t", "v"}`; colors are linear RGBA. - Inputs are the graph's input nodes. Mesh maps feed them by identifier: `ambientOcclusion`,