From bc2f20b36509da8f316409d7d195137fac5f7bea Mon Sep 17 00:00:00 2001 From: chasse20 Date: Mon, 9 Nov 2026 23:59:27 -0500 Subject: [PATCH] Fix library review, graph annotations and processor sampling --- assets/sbs/functions.sbs | 2 +- crates/core/src/canvas_annotations.rs | 32 ++++ crates/core/src/function_graph.rs | 2 + crates/core/src/lib.rs | 2 + crates/core/src/pattern_graph.rs | 3 + crates/engine/src/annotation_commands.rs | 10 +- crates/engine/src/annotation_selection.rs | 6 +- crates/engine/src/annotation_target.rs | 150 +++++++++++++++ crates/engine/src/commands.rs | 5 +- crates/engine/src/comment_commands.rs | 22 ++- crates/engine/src/edit_cmds.rs | 15 +- crates/engine/src/frame_commands.rs | 37 ++-- crates/engine/src/function_graph_target.rs | 7 +- crates/engine/src/graph_cmds.rs | 25 +-- crates/engine/src/inspect.rs | 1 + crates/engine/src/lib.rs | 6 + crates/engine/src/linked_packages.rs | 14 ++ crates/engine/src/node_library.rs | 161 +++++++--------- crates/engine/src/node_library.test.rs | 38 +++- .../engine/src/node_library/library_canvas.rs | 11 ++ .../engine/src/node_library/library_entry.rs | 22 +++ .../engine/src/node_library/library_item.rs | 51 ++++++ .../src/node_library/library_placement.rs | 8 + crates/engine/src/node_library_commands.rs | 75 +++++++- .../engine/src/node_library_commands.test.rs | 46 +++++ crates/engine/src/open_document.rs | 5 + crates/engine/src/pin_commands.rs | 65 +++++++ crates/engine/src/session.rs | 22 ++- crates/engine/src/snapshot.rs | 1 + crates/engine/tests/it/annotations.rs | 107 +++++++++++ crates/engine/tests/it/embedded_edit.rs | 59 ++++-- crates/engine/tests/it/node_library.rs | 48 ++++- crates/engine/tests/support/node_library.rs | 27 +++ crates/eval/src/tests.rs | 6 +- .../standard_function_library/convert.rs | 2 - .../standard_function_library/tests.rs | 26 ++- crates/formats/src/sbs/canvas.rs | 17 +- crates/formats/src/sbs/function_graph.rs | 12 +- crates/formats/src/sbs/layout_frame.rs | 10 + crates/formats/src/sbs/layout_item.rs | 17 ++ crates/formats/src/sbs/library.rs | 8 + crates/formats/src/sbs/library_layout.rs | 55 +++--- crates/formats/src/sbs/mod.rs | 6 +- crates/formats/src/sbs/pattern_graph.rs | 12 +- crates/formats/src/sbs/sbs_reader.rs | 5 +- crates/formats/tests/function_library.rs | 12 +- .../src/annotation/comment_properties.rs | 8 +- .../src/annotation/frame_properties.rs | 2 +- crates/ui-egui/src/annotation/mod.rs | 38 ++++ .../ui-egui/src/annotation/pin_properties.rs | 28 +++ crates/ui-egui/src/control.rs | 2 + crates/ui-egui/src/explorer.rs | 8 +- crates/ui-egui/src/explorer/actions.rs | 7 + crates/ui-egui/src/explorer/context_menu.rs | 36 +--- .../src/explorer/explorer_menu_state.rs | 28 +++ crates/ui-egui/src/explorer/explorer_row.rs | 9 + crates/ui-egui/src/explorer/explorer_tree.rs | 3 +- crates/ui-egui/src/function/actions.rs | 8 +- crates/ui-egui/src/function/canvas.rs | 34 ++-- crates/ui-egui/src/function/context_menu.rs | 10 +- .../ui-egui/src/function/function_canvas.rs | 1 + .../ui-egui/src/function/function_editor.rs | 4 + crates/ui-egui/src/function/geometry.rs | 6 +- crates/ui-egui/src/function/input.rs | 22 ++- crates/ui-egui/src/function/library.rs | 3 +- crates/ui-egui/src/function/render.rs | 24 +-- crates/ui-egui/src/graph/actions.rs | 16 +- crates/ui-egui/src/graph/annotation_canvas.rs | 22 ++- crates/ui-egui/src/graph/annotation_input.rs | 43 ++++- crates/ui-egui/src/graph/canvas.rs | 6 +- crates/ui-egui/src/graph/editor_target.rs | 9 +- crates/ui-egui/src/graph/graph_drag.rs | 4 + crates/ui-egui/src/graph/graph_view.rs | 12 +- crates/ui-egui/src/graph/input.rs | 21 ++- crates/ui-egui/src/graph/interaction_tests.rs | 55 ++++++ crates/ui-egui/src/graph/toolbar.rs | 10 +- crates/ui-egui/src/library.rs | 172 ++++++++---------- crates/ui-egui/src/library.test.rs | 111 ++++++++--- crates/ui-egui/src/library/library_target.rs | 48 +++++ crates/ui-egui/src/material_craft_app.rs | 25 +++ crates/ui-egui/src/material_craft_app.test.rs | 14 ++ crates/ui-egui/src/menus.rs | 116 ++++++++---- crates/ui-egui/src/pattern/actions.rs | 16 +- crates/ui-egui/src/pattern/canvas.rs | 42 ++++- crates/ui-egui/src/pattern/context_menu.rs | 7 + crates/ui-egui/src/pattern/input.rs | 27 ++- crates/ui-egui/src/pattern/mod.rs | 1 + crates/ui-egui/src/pattern/pattern_canvas.rs | 12 ++ crates/ui-egui/src/pattern/pattern_editor.rs | 9 + crates/ui-egui/src/property/mod.rs | 5 +- crates/ui-egui/tests/snapshot.rs | 24 ++- .../tests/snapshot/function_library.rs | 41 +++++ crates/ui-egui/tests/snapshot/graph_items.rs | 68 +++++++ crates/ui-egui/tests/snapshot/library.rs | 4 + crates/ui-egui/tests/snapshot/menu.rs | 55 ++++++ docs/architecture.md | 2 +- docs/atomic-workflow.md | 7 +- docs/control-protocol.md | 30 ++- docs/file-format-parity.md | 9 +- 99 files changed, 2051 insertions(+), 546 deletions(-) create mode 100644 crates/core/src/canvas_annotations.rs create mode 100644 crates/engine/src/annotation_target.rs create mode 100644 crates/engine/src/node_library/library_canvas.rs create mode 100644 crates/engine/src/node_library/library_entry.rs create mode 100644 crates/engine/src/node_library/library_item.rs create mode 100644 crates/engine/src/node_library/library_placement.rs create mode 100644 crates/engine/src/node_library_commands.test.rs create mode 100644 crates/engine/src/pin_commands.rs create mode 100644 crates/engine/tests/support/node_library.rs create mode 100644 crates/formats/src/sbs/layout_frame.rs create mode 100644 crates/formats/src/sbs/layout_item.rs create mode 100644 crates/ui-egui/src/annotation/pin_properties.rs create mode 100644 crates/ui-egui/src/explorer/explorer_menu_state.rs create mode 100644 crates/ui-egui/src/explorer/explorer_row.rs create mode 100644 crates/ui-egui/src/library/library_target.rs create mode 100644 crates/ui-egui/src/pattern/pattern_canvas.rs create mode 100644 crates/ui-egui/tests/snapshot/graph_items.rs create mode 100644 crates/ui-egui/tests/snapshot/menu.rs diff --git a/assets/sbs/functions.sbs b/assets/sbs/functions.sbs index 0294f74a..c9713d33 100644 --- a/assets/sbs/functions.sbs +++ b/assets/sbs/functions.sbs @@ -1 +1 @@ - + diff --git a/crates/core/src/canvas_annotations.rs b/crates/core/src/canvas_annotations.rs new file mode 100644 index 00000000..93b3af6b --- /dev/null +++ b/crates/core/src/canvas_annotations.rs @@ -0,0 +1,32 @@ +use crate::{Comment, Frame, Pin}; +use serde::{Deserialize, Serialize}; + +/// Editable helpers belonging to one embedded graph canvas. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct CanvasAnnotations { + #[serde(default)] + pub frames: Vec, + #[serde(default)] + pub comments: Vec, + #[serde(default)] + pub pins: Vec, +} + +impl CanvasAnnotations { + /// Whether the canvas has no frames, comments or pins. + pub fn is_empty(&self) -> bool { + self.frames.is_empty() && self.comments.is_empty() && self.pins.is_empty() + } + + /// The next annotation id, or none when all ids have been exhausted. + pub fn next_id(&self) -> Option { + self.frames + .iter() + .map(|frame| frame.id) + .chain(self.comments.iter().map(|comment| comment.id)) + .chain(self.pins.iter().map(|pin| pin.id)) + .max() + .unwrap_or(0) + .checked_add(1) + } +} diff --git a/crates/core/src/function_graph.rs b/crates/core/src/function_graph.rs index c3f43bc2..84addc0f 100644 --- a/crates/core/src/function_graph.rs +++ b/crates/core/src/function_graph.rs @@ -6,6 +6,8 @@ use crate::FunctionNode; #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct FunctionGraph { + #[serde(default, skip_serializing_if = "crate::CanvasAnnotations::is_empty")] + pub annotations: crate::CanvasAnnotations, pub nodes: Vec, #[serde(default)] pub output: Option, diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 18105082..b02cfa30 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -3,6 +3,7 @@ mod attributes; mod base_parameters; +mod canvas_annotations; mod color; mod comment; mod component_usage; @@ -33,6 +34,7 @@ mod pattern_graph; mod pattern_node; mod pattern_node_kind; mod pin; +pub use canvas_annotations::CanvasAnnotations; mod preset; mod resource; mod resource_bytes; diff --git a/crates/core/src/pattern_graph.rs b/crates/core/src/pattern_graph.rs index d0275a82..d1c47bce 100644 --- a/crates/core/src/pattern_graph.rs +++ b/crates/core/src/pattern_graph.rs @@ -5,6 +5,8 @@ use crate::{PatternNode, PatternNodeKind}; #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct PatternGraph { + #[serde(default, skip_serializing_if = "crate::CanvasAnnotations::is_empty")] + pub annotations: crate::CanvasAnnotations, pub nodes: Vec, pub root: Option, } @@ -12,6 +14,7 @@ pub struct PatternGraph { impl PatternGraph { pub fn with_root(kind: PatternNodeKind) -> Self { Self { + annotations: Default::default(), root: Some(1), nodes: vec![PatternNode { id: 1, kind, children: vec![None; kind.child_count()], parameters: BTreeMap::new(), position: [0.0; 2] }], } diff --git a/crates/engine/src/annotation_commands.rs b/crates/engine/src/annotation_commands.rs index 5825ecab..e72f6df9 100644 --- a/crates/engine/src/annotation_commands.rs +++ b/crates/engine/src/annotation_commands.rs @@ -8,13 +8,15 @@ pub(crate) fn specs() -> Vec { "Select annotation", [], None, - "{kind?: frame|comment, id?} clears node selection; omit kind to deselect", + "{kind?: frame|comment|pin, id?} clears node selection; omit kind to deselect", has_graph, select )] } fn select(session: &mut Session, parameters: &Value) -> Result { + let target = crate::AnnotationTarget::resolve(session, parameters)?; + let items = target.items(session)?; let selection = match strp(parameters, "kind") { None => None, Some(kind) => { @@ -22,9 +24,10 @@ fn select(session: &mut Session, parameters: &Value) -> Result { let selection = match kind { "frame" => AnnotationSelection::Frame(id), "comment" => AnnotationSelection::Comment(id), - _ => return Err(bad("graph.annotation.select", "kind must be frame or comment")), + "pin" => AnnotationSelection::Pin(id), + _ => return Err(bad("graph.annotation.select", "kind must be frame, comment or pin")), }; - if !selection.exists(session.graph()?) { + if !selection.exists(&items) { return Err(bad("graph.annotation.select", "annotation does not exist")); } @@ -32,6 +35,7 @@ fn select(session: &mut Session, parameters: &Value) -> Result { } }; + session.annotation_target = target; session.annotation_selection = selection; if selection.is_some() { session.selection.clear(); diff --git a/crates/engine/src/annotation_selection.rs b/crates/engine/src/annotation_selection.rs index 8385ca6a..cd3b686d 100644 --- a/crates/engine/src/annotation_selection.rs +++ b/crates/engine/src/annotation_selection.rs @@ -1,4 +1,4 @@ -use materialcraft_core::Graph; +use materialcraft_core::CanvasAnnotations; use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -6,13 +6,15 @@ use serde::{Deserialize, Serialize}; pub enum AnnotationSelection { Frame(u64), Comment(u64), + Pin(u64), } impl AnnotationSelection { - pub fn exists(self, graph: &Graph) -> bool { + pub fn exists(self, graph: &CanvasAnnotations) -> bool { match self { Self::Frame(id) => graph.frames.iter().any(|frame| frame.id == id), Self::Comment(id) => graph.comments.iter().any(|comment| comment.id == id), + Self::Pin(id) => graph.pins.iter().any(|pin| pin.id == id), } } } diff --git a/crates/engine/src/annotation_target.rs b/crates/engine/src/annotation_target.rs new file mode 100644 index 00000000..255ff675 --- /dev/null +++ b/crates/engine/src/annotation_target.rs @@ -0,0 +1,150 @@ +use crate::{FrameContents, FunctionGraphTarget, Result, SelectionTarget, Session, commands::bad}; +use materialcraft_core::{CanvasAnnotations, Frame, NodeId, Value}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value as Json, json}; + +/// Canvas that owns the selected frame, comment or navigation pin. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum AnnotationTarget { + #[default] + Graph, + Function { + target: FunctionGraphTarget, + }, + Pattern { + owner: NodeId, + }, +} + +impl AnnotationTarget { + pub(crate) fn resolve(session: &Session, parameters: &Json) -> Result { + Ok(match SelectionTarget::resolve(session, parameters)? { + None | Some(SelectionTarget::Function(FunctionGraphTarget::Graph)) => Self::Graph, + Some(SelectionTarget::Function(target)) => Self::Function { target }, + Some(SelectionTarget::Pattern(owner)) => Self::Pattern { owner }, + }) + } + + /// Command parameters that address this canvas. + pub fn parameters(&self) -> Json { + match self { + Self::Graph => json!({}), + Self::Function { target } => json!({"function": target}), + Self::Pattern { owner } => json!({"pattern": owner.0}), + } + } + + /// Copy the annotations owned by this canvas. + pub fn items(&self, session: &Session) -> Result { + Ok(match self { + Self::Graph => { + let graph = session.graph()?; + CanvasAnnotations { frames: graph.frames.clone(), comments: graph.comments.clone(), pins: graph.pins.clone() } + } + Self::Function { target } => target.current(session)?.annotations.clone(), + Self::Pattern { owner } => SelectionTarget::pattern(session, *owner)?.annotations.clone(), + }) + } + + pub(crate) fn replace(&self, session: &mut Session, items: CanvasAnnotations) -> Result<()> { + match self { + Self::Graph => { + let graph = session.graph_mut()?; + graph.next_id = graph.next_id.max(items.next_id().unwrap_or(u64::MAX)); + graph.frames = items.frames; + graph.comments = items.comments; + graph.pins = items.pins; + } + Self::Function { target } => { + let mut function = target.current(session)?.clone(); + function.annotations = items; + target.replace(session, function)?; + } + Self::Pattern { owner } => { + let mut graph = SelectionTarget::pattern(session, *owner)?.clone(); + graph.annotations = items; + session.graph_mut()?.node_mut(*owner)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph))); + } + } + Ok(()) + } + + pub(crate) fn next_id(&self, session: &Session, items: &CanvasAnnotations) -> Result { + let next = items.next_id().ok_or_else(|| bad("graph annotation", "no available annotation id"))?; + Ok(if *self == Self::Graph { next.max(session.graph()?.next_id) } else { next }) + } + + /// Node positions in this canvas, using the shared node-id representation. + pub fn positions(&self, session: &Session) -> Result> { + Ok(match self { + Self::Graph => { + let graph = session.graph()?; + match &graph.function { + Some(function) => function.nodes.iter().map(|node| (NodeId(u64::from(node.id)), node.pos)).collect(), + None => graph.nodes.iter().map(|node| (node.id, node.pos)).collect(), + } + } + Self::Function { target } => target.current(session)?.nodes.iter().map(|node| (NodeId(u64::from(node.id)), node.pos)).collect(), + Self::Pattern { owner } => { + SelectionTarget::pattern(session, *owner)?.nodes.iter().map(|node| (NodeId(u64::from(node.id)), node.position)).collect() + } + }) + } + + /// Capture the nodes and annotations moved with a frame. + pub fn capture_frame(&self, session: &Session, frame: &Frame) -> Result { + if *self == Self::Graph { + return Ok(FrameContents::capture(session.graph()?, frame)); + } + + let items = self.items(session)?; + let nodes: Vec<_> = self.positions(session)?.into_iter().filter(|(_, position)| frame.contains_position(*position)).map(|(id, _)| id).collect(); + Ok(FrameContents { + function_nodes: nodes.iter().filter_map(|id| u32::try_from(id.0).ok()).collect(), + nodes, + comments: items.comments.iter().filter(|comment| frame.contains_position(comment.pos)).map(|comment| comment.id).collect(), + frames: items.frames.iter().filter(|candidate| candidate.id == frame.id || frame.contains_rect(candidate.rect)).map(|frame| frame.id).collect(), + pins: items.pins.iter().filter(|pin| frame.contains_position(pin.pos)).map(|pin| pin.id).collect(), + }) + } + + pub(crate) fn move_contents(&self, session: &mut Session, contents: &FrameContents, offset: [f32; 2]) -> Result<()> { + if *self == Self::Graph { + contents.translate(session.graph_mut()?, offset); + return Ok(()); + } + + let translate = |position: [f32; 2]| crate::graph_grid::snap_position([position[0] + offset[0], position[1] + offset[1]], false); + match self { + Self::Function { target } => { + let mut graph = target.current(session)?.clone(); + for node in graph.nodes.iter_mut().filter(|node| contents.function_nodes.contains(&node.id)) { + node.pos = translate(node.pos); + } + target.replace(session, graph)?; + } + Self::Pattern { owner } => { + let mut graph = SelectionTarget::pattern(session, *owner)?.clone(); + for node in graph.nodes.iter_mut().filter(|node| contents.nodes.contains(&NodeId(u64::from(node.id)))) { + node.position = translate(node.position); + } + session.graph_mut()?.node_mut(*owner)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph))); + } + Self::Graph => {} + } + let mut items = self.items(session)?; + for comment in items.comments.iter_mut().filter(|comment| contents.comments.contains(&comment.id)) { + comment.pos = translate(comment.pos); + } + for frame in items.frames.iter_mut().filter(|frame| contents.frames.contains(&frame.id)) { + let position = translate([frame.rect[0], frame.rect[1]]); + frame.rect[0] = position[0]; + frame.rect[1] = position[1]; + } + for pin in items.pins.iter_mut().filter(|pin| contents.pins.contains(&pin.id)) { + pin.pos = translate(pin.pos); + } + self.replace(session, items) + } +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 84321f38..51ccc347 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -77,6 +77,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::function_variable_commands::specs()); v.extend(crate::evaluation_environment_commands::specs()); v.extend(crate::comment_commands::specs()); + v.extend(crate::pin_commands::specs()); v.extend(crate::node_cmds::specs()); v.extend(crate::node_graph_commands::specs()); v.extend(crate::pattern_graph_commands::specs()); @@ -101,7 +102,7 @@ pub fn execute(s: &mut Session, id: &str, params: &J) -> 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))) { + if !s.selection.is_empty() || s.annotation_selection.is_some_and(|selection| !s.annotation_target.items(s).is_ok_and(|items| selection.exists(&items))) { s.annotation_selection = None; } @@ -117,6 +118,8 @@ pub fn list(s: &Session, filter: Option<&str>) -> J { .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": 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 if c.id.starts_with("graph.annotation.") || c.id.starts_with("graph.frame.") || c.id.starts_with("graph.comment.") { + format!("{}; optional function: FunctionGraphTarget or pattern: owner node id", 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/comment_commands.rs b/crates/engine/src/comment_commands.rs index 103091e6..ca0113e9 100644 --- a/crates/engine/src/comment_commands.rs +++ b/crates/engine/src/comment_commands.rs @@ -13,13 +13,16 @@ pub(crate) fn specs() -> Vec { } fn comment_add(session: &mut Session, parameters: &J) -> Result { + let target = crate::AnnotationTarget::resolve(session, parameters)?; let at = point(parameters, "at").or_else(|| nodes_rect(session, &session.selection).map(|rect| [rect[0], rect[1] - 90.0])).unwrap_or([0.0, -120.0]); let text = strp(parameters, "text").unwrap_or("Comment").to_string(); session.edit("Add comment", |session| { - let graph = session.graph_mut()?; - let id = graph.alloc_id(); - graph.comments.push(Comment { id, text, pos: at, size: [180.0, 70.0] }); + let mut items = target.items(session)?; + let id = target.next_id(session, &items)?; + items.comments.push(Comment { id, text, pos: at, size: [180.0, 70.0] }); + target.replace(session, items)?; + session.annotation_target = target; session.selection.clear(); session.annotation_selection = Some(AnnotationSelection::Comment(id)); Ok(json!({"id": id})) @@ -27,11 +30,12 @@ fn comment_add(session: &mut Session, parameters: &J) -> Result { } fn comment_edit(session: &mut Session, parameters: &J) -> Result { + let target = crate::AnnotationTarget::resolve(session, parameters)?; let id = u64p(parameters, "id").ok_or_else(|| bad("graph.comment.edit", "`id` is required"))?; - session.edit_merged(&format!("comment{id}"), "Edit comment", |session| { - let comment = - session.graph_mut()?.comments.iter_mut().find(|comment| comment.id == id).ok_or_else(|| bad("graph.comment.edit", format!("no comment {id}")))?; + session.edit_merged(&format!("comment:{target:?}:{id}"), "Edit comment", |session| { + let mut items = target.items(session)?; + let comment = items.comments.iter_mut().find(|comment| comment.id == id).ok_or_else(|| bad("graph.comment.edit", format!("no comment {id}")))?; if let Some(text) = strp(parameters, "text") { comment.text = text.into(); } @@ -42,16 +46,20 @@ fn comment_edit(session: &mut Session, parameters: &J) -> Result { comment.size = [size[0].max(40.0), size[1].max(24.0)]; } + target.replace(session, items)?; Ok(J::Null) }) } fn comment_delete(session: &mut Session, parameters: &J) -> Result { + let target = crate::AnnotationTarget::resolve(session, parameters)?; let id = u64p(parameters, "id").ok_or_else(|| bad("graph.comment.delete", "`id` is required"))?; session.edit("Delete comment", |session| { - session.graph_mut()?.comments.retain(|comment| comment.id != id); + let mut items = target.items(session)?; + items.comments.retain(|comment| comment.id != id); + target.replace(session, items)?; Ok(J::Null) }) } diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs index 60321bef..7dc7e109 100644 --- a/crates/engine/src/edit_cmds.rs +++ b/crates/engine/src/edit_cmds.rs @@ -172,13 +172,16 @@ fn has_deletable_selection(session: &Session) -> std::result::Result<(), String> fn delete_annotation(session: &mut Session) -> Result { let selection = session.annotation_selection; + let target = session.annotation_target.clone(); + let mut items = target.items(session)?; + match selection { + Some(crate::AnnotationSelection::Frame(id)) => items.frames.retain(|frame| frame.id != id), + Some(crate::AnnotationSelection::Comment(id)) => items.comments.retain(|comment| comment.id != id), + Some(crate::AnnotationSelection::Pin(id)) => items.pins.retain(|pin| pin.id != id), + None => {} + } session.edit("Delete annotation", |session| { - let graph = session.graph_mut()?; - match selection { - Some(crate::AnnotationSelection::Frame(id)) => graph.frames.retain(|frame| frame.id != id), - Some(crate::AnnotationSelection::Comment(id)) => graph.comments.retain(|comment| comment.id != id), - None => {} - } + target.replace(session, items)?; session.annotation_selection = None; Ok(json!({"deleted": 1})) }) diff --git a/crates/engine/src/frame_commands.rs b/crates/engine/src/frame_commands.rs index a4672d49..47cf6042 100644 --- a/crates/engine/src/frame_commands.rs +++ b/crates/engine/src/frame_commands.rs @@ -1,6 +1,6 @@ use crate::commands::{CommandSpec, bad, boolp, has_graph, point, strp, u64p}; use crate::graph_cmds::nodes_rect; -use crate::{AnnotationSelection, FrameContents, Result, Session, cmd}; +use crate::{AnnotationSelection, Result, Session, cmd}; use materialcraft_core::Frame; use serde_json::{Value as J, json}; @@ -32,6 +32,7 @@ fn color_of(parameters: &J) -> Option<[f32; 4]> { } fn frame_add(session: &mut Session, parameters: &J) -> Result { + let target = crate::AnnotationTarget::resolve(session, parameters)?; let rect = match rect_of(parameters) { Some(rect) => rect, None => nodes_rect(session, &session.selection) @@ -45,9 +46,11 @@ fn frame_add(session: &mut Session, parameters: &J) -> Result { let description = strp(parameters, "description").unwrap_or("").to_string(); session.edit("Add frame", |session| { - let graph = session.graph_mut()?; - let id = graph.alloc_id(); - graph.frames.push(Frame { id, title, title_visible, description, rect, color }); + let mut items = target.items(session)?; + let id = target.next_id(session, &items)?; + items.frames.push(Frame { id, title, title_visible, description, rect, color }); + target.replace(session, items)?; + session.annotation_target = target; session.selection.clear(); session.annotation_selection = Some(AnnotationSelection::Frame(id)); Ok(json!({"id": id})) @@ -55,10 +58,12 @@ fn frame_add(session: &mut Session, parameters: &J) -> Result { } fn frame_edit(session: &mut Session, parameters: &J) -> Result { + let target = crate::AnnotationTarget::resolve(session, parameters)?; let id = u64p(parameters, "id").ok_or_else(|| bad("graph.frame.edit", "`id` is required"))?; - session.edit_merged(&format!("frame{id}"), "Edit frame", |session| { - let frame = session.graph_mut()?.frames.iter_mut().find(|frame| frame.id == id).ok_or_else(|| bad("graph.frame.edit", format!("no frame {id}")))?; + session.edit_merged(&format!("frame:{target:?}:{id}"), "Edit frame", |session| { + let mut items = target.items(session)?; + let frame = items.frames.iter_mut().find(|frame| frame.id == id).ok_or_else(|| bad("graph.frame.edit", format!("no frame {id}")))?; if let Some(text) = strp(parameters, "title") { frame.title = text.into(); } @@ -75,35 +80,39 @@ fn frame_edit(session: &mut Session, parameters: &J) -> Result { frame.color = color; } + target.replace(session, items)?; Ok(J::Null) }) } fn frame_delete(session: &mut Session, parameters: &J) -> Result { + let target = crate::AnnotationTarget::resolve(session, parameters)?; let id = u64p(parameters, "id").ok_or_else(|| bad("graph.frame.delete", "`id` is required"))?; session.edit("Delete frame", |session| { - let graph = session.graph_mut()?; - let previous_count = graph.frames.len(); - graph.frames.retain(|frame| frame.id != id); - if previous_count == graph.frames.len() { + let mut items = target.items(session)?; + let previous_count = items.frames.len(); + items.frames.retain(|frame| frame.id != id); + if previous_count == items.frames.len() { return Err(bad("graph.frame.delete", format!("no frame {id}"))); } + target.replace(session, items)?; Ok(J::Null) }) } fn frame_move(session: &mut Session, parameters: &J) -> Result { + let target = crate::AnnotationTarget::resolve(session, parameters)?; let id = u64p(parameters, "id").ok_or_else(|| bad("graph.frame.move", "`id` is required"))?; let offset = point(parameters, "by").ok_or_else(|| bad("graph.frame.move", "`by` is required"))?; let offset = crate::graph_grid::snap_position(offset, boolp(parameters, "snapToGrid").unwrap_or(false)); - let graph = session.graph()?; - let frame = graph.frames.iter().find(|frame| frame.id == id).ok_or_else(|| bad("graph.frame.move", "frame does not exist"))?; - let contents = FrameContents::capture(graph, frame); + let items = target.items(session)?; + let frame = items.frames.iter().find(|frame| frame.id == id).ok_or_else(|| bad("graph.frame.move", "frame does not exist"))?; + let contents = target.capture_frame(session, frame)?; session.edit("Move frame and contents", |session| { - contents.translate(session.graph_mut()?, offset); + target.move_contents(session, &contents, offset)?; Ok(J::Null) }) diff --git a/crates/engine/src/function_graph_target.rs b/crates/engine/src/function_graph_target.rs index 5e7f8c1f..644b3ac9 100644 --- a/crates/engine/src/function_graph_target.rs +++ b/crates/engine/src/function_graph_target.rs @@ -27,10 +27,9 @@ impl FunctionGraphTarget { crate::function_variables::suggestions(self, session, id) } - pub fn available_operations(&self, session: &Session) -> impl Iterator + use<> { - let value_processor = matches!(self, Self::Parameter { node, parameter } - if parameter == "function" && session.graph().ok().and_then(|graph| graph.node(*node).ok()).is_some_and(|node| node.def == "value_processor")); - materialcraft_nodes::function::FUNCTIONS.iter().filter(move |operation| !value_processor || !matches!(operation.id, "samplelum" | "samplecol")) + /// All function targets accept the native catalog, including samplers for processor image inputs. + pub fn available_operations(&self, _session: &Session) -> impl Iterator + use<> { + materialcraft_nodes::function::FUNCTIONS.iter() } pub fn current<'a>(&self, session: &'a Session) -> Result<&'a FunctionGraph> { diff --git a/crates/engine/src/graph_cmds.rs b/crates/engine/src/graph_cmds.rs index 3c4356e5..ecf8077f 100644 --- a/crates/engine/src/graph_cmds.rs +++ b/crates/engine/src/graph_cmds.rs @@ -2,9 +2,9 @@ use serde_json::{Value as J, json}; -use materialcraft_core::{ExposedParameter, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Pin, Value}; +use materialcraft_core::{ExposedParameter, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Value}; -use crate::commands::{CommandSpec, always, bad, boolp, f32p, has_graph, has_selection, i64p, ids_param, point, strp, u64p}; +use crate::commands::{CommandSpec, always, bad, boolp, f32p, has_graph, has_selection, i64p, ids_param, strp, u64p}; use crate::{Result, Session, cmd}; pub(crate) fn specs() -> Vec { @@ -31,8 +31,6 @@ pub(crate) fn specs() -> Vec { has_graph, cook ), - cmd!("graph.pin.add", "Add Navigation pin", [], None, "{name?, at? [x, y]}", has_graph, pin_add), - cmd!("graph.pin.delete", "Delete pin", [], None, "{id}", has_graph, pin_delete), cmd!( "graph.exposed.add", "Expose parameter", @@ -194,25 +192,6 @@ pub fn nodes_rect(s: &Session, ids: &[NodeId]) -> Option<[f32; 4]> { (r[0] < f32::MAX).then(|| [r[0], r[1], r[2] - r[0], r[3] - r[1]]) } -fn pin_add(s: &mut Session, p: &J) -> Result { - let at = point(p, "at").unwrap_or([0.0, 0.0]); - s.edit("Add pin", |s| { - let g = s.graph_mut()?; - let id = g.alloc_id(); - let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| format!("Pin {}", g.pins.len() + 1)); - g.pins.push(Pin { id, name, pos: at }); - Ok(json!({"id": id})) - }) -} - -fn pin_delete(s: &mut Session, p: &J) -> Result { - let id = u64p(p, "id").ok_or_else(|| bad("graph.pin.delete", "`id` is required"))?; - s.edit("Delete pin", |s| { - s.graph_mut()?.pins.retain(|c| c.id != id); - Ok(J::Null) - }) -} - fn exposed_add(s: &mut Session, p: &J) -> Result { // From a bound node parameter: its value, range and options become the input's let bind = p.get("bind").and_then(|b| Some((NodeId(b.get("node")?.as_u64()?), b.get("param")?.as_str()?.to_string()))); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 27c64b6c..71942ebb 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -70,6 +70,7 @@ pub fn session(s: &Session, graph: Option) -> J { "openGraph": g.map(|_| s.graph), "graph": graph_json, "annotationSelection": s.annotation_selection, + "annotationTarget": s.annotation_target, "selection": s.selection.iter().map(|i| i.0).collect::>(), "view2d": s.view2d, "view3d": s.view3d, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 0862a4c0..31c0ae18 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1,6 +1,9 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(test)] +extern crate self as materialcraft_engine; + mod document_path; mod evaluation_environment_commands; mod explorer_clipboard; @@ -102,12 +105,15 @@ pub use exported::Exported; mod annotation_commands; mod annotation_selection; +mod annotation_target; +pub use annotation_target::AnnotationTarget; mod comment_commands; mod frame_commands; mod frame_contents; mod function_commands; mod node_graph_commands; mod pattern_graph_commands; +mod pin_commands; mod snapshot; pub use annotation_selection::AnnotationSelection; pub use frame_contents::FrameContents; diff --git a/crates/engine/src/linked_packages.rs b/crates/engine/src/linked_packages.rs index 01fad15e..f0038f3c 100644 --- a/crates/engine/src/linked_packages.rs +++ b/crates/engine/src/linked_packages.rs @@ -97,8 +97,15 @@ impl Session { self.refresh_links_from(BTreeSet::new()); } + /// Refresh linked interfaces and retain ownership of installed library snapshots. pub(crate) fn refresh_links_from(&mut self, mut changed: BTreeSet) { + // Replaced snapshots belong to the caller, even when their library alias is unchanged + self.library_sources.retain(|path, owned| self.linked_sources.get(path).is_some_and(|source| Arc::ptr_eq(source, owned))); + let open_paths: BTreeSet<_> = self.open_packages().into_iter().filter_map(|(_, _, path, _)| path.map(str::to_string)).collect(); + self.library_sources.retain(|path, _| !open_paths.contains(path)); + let mut sources = self.linked_sources.clone(); + // Interface types can propagate through several files; the workspace has at most 64 open packages for _ in 0..64 { for (_, package, path, _) in self.open_packages() { @@ -142,6 +149,13 @@ impl Session { } document.pkg.dependencies = sources.clone(); } + + // Interface refreshes replace Arcs without changing who owns the source + for (path, owned) in &mut self.library_sources { + if let Some(source) = sources.get(path) { + *owned = source.clone(); + } + } self.linked_sources = sources; } } diff --git a/crates/engine/src/node_library.rs b/crates/engine/src/node_library.rs index b2541aae..24bf9be2 100644 --- a/crates/engine/src/node_library.rs +++ b/crates/engine/src/node_library.rs @@ -1,13 +1,21 @@ //! The node library. Every SBS package in the library folder (`assets/sbs`, or the bundled copies) //! is loaded once per process and lends its graphs: function graphs go under Functions (sorted by -//! their folder), other graphs under their attribute category. Native nodes, function operations, +//! their classification tags, with folder fallbacks), other graphs under their attribute category. Native nodes, function operations, //! FX-Map nodes and graph items fill the rest of the tree. A package whose titled frames are library //! categories ("Filters - Blurs") can also lay the library out: each node inside a frame becomes an //! entry in that category, listed as missing until a package provides it. +mod library_canvas; +mod library_entry; +mod library_item; +mod library_placement; +pub use library_canvas::LibraryCanvas; +pub use library_entry::LibraryEntry; +pub use library_item::LibraryItem; +use library_placement::LibraryPlacement; + use materialcraft_core::{Package, PatternNodeKind}; use materialcraft_formats::sbs::{LayoutItem, library}; -use serde::Serialize; use std::collections::{BTreeMap, BTreeSet}; use std::sync::{Arc, Mutex}; @@ -47,86 +55,6 @@ const SUB_KEYWORDS: &[(&str, &str, &[&str])] = &[ ("PBR materials", "Stone", &["stone", "rock", "marble", "granite"]), ]; -/// The graph kind that can take an entry -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub enum LibraryCanvas { - Material, - Function, - Pattern, -} - -/// What adding an entry puts in the graph -#[derive(Clone, Debug, PartialEq, Serialize)] -#[serde(tag = "type", rename_all = "camelCase")] -pub enum LibraryItem { - /// A native node, by catalog id - Node { - def: String, - }, - Comment, - Frame, - Pin, - /// An instance of a graph from a library package - Instance { - package: String, - graph: String, - }, - /// A native function operation - Operation { - operation: String, - }, - /// An instance of a function graph from a library package - FunctionInstance { - package: String, - graph: String, - }, - /// An FX-Map node - Pattern { - kind: PatternNodeKind, - }, - /// An environment image - Bitmap { - resource: String, - }, -} - -impl LibraryItem { - pub fn canvas(&self) -> LibraryCanvas { - match self { - Self::Operation { .. } | Self::FunctionInstance { .. } => LibraryCanvas::Function, - Self::Pattern { .. } => LibraryCanvas::Pattern, - _ => LibraryCanvas::Material, - } - } -} - -#[derive(Clone, Debug, PartialEq, Serialize)] -pub struct LibraryEntry { - /// Stable id, e.g. `node:blur`, `function:add`, `sbs://functions.sbs#Functions/Math/Pi` - pub id: String, - pub label: String, - /// `Top` or `Top/Sub`, from [`CATEGORIES`] - pub category: String, - pub description: String, - #[serde(flatten)] - pub item: LibraryItem, - pub canvas: LibraryCanvas, - /// Why the entry can't be added yet (the package it needs is not in MaterialCraft) - #[serde(skip_serializing_if = "Option::is_none")] - pub missing: Option, - /// It can be added, but is incomplete (it uses operations MaterialCraft lacks) - #[serde(skip_serializing_if = "Option::is_none")] - pub warning: Option, -} - -/// A layout placement, before it is resolved against the loaded packages -#[derive(Clone, Debug)] -struct Placement { - category: String, - item: LayoutItem, -} - /// Everything loaded from the library folder #[derive(Debug, Default)] pub struct NodeLibrary { @@ -135,7 +63,7 @@ pub struct NodeLibrary { /// The `sbs://` files that laid the library out pub layouts: Vec, pub warnings: Vec, - placements: Vec, + placements: Vec, } static SHARED: Mutex>> = Mutex::new(None); @@ -165,6 +93,7 @@ impl NodeLibrary { continue; } }; + // A layout's frames name library categories; anything else is a package of graphs let placements = match materialcraft_formats::sbs::read_layout(&bytes, uri) { Ok(frames) => placements(&frames), @@ -178,6 +107,7 @@ impl NodeLibrary { out.layouts.push(uri.clone()); continue; } + match materialcraft_formats::sbs::read_sbs(&bytes, uri, &crate::file_cmds::linked_files(uri)) { Ok(mut read) => { crate::linked_files::normalize_references(&mut read.pkg, uri); @@ -202,6 +132,13 @@ impl NodeLibrary { let mut ids = BTreeSet::new(); let mut placed_graphs = BTreeSet::new(); let mut push = |out: &mut Vec, mut entry: LibraryEntry| { + // Reroute nodes are placed through the shared Graph items entry + if matches!(&entry.item, LibraryItem::Operation { operation } if operation == "passthrough") + || matches!(&entry.item, LibraryItem::Pattern { kind: PatternNodeKind::Dot }) + || matches!(&entry.item, LibraryItem::Node { def } if def == "dot" && entry.category != "Graph items") + { + return; + } // The same node may sit in two categories; the id keeps each placement apart if !ids.insert(entry.id.clone()) { entry.id = format!("{}@{}", entry.id, entry.category); @@ -233,7 +170,9 @@ impl NodeLibrary { if definition.id == "graph_instance" || listed.contains(&id) { continue; } + let item = LibraryItem::Node { def: definition.id.into() }; + // Graph inputs and outputs sit with the atomic nodes; Graph items holds annotations and the Dot let category = if matches!(definition.id, "input_color" | "input_grayscale" | "input_value" | "output") { "Atomic nodes" } else { definition.category }; @@ -241,13 +180,14 @@ impl NodeLibrary { } for operation in materialcraft_nodes::function::FUNCTIONS { let id = format!("function:{}", operation.id); - if listed.contains(&id) { + if operation.id == "passthrough" || listed.contains(&id) { continue; } + let category = category_path("Function nodes", Some(operation.category)); push(&mut out, entry(id, operation.label, &category, "", LibraryItem::Operation { operation: operation.id.into() }, None)); } - for kind in PatternNodeKind::ALL { + for kind in PatternNodeKind::ALL.into_iter().filter(|kind| *kind != PatternNodeKind::Dot) { let id = format!("pattern:{}", kind.native_id()); push(&mut out, entry(id, kind.label(), "FxMap nodes", "", LibraryItem::Pattern { kind }, None)); } @@ -258,15 +198,24 @@ impl NodeLibrary { if placed_graphs.contains(&(path.clone(), name.clone())) { continue; } - let placement = if graph.function.is_some() { - let category = known_category(&graph.attributes.category).unwrap_or_else(|| function_category(&name)); - Placement { category, item: LayoutItem::FunctionInstance { package: path.clone(), graph: name } } - } else if graph.nodes.iter().any(|node| node.def == "output") { + + if graph.function.is_some() { + for category in function_categories(graph) { + let placement = LibraryPlacement { category, item: LayoutItem::FunctionInstance { package: path.clone(), graph: name.clone() } }; + if let Some(entry) = resolve(&placement, dependencies) { + push(&mut out, entry); + } + } + continue; + } + + let placement = if graph.nodes.iter().any(|node| node.def == "output") { let category = known_category(&graph.attributes.category).unwrap_or_else(|| "Other".into()); - Placement { category, item: LayoutItem::Instance { package: path.clone(), graph: name, outputs: Vec::new() } } + LibraryPlacement { category, item: LayoutItem::Instance { package: path.clone(), graph: name, outputs: Vec::new() } } } else { continue; }; + if let Some(entry) = resolve(&placement, dependencies) { push(&mut out, entry); } @@ -276,13 +225,14 @@ impl NodeLibrary { } } +/// Build an entry with a canvas derived from its item kind. fn entry(id: String, label: &str, category: &str, description: &str, item: LibraryItem, missing: Option) -> LibraryEntry { let canvas = item.canvas(); LibraryEntry { id, label: label.into(), category: category.into(), description: description.into(), item, canvas, missing, warning: None } } /// A layout item as an entry, its label and availability taken from the loaded packages -fn resolve(placement: &Placement, dependencies: &BTreeMap>) -> Option { +fn resolve(placement: &LibraryPlacement, dependencies: &BTreeMap>) -> Option { let category = placement.category.as_str(); Some(match &placement.item { LayoutItem::Atomic { node: Some(def), .. } | LayoutItem::Node(def) => { @@ -319,6 +269,7 @@ fn resolve(placement: &Placement, dependencies: &BTreeMap>) .map(|_| "This function uses nodes MaterialCraft does not have yet".to_string()); out } + // A bitmap anywhere but the 3D view stands for the atomic Bitmap node, not its image LayoutItem::Bitmap { .. } if !category.starts_with("3D view") => { let definition = materialcraft_nodes::find("bitmap")?; @@ -333,12 +284,12 @@ fn resolve(placement: &Placement, dependencies: &BTreeMap>) } /// The categories of a layout's frames, and what each places -fn placements(frames: &[materialcraft_formats::sbs::LayoutFrame]) -> Vec { +fn placements(frames: &[materialcraft_formats::sbs::LayoutFrame]) -> Vec { let mut out = Vec::new(); for frame in frames { let native = frame.items.iter().any(|item| matches!(item, LayoutItem::Operation(_))); let Some(category) = frame_category(&frame.title, frame.function, native) else { continue }; - out.extend(frame.items.iter().map(|item| Placement { category: category.clone(), item: item.clone() })); + out.extend(frame.items.iter().map(|item| LibraryPlacement { category: category.clone(), item: item.clone() })); } out } @@ -374,6 +325,7 @@ fn known_category(text: &str) -> Option { let mut parts = text.split('/'); let top = parts.next()?; let (top, subs) = CATEGORIES.iter().find(|(name, _)| key(name) == key(top))?; + // A sub-category the tree doesn't have names no category ("Functions/colorValues" is a folder) let sub = match parts.next() { None => None, @@ -382,6 +334,27 @@ fn known_category(text: &str) -> Option { Some(category_path(top, sub)) } +/// Function tags select filters; explicit category paths and package paths remain fallbacks. +fn function_categories(graph: &materialcraft_core::Graph) -> Vec { + let subcategories = CATEGORIES.iter().find(|(name, _)| *name == "Functions").map_or(&[][..], |(_, subcategories)| *subcategories); + let mut categories = Vec::new(); + for tag in graph.attributes.tags.split([',', ';']) { + let tag = key(tag); + let tag = if tag == "easing" { "easings" } else { tag.as_str() }; + if let Some(subcategory) = subcategories.iter().find(|subcategory| key(subcategory) == tag) { + let category = category_path("Functions", Some(subcategory)); + if !categories.contains(&category) { + categories.push(category); + } + } + } + if categories.is_empty() { + categories.push(known_category(&graph.attributes.category).unwrap_or_else(|| function_category(&graph.sbs_path()))); + } + categories +} + +/// Join a top-level category with its optional subcategory. fn category_path(top: &str, sub: Option<&str>) -> String { match sub { Some(sub) => format!("{top}/{sub}"), @@ -394,6 +367,7 @@ fn sub_category(category: &str, graph: &str) -> String { if category.contains('/') { return category.to_string(); } + let name = graph.rsplit('/').next().unwrap_or(graph).to_ascii_lowercase(); SUB_KEYWORDS .iter() @@ -471,6 +445,7 @@ pub fn humanize(identifier: &str) -> String { if let Some((_, known)) = WORDS.iter().find(|(from, _)| *from == lower) { return (*known).to_string(); } + let mut chars = word.chars(); chars.next().map_or_else(String::new, |first| first.to_uppercase().chain(chars).collect()) }) diff --git a/crates/engine/src/node_library.test.rs b/crates/engine/src/node_library.test.rs index 1c6fbd4c..8eef6dc9 100644 --- a/crates/engine/src/node_library.test.rs +++ b/crates/engine/src/node_library.test.rs @@ -1,6 +1,10 @@ use super::*; use materialcraft_core::Graph; +#[path = "../tests/support/node_library.rs"] +mod fixture; + +/// Category aliases and frame kinds resolve only to recognized categories. #[test] fn frame_titles_map_to_library_categories() { assert_eq!(frame_category("Texture Generators - Noises", false, false).as_deref(), Some("Texture generators/Noises")); @@ -9,6 +13,7 @@ fn frame_titles_map_to_library_categories() { assert_eq!(frame_category("Mesh-based generators - Weathering", false, false).as_deref(), Some("Mesh-based generators/Weathering")); assert_eq!(frame_category("PBR Materials", false, false).as_deref(), Some("PBR materials")); assert_eq!(frame_category("Atomic Nodes", false, false).as_deref(), Some("Atomic nodes")); + // The category MaterialCraft renamed still reads from older layouts assert_eq!(frame_category("SDF functions - Primitives", false, false).as_deref(), Some("MCF functions/Primitives")); assert_eq!(frame_category("Functions Inside", false, false), None); @@ -18,6 +23,7 @@ fn frame_titles_map_to_library_categories() { assert_eq!(frame_category("Unknown", true, true), None); } +/// Identifier labels preserve recognized acronyms and omit empty words. #[test] fn identifiers_read_as_labels() { assert_eq!(humanize("3D_perlin_noise"), "3D Perlin Noise"); @@ -27,6 +33,7 @@ fn identifiers_read_as_labels() { assert_eq!(humanize("__"), ""); } +/// Function categories use exact path segments and known name overrides. #[test] fn functions_sort_into_sub_categories_by_folder_and_name() { assert_eq!(function_category("Functions/Math/Pi"), "Functions/Constant"); @@ -41,9 +48,10 @@ fn functions_sort_into_sub_categories_by_folder_and_name() { assert_eq!(function_category("Loose"), "Functions"); } +/// The isolated bundled catalog has unique entries in recognized categories. #[test] fn the_bundled_library_fills_the_tree_with_what_materialcraft_has() { - let library = NodeLibrary::shared(); + let library = fixture::library(); assert!(library.layouts.is_empty()); assert!(library.packages.contains_key("sbs://functions.sbs")); @@ -68,8 +76,10 @@ fn the_bundled_library_fills_the_tree_with_what_materialcraft_has() { assert!(count(&format!("{top}/{sub}")) > 0, "{top}/{sub} is empty"); } } + // Every bundled function has a sub-category - assert_eq!(entries.iter().filter(|entry| entry.category.starts_with("Functions/")).count(), 171); + let functions = library.packages["sbs://functions.sbs"].graphs.iter().filter(|graph| graph.function.is_some()).count(); + assert_eq!(entries.iter().filter(|entry| entry.category.starts_with("Functions/")).count(), functions); assert_eq!(count("Functions"), 0); assert_eq!(find("sbs://functions.sbs#Functions/Tonemappers/tonemap_ACES").category, "Functions/Color"); assert_eq!( @@ -99,6 +109,7 @@ const LAYOUT: &str = r#" </GUIObject> </GUIObjects></graph></content></package>"#; +/// A missing layout entry becomes available when its package is supplied. #[test] fn a_layout_lists_what_it_places_and_a_library_package_makes_it_available() { let frames = materialcraft_formats::sbs::read_layout(LAYOUT.as_bytes(), "sbs://layout.sbs").unwrap(); @@ -128,6 +139,7 @@ fn a_layout_lists_what_it_places_and_a_library_package_makes_it_available() { assert_eq!((loose.category.as_str(), loose.canvas), ("Filters/Blurs", LibraryCanvas::Material)); } +/// Invalid library files produce warnings while native entries remain usable. #[test] fn unreadable_library_files_warn_instead_of_failing() { let library = NodeLibrary::load(&["sbs://does_not_exist.sbs".into(), "sbs://../escape.sbs".into()]); @@ -137,3 +149,25 @@ fn unreadable_library_files_warn_instead_of_failing() { assert!(entries.iter().any(|entry| entry.id == "node:blur" && entry.category == "Atomic nodes")); assert!(entries.iter().any(|entry| entry.id == "function:add" && entry.category == "Function nodes/Operator")); } + +/// Classification tags take precedence over package folders and support multiple placements. +#[test] +fn function_tags_choose_library_filters_before_path_fallbacks() { + let mut package = Package::new("Functions"); + for (name, category, tags) in [("Pi", "Function", "Maths"), ("Tagged", "", "Comparison; Easing"), ("Fallback", "", "Unknown")] { + let mut graph = Graph::new(name); + graph.folder = "Functions/Math".into(); + graph.function = Some(Default::default()); + graph.attributes.category = category.into(); + graph.attributes.tags = tags.into(); + package.graphs.push(graph); + } + let dependencies = BTreeMap::from([("sbs://classification.sbs".to_string(), Arc::new(package))]); + + let entries = NodeLibrary::default().entries(&dependencies); + let categories = |name: &str| entries.iter().filter(|entry| entry.label == name).map(|entry| entry.category.as_str()).collect::<Vec<_>>(); + + assert_eq!(categories("Pi"), ["Functions/Maths"]); + assert_eq!(categories("Tagged"), ["Functions/Comparison", "Functions/Easings"]); + assert_eq!(categories("Fallback"), ["Functions/Maths"]); +} diff --git a/crates/engine/src/node_library/library_canvas.rs b/crates/engine/src/node_library/library_canvas.rs new file mode 100644 index 00000000..f119b11f --- /dev/null +++ b/crates/engine/src/node_library/library_canvas.rs @@ -0,0 +1,11 @@ +use serde::Serialize; + +/// The graph kind that can take an entry +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum LibraryCanvas { + Any, + Material, + Function, + Pattern, +} diff --git a/crates/engine/src/node_library/library_entry.rs b/crates/engine/src/node_library/library_entry.rs new file mode 100644 index 00000000..33298581 --- /dev/null +++ b/crates/engine/src/node_library/library_entry.rs @@ -0,0 +1,22 @@ +use super::{LibraryCanvas, LibraryItem}; +use serde::Serialize; + +/// One selectable library entry and its availability on a destination canvas. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct LibraryEntry { + /// Stable id, e.g. `node:blur`, `function:add`, `sbs://functions.sbs#Functions/Math/Pi` + pub id: String, + pub label: String, + /// `Top` or `Top/Sub`, from [`super::CATEGORIES`] + pub category: String, + pub description: String, + #[serde(flatten)] + pub item: LibraryItem, + pub canvas: LibraryCanvas, + /// Why the entry can't be added yet (the package it needs is not in MaterialCraft) + #[serde(skip_serializing_if = "Option::is_none")] + pub missing: Option<String>, + /// It can be added, but is incomplete (it uses operations MaterialCraft lacks) + #[serde(skip_serializing_if = "Option::is_none")] + pub warning: Option<String>, +} diff --git a/crates/engine/src/node_library/library_item.rs b/crates/engine/src/node_library/library_item.rs new file mode 100644 index 00000000..583ba54b --- /dev/null +++ b/crates/engine/src/node_library/library_item.rs @@ -0,0 +1,51 @@ +use super::LibraryCanvas; +use materialcraft_core::PatternNodeKind; +use serde::Serialize; + +/// What adding an entry puts in the graph +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(tag = "type", rename_all = "camelCase")] +pub enum LibraryItem { + /// A native node, by catalog id + Node { + def: String, + }, + Comment, + Frame, + Pin, + /// An instance of a graph from a library package + Instance { + package: String, + graph: String, + }, + /// A native function operation + Operation { + operation: String, + }, + /// An instance of a function graph from a library package + FunctionInstance { + package: String, + graph: String, + }, + /// An FX-Map node + Pattern { + kind: PatternNodeKind, + }, + /// An environment image + Bitmap { + resource: String, + }, +} + +impl LibraryItem { + /// Return the canvas that accepts this item. + pub fn canvas(&self) -> LibraryCanvas { + match self { + Self::Comment | Self::Frame | Self::Pin => LibraryCanvas::Any, + Self::Node { def } if def == "dot" => LibraryCanvas::Any, + Self::Operation { .. } | Self::FunctionInstance { .. } => LibraryCanvas::Function, + Self::Pattern { .. } => LibraryCanvas::Pattern, + _ => LibraryCanvas::Material, + } + } +} diff --git a/crates/engine/src/node_library/library_placement.rs b/crates/engine/src/node_library/library_placement.rs new file mode 100644 index 00000000..a4cbd2d3 --- /dev/null +++ b/crates/engine/src/node_library/library_placement.rs @@ -0,0 +1,8 @@ +use materialcraft_formats::sbs::LayoutItem; + +/// A layout placement, before it is resolved against the loaded packages +#[derive(Clone, Debug)] +pub(super) struct LibraryPlacement { + pub(super) category: String, + pub(super) item: LayoutItem, +} diff --git a/crates/engine/src/node_library_commands.rs b/crates/engine/src/node_library_commands.rs index 29d67094..3dab4425 100644 --- a/crates/engine/src/node_library_commands.rs +++ b/crates/engine/src/node_library_commands.rs @@ -9,6 +9,7 @@ use std::collections::BTreeSet; const ADD: &str = "library.add"; +/// Register catalog queries, insertion and library reload commands. pub(crate) fn specs() -> Vec<CommandSpec> { vec![ cmd!( @@ -25,7 +26,7 @@ pub(crate) fn specs() -> Vec<CommandSpec> { "Add library entry", [], None, - "{entry (id from library.tree), at? [x, y], snapToGrid?, function?: FunctionGraphTarget} adds a library entry to the open graph (function entries to a Function canvas)", + "{entry (id from library.tree), at? [x, y], snapToGrid?, function?: FunctionGraphTarget, pattern?: owner node id} adds a library entry to the open graph (function entries to a Function canvas)", has_graph, add ), @@ -40,6 +41,7 @@ impl Session { } } +/// List entries that match the requested text, category and destination canvas. fn tree(session: &mut Session, parameters: &Value) -> Result<Value> { let filter = strp(parameters, "filter").unwrap_or("").to_lowercase(); let category = strp(parameters, "category").unwrap_or(""); @@ -54,13 +56,14 @@ fn tree(session: &mut Session, parameters: &Value) -> Result<Value> { .library_entries() .into_iter() .filter(|entry| category.is_empty() || entry.category == category || entry.category.starts_with(&format!("{category}/"))) - .filter(|entry| canvas.is_none_or(|canvas| entry.canvas == canvas)) + .filter(|entry| canvas.is_none_or(|canvas| entry.canvas == LibraryCanvas::Any || entry.canvas == canvas)) .filter(|entry| filter.is_empty() || entry.label.to_lowercase().contains(&filter) || entry.id.to_lowercase().contains(&filter)) .collect(); let categories: Vec<_> = CATEGORIES.iter().map(|(name, subcategories)| json!({"name": name, "subcategories": subcategories})).collect(); Ok(json!({"categories": categories, "layouts": session.library.layouts, "entries": entries})) } +/// Validate an entry and dispatch its insertion through the destination graph command. fn add(session: &mut Session, parameters: &Value) -> Result<Value> { let id = strp(parameters, "entry").ok_or_else(|| bad(ADD, "`entry` is required (an id from library.tree)"))?; let entry = session.library_entries().into_iter().find(|entry| entry.id == id).ok_or_else(|| bad(ADD, format!("no library entry `{id}`")))?; @@ -72,6 +75,39 @@ fn add(session: &mut Session, parameters: &Value) -> Result<Value> { let snap = boolp(parameters, "snapToGrid").unwrap_or(false); let function_graph = session.graph()?.function.is_some(); let target = parameters.get("function").cloned().filter(|target| !target.is_null()); + if entry.canvas == LibraryCanvas::Any { + let destination = crate::AnnotationTarget::resolve(session, parameters)?; + let mut arguments = destination.parameters(); + arguments["at"] = json!(at); + let command = match &entry.item { + LibraryItem::Comment => "graph.comment.add", + LibraryItem::Frame => { + arguments["rect"] = json!([at[0], at[1], 400.0, 260.0]); + "graph.frame.add" + } + LibraryItem::Pin => "graph.pin.add", + LibraryItem::Node { def } if def == "dot" => match crate::SelectionTarget::resolve(session, parameters)? { + Some(crate::SelectionTarget::Function(target)) => { + arguments = json!({"target": target, "edit": {"action": "add", "operation": "passthrough", "at": at, "snap": snap}}); + "graph.function.edit" + } + Some(crate::SelectionTarget::Pattern(owner)) => { + arguments = json!({"id": owner.0, "edit": {"action": "add", "kind": "passthrough", "at": at, "snap": snap}}); + "graph.pattern.edit" + } + None => { + arguments = json!({"def": "dot", "at": at, "snapToGrid": snap}); + "graph.node.add" + } + }, + _ => return Err(bad(ADD, "unknown graph item")), + }; + let result = crate::execute(session, command, &arguments)?; + if matches!(&entry.item, LibraryItem::Node { .. }) { + session.annotation_selection = None; + } + return Ok(json!({"entry": entry.id, "result": result})); + } if entry.canvas == LibraryCanvas::Function { let target = match target { Some(target) => serde_json::from_value::<FunctionGraphTarget>(target).map_err(|error| bad(ADD, error.to_string()))?, @@ -92,10 +128,12 @@ fn add(session: &mut Session, parameters: &Value) -> Result<Value> { }; return Ok(json!({"entry": entry.id, "result": result})); } + if entry.canvas == LibraryCanvas::Pattern { return Err(bad(ADD, format!("{} is an FX-Map node: add it with graph.pattern.edit", entry.label))); } - if function_graph { + + if function_graph || target.is_some() || parameters.get("pattern").is_some() { return Err(bad(ADD, format!("{} goes in a material graph, not a Function Graph", entry.label))); } @@ -112,20 +150,45 @@ fn add(session: &mut Session, parameters: &Value) -> Result<Value> { Ok(json!({"entry": entry.id, "result": result})) } -fn reload(session: &mut Session, _: &Value) -> Result<Value> { - let library = NodeLibrary::reload(); +/// Replace library-owned snapshots while retaining explicit user dependencies. +fn replace_library(session: &mut Session, library: std::sync::Arc<NodeLibrary>) { let mut changed = BTreeSet::new(); + session.library_sources.retain(|path, owned| session.linked_sources.get(path).is_some_and(|source| std::sync::Arc::ptr_eq(source, owned))); + for path in session.library_sources.keys() { + if !library.packages.contains_key(path) { + session.linked_sources.remove(path); + changed.insert(path.clone()); + } + } + session.library_sources.retain(|path, _| library.packages.contains_key(path)); + for (path, package) in &library.packages { - if session.linked_sources.get(path).is_none_or(|current| current.graphs != package.graphs || current.resources != package.resources) { + if session.linked_sources.contains_key(path) && !session.library_sources.contains_key(path) { + continue; + } + + if session.linked_sources.get(path).is_none_or(|current| current.as_ref() != package.as_ref()) { session.linked_sources.insert(path.clone(), package.clone()); changed.insert(path.clone()); } + if let Some(source) = session.linked_sources.get(path) { + session.library_sources.insert(path.clone(), source.clone()); + } } for warning in &library.warnings { session.warn(warning.clone()); } session.library = library; session.refresh_links_from(changed); +} + +/// Reload the installed library and report the catalog visible to this session. +fn reload(session: &mut Session, _: &Value) -> Result<Value> { + replace_library(session, NodeLibrary::reload()); let entries = session.library_entries(); Ok(json!({"entries": entries.len(), "available": entries.iter().filter(|entry| entry.missing.is_none()).count(), "layouts": session.library.layouts})) } + +#[cfg(test)] +#[path = "node_library_commands.test.rs"] +mod tests; diff --git a/crates/engine/src/node_library_commands.test.rs b/crates/engine/src/node_library_commands.test.rs new file mode 100644 index 00000000..10774ac9 --- /dev/null +++ b/crates/engine/src/node_library_commands.test.rs @@ -0,0 +1,46 @@ +use super::*; +use materialcraft_core::{FunctionGraph, Graph, Package}; +use std::sync::Arc; + +/// Build a small library with one reusable function and no filesystem dependencies. +fn library(name: &str) -> Arc<NodeLibrary> { + let mut function = Graph::new(name); + function.function = Some(FunctionGraph::default()); + let mut package = Package::new("Custom library"); + package.graphs.push(function); + let mut library = NodeLibrary::default(); + library.packages.insert("sbs://custom.sbs".into(), Arc::new(package)); + Arc::new(library) +} + +/// Reload replaces owned sources and removes sources no longer installed. +#[test] +fn reload_updates_and_removes_library_owned_sources() { + let mut session = Session::with_library(Package::new("Project"), library("Before")); + + replace_library(&mut session, library("After")); + + assert!(session.library_entries().iter().any(|entry| entry.id == "sbs://custom.sbs#After")); + assert!(!session.library_entries().iter().any(|entry| entry.id == "sbs://custom.sbs#Before")); + + replace_library(&mut session, Arc::new(NodeLibrary::default())); + + assert!(!session.pkg.dependencies.contains_key("sbs://custom.sbs")); + assert!(!session.library_entries().iter().any(|entry| entry.id.starts_with("sbs://custom.sbs#"))); + assert!(!session.modified); +} + +/// Opening a package transfers dependency ownership even after initial session construction. +#[test] +fn reload_keeps_dependencies_supplied_by_later_opened_packages() { + let mut session = Session::with_library(Package::new("First"), library("Original")); + let custom = library("User_function"); + let mut package = Package::new("Second"); + package.dependencies = custom.packages.clone(); + session.open_package(package, None).unwrap(); + + replace_library(&mut session, library("Replacement")); + + assert!(session.library_entries().iter().any(|entry| entry.id == "sbs://custom.sbs#User_function")); + assert!(!session.library_entries().iter().any(|entry| entry.id == "sbs://custom.sbs#Replacement")); +} diff --git a/crates/engine/src/open_document.rs b/crates/engine/src/open_document.rs index df40c19e..8781f1c6 100644 --- a/crates/engine/src/open_document.rs +++ b/crates/engine/src/open_document.rs @@ -10,6 +10,7 @@ pub struct OpenDocument { pub modified: bool, selection: Vec<NodeId>, annotation_selection: Option<AnnotationSelection>, + annotation_target: crate::AnnotationTarget, view2d: View2d, view3d: View3d, material_preview: MaterialPreview, @@ -26,6 +27,7 @@ impl OpenDocument { graph: self.graph, selection: self.selection.clone(), annotation_selection: self.annotation_selection, + annotation_target: self.annotation_target.clone(), material_preview: self.material_preview.clone(), label: label.into(), modified: self.modified, @@ -40,6 +42,7 @@ impl OpenDocument { self.graph = snapshot.graph.min(self.pkg.graphs.len().saturating_sub(1)); self.selection = snapshot.selection; self.annotation_selection = snapshot.annotation_selection; + self.annotation_target = snapshot.annotation_target; self.material_preview = snapshot.material_preview; self.modified = snapshot.modified; } @@ -90,6 +93,7 @@ impl OpenDocument { modified: false, selection: Vec::new(), annotation_selection: None, + annotation_target: Default::default(), view2d: View2d::default(), view3d: View3d::default(), load_warnings: Vec::new(), @@ -114,6 +118,7 @@ impl OpenDocument { modified, selection, annotation_selection, + annotation_target, view2d, view3d, material_preview, diff --git a/crates/engine/src/pin_commands.rs b/crates/engine/src/pin_commands.rs new file mode 100644 index 00000000..8a922750 --- /dev/null +++ b/crates/engine/src/pin_commands.rs @@ -0,0 +1,65 @@ +use crate::commands::{CommandSpec, bad, has_graph, point, strp, u64p}; +use crate::{AnnotationSelection, AnnotationTarget, Result, Session, cmd}; +use materialcraft_core::Pin; +use serde_json::{Value, json}; + +/// Register navigation pin creation, description/position editing and deletion. +pub(crate) fn specs() -> Vec<CommandSpec> { + vec![ + cmd!("graph.pin.add", "Add Navigation pin", [], None, "{name?, description?, at? [x, y], function?, pattern?}", has_graph, add), + cmd!("graph.pin.edit", "Edit Navigation pin", [], None, "{id, description?, at? [x, y], function?, pattern?}", has_graph, edit), + cmd!("graph.pin.delete", "Delete pin", [], None, "{id, function?, pattern?}", has_graph, delete), + ] +} + +fn add(session: &mut Session, parameters: &Value) -> Result<Value> { + let target = AnnotationTarget::resolve(session, parameters)?; + let mut items = target.items(session)?; + let id = target.next_id(session, &items)?; + let name = + strp(parameters, "description").or_else(|| strp(parameters, "name")).map(str::to_string).unwrap_or_else(|| format!("Pin {}", items.pins.len() + 1)); + let pos = point(parameters, "at").unwrap_or([0.0; 2]); + items.pins.push(Pin { id, name, pos }); + + session.edit("Add pin", |session| { + target.replace(session, items)?; + session.selection.clear(); + session.annotation_target = target; + session.annotation_selection = Some(AnnotationSelection::Pin(id)); + Ok(json!({"id": id})) + }) +} + +fn edit(session: &mut Session, parameters: &Value) -> Result<Value> { + let target = AnnotationTarget::resolve(session, parameters)?; + let id = u64p(parameters, "id").ok_or_else(|| bad("graph.pin.edit", "`id` is required"))?; + let mut items = target.items(session)?; + let pin = items.pins.iter_mut().find(|pin| pin.id == id).ok_or_else(|| bad("graph.pin.edit", format!("no pin {id}")))?; + if let Some(description) = strp(parameters, "description").or_else(|| strp(parameters, "name")) { + pin.name = description.into(); + } + if let Some(position) = point(parameters, "at") { + pin.pos = position; + } + + session.edit_merged(&format!("pin:{target:?}:{id}"), "Edit pin", |session| { + target.replace(session, items)?; + Ok(Value::Null) + }) +} + +fn delete(session: &mut Session, parameters: &Value) -> Result<Value> { + let target = AnnotationTarget::resolve(session, parameters)?; + let id = u64p(parameters, "id").ok_or_else(|| bad("graph.pin.delete", "`id` is required"))?; + let mut items = target.items(session)?; + let previous = items.pins.len(); + items.pins.retain(|pin| pin.id != id); + if previous == items.pins.len() { + return Err(bad("graph.pin.delete", format!("no pin {id}"))); + } + + session.edit("Delete pin", |session| { + target.replace(session, items)?; + Ok(Value::Null) + }) +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 03517e8a..38b9ce9c 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -123,6 +123,8 @@ pub struct Session { pub(crate) next_document_id: u64, pub(crate) documents: std::collections::BTreeMap<u64, crate::OpenDocument>, pub(crate) linked_sources: std::collections::BTreeMap<String, Arc<Package>>, + /// Snapshots inserted by the library, excluding explicitly supplied dependencies + pub(crate) library_sources: std::collections::BTreeMap<String, Arc<Package>>, pub pkg: Package, /// Where the package was opened from or last saved to. pub path: Option<String>, @@ -130,6 +132,7 @@ pub struct Session { pub graph: usize, pub selection: Vec<NodeId>, pub annotation_selection: Option<AnnotationSelection>, + pub annotation_target: crate::AnnotationTarget, pub view2d: View2d, pub view3d: View3d, pub material_preview: crate::MaterialPreview, @@ -165,10 +168,19 @@ pub struct Session { } impl Session { - pub fn new(mut pkg: Package) -> Session { - let library = crate::node_library::NodeLibrary::shared(); + /// Open a package with the process's installed node library. + pub fn new(pkg: Package) -> Session { + Self::with_library(pkg, crate::node_library::NodeLibrary::shared()) + } + + /// Open a package with an explicit library, preserving dependencies supplied by the caller. + pub fn with_library(mut pkg: Package, library: Arc<crate::NodeLibrary>) -> Session { + let mut library_sources = std::collections::BTreeMap::new(); for (path, package) in &library.packages { - pkg.dependencies.entry(path.clone()).or_insert_with(|| package.clone()); + if let std::collections::btree_map::Entry::Vacant(entry) = pkg.dependencies.entry(path.clone()) { + entry.insert(package.clone()); + library_sources.insert(path.clone(), package.clone()); + } } let mut session = Session { environment: Default::default(), @@ -177,6 +189,7 @@ impl Session { next_document_id: 1, documents: std::collections::BTreeMap::new(), linked_sources: pkg.dependencies.clone(), + library_sources, material_preview: crate::MaterialPreview::for_graph(&pkg, 0), cooked_graph: None, material_cooked: std::collections::BTreeMap::new(), @@ -185,6 +198,7 @@ impl Session { graph: 0, selection: Vec::new(), annotation_selection: None, + annotation_target: Default::default(), view2d: View2d { channel: "rgba".into(), ..View2d::default() }, view3d: View3d::default(), preview_size: Some(512), @@ -232,6 +246,7 @@ impl Session { graph: self.graph, selection: self.selection.clone(), annotation_selection: self.annotation_selection, + annotation_target: self.annotation_target.clone(), material_preview: self.material_preview.clone(), label: label.into(), modified: self.modified, @@ -330,6 +345,7 @@ 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.annotation_target = s.annotation_target; self.material_preview = s.material_preview; self.modified = s.modified; self.dirty = s.dirty || self.cook_epoch != s.cook_epoch; diff --git a/crates/engine/src/snapshot.rs b/crates/engine/src/snapshot.rs index 4fe9829d..cf70834d 100644 --- a/crates/engine/src/snapshot.rs +++ b/crates/engine/src/snapshot.rs @@ -7,6 +7,7 @@ pub(crate) struct Snapshot { pub(crate) graph: usize, pub(crate) selection: Vec<NodeId>, pub(crate) annotation_selection: Option<AnnotationSelection>, + pub(crate) annotation_target: crate::AnnotationTarget, pub(crate) material_preview: crate::MaterialPreview, pub(crate) label: String, pub(crate) modified: bool, diff --git a/crates/engine/tests/it/annotations.rs b/crates/engine/tests/it/annotations.rs index 6ab91d02..5043728a 100644 --- a/crates/engine/tests/it/annotations.rs +++ b/crates/engine/tests/it/annotations.rs @@ -66,3 +66,110 @@ fn annotation_properties_and_selection_survive_edits_undo_and_native_save() { assert!(session.graph().unwrap().frames.is_empty()); assert_eq!(session.graph().unwrap().comments.len(), 1); } + +/// Pins share annotation selection, properties, deletion and undo. +#[test] +fn navigation_pins_select_edit_delete_and_save() { + for kind in ["material", "function"] { + let mut session = new_session(); + if kind == "function" { + execute(&mut session, "file.new", &json!({"kind": kind})).unwrap(); + } + let id = execute(&mut session, "graph.pin.add", &json!({"at": [-64, 128]})).unwrap()["id"].as_u64().unwrap(); + execute(&mut session, "graph.annotation.select", &json!({"kind": "pin", "id": id})).unwrap(); + execute(&mut session, "graph.pin.edit", &json!({"id": id, "description": "Start & <finish>", "at": [48, -96]})).unwrap(); + let loaded = read_sbs(&write_sbs(&session.pkg).unwrap(), "pins.sbs", &|_| None).unwrap(); + assert!(loaded.warnings.is_empty()); + let graph = loaded.pkg.graph_by_name(&session.graph().unwrap().sbs_path()).unwrap().1; + assert_eq!(graph.pins[0].name, "Start & <finish>"); + assert_eq!(graph.pins[0].pos, [48.0, -96.0]); + + execute(&mut session, "edit.delete", &json!({})).unwrap(); + assert!(session.graph().unwrap().pins.is_empty()); + assert!(session.annotation_selection.is_none()); + session.undo().unwrap(); + assert_eq!(session.graph().unwrap().pins[0].name, "Start & <finish>"); + assert_eq!(serde_json::to_value(session.annotation_selection).unwrap(), json!({"kind": "pin", "id": id})); + let original = session.pkg.clone(); + assert!(execute(&mut session, "graph.pin.edit", &json!({"id": 999999, "description": "Missing"})).is_err()); + assert_eq!(session.pkg, original); + } +} + +/// Every graph item edits its destination canvas and survives native SBS save/reload. +#[test] +fn library_graph_items_work_in_material_function_and_embedded_canvases() { + use materialcraft_engine::{ + AnnotationTarget, FunctionGraphTarget, Session, + core::{FunctionGraph, NodeId, Value}, + }; + for kind in ["material", "function", "pixel_processor", "value_processor", "dynamic", "fx_map"] { + let mut session = new_session(); + let target = match kind { + "material" => AnnotationTarget::Graph, + "function" => { + execute(&mut session, "file.new", &json!({"kind": "function"})).unwrap(); + AnnotationTarget::Graph + } + _ => { + let definition = if kind == "dynamic" { "uniform" } else { kind }; + let node = NodeId(execute(&mut session, "graph.node.add", &json!({"def": definition})).unwrap()["id"].as_u64().unwrap()); + match kind { + "fx_map" => AnnotationTarget::Pattern { owner: node }, + "dynamic" => { + session.graph_mut().unwrap().node_mut(node).unwrap().functions.insert("color".into(), FunctionGraph::default()); + AnnotationTarget::Function { target: FunctionGraphTarget::Dynamic { node, parameter: "color".into() } } + } + _ => AnnotationTarget::Function { target: FunctionGraphTarget::Parameter { node, parameter: "function".into() } }, + } + } + }; + let mut parameters = target.parameters(); + parameters["at"] = json!([64, 128]); + for entry in ["item:comment", "item:frame", "item:pin", "node:dot"] { + parameters["entry"] = json!(entry); + let before = session.pkg.clone(); + execute(&mut session, "library.add", ¶meters).unwrap(); + let after = session.pkg.clone(); + session.undo().unwrap(); + assert_eq!(session.pkg, before, "{kind}: {entry} undo"); + session.redo().unwrap(); + assert_eq!(session.pkg, after, "{kind}: {entry} redo"); + } + let items = target.items(&session).unwrap(); + assert_eq!((items.comments.len(), items.frames.len(), items.pins.len()), (1, 1, 1), "{kind}"); + let mut pin_parameters = target.parameters(); + pin_parameters["id"] = json!(items.pins[0].id); + pin_parameters["kind"] = json!("pin"); + execute(&mut session, "graph.annotation.select", &pin_parameters).unwrap(); + pin_parameters["description"] = json!("Checkpoint & <finish>"); + execute(&mut session, "graph.pin.edit", &pin_parameters).unwrap(); + + let loaded = read_sbs(&write_sbs(&session.pkg).unwrap(), "graph-items.sbs", &|_| None).unwrap(); + let mut reopened = Session::new(loaded.pkg); + reopened.graph = reopened.pkg.graph_by_name(&session.graph().unwrap().sbs_path()).unwrap().0; + let graph = reopened.graph().unwrap(); + let saved = match kind { + "material" | "function" => AnnotationTarget::Graph.items(&reopened).unwrap(), + "fx_map" => match &graph.nodes.iter().find(|node| node.def == kind).unwrap().params["pattern"] { + Value::PatternGraph(graph) => graph.annotations.clone(), + other => panic!("unexpected {other:?}"), + }, + "dynamic" => graph.nodes.iter().find(|node| node.def == "uniform").unwrap().functions["color"].annotations.clone(), + _ => match &graph.nodes.iter().find(|node| node.def == kind).unwrap().params["function"] { + Value::Function(graph) => graph.annotations.clone(), + other => panic!("unexpected {other:?}"), + }, + }; + assert_eq!((saved.comments.len(), saved.frames.len(), saved.pins.len()), (1, 1, 1), "{kind}"); + assert_eq!(saved.pins[0].name, "Checkpoint & <finish>", "{kind}"); + assert_eq!(saved.pins[0].pos, [64.0, 128.0], "{kind}"); + if target != AnnotationTarget::Graph { + assert!(graph.frames.is_empty() && graph.comments.is_empty() && graph.pins.is_empty(), "{kind}: parent must stay untouched"); + } + execute(&mut session, "edit.delete", &json!({})).unwrap(); + assert!(target.items(&session).unwrap().pins.is_empty(), "{kind}"); + session.undo().unwrap(); + assert_eq!(target.items(&session).unwrap().pins[0].name, "Checkpoint & <finish>"); + } +} diff --git a/crates/engine/tests/it/embedded_edit.rs b/crates/engine/tests/it/embedded_edit.rs index 32bf8adc..1227d967 100644 --- a/crates/engine/tests/it/embedded_edit.rs +++ b/crates/engine/tests/it/embedded_edit.rs @@ -594,20 +594,19 @@ fn processor_node_availability_is_shared_and_preserves_existing_sampler_graphs() 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_eq!(operations.len(), full_catalog.len()); assert!(operations.contains(&"add")); for sampler in ["samplelum", "samplecol"] { - assert_eq!(operations.contains(&sampler), sampling); + assert!(operations.contains(&sampler)); 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); - } + + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": sampler, "at": [0, 0]}})).unwrap(); + + let inserted = session.pkg.clone(); + session.undo().unwrap(); + assert_eq!(session.pkg, original); + session.redo().unwrap(); + assert_eq!(session.pkg, inserted); } let mut existing = FunctionGraph::default(); existing.add("samplelum", &[], Some(Value::Int2([0, 1]))); @@ -619,3 +618,41 @@ fn processor_node_availability_is_shared_and_preserves_existing_sampler_graphs() assert_eq!(target.available_operations(&session).count(), materialcraft_engine::nodes::function::FUNCTIONS.len()); } } + +#[test] +fn library_samplers_read_image_inputs_in_both_processors() { + for definition in ["pixel_processor", "value_processor"] { + for sampler in ["samplelum", "samplecol"] { + let mut session = new_session(); + session.preview_size = Some(16); + let color = [0.25, 0.5, 0.75, 1.0]; + let image = NodeId( + execute(&mut session, "graph.node.add", &json!({"def": "uniform", "params": {"color_mode": true, "color": color}})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let parameters = if definition == "pixel_processor" { json!({"color_mode": sampler == "samplecol"}) } else { json!({}) }; + let owner = NodeId(execute(&mut session, "graph.node.add", &json!({"def": definition, "params": parameters})).unwrap()["id"].as_u64().unwrap()); + session.graph_mut().unwrap().connect(image, "output", owner, "input0").unwrap(); + let target = FunctionGraphTarget::Parameter { node: owner, parameter: "function".into() }; + let mut function = FunctionGraph::default(); + let position = function.add_constant(Value::Float2([0.5; 2])); + execute(&mut session, "graph.function.set", &json!({"target": target, "function": function})).unwrap(); + + let result = execute(&mut session, "library.add", &json!({"entry": format!("function:{sampler}"), "function": target, "at": [160, 0]})).unwrap(); + let id = result["result"]["id"].as_u64().unwrap(); + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "connect", "from": position, "to": id, "input": 0}})) + .unwrap(); + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "output", "id": id}})).unwrap(); + session.cook(); + + if definition == "value_processor" { + let expected = if sampler == "samplecol" { Value::Float4(color) } else { Value::Float(color[0]) }; + assert_eq!(session.cooked.value(owner, 0), Some(&expected)); + } else { + let expected = if sampler == "samplecol" { color } else { [color[0], color[0], color[0], 1.0] }; + assert_eq!(session.cooked.image(owner, 0).unwrap().get(0, 0, false), expected); + } + } + } +} diff --git a/crates/engine/tests/it/node_library.rs b/crates/engine/tests/it/node_library.rs index 720c6e63..0b978435 100644 --- a/crates/engine/tests/it/node_library.rs +++ b/crates/engine/tests/it/node_library.rs @@ -1,17 +1,22 @@ use materialcraft_engine::{ Session, core::{FunctionGraph, Graph, Package}, - execute, new_session, + execute, }; use serde_json::{Value, json}; +#[path = "../support/node_library.rs"] +mod fixture; + +/// Return the catalog entries exposed by the library command. fn entries(session: &mut Session, parameters: Value) -> Vec<Value> { execute(session, "library.tree", ¶meters).unwrap()["entries"].as_array().unwrap().clone() } +/// Catalog filters preserve matching entries and reject unknown canvases. #[test] fn the_library_tree_lists_categories_and_filters_entries() { - let mut session = new_session(); + let mut session = fixture::session(); let tree = execute(&mut session, "library.tree", &json!({})).unwrap(); let names: Vec<_> = tree["categories"].as_array().unwrap().iter().map(|category| category["name"].as_str().unwrap()).collect(); assert_eq!(names[..4], ["Graph items", "Atomic nodes", "FxMap nodes", "Function nodes"]); @@ -21,19 +26,21 @@ fn the_library_tree_lists_categories_and_filters_entries() { let constants = entries(&mut session, json!({"category": "Functions/Constant"})); assert!(constants.iter().any(|entry| entry["label"] == "Pi")); let functions = entries(&mut session, json!({"category": "Functions"})); - assert_eq!(functions.len(), 171, "every bundled function, across the sub-categories"); + let expected = fixture::library().packages["sbs://functions.sbs"].graphs.iter().filter(|graph| graph.function.is_some()).count(); + assert_eq!(functions.len(), expected, "every bundled function, across the sub-categories"); assert!(entries(&mut session, json!({})).iter().all(|entry| entry["missing"].is_null())); assert!(entries(&mut session, json!({"category": "Texture generators"})).is_empty()); let functions = entries(&mut session, json!({"canvas": "function", "filter": "pi"})); assert!(functions.iter().any(|entry| entry["id"] == "sbs://functions.sbs#Functions/Math/Pi" && entry["type"] == "functionInstance")); - assert!(functions.iter().all(|entry| entry["canvas"] == "function")); + assert!(functions.iter().all(|entry| entry["canvas"] == "function" || entry["canvas"] == "any")); assert!(execute(&mut session, "library.tree", &json!({"canvas": "teapot"})).is_err()); } +/// Library additions use compatible canvases and participate in undo. #[test] fn library_entries_add_to_the_graph_they_fit() { - let mut session = new_session(); + let mut session = fixture::session(); let before = session.graph().unwrap().nodes.len(); let added = execute(&mut session, "library.add", &json!({"entry": "node:blur", "at": [32.0, 64.0]})).unwrap(); assert_eq!(added["entry"], "node:blur"); @@ -51,6 +58,7 @@ fn library_entries_add_to_the_graph_they_fit() { assert!(execute(&mut session, "library.add", &json!({"entry": "nothing"})).is_err()); assert!(execute(&mut session, "library.add", &json!({})).is_err()); + // Function entries need a Function canvas assert!(execute(&mut session, "library.add", &json!({"entry": "function:add"})).is_err()); assert!(execute(&mut session, "library.add", &json!({"entry": "pattern:paramset"})).is_err()); @@ -59,7 +67,7 @@ fn library_entries_add_to_the_graph_they_fit() { let mut graph = Graph::new("Caller"); graph.function = Some(FunctionGraph::default()); package.graphs.push(graph); - let mut session = Session::new(package); + let mut session = Session::with_library(package, fixture::library()); execute(&mut session, "library.add", &json!({"entry": "function:add", "at": [0.0, 0.0]})).unwrap(); execute(&mut session, "library.add", &json!({"entry": "sbs://functions.sbs#Functions/Math/Pi", "at": [140.0, 0.0]})).unwrap(); let function = session.graph().unwrap().function.as_ref().unwrap(); @@ -71,12 +79,32 @@ fn library_entries_add_to_the_graph_they_fit() { assert_eq!(session.graph().unwrap().function.as_ref().unwrap().nodes.len(), 1); } +/// Reload reports the installed catalog without modifying an unrelated graph. #[test] fn reloading_the_library_keeps_open_work_unmodified() { - let mut session = new_session(); + let mut session = fixture::session(); let reloaded = execute(&mut session, "library.reload", &json!({})).unwrap(); - assert!(reloaded["entries"].as_u64().unwrap() > 250); - assert_eq!(reloaded["available"], reloaded["entries"]); + let entries = session.library_entries(); + assert_eq!(reloaded["entries"].as_u64(), Some(entries.len() as u64)); + assert_eq!(reloaded["available"].as_u64(), Some(entries.iter().filter(|entry| entry.missing.is_none()).count() as u64)); assert!(!session.modified); - assert!(session.pkg.dependencies.contains_key("sbs://functions.sbs")); + assert!(session.library.packages.keys().all(|path| session.pkg.dependencies.contains_key(path))); +} + +/// Reload must retain an explicitly supplied package even when its alias matches the library. +#[test] +fn review_reload_preserves_user_library_alias() { + let mut dependency = Package::new("User functions"); + let mut function = Graph::new("User_function"); + function.function = Some(FunctionGraph::default()); + dependency.graphs.push(function); + let mut package = Package::new("Project"); + package.graphs.push(Graph::new("Material")); + package.dependencies.insert("sbs://functions.sbs".into(), std::sync::Arc::new(dependency.clone())); + let mut session = Session::with_library(package, fixture::library()); + + execute(&mut session, "library.reload", &json!({})).unwrap(); + + assert!(session.pkg.dependencies["sbs://functions.sbs"].graphs == dependency.graphs, "the user dependency was replaced"); + assert!(entries(&mut session, json!({})).iter().any(|entry| entry["id"] == "sbs://functions.sbs#User_function")); } diff --git a/crates/engine/tests/support/node_library.rs b/crates/engine/tests/support/node_library.rs new file mode 100644 index 00000000..1af8ecd8 --- /dev/null +++ b/crates/engine/tests/support/node_library.rs @@ -0,0 +1,27 @@ +//! An isolated catalog fixture shared by the library unit and integration tests. + +use materialcraft_core::{Graph, Package}; +use materialcraft_engine::{NodeLibrary, Session}; +use std::sync::{Arc, OnceLock}; + +/// Load only the embedded functions, independent of the installed library directory. +pub fn library() -> Arc<NodeLibrary> { + static LIBRARY: OnceLock<Arc<NodeLibrary>> = OnceLock::new(); + LIBRARY + .get_or_init(|| { + let read = materialcraft_formats::sbs::read_sbs(include_bytes!("../../../../assets/sbs/functions.sbs"), "sbs://functions.sbs", &|_| None).unwrap(); + assert!(read.warnings.is_empty(), "{:?}", read.warnings); + let mut library = NodeLibrary::default(); + library.packages.insert("sbs://functions.sbs".into(), Arc::new(read.pkg)); + Arc::new(library) + }) + .clone() +} + +/// Start an empty material graph with the isolated bundled library. +#[allow(dead_code)] +pub fn session() -> Session { + let mut package = Package::new("Library tests"); + package.graphs.push(Graph::new("Material")); + Session::with_library(package, library()) +} diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index ee5991bb..46845311 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -265,7 +265,11 @@ fn input_change_recooks_only_readers() { value: Some(Value::Text("a".into())), pos: [0.0; 2], }; - p.graphs[0].node_mut(reader).unwrap().params.insert("function".into(), Value::Function(Box::new(FunctionGraph { nodes: vec![get_a], output: Some(1) }))); + p.graphs[0] + .node_mut(reader) + .unwrap() + .params + .insert("function".into(), Value::Function(Box::new(FunctionGraph { nodes: vec![get_a], output: Some(1), ..Default::default() }))); let cache = &Mutex::new(Cache::default()); let mut opts = Options::new(&no_res); opts.overrides.insert("a".into(), Value::Float(0.25)); diff --git a/crates/formats/examples/standard_function_library/convert.rs b/crates/formats/examples/standard_function_library/convert.rs index 6c88540c..19e7912e 100644 --- a/crates/formats/examples/standard_function_library/convert.rs +++ b/crates/formats/examples/standard_function_library/convert.rs @@ -32,11 +32,9 @@ pub(super) fn package(bytes: &[u8], source: &str) -> Result<Package, Box<dyn std graph.exposed.iter().map(|parameter| parameter.id.as_str()).collect::<Vec<_>>().join(", ") }; graph.attributes.description = format!("Evaluates the {} function graph. Result type: {}. Inputs: {inputs}.", graph.name, result.label()); - graph.attributes.category = graph.folder.clone(); graph.attributes.author.clear(); graph.attributes.author_url.clear(); graph.attributes.user_data.clear(); - graph.attributes.tags.clear(); graph.frames.clear(); graph.comments.clear(); graph.pins.clear(); diff --git a/crates/formats/examples/standard_function_library/tests.rs b/crates/formats/examples/standard_function_library/tests.rs index 45bcdff8..1d82f19e 100644 --- a/crates/formats/examples/standard_function_library/tests.rs +++ b/crates/formats/examples/standard_function_library/tests.rs @@ -10,7 +10,8 @@ fn conversion_preserves_function_bodies_and_replaces_presentation_metadata() { graph.attributes.author = "Source author".into(); graph.attributes.author_url = "https://example.org/source".into(); graph.attributes.user_data = "Source notes".into(); - graph.attributes.tags = "Source tags".into(); + graph.attributes.category = "Function".into(); + graph.attributes.tags = "Maths".into(); graph.function_type = 256; let mut body = FunctionGraph::default(); let left = body.add_constant(Value::Float(1.0)); @@ -30,7 +31,10 @@ fn conversion_preserves_function_bodies_and_replaces_presentation_metadata() { assert!(converted.graphs[0].attributes.author.is_empty()); assert!(converted.graphs[0].attributes.author_url.is_empty()); assert!(converted.graphs[0].attributes.user_data.is_empty()); - assert!(converted.graphs[0].attributes.tags.is_empty()); + assert_eq!(converted.graphs[0].attributes.category, "Function"); + assert_eq!(converted.graphs[0].attributes.tags, "Maths"); + assert_eq!(reopened.graphs[0].attributes.category, "Function"); + assert_eq!(reopened.graphs[0].attributes.tags, "Maths"); assert_eq!(converted.graphs[0].function, reopened.graphs[0].function); let mut restored = converted.graphs[0].function.clone().unwrap(); let original = imported.graphs[0].function.as_ref().unwrap(); @@ -64,3 +68,21 @@ fn layout_separates_nodes_and_rejects_invalid_connections_without_partial_edits( function.nodes[0].inputs = vec![Some(9999)]; assert!(super::layout::reposition(&mut function).unwrap_err().contains("missing node")); } + +#[test] +fn conversion_preserves_empty_classification_attributes() { + let mut package = Package::new("Functions"); + let mut graph = Graph::new("EmptyMetadata"); + graph.folder = "Functions/Math".into(); + let mut function = FunctionGraph::default(); + function.output = Some(function.add_constant(Value::Float(1.0))); + graph.function = Some(function); + graph.function_type = 256; + package.graphs.push(graph); + let bytes = write_sbs(&package).unwrap(); + + let converted = super::convert::package(&bytes, "source.sbs").unwrap(); + + assert!(converted.graphs[0].attributes.category.is_empty()); + assert!(converted.graphs[0].attributes.tags.is_empty()); +} diff --git a/crates/formats/src/sbs/canvas.rs b/crates/formats/src/sbs/canvas.rs index c4d536f7..1aec328f 100644 --- a/crates/formats/src/sbs/canvas.rs +++ b/crates/formats/src/sbs/canvas.rs @@ -8,9 +8,13 @@ use roxmltree::Node as XmlNode; use std::fmt::Write as _; pub(super) fn write_canvas_items(output: &mut String, graph: &Graph, writer: &mut SbsWriter) { + write_items(output, &graph.frames, &graph.comments, &graph.pins, writer); +} + +pub(super) fn write_items(output: &mut String, frames: &[Frame], comments: &[Comment], pins: &[Pin], writer: &mut SbsWriter) { output.push_str("<GUIObjects>"); - for frame in &graph.frames { + for frame in frames { let [x, y, width, height] = frame.rect.map(format_float); let [red, green, blue] = [0, 1, 2].map(|channel| format_float(linear_to_srgb(frame.color[channel]))); let _ = write!( @@ -24,7 +28,7 @@ pub(super) fn write_canvas_items(output: &mut String, graph: &Graph, writer: &mu ); } - for comment in &graph.comments { + for comment in comments { let [x, y] = comment.pos.map(format_float); let [width, height] = comment.size.map(format_float); let _ = write!( @@ -35,7 +39,7 @@ pub(super) fn write_canvas_items(output: &mut String, graph: &Graph, writer: &mu ); } - for pin in &graph.pins { + for pin in pins { let [x, y] = pin.pos.map(format_float); let _ = write!( output, @@ -85,3 +89,10 @@ pub(super) fn read_canvas_items(element: XmlNode, graph: &mut Graph, warnings: & } } } + +/// Embedded canvases use the same GUIObjects schema as document graphs. +pub(super) fn read_embedded(element: XmlNode) -> materialcraft_core::CanvasAnnotations { + let mut graph = Graph::new("embedded"); + read_canvas_items(element, &mut graph, &mut Warnings::default()); + materialcraft_core::CanvasAnnotations { frames: graph.frames, comments: graph.comments, pins: graph.pins } +} diff --git a/crates/formats/src/sbs/function_graph.rs b/crates/formats/src/sbs/function_graph.rs index f07c4ea7..fee5210e 100644 --- a/crates/formats/src/sbs/function_graph.rs +++ b/crates/formats/src/sbs/function_graph.rs @@ -8,7 +8,11 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write; pub(super) fn read(element: XmlNode<'_, '_>) -> Result<FunctionGraph, String> { - let mut graph = FunctionGraph { output: child_value(element, "rootnode").and_then(|value| value.parse().ok()), nodes: Vec::new() }; + let mut graph = FunctionGraph { + output: child_value(element, "rootnode").and_then(|value| value.parse().ok()), + nodes: Vec::new(), + annotations: super::canvas::read_embedded(element), + }; let mut ids = BTreeSet::new(); for element in child_element(element, "paramNodes").into_iter().flat_map(|nodes| children_named(nodes, "paramNode")) { if graph.nodes.len() >= 4096 { @@ -153,7 +157,11 @@ pub(super) fn write(graph: &FunctionGraph, writer: &mut SbsWriter) -> Result<Str } output.push_str("</paramNode>"); } - output.push_str("</paramNodes></dynamicValue>"); + output.push_str("</paramNodes>"); + if !graph.annotations.is_empty() { + super::canvas::write_items(&mut output, &graph.annotations.frames, &graph.annotations.comments, &graph.annotations.pins, writer); + } + output.push_str("</dynamicValue>"); Ok(output) } diff --git a/crates/formats/src/sbs/layout_frame.rs b/crates/formats/src/sbs/layout_frame.rs new file mode 100644 index 00000000..4a5396b6 --- /dev/null +++ b/crates/formats/src/sbs/layout_frame.rs @@ -0,0 +1,10 @@ +use super::LayoutItem; + +/// A titled frame and the nodes inside it, top to bottom +#[derive(Clone, Debug, PartialEq)] +pub struct LayoutFrame { + pub title: String, + /// The frame groups function nodes (it sits in a function graph or a parameter function) + pub function: bool, + pub items: Vec<LayoutItem>, +} diff --git a/crates/formats/src/sbs/layout_item.rs b/crates/formats/src/sbs/layout_item.rs new file mode 100644 index 00000000..49450ccc --- /dev/null +++ b/crates/formats/src/sbs/layout_item.rs @@ -0,0 +1,17 @@ +/// One node placed in a layout frame +#[derive(Clone, Debug, PartialEq)] +pub enum LayoutItem { + /// An atomic SBS filter by its SBS name, with the MaterialCraft node it reads as (`None` + /// when MaterialCraft has no counterpart yet) + Atomic { filter: String, node: Option<&'static str> }, + /// A graph input (`input_color`, `input_grayscale`, `input_value`) or `output` + Node(&'static str), + /// An instance of graph `graph` from the library package `package` + Instance { package: String, graph: String, outputs: Vec<String> }, + /// A native function operation, e.g. `add` + Operation(String), + /// An instance of function graph `graph` from the library package `package` + FunctionInstance { package: String, graph: String }, + /// A bitmap showing one of the layout package's own resources, e.g. an environment image + Bitmap { resource: String }, +} diff --git a/crates/formats/src/sbs/library.rs b/crates/formats/src/sbs/library.rs index 535ebeb2..14ada77e 100644 --- a/crates/formats/src/sbs/library.rs +++ b/crates/formats/src/sbs/library.rs @@ -10,6 +10,7 @@ pub fn relative_path(uri: &str) -> Result<&str, String> { { return Err("invalid SBS library path".into()); } + Ok(path) } @@ -51,15 +52,18 @@ pub fn root() -> std::path::PathBuf { if let Some(root) = std::env::var_os("MATERIALCRAFT_SBS_DIR") { return root.into(); } + if let Ok(executable) = std::env::current_exe() && let Some(parent) = executable.parent() && parent.join("assets/sbs").is_dir() { return parent.join("assets/sbs"); } + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/sbs") } +/// Read a validated library alias from the configured directory or the embedded fallback. pub fn read(uri: &str) -> Result<Vec<u8>, String> { let relative = relative_path(uri)?; #[cfg(not(target_arch = "wasm32"))] @@ -106,6 +110,7 @@ pub fn files() -> Vec<String> { BUNDLED.iter().map(|uri| uri.to_string()).collect() } +/// Discover packages in deterministic order within the depth and file limits. #[cfg(not(target_arch = "wasm32"))] fn scan(directory: &std::path::Path, prefix: &str, depth: usize, found: &mut Vec<String>) { let Ok(entries) = std::fs::read_dir(directory) else { return }; @@ -115,9 +120,11 @@ fn scan(directory: &std::path::Path, prefix: &str, depth: usize, found: &mut Vec if found.len() >= MAX_FILES { return; } + let Some(name) = entry.file_name().to_str().map(str::to_string) else { continue }; let Ok(kind) = entry.file_type() else { continue }; let uri = format!("sbs://{prefix}{name}"); + // Symlinks are skipped: `read` refuses files that leave the asset folder anyway if kind.is_dir() && depth < MAX_DEPTH && !name.ends_with(".resources") && !name.starts_with('.') { scan(&entry.path(), &format!("{prefix}{name}/"), depth + 1, found); @@ -132,6 +139,7 @@ fn scan(directory: &std::path::Path, prefix: &str, depth: usize, found: &mut Vec mod tests { use super::*; + /// Discovered packages have unique valid aliases and the embedded fallback is present. #[test] fn the_library_lists_every_package_once_and_bundles_a_fallback() { let files = files(); diff --git a/crates/formats/src/sbs/library_layout.rs b/crates/formats/src/sbs/library_layout.rs index c127a157..8dff9d69 100644 --- a/crates/formats/src/sbs/library_layout.rs +++ b/crates/formats/src/sbs/library_layout.rs @@ -4,6 +4,7 @@ //! which frame titles are library categories. use super::{ + LayoutFrame, LayoutItem, constant::MAX_XML_NODES, filter_map::FILTERS, xml::{child_element, child_value, children_named, parse_floats}, @@ -16,33 +17,6 @@ use std::collections::HashMap; const MAX_FRAMES: usize = 4096; const MAX_ITEMS: usize = 65_536; -/// A titled frame and the nodes inside it, top to bottom -#[derive(Clone, Debug, PartialEq)] -pub struct LayoutFrame { - pub title: String, - /// The frame groups function nodes (it sits in a function graph or a parameter function) - pub function: bool, - pub items: Vec<LayoutItem>, -} - -/// One node placed in a layout frame -#[derive(Clone, Debug, PartialEq)] -pub enum LayoutItem { - /// An atomic SBS filter by its SBS name, with the MaterialCraft node it reads as (`None` - /// when MaterialCraft has no counterpart yet) - Atomic { filter: String, node: Option<&'static str> }, - /// A graph input (`input_color`, `input_grayscale`, `input_value`) or `output` - Node(&'static str), - /// An instance of graph `graph` from the library package `package` - Instance { package: String, graph: String, outputs: Vec<String> }, - /// A native function operation, e.g. `add` - Operation(String), - /// An instance of function graph `graph` from the library package `package` - FunctionInstance { package: String, graph: String }, - /// A bitmap showing one of the layout package's own resources, e.g. an environment image - Bitmap { resource: String }, -} - /// The frames of every graph and parameter function in `bytes`, in document order pub fn read_layout(bytes: &[u8], uri: &str) -> Result<Vec<LayoutFrame>> { let text = std::str::from_utf8(bytes).map_err(|e| FormatError::BadPackage(format!("the SBS file is not UTF-8 text: {e}")))?; @@ -57,8 +31,8 @@ pub fn read_layout(bytes: &[u8], uri: &str) -> Result<Vec<LayoutFrame>> { let mut dependencies = HashMap::new(); for dependency in child_element(root, "dependencies").into_iter().flat_map(|d| children_named(d, "dependency")) { if let (Some(uid), Some(file)) = (child_value(dependency, "uid"), child_value(dependency, "filename")) { - let file = if file == "?himself" { uri } else { file }; - dependencies.insert(uid, file.to_string()); + let file = if file == "?himself" { uri.to_string() } else { super::library::resolve(uri, file).map_err(FormatError::BadPackage)? }; + dependencies.insert(uid, file); } } @@ -85,6 +59,7 @@ pub fn read_layout(bytes: &[u8], uri: &str) -> Result<Vec<LayoutFrame>> { if items >= MAX_ITEMS { break; } + // The smallest frame holding the node wins, so nested frames keep their own nodes let Some(frame) = scope_frames .iter() @@ -95,6 +70,7 @@ pub fn read_layout(bytes: &[u8], uri: &str) -> Result<Vec<LayoutFrame>> { else { continue; }; + let item = if function { function_item(node, &dependencies) } else { graph_item(scope, node, &dependencies) }; if let Some(item) = item { placed.push((frame, at, item)); @@ -112,6 +88,7 @@ pub fn read_layout(bytes: &[u8], uri: &str) -> Result<Vec<LayoutFrame>> { if frames.len() >= MAX_FRAMES { break; } + frames.push(LayoutFrame { title, function, items }); } } @@ -136,6 +113,7 @@ fn scope_frames(scope: XmlNode) -> Vec<(String, [f32; 4])> { .collect() } +/// Read a node position when its layout has both coordinates. fn position(node: XmlNode) -> Option<[f32; 2]> { let at = parse_floats(child_value(child_element(node, "GUILayout")?, "gpos")?); Some([*at.first()?, *at.get(1)?]) @@ -151,6 +129,7 @@ fn reference(path: &str, dependencies: &HashMap<&str, String>) -> Option<(String (!graph.is_empty()).then(|| (graph.chars().take(1024).collect(), package)) } +/// Translate a graph node into a library placement without cooking it. fn graph_item(graph: XmlNode, node: XmlNode, dependencies: &HashMap<&str, String>) -> Option<LayoutItem> { let implementation = child_element(node, "compImplementation")?.children().find(|c| c.is_element())?; match implementation.tag_name().name() { @@ -163,6 +142,7 @@ fn graph_item(graph: XmlNode, node: XmlNode, dependencies: &HashMap<&str, String let resource = resource.split_once('?').map_or(resource, |(path, _)| path); return Some(LayoutItem::Bitmap { resource: resource.chars().take(1024).collect() }); } + Some(LayoutItem::Atomic { filter: filter.chars().take(128).collect(), node: FILTERS.iter().find(|f| f.sbs == filter).map(|f| f.def) }) } "compInstance" => { @@ -193,6 +173,7 @@ fn graph_item(graph: XmlNode, node: XmlNode, dependencies: &HashMap<&str, String } } +/// Translate a native operation or reusable function reference into a placement. fn function_item(node: XmlNode, dependencies: &HashMap<&str, String>) -> Option<LayoutItem> { let operation = child_value(node, "function")?; if operation != "instance" { @@ -209,6 +190,7 @@ fn function_item(node: XmlNode, dependencies: &HashMap<&str, String>) -> Option< Some(LayoutItem::FunctionInstance { package, graph }) } +/// Read a named static string parameter from an atomic filter. fn string_parameter<'a>(filter: XmlNode<'a, '_>, name: &str) -> Option<&'a str> { child_element(filter, "parameters") .into_iter() @@ -251,6 +233,7 @@ mod tests { <GUIObject><type v="COMMENT"/><GUILayout><gpos v="0 0 0"/><size v="10 10"/></GUILayout></GUIObject> </GUIObjects></graph></content></package>"#; + /// Frames preserve spatial ordering and distinguish material and function entries. #[test] fn frames_list_what_sits_inside_them_top_to_bottom() { let frames = read_layout(LAYOUT.as_bytes(), "sbs://layout.sbs").unwrap(); @@ -274,6 +257,7 @@ mod tests { assert_eq!(function[1].items, vec![LayoutItem::FunctionInstance { package: "sbs://functions.sbs".into(), graph: "Functions/Math/Pi".into() }]); } + /// Missing layouts and malformed input remain nonfatal. #[test] fn packages_without_frames_have_no_layout_and_bad_input_errors() { assert!(read_layout(b"<package><content><graph><compNodes/></graph></content></package>", "sbs://x.sbs").unwrap().is_empty()); @@ -281,4 +265,17 @@ mod tests { assert!(read_layout(b"\xff\xfe", "sbs://x.sbs").is_err()); assert!(read_layout(b"<package><content><graph><compNodes><compNode><GUILayout><gpos v=\"nan\"/></GUILayout></compNode></compNodes><GUIObjects><GUIObject><type v=\"COMMENT\"/><GUILayout><gpos v=\"0 0\"/><size v=\"-5 1e40\"/></GUILayout><title v=\"X\"/></GUIObject></GUIObjects></graph></content></package>", "sbs://x.sbs").unwrap().is_empty()); } + + /// Relative layout references resolve beside the layout, including parent directories. + #[test] + fn review_layout_resolves_relative_dependencies() { + let layout = LAYOUT.replace("sbs://noise.sbs", "../noise.sbs").replace("sbs://functions.sbs", "functions.sbs"); + + let frames = read_layout(layout.as_bytes(), "sbs://layouts/library.sbs").unwrap(); + + assert!(frames.iter().flat_map(|frame| &frame.items).any(|item| matches!(item, + LayoutItem::Instance { package, .. } if package == "sbs://noise.sbs"))); + assert!(frames.iter().flat_map(|frame| &frame.items).any(|item| matches!(item, + LayoutItem::FunctionInstance { package, .. } if package == "sbs://layouts/functions.sbs"))); + } } diff --git a/crates/formats/src/sbs/mod.rs b/crates/formats/src/sbs/mod.rs index ea54381d..583e6d6e 100644 --- a/crates/formats/src/sbs/mod.rs +++ b/crates/formats/src/sbs/mod.rs @@ -11,6 +11,8 @@ mod graph_attributes; mod group_layout; mod image_input; mod input_bridge; +mod layout_frame; +mod layout_item; pub mod library; mod library_layout; mod node_identifiers; @@ -30,7 +32,9 @@ mod warnings; mod xml; pub use constant::SBS_EXT; -pub use library_layout::{LayoutFrame, LayoutItem, read_layout}; +pub use layout_frame::LayoutFrame; +pub use layout_item::LayoutItem; +pub use library_layout::read_layout; pub use read::{is_sbs, read_sbs}; pub use sbs_read::SbsRead; pub use write::write_sbs; diff --git a/crates/formats/src/sbs/pattern_graph.rs b/crates/formats/src/sbs/pattern_graph.rs index 6e707ad3..6fa72c8c 100644 --- a/crates/formats/src/sbs/pattern_graph.rs +++ b/crates/formats/src/sbs/pattern_graph.rs @@ -32,7 +32,11 @@ pub(super) fn read(element: XmlNode<'_, '_>) -> Result<PatternGraph, String> { } } - let mut graph = PatternGraph { root: child_value(element, "rootnode").and_then(|id| id.parse().ok()), nodes: Vec::new() }; + let mut graph = PatternGraph { + root: child_value(element, "rootnode").and_then(|id| id.parse().ok()), + nodes: Vec::new(), + annotations: super::canvas::read_embedded(element), + }; for element in child_element(element, "paramsGraphNodes").into_iter().flat_map(|nodes| children_named(nodes, "paramsGraphNode")) { if graph.nodes.len() >= 4096 { return Err("pattern graph exceeds the 4096-node limit".into()); @@ -111,6 +115,10 @@ pub(super) fn write(graph: &PatternGraph, writer: &mut SbsWriter) -> Result<Stri } output.push_str("</connections></paramsGraphNode>"); } - output.push_str("</paramsGraphNodes></paramsGraph></paramsGraphs>"); + output.push_str("</paramsGraphNodes>"); + if !graph.annotations.is_empty() { + super::canvas::write_items(&mut output, &graph.annotations.frames, &graph.annotations.comments, &graph.annotations.pins, writer); + } + output.push_str("</paramsGraph></paramsGraphs>"); Ok(output) } diff --git a/crates/formats/src/sbs/sbs_reader.rs b/crates/formats/src/sbs/sbs_reader.rs index a945775b..52552dbc 100644 --- a/crates/formats/src/sbs/sbs_reader.rs +++ b/crates/formats/src/sbs/sbs_reader.rs @@ -184,7 +184,10 @@ impl<'text> SbsReader<'text, '_> { let dynamic = child_element(element, "paramValue").and_then(|value| child_element(value, "dynamicValue")); let function = dynamic.ok_or_else(|| "missing function body".to_string()).and_then(super::function_graph::read); graph.function = Some(match function { - Ok(function) => function, + Ok(mut function) => { + function.annotations = Default::default(); + function + } Err(error) => { self.warnings.add(format!("function graph `{name}`: {error}")); materialcraft_core::FunctionGraph::default() diff --git a/crates/formats/tests/function_library.rs b/crates/formats/tests/function_library.rs index 6b0d5e9e..2a4bd944 100644 --- a/crates/formats/tests/function_library.rs +++ b/crates/formats/tests/function_library.rs @@ -167,9 +167,19 @@ fn bundled_library_has_complete_bodies_and_current_export_metadata() { assert!(function.output.is_some(), "{}", graph.sbs_path()); assert!(function.nodes.iter().all(|node| node.missing.is_none()), "{}", graph.sbs_path()); assert!(!graph.attributes.description.is_empty()); - assert!(graph.attributes.author.is_empty() && graph.attributes.tags.is_empty()); + assert!(graph.attributes.author.is_empty()); assert!(graph.frames.is_empty() && graph.comments.is_empty() && graph.pins.is_empty()); } + let pi = &read.pkg.graph_by_name("Functions/Math/Pi").unwrap().1.attributes; + assert!(pi.category.is_empty()); + assert_eq!(pi.tags, "Constant"); + let saved = write_sbs(&read.pkg).unwrap(); + let reopened = read_sbs(&saved, "functions.sbs", &|_| None).unwrap(); + for graph in &read.pkg.graphs { + let reloaded = reopened.pkg.graph_by_name(&graph.sbs_path()).unwrap().1; + assert_eq!(reloaded.attributes.category, graph.attributes.category); + assert_eq!(reloaded.attributes.tags, graph.attributes.tags); + } assert!(!xml.descendants().any(|element| element.has_tag_name("icon"))); } diff --git a/crates/ui-egui/src/annotation/comment_properties.rs b/crates/ui-egui/src/annotation/comment_properties.rs index a073e422..bdaa9507 100644 --- a/crates/ui-egui/src/annotation/comment_properties.rs +++ b/crates/ui-egui/src/annotation/comment_properties.rs @@ -3,7 +3,13 @@ use egui::Ui; use serde_json::json; pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, id: u64) { - let Some(mut text) = app.session.graph().ok().and_then(|graph| graph.comments.iter().find(|comment| comment.id == id)).map(|comment| comment.text.clone()) + let Some(mut text) = app + .session + .annotation_target + .items(&app.session) + .ok() + .and_then(|items| items.comments.into_iter().find(|comment| comment.id == id)) + .map(|comment| comment.text) else { return; }; diff --git a/crates/ui-egui/src/annotation/frame_properties.rs b/crates/ui-egui/src/annotation/frame_properties.rs index 7cc12e97..0748b6a0 100644 --- a/crates/ui-egui/src/annotation/frame_properties.rs +++ b/crates/ui-egui/src/annotation/frame_properties.rs @@ -3,7 +3,7 @@ use egui::Ui; use serde_json::json; pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, id: u64) { - let Some(mut frame) = app.session.graph().ok().and_then(|graph| graph.frames.iter().find(|frame| frame.id == id)).cloned() else { + let Some(mut frame) = app.session.annotation_target.items(&app.session).ok().and_then(|items| items.frames.into_iter().find(|frame| frame.id == id)) else { return; }; diff --git a/crates/ui-egui/src/annotation/mod.rs b/crates/ui-egui/src/annotation/mod.rs index 3068951f..afe078da 100644 --- a/crates/ui-egui/src/annotation/mod.rs +++ b/crates/ui-egui/src/annotation/mod.rs @@ -1,5 +1,6 @@ mod comment_properties; mod frame_properties; +mod pin_properties; use crate::MaterialCraftApp; use egui::Ui; @@ -9,5 +10,42 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, selection: Annotatio match selection { AnnotationSelection::Frame(id) => frame_properties::show(app, ui, id), AnnotationSelection::Comment(id) => comment_properties::show(app, ui, id), + AnnotationSelection::Pin(id) => pin_properties::show(app, ui, id), + } +} + +/// Resolve the destination before an editor is temporarily borrowed for drawing. +pub(crate) fn target(app: &MaterialCraftApp) -> materialcraft_engine::AnnotationTarget { + use materialcraft_engine::{AnnotationTarget, FunctionGraphTarget}; + if let Some(target) = app.function_editor.as_ref().and_then(|editor| editor.command_target()) { + return match target { + FunctionGraphTarget::Graph => AnnotationTarget::Graph, + target => AnnotationTarget::Function { target }, + }; + } + if crate::pattern::active(app) + && let Some(editor) = &app.pattern_editor + { + return AnnotationTarget::Pattern { owner: editor.node }; + } + AnnotationTarget::Graph +} + +pub(crate) fn activate(app: &mut MaterialCraftApp, target: materialcraft_engine::AnnotationTarget) { + if app.graph.annotation_target != target { + app.session.annotation_selection = None; + app.graph.cancel_drag(); + } + app.graph.annotation_target = target; +} + +/// Read the active editor camera without replacing the parent graph's saved view. +pub(crate) fn camera(app: &MaterialCraftApp) -> crate::state::GraphCamera { + if let Some(editor) = &app.function_editor { + editor.camera() + } else if let Some(editor) = &app.pattern_editor { + editor.camera() + } else { + app.ui.graph_camera } } diff --git a/crates/ui-egui/src/annotation/pin_properties.rs b/crates/ui-egui/src/annotation/pin_properties.rs new file mode 100644 index 00000000..c6d4b4ac --- /dev/null +++ b/crates/ui-egui/src/annotation/pin_properties.rs @@ -0,0 +1,28 @@ +use crate::{MaterialCraftApp, i18n::tr}; +use egui::Ui; +use serde_json::json; + +/// The SBS pin label is edited as its Description property. +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, id: u64) { + let Some(mut name) = + app.session.annotation_target.items(&app.session).ok().and_then(|items| items.pins.into_iter().find(|pin| pin.id == id)).map(|pin| pin.name) + else { + return; + }; + + crate::properties::section(ui, "pin-parameters", tr("Parameters"), |ui| { + ui.label(tr("Description")); + let description = ui.add(egui::TextEdit::multiline(&mut name).desired_rows(4).desired_width(f32::INFINITY)); + crate::widgets::name(&description, egui::Role::TextInput, "Navigation Pin description"); + if app.graph.pin_description_focus == Some(id) { + description.request_focus(); + app.graph.pin_description_focus = None; + } + if description.changed() { + app.run("graph.pin.edit", json!({"id": id, "description": name})); + } + if description.lost_focus() { + app.session.finish_edit(); + } + }); +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 127fffc5..90f9df9a 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -311,6 +311,8 @@ fn handle_inner(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p crate::graph::editor_target::EditorTarget::Material => None, }, "annotationSelection": app.session.annotation_selection, + "annotationTarget": app.session.annotation_target, + "pins": app.graph.pins.iter().map(|(id, bounds)| json!({"id": id, "rect": rect(*bounds)})).collect::<Vec<_>>(), "frames": app.graph.frames.iter().map(|(id, bounds)| json!({"id": id, "rect": rect(*bounds)})).collect::<Vec<_>>(), "comments": app.graph.comments.iter().map(|(id, bounds)| json!({"id": id, "rect": rect(*bounds)})).collect::<Vec<_>>(), "nodes": nodes.iter().map(|(id, r)| json!({"id": id.0, "rect": rect(*r)})).collect::<Vec<_>>(), diff --git a/crates/ui-egui/src/explorer.rs b/crates/ui-egui/src/explorer.rs index 81cbcdbe..b0301797 100644 --- a/crates/ui-egui/src/explorer.rs +++ b/crates/ui-egui/src/explorer.rs @@ -4,6 +4,8 @@ use egui::Ui; mod actions; mod context_menu; +mod explorer_menu_state; +pub(crate) mod explorer_row; mod explorer_state; mod explorer_target; mod explorer_tree; @@ -16,6 +18,7 @@ use serde_json::json; use crate::MaterialCraftApp; use crate::i18n::tr; +/// Draw open packages and dispatch selection, resource and context-menu actions. pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 2.0; @@ -115,9 +118,10 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { /// Enter opens, F2 renames and Delete removes the selected graph or folder while the pointer is /// over the Explorer; elsewhere those keys keep their graph shortcuts. True when a key was used pub(crate) fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) -> bool { - if !app.ui.explorer.hovered || app.ui.explorer.rename.is_some() { + if !app.ui.dock.is_visible(crate::docking::Panel::Explorer) || !app.ui.explorer.hovered || app.ui.explorer.rename.is_some() { return false; } + let Some(target) = app.ui.explorer.selected.clone() else { return false }; let command = match &target { ExplorerTarget::Graph { .. } => [(egui::Key::Enter, "graph.open"), (egui::Key::F2, "graph.rename"), (egui::Key::Delete, "graph.delete")] @@ -134,10 +138,12 @@ pub(crate) fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) -> bool true } +/// Match an unmodified Explorer shortcut key. fn pressed(ctx: &egui::Context, key: egui::Key) -> bool { ctx.input(|input| input.modifiers.is_none() && input.key_pressed(key)) } +/// Draw the pending Explorer rename dialog. pub(crate) fn dialogs(app: &mut MaterialCraftApp, ctx: &egui::Context) { actions::rename_dialog(app, ctx); } diff --git a/crates/ui-egui/src/explorer/actions.rs b/crates/ui-egui/src/explorer/actions.rs index b04b9081..aa08cc9b 100644 --- a/crates/ui-egui/src/explorer/actions.rs +++ b/crates/ui-egui/src/explorer/actions.rs @@ -2,10 +2,12 @@ use super::ExplorerTarget; use crate::{MaterialCraftApp, i18n::tr}; use serde_json::json; +/// Activate the target package before dispatching its Explorer action. pub(super) fn activate(app: &mut MaterialCraftApp, document: u64) -> bool { document == app.session.document_id || app.run("package.activate", json!({"document": document})).is_some() } +/// Dispatch an Explorer action using the selected item and its owning package. pub(super) fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, target: ExplorerTarget, command: &str) { if command == "graph.resource.add" { let mut parameters = target.parameters(); @@ -106,11 +108,13 @@ fn compute_outputs(app: &mut MaterialCraftApp, target: &ExplorerTarget) { } } +/// Return the active package path for native file actions. #[cfg(not(target_arch = "wasm32"))] fn package_path(app: &MaterialCraftApp) -> Option<String> { app.session.open_packages().into_iter().find(|entry| entry.0 == app.session.document_id).and_then(|entry| entry.2.map(str::to_string)) } +/// Reveal the active package file when supported by the platform. #[cfg(not(target_arch = "wasm32"))] fn show_in_folder(app: &mut MaterialCraftApp) { let Some(path) = package_path(app) else { return }; @@ -119,6 +123,7 @@ fn show_in_folder(app: &mut MaterialCraftApp) { } } +/// Reveal the active package file when supported by the platform. #[cfg(target_arch = "wasm32")] fn show_in_folder(_: &mut MaterialCraftApp) {} @@ -133,9 +138,11 @@ fn open_dependencies(app: &mut MaterialCraftApp) { activate(app, document); } +/// Native dependency-file actions are unavailable in the browser. #[cfg(target_arch = "wasm32")] fn open_dependencies(_: &mut MaterialCraftApp) {} +/// Apply a validated graph or folder rename through the engine. pub(super) fn rename_dialog(app: &mut MaterialCraftApp, ctx: &egui::Context) { let Some((target, mut name)) = app.ui.explorer.rename.clone() else { return }; let mut open = true; diff --git a/crates/ui-egui/src/explorer/context_menu.rs b/crates/ui-egui/src/explorer/context_menu.rs index 0ef82535..3bc73f51 100644 --- a/crates/ui-egui/src/explorer/context_menu.rs +++ b/crates/ui-egui/src/explorer/context_menu.rs @@ -1,38 +1,13 @@ -use super::ExplorerTarget; +use super::{ExplorerTarget, explorer_menu_state::ExplorerMenuState}; use crate::menus::{self, ExplorerRow}; use crate::{i18n::tr, menus::shortcut_label}; -/// What the right-clicked item allows right now -#[derive(Clone, Copy, Debug, Default)] -pub(super) struct MenuState { - /// The Explorer clipboard holds something to paste - pub paste: bool, - /// The package has a file on disk (reload, show in folder) - pub saved: bool, - /// The package links other package files - pub dependencies: bool, - /// The graph (or, for a package, one of its graphs) has image outputs - pub outputs: bool, -} - -impl MenuState { - fn enabled(&self, command: &str) -> bool { - match command { - "" => false, - "explorer.paste" => self.paste, - "file.reload" | menus::EXPLORER_SHOW_IN_FOLDER => self.saved, - menus::EXPLORER_OPEN_DEPENDENCIES => self.dependencies, - menus::EXPLORER_COMPUTE | menus::EXPLORER_VIEW_OUTPUTS | menus::EXPLORER_EXPORT_OUTPUTS => self.outputs, - _ => true, - } - } -} - /// Rows the browser can't offer: it has no folders to show or package files to open fn hidden(command: &str) -> bool { cfg!(target_arch = "wasm32") && matches!(command, menus::EXPLORER_SHOW_IN_FOLDER | menus::EXPLORER_OPEN_DEPENDENCIES) } +/// Draw one action with its shortcut and disabled-state explanation. fn item(ui: &mut egui::Ui, label: &str, command: &'static str, shortcut: Option<&str>, enabled: bool, action: &mut Option<&'static str>) { let mut button = egui::Button::new(tr(label)); if let Some(shortcut) = shortcut { @@ -46,7 +21,8 @@ fn item(ui: &mut egui::Ui, label: &str, command: &'static str, shortcut: Option< } } -fn rows(ui: &mut egui::Ui, rows: &[ExplorerRow], state: &MenuState, resources: bool, action: &mut Option<&'static str>) { +/// Draw menu rows while respecting resource-folder and platform restrictions. +fn rows(ui: &mut egui::Ui, rows: &[ExplorerRow], state: &ExplorerMenuState, resources: bool, action: &mut Option<&'static str>) { for row in rows { match *row { ExplorerRow::Separator => { @@ -63,6 +39,7 @@ fn rows(ui: &mut egui::Ui, rows: &[ExplorerRow], state: &MenuState, resources: b if resources && label == "New" && *command != "folder.create" { continue; } + item(ui, entry, command, None, state.enabled(command), action); } }); @@ -73,7 +50,8 @@ fn rows(ui: &mut egui::Ui, rows: &[ExplorerRow], state: &MenuState, resources: b } } -pub(super) fn show(ui: &mut egui::Ui, target: &ExplorerTarget, state: &MenuState) -> Option<&'static str> { +/// Build the context menu for a package, folder, graph or resource. +pub(super) fn show(ui: &mut egui::Ui, target: &ExplorerTarget, state: &ExplorerMenuState) -> Option<&'static str> { ui.set_min_width(220.0); let mut action = None; let resources = target.is_resources(); diff --git a/crates/ui-egui/src/explorer/explorer_menu_state.rs b/crates/ui-egui/src/explorer/explorer_menu_state.rs new file mode 100644 index 00000000..8ba54fd4 --- /dev/null +++ b/crates/ui-egui/src/explorer/explorer_menu_state.rs @@ -0,0 +1,28 @@ +use crate::menus; + +/// What the right-clicked item allows right now +#[derive(Clone, Copy, Debug, Default)] +pub(super) struct ExplorerMenuState { + /// The Explorer clipboard holds something to paste + pub paste: bool, + /// The package has a file on disk (reload, show in folder) + pub saved: bool, + /// The package links other package files + pub dependencies: bool, + /// The graph (or, for a package, one of its graphs) has image outputs + pub outputs: bool, +} + +impl ExplorerMenuState { + /// Check the selected item supports this context-menu command. + pub(super) fn enabled(&self, command: &str) -> bool { + match command { + "" => false, + "explorer.paste" => self.paste, + "file.reload" | menus::EXPLORER_SHOW_IN_FOLDER => self.saved, + menus::EXPLORER_OPEN_DEPENDENCIES => self.dependencies, + menus::EXPLORER_COMPUTE | menus::EXPLORER_VIEW_OUTPUTS | menus::EXPLORER_EXPORT_OUTPUTS => self.outputs, + _ => true, + } + } +} diff --git a/crates/ui-egui/src/explorer/explorer_row.rs b/crates/ui-egui/src/explorer/explorer_row.rs new file mode 100644 index 00000000..c6b19791 --- /dev/null +++ b/crates/ui-egui/src/explorer/explorer_row.rs @@ -0,0 +1,9 @@ +/// A row of an Explorer context menu +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum ExplorerRow { + /// A label, the action id (empty: not available yet) and the shortcut shown beside it + Item(&'static str, &'static str, Option<&'static str>), + /// A submenu of (label, action id); an empty id is not available yet + Sub(&'static str, &'static [(&'static str, &'static str)]), + Separator, +} diff --git a/crates/ui-egui/src/explorer/explorer_tree.rs b/crates/ui-egui/src/explorer/explorer_tree.rs index 5c80cbe0..9fef6283 100644 --- a/crates/ui-egui/src/explorer/explorer_tree.rs +++ b/crates/ui-egui/src/explorer/explorer_tree.rs @@ -163,7 +163,8 @@ impl ExplorerTree<'_> { _ => package.graphs.iter().any(|graph| graph.function.is_none()), }; let dependencies = package.dependencies.keys().any(|path| super::actions::is_package_file(path)); - let state = context_menu::MenuState { paste: self.session.explorer_clipboard.is_some(), saved: reload, dependencies, outputs }; + let state = + super::explorer_menu_state::ExplorerMenuState { paste: self.session.explorer_clipboard.is_some(), saved: reload, dependencies, outputs }; if let Some(command) = context_menu::show(ui, target, &state) { self.action = Some((target.clone(), command)); } diff --git a/crates/ui-egui/src/function/actions.rs b/crates/ui-egui/src/function/actions.rs index 88f5c4b2..c866979b 100644 --- a/crates/ui-egui/src/function/actions.rs +++ b/crates/ui-egui/src/function/actions.rs @@ -1,4 +1,4 @@ -use super::{FunctionEditor, FunctionTarget}; +use super::FunctionEditor; use crate::MaterialCraftApp; pub(super) fn editor_enabled(app: &MaterialCraftApp, editor: &FunctionEditor, command: &str) -> Option<bool> { @@ -12,8 +12,8 @@ pub(super) fn editor_enabled(app: &MaterialCraftApp, editor: &FunctionEditor, co if let Some(enabled) = crate::graph::wire_actions::enabled(app, command, &editor.selected_wires, target.as_ref()) { return Some(enabled && editor.current(app).is_some()); } - let standalone = matches!(editor.target, FunctionTarget::Graph); - if standalone && app.session.annotation_selection.is_some() && matches!(command, "edit.delete" | "edit.deleteRelink") { + + if app.session.annotation_selection.is_some() && matches!(command, "edit.delete" | "edit.deleteRelink") { return None; } if let Some(target) = editor.command_target() @@ -28,7 +28,7 @@ pub(super) fn editor_enabled(app: &MaterialCraftApp, editor: &FunctionEditor, co } 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, + "ui.graph.previousPin" | "ui.graph.nextPin" | "graph.comment.add" | "graph.frame.add" | "graph.pin.add" => None, command if command.starts_with("graph.") || command.starts_with("ui.graph.") || command.starts_with("edit.") => Some(false), _ => None, } diff --git a/crates/ui-egui/src/function/canvas.rs b/crates/ui-egui/src/function/canvas.rs index 36978e0c..d4007852 100644 --- a/crates/ui-egui/src/function/canvas.rs +++ b/crates/ui-egui/src/function/canvas.rs @@ -11,9 +11,10 @@ pub(super) fn canvas(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui app.ui.frame_all = false; if standalone { 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(); } + app.graph.frames = frame.frames.iter().map(|frame| (frame.id, frame.rect)).collect(); + app.graph.comments = frame.comments.clone(); + app.graph.pins = frame.pins.clone(); if frame.clear_annotation { app.run("graph.annotation.select", json!({})); } @@ -30,25 +31,24 @@ pub(super) fn canvas(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui super::context_menu::show(app, editor, ui, Some(*id)); }); } - 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))); + 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)) + || frame.pins.iter().any(|(_, rect)| rect.contains(pointer)) + }); super::input::handle(app, editor, ui, &frame.response, &frame.ports, &frame.geometry, on_annotation); frame.geometry.publish(&mut app.graph, frame.response.rect); - if standalone { - if editor.drag.is_none() { - 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(); - editor.selected_wires.clear(); - } + if editor.drag.is_none() { + 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, &frame.pins); + if app.session.annotation_selection.is_some() { + editor.selection.clear(); + editor.selected_wires.clear(); } - app.ui.graph_camera = crate::state::GraphCamera { pan: editor.pan.into(), zoom: editor.zoom }; + } + if standalone { + app.ui.graph_camera = editor.camera(); 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); } diff --git a/crates/ui-egui/src/function/context_menu.rs b/crates/ui-egui/src/function/context_menu.rs index 98b0b126..84befd3c 100644 --- a/crates/ui-egui/src/function/context_menu.rs +++ b/crates/ui-egui/src/function/context_menu.rs @@ -1,4 +1,4 @@ -use super::{FunctionEditor, FunctionTarget}; +use super::FunctionEditor; use crate::{MaterialCraftApp, graph::edit_menu, i18n::tr, menus}; use egui::Ui; use materialcraft_engine::FunctionEdit; @@ -54,14 +54,13 @@ fn background_actions(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, u let Some(target) = editor.command_target() else { return }; let mut add = None; - let standalone = matches!(editor.target, FunctionTarget::Graph); ui.menu_button(tr("Add node"), |ui| { let entries = target.available_operations(&app.session).filter(|operation| operation.id != "passthrough").map(|operation| (operation.id, operation.label, "")); add = crate::graph::add_node_menu::show(app, ui, entries); }); annotations(app, editor, ui); - if edit_menu::button(ui, "Add Navigation pin", "graph.pin.add", standalone) { + if edit_menu::button(ui, "Add Navigation pin", "graph.pin.add", true) { app.run("graph.pin.add", json!({"at": [editor.menu_at.x, editor.menu_at.y]})); editor.selection.clear(); } @@ -77,7 +76,7 @@ fn background_actions(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, u selection_action(app, editor, ui, label, command); } for (label, command) in [("Previous pin", "ui.graph.previousPin"), ("Next pin", "ui.graph.nextPin")] { - if edit_menu::button(ui, label, command, standalone && menus::enabled(app, command)) { + if edit_menu::button(ui, label, command, menus::enabled(app, command)) { crate::graph::actions::invoke(app, command); editor.set_camera(app.ui.graph_camera); } @@ -89,12 +88,11 @@ fn background_actions(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, u } fn annotations(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) { - let standalone = matches!(editor.target, FunctionTarget::Graph); 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]})), ] { - if edit_menu::button(ui, label, command, standalone) { + if edit_menu::button(ui, label, command, true) { app.run(command, parameters); editor.selection.clear(); } diff --git a/crates/ui-egui/src/function/function_canvas.rs b/crates/ui-egui/src/function/function_canvas.rs index 16b60998..c17d9a89 100644 --- a/crates/ui-egui/src/function/function_canvas.rs +++ b/crates/ui-egui/src/function/function_canvas.rs @@ -12,5 +12,6 @@ pub(super) struct FunctionCanvas { pub values: Vec<(u32, Value)>, pub frames: Vec<FrameHit>, pub comments: Vec<(u64, Rect)>, + pub pins: Vec<(u64, Rect)>, pub clear_annotation: bool, } diff --git a/crates/ui-egui/src/function/function_editor.rs b/crates/ui-egui/src/function/function_editor.rs index 67ca80b9..ea1304d6 100644 --- a/crates/ui-egui/src/function/function_editor.rs +++ b/crates/ui-egui/src/function/function_editor.rs @@ -26,6 +26,10 @@ impl FunctionEditor { Self::with_target(graph, None, FunctionTarget::Graph) } + pub(crate) fn camera(&self) -> crate::state::GraphCamera { + crate::state::GraphCamera { pan: self.pan.into(), zoom: self.zoom } + } + pub(crate) fn set_camera(&mut self, camera: crate::state::GraphCamera) { self.pan = camera.pan.into(); self.zoom = camera.zoom; diff --git a/crates/ui-egui/src/function/geometry.rs b/crates/ui-egui/src/function/geometry.rs index ffdd9419..e08fe20d 100644 --- a/crates/ui-egui/src/function/geometry.rs +++ b/crates/ui-egui/src/function/geometry.rs @@ -1,4 +1,4 @@ -use super::{FunctionDrag, FunctionEditor, FunctionTarget}; +use super::{FunctionDrag, FunctionEditor}; use crate::{MaterialCraftApp, graph::node_card}; use egui::{Color32, Pos2, Rect, vec2}; use materialcraft_engine::core::FunctionNode; @@ -39,8 +39,6 @@ pub(super) fn preview_rect(app: &MaterialCraftApp, editor: &FunctionEditor, node 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 = 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 index 67571c5b..8a83934c 100644 --- a/crates/ui-egui/src/function/input.rs +++ b/crates/ui-egui/src/function/input.rs @@ -30,11 +30,7 @@ pub(super) fn handle( && !on_annotation && !ui.input(|input| input.modifiers.alt) && crate::graph::wire_selection::handle(&mut editor.selected_wires, &mut editor.selection, ui, response, &geometry.wires); - if on_wire - && matches!(editor.target, super::FunctionTarget::Graph) - && app.session.annotation_selection.is_some() - && (ui.input(|input| input.pointer.primary_pressed()) || response.secondary_clicked()) - { + if on_wire && app.session.annotation_selection.is_some() && (ui.input(|input| input.pointer.primary_pressed()) || response.secondary_clicked()) { app.run("graph.annotation.select", serde_json::json!({})); } @@ -68,7 +64,7 @@ pub(super) fn handle( && !on_annotation && !on_wire { - if matches!(editor.target, super::FunctionTarget::Graph) && app.session.annotation_selection.is_some() { + if app.session.annotation_selection.is_some() { app.run("graph.annotation.select", serde_json::json!({})); } editor.drag = Some(FunctionDrag::Box { start }); @@ -170,6 +166,20 @@ pub(super) fn handle( } } + if let Some(payload) = crate::widgets::dnd_release::<crate::graph::LibraryDrag>(response) + && let Some(pointer) = pointer + { + let at = camera.to_graph(pointer); + if let Some(result) = app.run("library.add", serde_json::json!({"entry": payload.0, "at": [at.x, at.y], "snapToGrid": snap})) { + editor.selection = if app.session.annotation_selection.is_some() { + Vec::new() + } else { + result["result"]["id"].as_u64().and_then(|id| u32::try_from(id).ok()).into_iter().collect() + }; + editor.selected_wires.clear(); + } + } + // Adding operations if response.secondary_clicked() && let Some(pointer_position) = pointer diff --git a/crates/ui-egui/src/function/library.rs b/crates/ui-egui/src/function/library.rs index 5c6a63ad..8b63115c 100644 --- a/crates/ui-egui/src/function/library.rs +++ b/crates/ui-egui/src/function/library.rs @@ -11,8 +11,7 @@ pub(crate) fn add(app: &mut MaterialCraftApp, entry: &FunctionLibraryDrag) { } } -/// The native operations the open Function canvas can take (processors that only compute a -/// value cannot sample images) +/// The native operations accepted by the open Function canvas. pub(crate) fn available_operations(app: &MaterialCraftApp) -> Vec<&'static str> { app.function_editor .as_ref() diff --git a/crates/ui-egui/src/function/render.rs b/crates/ui-egui/src/function/render.rs index 9658e38c..e1725325 100644 --- a/crates/ui-egui/src/function/render.rs +++ b/crates/ui-egui/src/function/render.rs @@ -1,12 +1,14 @@ use super::geometry::{in_port, node_rect, out_port, preview_rect}; -use super::{FunctionDrag, FunctionEditor, FunctionTarget, port_label::port_label}; +use super::{FunctionDrag, FunctionEditor, 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, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2}; use std::collections::{BTreeMap, BTreeSet}; -pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) -> Option<FunctionCanvas> { +pub(super) fn paint(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) -> Option<FunctionCanvas> { + let (canvas_bounds, response) = ui.allocate_exact_size(ui.available_size().max(vec2(200.0, 200.0)), Sense::click_and_drag()); + app.graph.view = canvas_bounds; let graph = editor.current(app)?; let snap = app.ui.prefs.snap_to_grid; let selected: BTreeSet<_> = editor.selection.iter().copied().collect(); @@ -21,9 +23,8 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu .is_some_and(Option::is_some) }); editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node); - let standalone = matches!(editor.target, FunctionTarget::Graph); + let document = app.graph.annotation_target.items(&app.session).ok(); 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)); @@ -42,10 +43,7 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu .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() - { + if !selected_only && let Some(document) = &document { 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))); } @@ -59,7 +57,7 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu 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); @@ -167,7 +165,7 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu if !keep_wires { editor.selected_wires.clear(); } - if standalone && app.session.annotation_selection.is_some() { + if app.session.annotation_selection.is_some() { clear_annotation = true; } } @@ -193,8 +191,6 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu .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 }) + let pins = document.as_ref().map(|document| crate::graph::annotation_canvas::pins(app, ui, &document.pins, &camera)).unwrap_or_default(); + Some(FunctionCanvas { response, camera, geometry, ports, nodes, values, frames: frame_hits, comments, pins, clear_annotation }) } diff --git a/crates/ui-egui/src/graph/actions.rs b/crates/ui-egui/src/graph/actions.rs index b44ef1cb..edce941d 100644 --- a/crates/ui-egui/src/graph/actions.rs +++ b/crates/ui-egui/src/graph/actions.rs @@ -7,7 +7,7 @@ pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option<bool> { 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())), + "ui.graph.previousPin" | "ui.graph.nextPin" => Some(app.graph.annotation_target.items(&app.session).is_ok_and(|items| !items.pins.is_empty())), command if command.starts_with("ui.graph.") => Some(app.session.graph().is_ok()), _ => None, } @@ -73,12 +73,12 @@ pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool { } fn navigate_pin(app: &mut MaterialCraftApp, forward: bool) { - let Ok(graph) = app.session.graph() else { return }; + let Ok(graph) = app.graph.annotation_target.items(&app.session) else { return }; if graph.pins.is_empty() { return; } - let camera = &mut app.ui.graph_camera; + let mut camera = crate::annotation::camera(app); let zoom = camera.zoom.clamp(0.08, 4.0); let center = [camera.pan[0] + app.graph.view.width() * 0.5 / zoom, camera.pan[1] + app.graph.view.height() * 0.5 / zoom]; let current = graph.pins.iter().position(|pin| (pin.pos[0] - center[0]).abs() < 0.1 && (pin.pos[1] - center[1]).abs() < 0.1); @@ -92,9 +92,11 @@ 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); + if let Some(editor) = &mut app.function_editor { + editor.set_camera(camera); + } else if let Some(editor) = &mut app.pattern_editor { + editor.set_camera(camera); + } else { + app.ui.graph_camera = camera; } } diff --git a/crates/ui-egui/src/graph/annotation_canvas.rs b/crates/ui-egui/src/graph/annotation_canvas.rs index e37bb4d0..e448f8e6 100644 --- a/crates/ui-egui/src/graph/annotation_canvas.rs +++ b/crates/ui-egui/src/graph/annotation_canvas.rs @@ -87,16 +87,28 @@ pub(crate) fn comments(app: &MaterialCraftApp, ui: &Ui, comments: &[Comment], ca hits } -pub(crate) fn pins(app: &MaterialCraftApp, ui: &Ui, pins: &[Pin], camera: &GraphCamera) { +pub(crate) fn pins(app: &MaterialCraftApp, ui: &Ui, pins: &[Pin], 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(pins.len()); for pin in pins { - let position = pos2(pin.pos[0], pin.pos[1]) + offset(app, |contents| contents.pins.contains(&pin.id)); + let mut position = pos2(pin.pos[0], pin.pos[1]) + offset(app, |contents| contents.pins.contains(&pin.id)); + if let Some(GraphDrag::Pin { id, delta }) = &app.graph.drag + && *id == pin.id + { + position += *delta; + } let position = camera.to_screen(position); - painter.text(position, Align2::CENTER_BOTTOM, icon::MAP_PIN, FontId::proportional(18.0), theme.accent); - painter.text(position + vec2(10.0, -10.0), Align2::LEFT_CENTER, &pin.name, FontId::proportional(11.0), theme.text); + let selected = app.session.annotation_selection == Some(AnnotationSelection::Pin(pin.id)); + let marker = painter.text(position, Align2::CENTER_BOTTOM, icon::MAP_PIN, FontId::proportional(18.0), theme.accent); + let label = painter.text(position + vec2(10.0, -10.0), Align2::LEFT_CENTER, &pin.name, FontId::proportional(11.0), theme.text); + let bounds = marker.union(label).expand(3.0); + if selected { + painter.rect_stroke(bounds, 2.0, Stroke::new(1.0, theme.accent), StrokeKind::Outside); + } + hits.push((pin.id, bounds)); } + hits } pub(crate) fn offset(app: &MaterialCraftApp, contains: impl FnOnce(&materialcraft_engine::FrameContents) -> bool) -> Vec2 { diff --git a/crates/ui-egui/src/graph/annotation_input.rs b/crates/ui-egui/src/graph/annotation_input.rs index 565462af..e08ee3a8 100644 --- a/crates/ui-egui/src/graph/annotation_input.rs +++ b/crates/ui-egui/src/graph/annotation_input.rs @@ -3,7 +3,7 @@ use crate::MaterialCraftApp; 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)]) { +pub(crate) fn handle(app: &mut MaterialCraftApp, ui: &Ui, camera: &GraphCamera, frames: &[FrameHit], comments: &[(u64, Rect)], pins: &[(u64, Rect)]) { if super::gesture::cancelled(ui) { app.graph.drag = None; return; @@ -12,17 +12,24 @@ pub(crate) fn handle(app: &mut MaterialCraftApp, ui: &Ui, camera: &GraphCamera, let Some(pointer) = ui.input(|input| input.pointer.interact_pos()) else { return }; let pressed = ui.input(|input| input.pointer.primary_pressed()); + if ui.input(|input| input.pointer.secondary_clicked()) + && let Some((id, _)) = pins.iter().rev().find(|(_, rect)| rect.contains(pointer)) + { + app.run("graph.annotation.select", json!({"kind": "pin", "id": id})); + } 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)) { + if let Some((id, _)) = pins.iter().rev().find(|(_, rect)| rect.contains(pointer)) { + begin_pin(app, *id); + } else if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(pointer)) { begin_comment(app, *id); } else if let Some(hit) = frames.iter().rev().find(|hit| hit.contains(pointer)) { begin_frame(app, hit.id, hit.grip.contains(pointer)); } else { app.run("graph.annotation.select", json!({})); } - } else if let Some(GraphDrag::Frame { delta, .. } | GraphDrag::Comment { delta, .. }) = &mut app.graph.drag { + } else if let Some(GraphDrag::Frame { delta, .. } | GraphDrag::Comment { delta, .. } | GraphDrag::Pin { delta, .. }) = &mut app.graph.drag { *delta += motion; } @@ -40,10 +47,13 @@ pub(super) fn begin_comment(app: &mut MaterialCraftApp, id: u64) { pub(super) fn begin_frame(app: &mut MaterialCraftApp, id: u64, resize: bool) { let contents = app - .session - .graph() + .graph + .annotation_target + .items(&app.session) .ok() - .and_then(|graph| graph.frames.iter().find(|frame| frame.id == id).map(|frame| materialcraft_engine::FrameContents::capture(graph, frame))) + .and_then(|items| { + items.frames.iter().find(|frame| frame.id == id).and_then(|frame| app.graph.annotation_target.capture_frame(&app.session, frame).ok()) + }) .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 }); @@ -53,7 +63,9 @@ 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)) { + if let Some(frame) = + app.graph.annotation_target.items(&app.session).ok().and_then(|items| items.frames.into_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})); } @@ -62,11 +74,26 @@ pub(super) fn finish(app: &mut MaterialCraftApp, drag: GraphDrag) { } } 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)) { + if let Some(comment) = + app.graph.annotation_target.items(&app.session).ok().and_then(|items| items.comments.into_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::Pin { id, delta } if delta.length() > 0.5 => { + if let Some(pin) = app.graph.annotation_target.items(&app.session).ok().and_then(|items| items.pins.into_iter().find(|pin| pin.id == id)) { + app.run("graph.pin.edit", json!({"id": id, "at": [pin.pos[0] + delta.x, pin.pos[1] + delta.y]})); + app.session.finish_edit(); + } + } _ => {} } } + +pub(super) fn begin_pin(app: &mut MaterialCraftApp, id: u64) { + app.run("graph.annotation.select", json!({"kind": "pin", "id": id})); + app.inspected_folder = None; + app.inspected_graph = None; + app.graph.drag = Some(GraphDrag::Pin { id, delta: Vec2::ZERO }); +} diff --git a/crates/ui-egui/src/graph/canvas.rs b/crates/ui-egui/src/graph/canvas.rs index 14e09a16..87c8d4be 100644 --- a/crates/ui-egui/src/graph/canvas.rs +++ b/crates/ui-egui/src/graph/canvas.rs @@ -33,6 +33,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } } + crate::annotation::activate(app, crate::annotation::target(app)); super::toolbar::show(app, ui); if app.function_editor.is_some() { crate::function::show_graph(app, ui); @@ -278,7 +279,8 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let comment_hits = super::annotation_canvas::comments(app, ui, &graph.comments, &camera); app.graph.comments = comment_hits.clone(); - super::annotation_canvas::pins(app, ui, &graph.pins, &camera); + let pin_hits = super::annotation_canvas::pins(app, ui, &graph.pins, &camera); + app.graph.pins = pin_hits.clone(); // Ports (drawn last, interactable over the node cards) // except on a dot's body: its port hit circles would otherwise cover it and it could never be moved @@ -311,7 +313,7 @@ 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); - super::input::handle(app, ui, &resp, rect, &camera, &node_responses, &frame_hits, &comment_hits, port_hover, wire_hover); + super::input::handle(app, ui, &resp, rect, &camera, &node_responses, &frame_hits, &comment_hits, &pin_hits, port_hover, wire_hover); app.graph.inspected_node = super::node_selection::inspected(&app.session.selection, app.graph.inspected_node); // GraphDrag previews diff --git a/crates/ui-egui/src/graph/editor_target.rs b/crates/ui-egui/src/graph/editor_target.rs index 18f7b31f..5f619a66 100644 --- a/crates/ui-egui/src/graph/editor_target.rs +++ b/crates/ui-egui/src/graph/editor_target.rs @@ -1,4 +1,4 @@ -use crate::{MaterialCraftApp, function::FunctionTarget}; +use crate::MaterialCraftApp; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum EditorTarget { @@ -9,12 +9,7 @@ pub(crate) enum EditorTarget { 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, - } + app.session.annotation_selection.is_some() && app.session.annotation_target == app.graph.annotation_target } pub(crate) fn resolve(app: &MaterialCraftApp) -> Self { diff --git a/crates/ui-egui/src/graph/graph_drag.rs b/crates/ui-egui/src/graph/graph_drag.rs index ea463aeb..65241450 100644 --- a/crates/ui-egui/src/graph/graph_drag.rs +++ b/crates/ui-egui/src/graph/graph_drag.rs @@ -30,6 +30,10 @@ pub(super) enum GraphDrag { resize: bool, contents: materialcraft_engine::FrameContents, }, + Pin { + id: u64, + delta: Vec2, + }, Comment { id: u64, delta: Vec2, diff --git a/crates/ui-egui/src/graph/graph_view.rs b/crates/ui-egui/src/graph/graph_view.rs index 5dc9e9d5..f032e462 100644 --- a/crates/ui-egui/src/graph/graph_view.rs +++ b/crates/ui-egui/src/graph/graph_view.rs @@ -13,6 +13,9 @@ pub struct GraphView { pub ports: Vec<PortHit>, pub frames: Vec<(u64, Rect)>, pub comments: Vec<(u64, Rect)>, + pub pins: Vec<(u64, Rect)>, + pub(crate) annotation_target: materialcraft_engine::AnnotationTarget, + pub(crate) pin_description_focus: Option<u64>, /// The canvas rectangle last frame pub view: Rect, /// Graph point of the last right-click (context menu actions add things there) @@ -28,10 +31,14 @@ pub struct GraphView { } impl GraphView { - pub(crate) fn cancel_gesture(&mut self) { + pub(crate) fn cancel_drag(&mut self) { self.drag = None; self.search = None; self.menu_wire = None; + } + + pub(crate) fn cancel_gesture(&mut self) { + self.cancel_drag(); self.framed_graph = None; } pub(crate) fn is_dragging(&self) -> bool { @@ -51,6 +58,9 @@ impl Default for GraphView { ports: Vec::new(), frames: Vec::new(), comments: Vec::new(), + pins: Vec::new(), + annotation_target: Default::default(), + pin_description_focus: None, view: Rect::NOTHING, menu_at: Pos2::ZERO, framed_graph: None, diff --git a/crates/ui-egui/src/graph/input.rs b/crates/ui-egui/src/graph/input.rs index 9e2a5bb0..503ab733 100644 --- a/crates/ui-egui/src/graph/input.rs +++ b/crates/ui-egui/src/graph/input.rs @@ -15,6 +15,7 @@ pub(super) fn handle( nodes: &[(NodeId, egui::Response)], frames: &[super::frame_hit::FrameHit], comments: &[(u64, Rect)], + pins: &[(u64, Rect)], port_hover: Option<PortHit>, wire_hover: Option<WireRef>, ) { @@ -42,7 +43,9 @@ pub(super) fn handle( app.run("graph.annotation.select", json!({})); } - let on_card = nodes.iter().any(|(_, response)| response.rect.contains(position)) || comments.iter().any(|(_, bounds)| bounds.contains(position)); + let on_card = nodes.iter().any(|(_, response)| response.rect.contains(position)) + || comments.iter().any(|(_, bounds)| bounds.contains(position)) + || pins.iter().any(|(_, bounds)| bounds.contains(position)); let wire = wire_hover.as_ref().filter(|_| port_hover.is_none() && !on_card); if wire.is_none() { super::node_selection::select(&mut app.graph.selected_wires, None, modifiers); @@ -59,6 +62,8 @@ pub(super) fn handle( } else { app.graph.drag = Some(GraphDrag::InputWire { to: (port.node, port.port.clone()) }); } + } else if let Some((id, _)) = pins.iter().rev().find(|(_, bounds)| bounds.contains(position)) { + super::annotation_input::begin_pin(app, *id); } else if let Some((id, _)) = comments.iter().rev().find(|(_, bounds)| bounds.contains(position)) { super::annotation_input::begin_comment(app, *id); } else if let Some((id, _)) = nodes.iter().rev().find(|(_, response)| response.rect.contains(position)) { @@ -78,7 +83,10 @@ pub(super) fn handle( let delta = context.input(|input| input.pointer.delta()) / zoom; app.ui.graph_camera.pan = [app.ui.graph_camera.pan[0] - delta.x, app.ui.graph_camera.pan[1] - delta.y]; } - Some(GraphDrag::Nodes { delta }) | Some(GraphDrag::Frame { delta, .. }) | Some(GraphDrag::Comment { delta, .. }) => *delta += motion, + Some(GraphDrag::Nodes { delta }) + | Some(GraphDrag::Frame { delta, .. }) + | Some(GraphDrag::Comment { delta, .. }) + | Some(GraphDrag::Pin { 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(position) = pointer @@ -145,7 +153,7 @@ pub(super) fn handle( app.run("graph.connect", json!({"from": source.node.0, "fromPort": source.port, "to": to.0.0, "toPort": to.1})); } } - GraphDrag::Frame { .. } | GraphDrag::Comment { .. } => super::annotation_input::finish(app, drag), + GraphDrag::Frame { .. } | GraphDrag::Comment { .. } | GraphDrag::Pin { .. } => super::annotation_input::finish(app, drag), } } @@ -183,6 +191,7 @@ pub(super) fn handle( let on_node = pointer.is_some_and(|position| { nodes.iter().any(|(_, response)| response.rect.contains(position)) || comments.iter().any(|(_, bounds)| bounds.contains(position)) + || pins.iter().any(|(_, bounds)| bounds.contains(position)) || frames.iter().any(|frame| frame.contains(position)) }); if canvas.double_clicked() @@ -204,7 +213,9 @@ pub(super) fn handle( && let Some(position) = pointer { app.graph.menu_at = camera.to_graph(position); - if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(position)) { + if let Some((id, _)) = pins.iter().rev().find(|(_, rect)| rect.contains(position)) { + app.run("graph.annotation.select", json!({"kind": "pin", "id": id})); + } else if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(position)) { app.run("graph.annotation.select", json!({"kind": "comment", "id": id})); } else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(position)) { app.run("graph.annotation.select", json!({"kind": "frame", "id": hit.id})); @@ -247,7 +258,7 @@ pub(super) fn handle( { let graph_position = camera.to_graph(position); let at = [graph_position.x - NODE_W * 0.5, graph_position.y - 20.0]; - app.run("library.add", json!({"entry": payload.0, "at": at})); + app.run("library.add", json!({"entry": payload.0, "at": at, "snapToGrid": app.ui.prefs.snap_to_grid})); } // Keys over the canvas diff --git a/crates/ui-egui/src/graph/interaction_tests.rs b/crates/ui-egui/src/graph/interaction_tests.rs index acb396fd..76d0481a 100644 --- a/crates/ui-egui/src/graph/interaction_tests.rs +++ b/crates/ui-egui/src/graph/interaction_tests.rs @@ -867,3 +867,58 @@ fn wires_pulled_from_an_unconnected_input_connect_on_an_output() { frames.app.session.undo().unwrap(); assert_eq!(wires(&frames).len(), 2); } + +/// A library drop uses the same snapping preference as other node additions. +#[test] +fn review_library_drop_respects_grid_preference() { + for snapping in [true, false] { + let mut frames = Frames::new(new_session()); + frames.app.ui.prefs.snap_to_grid = snapping; + let position = frames.app.graph.view.center() + vec2(113.0, 77.0); + frames.run(vec![Event::PointerMoved(position)], Modifiers::NONE); + frames.run(vec![Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }], Modifiers::NONE); + egui::DragAndDrop::set_payload(&frames.ctx, super::LibraryDrag("node:blur".into())); + let camera = + super::GraphCamera { origin: frames.app.graph.view.min, pan: frames.app.ui.graph_camera.pan.into(), zoom: frames.app.ui.graph_camera.zoom }; + let graph_position = camera.to_graph(position); + let expected = materialcraft_engine::graph_grid::snap_position([graph_position.x - super::NODE_W * 0.5, graph_position.y - 20.0], snapping); + let before = frames.app.session.graph().unwrap().nodes.len(); + + frames.run(vec![Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }], Modifiers::NONE); + + let graph = frames.app.session.graph().unwrap(); + assert_eq!(graph.nodes.len(), before + 1); + assert_eq!(graph.nodes.last().unwrap().pos, expected, "snapping: {snapping}"); + } +} + +/// Both standalone canvases hit the pin marker and description and preserve drag undo. +#[test] +fn navigation_pins_can_be_selected_dragged_and_deleted() { + for function in [false, true] { + let mut session = new_session(); + if function { + materialcraft_engine::execute(&mut session, "file.new", &json!({"kind": "function"})).unwrap(); + } + let mut frames = Frames::new(session); + let camera = &frames.app.ui.graph_camera; + let position = egui::Pos2::from(camera.pan) + frames.app.graph.view.size() * 0.5 / camera.zoom; + let id = frames.app.run("graph.pin.add", json!({"at": [position.x, position.y], "name": "Review checkpoint"})).unwrap()["id"].as_u64().unwrap(); + frames.app.run("graph.annotation.select", json!({})); + frames.run(Vec::new(), Modifiers::NONE); + let from = frames.app.graph.view.center() + vec2(30.0, -10.0); + frames.click(from, Modifiers::NONE); + assert_eq!(serde_json::to_value(frames.app.session.annotation_selection).unwrap(), json!({"kind": "pin", "id": id})); + assert_eq!(crate::properties::title(&frames.app), "Navigation Pin - Properties"); + let before = frames.app.session.graph().unwrap().pins[0].pos; + let zoom = frames.app.ui.graph_camera.zoom; + drag(&mut frames, from, from + vec2(64.0, 32.0) * zoom); + let after = frames.app.session.graph().unwrap().pins[0].pos; + assert!((after[0] - before[0] - 64.0).abs() < 0.01); + assert!((after[1] - before[1] - 32.0).abs() < 0.01); + frames.app.session.undo().unwrap(); + assert_eq!(frames.app.session.graph().unwrap().pins[0].pos, before); + menus::invoke(&mut frames.app, &frames.ctx, "edit.delete"); + assert!(frames.app.session.graph().unwrap().pins.is_empty()); + } +} diff --git a/crates/ui-egui/src/graph/toolbar.rs b/crates/ui-egui/src/graph/toolbar.rs index c880127d..0b1f34c5 100644 --- a/crates/ui-egui/src/graph/toolbar.rs +++ b/crates/ui-egui/src/graph/toolbar.rs @@ -7,7 +7,6 @@ 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<u64> = if pattern { app.pattern_editor.as_ref().map(|editor| editor.selection.iter().copied().map(u64::from).collect()).unwrap_or_default() @@ -32,10 +31,10 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { }) { 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!({}) }; + let parameters = annotation_frame(app, &selection); app.run("graph.frame.add", parameters); } if b(ui, icon::NOTE, tr("Add comment")) { @@ -169,8 +168,9 @@ fn parent_size(app: &mut MaterialCraftApp, ui: &mut Ui) { } } -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 }; +fn annotation_frame(app: &MaterialCraftApp, selection: &[u64]) -> serde_json::Value { + let camera = crate::annotation::camera(app); + let camera = super::GraphCamera { origin: app.graph.view.min, pan: camera.pan.into(), zoom: 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!({}); diff --git a/crates/ui-egui/src/library.rs b/crates/ui-egui/src/library.rs index 5227ff38..60486774 100644 --- a/crates/ui-egui/src/library.rs +++ b/crates/ui-egui/src/library.rs @@ -12,16 +12,18 @@ use materialcraft_engine::{LibraryCanvas, LibraryEntry, LibraryItem}; use crate::MaterialCraftApp; use crate::function::library::FunctionLibraryDrag; -use crate::graph::editor_target::EditorTarget; +mod library_target; use crate::graph::{LibraryDrag, header_color}; use crate::i18n::tr; use crate::theme::Tokens; +pub(crate) use library_target::LibraryTarget; /// The category key of the Favorites row pub(crate) const FAVORITES: &str = "@favorites"; /// Function entries that need more nodes than MaterialCraft has are shown in this color const WARNING: Color32 = Color32::from_rgb(255, 90, 180); +/// Choose the icon for a known category or fall back to a folder. fn category_icon(category: &str) -> &'static str { match category { FAVORITES => icon::STAR, @@ -68,50 +70,6 @@ fn category_icon(category: &str) -> &'static str { } } -/// The graph the library adds to, and which native function operations it can take -pub(crate) struct Here { - canvas: LibraryCanvas, - operations: Vec<&'static str>, -} - -impl Here { - pub(crate) fn of(app: &MaterialCraftApp) -> Here { - match EditorTarget::resolve(app) { - EditorTarget::Material => Here { canvas: LibraryCanvas::Material, operations: Vec::new() }, - EditorTarget::Pattern => Here { canvas: LibraryCanvas::Pattern, operations: Vec::new() }, - EditorTarget::Function => Here { canvas: LibraryCanvas::Function, operations: crate::function::library::available_operations(app) }, - } - } - - /// Whether `entry` can go into the open graph now - pub(crate) fn takes(&self, entry: &LibraryEntry) -> bool { - entry.missing.is_none() - && entry.canvas == self.canvas - && match &entry.item { - LibraryItem::Operation { operation } => self.operations.contains(&operation.as_str()), - _ => true, - } - } - - /// Why `entry` can't go into the open graph, when it can't - fn refusal(&self, entry: &LibraryEntry) -> Option<String> { - if let Some(missing) = &entry.missing { - return Some(missing.clone()); - } - if entry.canvas != self.canvas { - return Some( - match entry.canvas { - LibraryCanvas::Material => tr("Open a graph to add this"), - LibraryCanvas::Function => tr("Open a function graph or a processor's function to add this"), - LibraryCanvas::Pattern => tr("Open an FX-Map to add this"), - } - .to_string(), - ); - } - (!self.takes(entry)).then(|| tr("This function can't use this node").to_string()) - } -} - /// The library's entries for the open session, rebuilt when its packages change fn entries(app: &MaterialCraftApp, ctx: &egui::Context) -> Arc<Vec<LibraryEntry>> { type Cached = (Vec<(String, usize)>, Arc<Vec<LibraryEntry>>); @@ -125,22 +83,24 @@ fn entries(app: &MaterialCraftApp, ctx: &egui::Context) -> Arc<Vec<LibraryEntry> { return list.clone(); } + let list = Arc::new(app.session.library_entries()); ctx.data_mut(|data| data.insert_temp(id, Arc::new((key, list.clone())))); list } +/// Draw the shared library tree and search results for the active editor. pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let here = Here::of(app); + let tokens = Tokens::get(ui.ctx()); + let target = LibraryTarget::of(app); let all = entries(app, ui.ctx()); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 2.0; - ui.label(RichText::new(icon::MAGNIFYING_GLASS).color(tk.text_dim)); - let hint = match here.canvas { + ui.label(RichText::new(icon::MAGNIFYING_GLASS).color(tokens.text_dim)); + let hint = match target.canvas { LibraryCanvas::Function => tr("Search functions"), LibraryCanvas::Pattern => tr("Search FX-Map nodes"), - LibraryCanvas::Material => tr("Search"), + LibraryCanvas::Any | LibraryCanvas::Material => tr("Search"), }; let width = (ui.available_width() - 5.0 * 24.0).max(40.0); let response = ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(hint).desired_width(width)); @@ -166,21 +126,23 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } }); ui.add_space(2.0); - let avail = ui.available_size(); + let available_size = ui.available_size(); + // The tree takes what the tiles leave: one column of tiles in a narrow panel - let tree_w = (avail.x * 0.6).clamp(120.0, 230.0).min(avail.x - 92.0).max(80.0); + let tree_width = (available_size.x * 0.6).clamp(120.0, 230.0).min(available_size.x - 92.0).max(80.0); let top_down = egui::Layout::top_down(egui::Align::Min); ui.horizontal_top(|ui| { - ui.allocate_ui_with_layout(vec2(tree_w, avail.y), top_down, |ui| { + ui.allocate_ui_with_layout(vec2(tree_width, available_size.y), top_down, |ui| { egui::ScrollArea::vertical().id_salt("lib-tree").auto_shrink([false, false]).show(ui, |ui| category_tree(app, ui, &all)); }); ui.separator(); - ui.allocate_ui_with_layout(vec2(ui.available_width(), avail.y), top_down, |ui| { - egui::ScrollArea::vertical().id_salt("lib-items").auto_shrink([false, false]).show(ui, |ui| items(app, ui, &all, &here)); + ui.allocate_ui_with_layout(vec2(ui.available_width(), available_size.y), top_down, |ui| { + egui::ScrollArea::vertical().id_salt("lib-items").auto_shrink([false, false]).show(ui, |ui| items(app, ui, &all, &target)); }); }); } +/// Expose availability and canvas filters without changing the selected category. fn filter_menu(app: &mut MaterialCraftApp, ui: &mut Ui) { let filtered = !app.ui.library_show_missing || !app.ui.library_show_other; let response = crate::widgets::icon_button(ui, icon::FUNNEL, tr("Filter"), filtered, 22.0); @@ -191,6 +153,7 @@ fn filter_menu(app: &mut MaterialCraftApp, ui: &mut Ui) { }); } +/// Toggle an entry while bounding the saved favorites list. fn toggle_favorite(app: &mut MaterialCraftApp, id: &str) { if let Some(index) = app.ui.library_favorites.iter().position(|favorite| favorite == id) { app.ui.library_favorites.remove(index); @@ -201,24 +164,24 @@ fn toggle_favorite(app: &mut MaterialCraftApp, id: &str) { /// One tree row: an optional disclosure triangle, the category icon and its name fn tree_row(app: &mut MaterialCraftApp, ui: &mut Ui, label: &str, category: &str, depth: usize, open: Option<bool>, count: usize) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let selected = app.ui.library_category == category; let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click()); crate::widgets::name(&response, egui::Role::TreeItem, label); let response = response.on_hover_text(crate::i18n::trf("{name}: {count} entries", &[("name", &label), ("count", &count)])); if selected { - ui.painter().rect_filled(rect, 4.0, tk.row_selected); + ui.painter().rect_filled(rect, 4.0, tokens.row_selected); } else if response.hovered() { - ui.painter().rect_filled(rect, 4.0, tk.row_hover); + ui.painter().rect_filled(rect, 4.0, tokens.row_hover); } let indent = 4.0 + depth as f32 * 14.0; let chevron = Rect::from_min_size(rect.min + vec2(indent, 0.0), vec2(14.0, rect.height())); if let Some(open) = open { let symbol = if open { icon::CARET_DOWN } else { icon::CARET_RIGHT }; - ui.painter().text(chevron.center(), egui::Align2::CENTER_CENTER, symbol, egui::FontId::proportional(11.0), tk.text_dim); + ui.painter().text(chevron.center(), egui::Align2::CENTER_CENTER, symbol, egui::FontId::proportional(11.0), tokens.text_dim); } let x = chevron.right() + 2.0; - let color = if selected { tk.text_strong } else { tk.text }; + let color = if selected { tokens.text_strong } else { tokens.text }; ui.painter().text(egui::pos2(x + 7.0, rect.center().y), egui::Align2::CENTER_CENTER, category_icon(category), egui::FontId::proportional(13.0), color); let font = if depth == 0 { 12.0 } else { 11.5 }; let galley = crate::widgets::elided(ui.painter(), label.to_string(), font, color, rect.right() - x - 22.0); @@ -236,6 +199,7 @@ fn tree_row(app: &mut MaterialCraftApp, ui: &mut Ui, label: &str, category: &str } } +/// Persist the expansion state of one category. fn set_open(app: &mut MaterialCraftApp, category: &str, open: bool) { if open { app.ui.library_expanded.insert(category.to_string()); @@ -249,6 +213,7 @@ fn count(entries: &[LibraryEntry], category: &str) -> usize { entries.iter().filter(|entry| entry.category == category || entry.category.strip_prefix(category).is_some_and(|rest| rest.starts_with('/'))).count() } +/// Draw known categories first, followed by categories supplied by packages. fn category_tree(app: &mut MaterialCraftApp, ui: &mut Ui, entries: &[LibraryEntry]) { ui.spacing_mut().item_spacing.y = 1.0; let favorites = app.ui.library_favorites.len(); @@ -263,6 +228,7 @@ fn category_tree(app: &mut MaterialCraftApp, ui: &mut Ui, entries: &[LibraryEntr } } } + // Packages can name categories the tree doesn't have; they go last let mut extra: Vec<&str> = Vec::new(); for entry in entries { @@ -276,72 +242,63 @@ fn category_tree(app: &mut MaterialCraftApp, ui: &mut Ui, entries: &[LibraryEntr } } -/// Entries matching the selected category, or the search across the whole library, with what the -/// open graph can take first when searching -pub(crate) fn visible<'a>(app: &MaterialCraftApp, entries: &'a [LibraryEntry], here: &Here) -> Vec<&'a LibraryEntry> { +/// Matching entries ordered by their displayed names in tiles and list views. +pub(crate) fn visible<'a>(app: &MaterialCraftApp, entries: &'a [LibraryEntry], target: &LibraryTarget) -> Vec<&'a LibraryEntry> { let search = app.ui.library_search.trim().to_lowercase(); let category = app.ui.library_category.as_str(); - let mut out: Vec<(u8, &LibraryEntry)> = entries + let mut visible: Vec<_> = entries .iter() .filter(|entry| app.ui.library_show_missing || entry.missing.is_none()) - .filter(|entry| app.ui.library_show_other || entry.canvas == here.canvas) - .filter_map(|entry| { + .filter(|entry| app.ui.library_show_other || entry.canvas == LibraryCanvas::Any || entry.canvas == target.canvas) + .filter(|entry| { if !search.is_empty() { - let label = entry.label.to_lowercase(); - let rank = if label == search { - 0 - } else if label.starts_with(&search) { - 1 - } else if label.contains(&search) || entry.id.to_lowercase().contains(&search) { - 2 - } else { - return None; - }; - return Some((rank + if here.takes(entry) { 0 } else { 3 }, entry)); + return tr(&entry.label).to_lowercase().contains(&search) || entry.id.to_lowercase().contains(&search); } - let fits = match category { + + match category { "" => true, FAVORITES => app.ui.library_favorites.contains(&entry.id), category => entry.category == category || entry.category.strip_prefix(category).is_some_and(|rest| rest.starts_with('/')), - }; - fits.then_some((0, entry)) + } }) .collect(); - out.sort_by_key(|(rank, _)| *rank); - out.into_iter().map(|(_, entry)| entry).collect() + visible.sort_by_cached_key(|entry| (tr(&entry.label).to_lowercase(), entry.id.as_str())); + visible } -fn items(app: &mut MaterialCraftApp, ui: &mut Ui, entries: &[LibraryEntry], here: &Here) { - let tk = Tokens::get(ui.ctx()); +/// Draw matching entries and dispatch compatible additions or favorite changes. +fn items(app: &mut MaterialCraftApp, ui: &mut Ui, entries: &[LibraryEntry], target: &LibraryTarget) { + let tokens = Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); - let list = visible(app, entries, here); + let list = visible(app, entries, target); if list.is_empty() { let text = match app.ui.library_category.as_str() { FAVORITES if app.ui.library_search.trim().is_empty() => tr("Select an entry and click the star to add it to Favorites"), category if app.ui.library_search.trim().is_empty() && !category.is_empty() => tr("Nothing in this category yet"), _ => tr("Nothing matches"), }; - ui.label(RichText::new(text).color(tk.text_dim)); + ui.label(RichText::new(text).color(tokens.text_dim)); return; } + let as_list = app.ui.prefs.library_list; let tile = vec2(78.0, 100.0); - let cols = if as_list { 1 } else { ((ui.available_width() + 4.0) / (tile.x + 4.0)).floor().max(1.0) as usize }; + let columns = if as_list { 1 } else { ((ui.available_width() + 4.0) / (tile.x + 4.0)).floor().max(1.0) as usize }; let mut add = None; let mut favorite = None; - for chunk in list.chunks(cols) { + for chunk in list.chunks(columns) { ui.horizontal(|ui| { ui.spacing_mut().item_spacing = vec2(4.0, 4.0); for entry in chunk { let size = if as_list { vec2(ui.available_width(), 26.0) } else { tile }; let (rect, response) = ui.allocate_exact_size(size, Sense::click_and_drag()); crate::widgets::name(&response, egui::Role::ListItem, &entry.label); - let takes = here.takes(entry); + let takes = target.takes(entry); let selected = app.ui.library_selected.as_deref() == Some(entry.id.as_str()); if selected { - ui.painter().rect_filled(rect, 6.0, tk.row_selected); + ui.painter().rect_filled(rect, 6.0, tokens.row_selected); } else if response.hovered() { - ui.painter().rect_filled(rect, 6.0, tk.row_hover); + ui.painter().rect_filled(rect, 6.0, tokens.row_hover); } let fade = if takes { 1.0 } else { 0.4 }; let image = if as_list { @@ -350,7 +307,7 @@ fn items(app: &mut MaterialCraftApp, ui: &mut Ui, entries: &[LibraryEntry], here Rect::from_min_size(rect.min + vec2(5.0, 4.0), vec2(68.0, 68.0)) }; preview(app, ui, &ctx, entry, image, fade); - let color = if entry.warning.is_some() { WARNING } else { tk.text }; + let color = if entry.warning.is_some() { WARNING } else { tokens.text }; let color = color.gamma_multiply(if takes { 1.0 } else { 0.55 }); if as_list { let galley = crate::widgets::elided(ui.painter(), entry.label.clone(), 11.5, color, rect.width() - 34.0); @@ -361,14 +318,20 @@ fn items(app: &mut MaterialCraftApp, ui: &mut Ui, entries: &[LibraryEntry], here ui.painter().with_clip_rect(rect).galley(pos, galley, color); } if app.ui.library_favorites.contains(&entry.id) { - ui.painter().text(rect.right_top() + vec2(-8.0, 9.0), egui::Align2::CENTER_CENTER, icon::STAR, egui::FontId::proportional(10.0), tk.accent); + ui.painter().text( + rect.right_top() + vec2(-8.0, 9.0), + egui::Align2::CENTER_CENTER, + icon::STAR, + egui::FontId::proportional(10.0), + tokens.accent, + ); } let mut tip = format!("{}\n{}", entry.label, tr(&entry.category)); if !entry.description.is_empty() { tip.push_str(&format!("\n\n{}", entry.description)); } - if let Some(reason) = here.refusal(entry).or_else(|| entry.warning.clone()) { + if let Some(reason) = target.refusal(entry).or_else(|| entry.warning.clone()) { tip.push_str(&format!("\n\n{reason}")); } let response = response.on_hover_text(tip); @@ -441,6 +404,7 @@ fn preview(app: &mut MaterialCraftApp, ui: &Ui, ctx: &egui::Context, entry: &Lib } } +/// Choose the preview accent for an entry category. fn category_color(category: &str) -> Color32 { match category.split('/').next().unwrap_or("") { "Graph items" | "Atomic nodes" | "FxMap nodes" => Color32::from_rgb(0x5c, 0x62, 0x6e), @@ -456,6 +420,7 @@ fn category_color(category: &str) -> Color32 { } } +/// Create the payload accepted by the destination canvas. fn drag(ctx: &egui::Context, entry: &LibraryEntry) { match &entry.item { LibraryItem::Operation { operation } => egui::DragAndDrop::set_payload(ctx, FunctionLibraryDrag::Operation(operation.clone())), @@ -469,6 +434,25 @@ fn drag(ctx: &egui::Context, entry: &LibraryEntry) { /// Add `entry` to the open graph: native nodes next to the selection, the rest in the view pub(crate) fn add_entry(app: &mut MaterialCraftApp, entry: &LibraryEntry) { + if entry.canvas == LibraryCanvas::Any { + let target = crate::annotation::target(app); + crate::annotation::activate(app, target); + let camera = crate::annotation::camera(app); + let at = [camera.pan[0] + app.graph.view.width() * 0.5 / camera.zoom, camera.pan[1] + app.graph.view.height() * 0.5 / camera.zoom]; + if let Some(result) = app.run("library.add", serde_json::json!({"entry": entry.id, "at": at, "snapToGrid": app.ui.prefs.snap_to_grid})) { + let id = result["result"]["id"].as_u64().and_then(|id| u32::try_from(id).ok()); + let selection = if app.session.annotation_selection.is_some() { Vec::new() } else { id.into_iter().collect() }; + if let Some(editor) = &mut app.function_editor { + editor.selection = selection.clone(); + editor.selected_wires.clear(); + } + if let Some(editor) = &mut app.pattern_editor { + editor.selection = selection; + editor.selected_wires.clear(); + } + } + return; + } match &entry.item { LibraryItem::Operation { operation } => crate::function::library::add(app, &FunctionLibraryDrag::Operation(operation.clone())), LibraryItem::FunctionInstance { package, graph } => { diff --git a/crates/ui-egui/src/library.test.rs b/crates/ui-egui/src/library.test.rs index 522ca150..03f38c40 100644 --- a/crates/ui-egui/src/library.test.rs +++ b/crates/ui-egui/src/library.test.rs @@ -2,15 +2,18 @@ use super::*; use materialcraft_engine::core::NodeId; use serde_json::json; +/// Create a headless material editor for library interactions. fn app() -> MaterialCraftApp { MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default()) } +/// Collect labels visible under the current library filter. fn labels(app: &MaterialCraftApp) -> Vec<String> { let entries = app.session.library_entries(); - visible(app, &entries, &Here::of(app)).into_iter().map(|entry| entry.label.clone()).collect() + visible(app, &entries, &LibraryTarget::of(app)).into_iter().map(|entry| entry.label.clone()).collect() } +/// Open project graphs remain separate from reusable library entries. #[test] fn open_package_graphs_are_explorer_resources_not_library_entries() { let mut app = app(); @@ -26,6 +29,7 @@ fn open_package_graphs_are_explorer_resources_not_library_entries() { assert!(labels(&app).iter().any(|label| label == "Uniform color")); } +/// Category filtering includes descendants and favorite toggles update membership. #[test] fn categories_include_their_sub_categories_and_favorites_follow_the_star() { let mut app = app(); @@ -45,41 +49,57 @@ fn categories_include_their_sub_categories_and_favorites_follow_the_star() { assert_eq!(labels(&app), ["Pi"]); } +/// Tiles and list rows stay alphabetical across categories, favorites and search. #[test] -fn search_puts_what_the_open_graph_takes_first_and_filters_hide_the_rest() { +fn library_previews_are_alphabetical_in_every_view() { let mut app = app(); - // "Uniform" names a native node and random functions; a material graph takes only the node - app.ui.library_search = "uniform".into(); - let found = labels(&app); - assert_eq!(found.first().map(String::as_str), Some("Uniform color"), "{found:?}"); - assert!(found.len() > 1, "{found:?}"); - let entries = app.session.library_entries(); - let here = Here::of(&app); - let shown = visible(&app, &entries, &here); - let first_refused = shown.iter().position(|entry| !here.takes(entry)).unwrap(); - assert!(shown[first_refused..].iter().all(|entry| !here.takes(entry)), "addable entries come first"); + for (category, search) in [("", ""), ("Graph items", ""), ("Atomic nodes", ""), ("Functions", ""), ("", "uniform")] { + app.ui.library_category = category.into(); + app.ui.library_search = search.into(); + let found = labels(&app); + assert!(found.len() > 1); + let keys: Vec<_> = found.iter().map(|label| tr(label).to_lowercase()).collect(); + assert!(keys.windows(2).all(|pair| pair[0] <= pair[1]), "{category}/{search}: {found:?}"); + } app.ui.library_show_missing = false; app.ui.library_show_other = false; let entries = app.session.library_entries(); - assert!(visible(&app, &entries, &here).iter().all(|entry| here.takes(entry))); + let target = LibraryTarget::of(&app); + assert!(visible(&app, &entries, &target).iter().all(|entry| target.takes(entry))); } +/// The FX-Map category contains its three processing nodes, without a Dot tile. +#[test] +fn fx_map_library_does_not_list_dot() { + let mut app = app(); + app.ui.library_category = "FxMap nodes".into(); + let mut found = labels(&app); + found.sort(); + assert_eq!(found, ["Iterate", "Quadrant", "Switch"]); +} + +/// Both processor canvases accept samplers and keep material operations separate. #[test] fn processor_functions_take_operations_their_canvas_allows() { - let mut app = app(); - let owner = NodeId(app.run("graph.node.add", json!({"def": "value_processor"})).unwrap()["id"].as_u64().unwrap()); - app.function_editor = Some(crate::function::FunctionEditor::new(app.session.graph, owner, crate::function::FunctionTarget::Parameter("function".into()))); - let here = Here::of(&app); - let entries = app.session.library_entries(); - let find = |id: &str| entries.iter().find(|entry| entry.id == id).unwrap(); - assert!(here.takes(find("function:add"))); - assert!(here.takes(find("sbs://functions.sbs#Functions/Math/Pi"))); - assert!(!here.takes(find("function:samplecol")), "value processors can't sample images"); - assert!(!here.takes(find("node:blur"))); - assert!(here.refusal(find("node:blur")).is_some()); + for definition in ["pixel_processor", "value_processor"] { + let mut app = app(); + let owner = NodeId(app.run("graph.node.add", json!({"def": definition})).unwrap()["id"].as_u64().unwrap()); + app.function_editor = + Some(crate::function::FunctionEditor::new(app.session.graph, owner, crate::function::FunctionTarget::Parameter("function".into()))); + let target = LibraryTarget::of(&app); + let entries = app.session.library_entries(); + let find = |id: &str| entries.iter().find(|entry| entry.id == id).unwrap(); + + for id in ["function:add", "function:samplelum", "function:samplecol", "sbs://functions.sbs#Functions/Math/Pi"] { + assert!(target.takes(find(id)), "{definition}: {id}"); + } + assert!(!target.takes(find("node:blur"))); + assert!(target.refusal(find("node:blur")).is_some()); + } } +/// Known categories have icons and compatible entries can be inserted. #[test] fn every_tree_category_has_an_icon_and_double_click_adds() { for (top, subs) in CATEGORIES { @@ -92,10 +112,11 @@ fn every_tree_category_has_an_icon_and_double_click_adds() { let mut app = app(); let before = app.session.graph().unwrap().nodes.len(); let entries = app.session.library_entries(); + // A material graph takes the Blur node, not a function for id in ["node:blur", "sbs://functions.sbs#Functions/Math/Pi"] { let entry = entries.iter().find(|entry| entry.id == id).unwrap(); - if Here::of(&app).takes(entry) { + if LibraryTarget::of(&app).takes(entry) { add_entry(&mut app, entry); } } @@ -104,3 +125,43 @@ fn every_tree_category_has_an_icon_and_double_click_adds() { add_entry(&mut app, entries.iter().find(|entry| entry.id == "item:comment").unwrap()); assert_eq!(app.session.graph().unwrap().comments.len(), comments + 1); } + +/// Dot is a graph item rather than a second entry among function operations. +#[test] +fn function_control_library_does_not_list_dot() { + let mut app = app(); + app.ui.library_category = "Function nodes/Control".into(); + assert!(!labels(&app).iter().any(|label| label.to_lowercase().contains("dot"))); +} + +/// The shared Graph items remain available when hiding entries for other canvas types. +#[test] +fn graph_items_are_available_and_insertable_in_every_editor() { + for kind in ["material", "function", "pixel_processor", "value_processor", "fx_map"] { + let mut app = app(); + if kind == "function" { + app.run("file.new", json!({"kind": "function"})).unwrap(); + app.function_editor = Some(crate::function::FunctionEditor::standalone(app.session.graph)); + } else if kind != "material" { + let owner = NodeId(app.run("graph.node.add", json!({"def": kind})).unwrap()["id"].as_u64().unwrap()); + if kind == "fx_map" { + app.pattern_editor = Some(crate::pattern::PatternEditor::new(app.session.graph, owner)); + } else { + app.function_editor = + Some(crate::function::FunctionEditor::new(app.session.graph, owner, crate::function::FunctionTarget::Parameter("function".into()))); + } + } + app.graph.view = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + app.ui.library_category = "Graph items".into(); + app.ui.library_show_other = false; + assert_eq!(labels(&app), ["Comment", "Dot node", "Frame", "Pin"], "{kind}"); + let entries = app.session.library_entries(); + let target = LibraryTarget::of(&app); + for entry in entries.iter().filter(|entry| entry.category == "Graph items") { + assert!(target.takes(entry), "{kind}: {}", entry.label); + add_entry(&mut app, entry); + } + let items = crate::annotation::target(&app).items(&app.session).unwrap(); + assert_eq!((items.comments.len(), items.frames.len(), items.pins.len()), (1, 1, 1), "{kind}"); + } +} diff --git a/crates/ui-egui/src/library/library_target.rs b/crates/ui-egui/src/library/library_target.rs new file mode 100644 index 00000000..cdb2908b --- /dev/null +++ b/crates/ui-egui/src/library/library_target.rs @@ -0,0 +1,48 @@ +use crate::{MaterialCraftApp, graph::editor_target::EditorTarget, i18n::tr}; +use materialcraft_engine::{LibraryCanvas, LibraryEntry, LibraryItem}; + +/// The graph the library adds to, and which native function operations it can take +pub(crate) struct LibraryTarget { + pub(super) canvas: LibraryCanvas, + operations: Vec<&'static str>, +} + +impl LibraryTarget { + /// Resolve the active editor and its permitted operations. + pub(crate) fn of(app: &MaterialCraftApp) -> LibraryTarget { + match EditorTarget::resolve(app) { + EditorTarget::Material => LibraryTarget { canvas: LibraryCanvas::Material, operations: Vec::new() }, + EditorTarget::Pattern => LibraryTarget { canvas: LibraryCanvas::Pattern, operations: Vec::new() }, + EditorTarget::Function => LibraryTarget { canvas: LibraryCanvas::Function, operations: crate::function::library::available_operations(app) }, + } + } + + /// Whether `entry` can go into the open graph now + pub(crate) fn takes(&self, entry: &LibraryEntry) -> bool { + entry.missing.is_none() + && (entry.canvas == LibraryCanvas::Any || entry.canvas == self.canvas) + && match &entry.item { + LibraryItem::Operation { operation } => self.operations.contains(&operation.as_str()), + _ => true, + } + } + + /// Why `entry` can't go into the open graph, when it can't + pub(super) fn refusal(&self, entry: &LibraryEntry) -> Option<String> { + if let Some(missing) = &entry.missing { + return Some(missing.clone()); + } + + if entry.canvas != LibraryCanvas::Any && entry.canvas != self.canvas { + return Some( + match entry.canvas { + LibraryCanvas::Any | LibraryCanvas::Material => tr("Open a graph to add this"), + LibraryCanvas::Function => tr("Open a function graph or a processor's function to add this"), + LibraryCanvas::Pattern => tr("Open an FX-Map to add this"), + } + .to_string(), + ); + } + (!self.takes(entry)).then(|| tr("This function can't use this node").to_string()) + } +} diff --git a/crates/ui-egui/src/material_craft_app.rs b/crates/ui-egui/src/material_craft_app.rs index e89d73c2..d958caa0 100644 --- a/crates/ui-egui/src/material_craft_app.rs +++ b/crates/ui-egui/src/material_craft_app.rs @@ -147,6 +147,21 @@ impl MaterialCraftApp { /// Run an engine command, reporting errors as toasts. Returns the result on success pub fn run(&mut self, id: &str, mut params: Value) -> Option<Value> { + if id.starts_with("graph.annotation.") + || id.starts_with("graph.frame.") + || id.starts_with("graph.comment.") + || id.starts_with("graph.pin.") + || id == "library.add" + { + if params.is_null() { + params = serde_json::json!({}); + } + if let (Some(parameters), Some(target)) = (params.as_object_mut(), self.graph.annotation_target.parameters().as_object()) { + for (name, value) in target { + parameters.entry(name).or_insert_with(|| value.clone()); + } + } + } if id.starts_with("file.") || id.starts_with("package.") || matches!(id, "graph.open" | "graph.delete" | "graph.duplicate" | "folder.remove" | "explorer.paste" | "edit.undo" | "edit.redo") @@ -186,6 +201,14 @@ impl MaterialCraftApp { match cook::execute_guarded(&mut self.session, id, ¶ms) { Ok(v) => { + if matches!(id, "graph.pin.add" | "library.add") + && let Some(materialcraft_engine::AnnotationSelection::Pin(pin)) = self.session.annotation_selection + { + self.graph.pin_description_focus = Some(pin); + self.inspected_folder = None; + self.inspected_graph = None; + self.ui.dock.focus(docking::Panel::Properties); + } if id == "view.previewSize" { self.ui.prefs.preview_size = self.session.preview_size.unwrap_or(0); } @@ -384,6 +407,7 @@ impl MaterialCraftApp { /// Draw the whole window into `ui` pub fn draw(&mut self, ui: &mut egui::Ui) { + crate::annotation::activate(self, crate::annotation::target(self)); if !self.fonts_ready { self.fonts_ready = true; return; @@ -395,6 +419,7 @@ impl MaterialCraftApp { menus::menu_bar(self, ui); toolbar::main_toolbar(self, ui); toolbar::status_bar(self, ui); + self.ui.explorer.hovered = false; egui::CentralPanel::default().frame(egui::Frame::NONE.fill(theme::Tokens::get(&ctx).chrome)).show(ui, |ui| docking::show(self, ui)); windows::show(self, &ctx); #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/material_craft_app.test.rs b/crates/ui-egui/src/material_craft_app.test.rs index 2cbb012c..7363dbc6 100644 --- a/crates/ui-egui/src/material_craft_app.test.rs +++ b/crates/ui-egui/src/material_craft_app.test.rs @@ -5,6 +5,20 @@ mod lib_tests { use materialcraft_engine::sample_session; use serde_json::json; + /// A frame which does not draw Explorer clears hover state left by its previous frame. + #[test] + fn review_hidden_explorer_drawing_clears_hover() { + let mut app = MaterialCraftApp::headless(sample_session(), UiState::default()); + app.fonts_ready = true; + app.ui.explorer.hovered = true; + app.ui.dock.close(crate::docking::Panel::Explorer); + let context = egui::Context::default(); + + context.run_ui(egui::RawInput::default(), |ui| app.draw(ui)).textures_delta.clear(); + + assert!(!app.ui.explorer.hovered); + } + #[test] fn run_reports_errors_as_toasts_and_keeps_the_session() { let mut app = MaterialCraftApp::headless(sample_session(), UiState::default()); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index cc703560..18ef4cff 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1,6 +1,7 @@ //! Menu actions and shortcuts share stable command ids use craft_keymap::{Active, Bindable, Binding, Chord, Keymap, Platform, Scope, Scopes}; +use egui::class::HasClasses as _; use serde_json::Value; use crate::MaterialCraftApp; @@ -27,15 +28,7 @@ pub const TOP: [&str; 5] = ["File", "Edit", "Tools", "Windows", "Help"]; pub(crate) const EXPLORER_NEW: &[(&str, &str)] = &[("Graph", "ui.newGraph"), ("Function Graph", "ui.newFunctionGraph"), ("Folder", "folder.create")]; pub(crate) const EXPLORER_IMPORT: &[(&str, &str)] = &[("Bitmap", "file.importBitmap"), ("Vector graphics", "file.importVector")]; pub(crate) const EXPLORER_RESOURCE: &[(&str, &str)] = &[("Add to graph", "graph.resource.add")]; -/// A row of an Explorer context menu -#[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) enum ExplorerRow { - /// A label, the action id (empty: not available yet) and the shortcut shown beside it - Item(&'static str, &'static str, Option<&'static str>), - /// A submenu of (label, action id); an empty id is not available yet - Sub(&'static str, &'static [(&'static str, &'static str)]), - Separator, -} +pub(crate) use crate::explorer::explorer_row::ExplorerRow; use ExplorerRow::{Item, Separator, Sub}; /// Linking keeps a resource outside the package; MaterialCraft only embeds resources so far @@ -294,44 +287,49 @@ pub fn shortcut_of(id: &str) -> Option<&'static str> { CATALOG.iter().find(|i| i.id == id).and_then(|i| i.shortcut).or_else(|| materialcraft_engine::find(id).and_then(|c| c.shortcut)) } +/// Draw menu bars with aligned labels and a separate gutter for checkmarks. pub fn menu_bar(app: &mut MaterialCraftApp, ui: &mut egui::Ui) { - let tk = Tokens::get(ui.ctx()); - egui::Panel::top("menu_bar").exact_size(24.0).frame(egui::Frame::NONE.fill(tk.chrome).inner_margin(egui::Margin::symmetric(6, 0))).show(ui, |ui| { + let tokens = Tokens::get(ui.ctx()); + egui::Panel::top("menu_bar").exact_size(24.0).frame(egui::Frame::NONE.fill(tokens.chrome).inner_margin(egui::Margin::symmetric(6, 0))).show(ui, |ui| { #[cfg(not(target_arch = "wasm32"))] let window_layout = app.window_layout.clone(); #[cfg(not(target_arch = "wasm32"))] if window_layout.is_some() { craft_window::title_bar::empty_area(ui, ui.max_rect()); } + egui::MenuBar::new().ui(ui, |ui| { - let ctx = ui.ctx().clone(); + let context = ui.ctx().clone(); #[cfg(not(target_arch = "wasm32"))] if let Some(layout) = &window_layout { - crate::window_controls::buttons(ui, &ctx, &layout.left); + crate::window_controls::buttons(ui, &context, &layout.left); } for top in TOP { ui.menu_button(tr(top), |ui| { ui.set_min_width(220.0); - let mut current_sub: Option<&str> = None; - let items: Vec<MenuItem> = CATALOG.iter().filter(|i| i.menu == top).copied().collect(); + let mut current_submenu: Option<&str> = None; + let items: Vec<MenuItem> = CATALOG.iter().filter(|item| item.menu == top).copied().collect(); for item in &items { - if let Some(s) = item.sub { - if current_sub == Some(s) { + if let Some(submenu) = item.sub { + if current_submenu == Some(submenu) { continue; } - current_sub = Some(s); - ui.menu_button(tr(s), |ui| { - for x in items.iter().filter(|x| x.sub == Some(s)) { - menu_item(app, &ctx, ui, x); + + current_submenu = Some(submenu); + ui.menu_button(menu_label(tr(submenu)), |ui| { + for entry in items.iter().filter(|entry| entry.sub == Some(submenu)) { + menu_item(app, &context, ui, entry); } }); continue; } + if item.label == "-" { ui.separator(); continue; } - menu_item(app, &ctx, ui, item); + + menu_item(app, &context, ui, item); } }); } @@ -340,46 +338,71 @@ pub fn menu_bar(app: &mut MaterialCraftApp, ui: &mut egui::Ui) { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let mut right = layout.right.clone(); right.reverse(); - crate::window_controls::buttons(ui, &ctx, &right); + crate::window_controls::buttons(ui, &context, &right); }); } }); }); } -fn menu_item(app: &mut MaterialCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, item: &MenuItem) { - let modality = Modality::capture(app, ctx); - let on = modality.allows(item.id) && enabled(app, item.id); - let mut b = egui::Button::new(tr(item.label)); - if let Some(sc) = item.shortcut { - b = b.shortcut_text(shortcut_label(ctx, sc)); +/// Reserve the same checkmark gutter for commands, toggles and submenus. +fn menu_label(label: &str) -> (egui::Atom<'_>, &str) { + (egui::Atom::custom(egui::IdSalt::new("menu-checkmark"), egui::vec2(12.0, 12.0)), label) +} + +/// Draw a command with an optional checkmark and dispatch it when activated. +fn menu_item(app: &mut MaterialCraftApp, context: &egui::Context, ui: &mut egui::Ui, item: &MenuItem) { + let modality = Modality::capture(app, context); + let is_enabled = modality.allows(item.id) && enabled(app, item.id); + let mut button = egui::Button::new(menu_label(tr(item.label))); + if let Some(shortcut) = item.shortcut { + button = button.shortcut_text(shortcut_label(context, shortcut)); } let checked = match item.id { "ui.view.graph" => Some(true), "ui.graph.snapToGrid" => Some(app.ui.prefs.snap_to_grid), - id if id.starts_with("ui.preview.") => id.strip_prefix("ui.preview.").and_then(|s| s.parse::<u32>().ok()).map(|s| s == app.ui.prefs.preview_size), - id => crate::docking::view_panel(id).map(|p| app.ui.dock.is_open(p)), + id if id.starts_with("ui.preview.") => { + id.strip_prefix("ui.preview.").and_then(|size| size.parse::<u32>().ok()).map(|size| size == app.ui.prefs.preview_size) + } + id => crate::docking::view_panel(id).map(|panel| app.ui.dock.is_open(panel)), }; - - if let Some(c) = checked { - b = b.selected(c); + if let Some(checked) = checked { + // Keep the accessible toggle state without styling the entire row as selected + button = button.selected(checked); + button.remove_class(egui::Button::CLASS_SELECTED); } - if ui.add_enabled(on, b).clicked() { - invoke(app, ctx, item.id); + + let response = ui.add_enabled(is_enabled, |ui: &mut egui::Ui| { + let response = button.atom_ui(ui); + if checked == Some(true) + && let Some(rect) = response.rect(egui::IdSalt::new("menu-checkmark")) + { + let center = rect.center(); + let color = ui.style().interact(&response).fg_stroke.color; + ui.painter().add(egui::Shape::line( + vec![center + egui::vec2(-4.0, 0.0), center + egui::vec2(-1.0, 3.0), center + egui::vec2(4.0, -3.0)], + egui::Stroke::new(1.5, color), + )); + } + response.response + }); + if response.clicked() { + invoke(app, context, item.id); ui.close(); } + #[cfg(not(target_arch = "wasm32"))] if item.id == "file.open" { ui.add_enabled_ui(!modality.is_blocked() && !app.ui.recent.is_empty(), |ui| { - ui.menu_button(tr("Recent packages"), |ui| { + ui.menu_button(menu_label(tr("Recent packages")), |ui| { for path in app.ui.recent.clone() { - if ui.button(&path).clicked() { + if ui.button(menu_label(&path)).clicked() { crate::windows::open_path(app, &path); ui.close(); } } ui.separator(); - if ui.button(tr("Clear recent packages")).clicked() { + if ui.button(menu_label(tr("Clear recent packages"))).clicked() { app.ui.recent.clear(); ui.close(); } @@ -641,6 +664,7 @@ mod tests { assert!(app.ui.windows.export); } + /// Explorer shortcuts affect the hovered selection and leave graph shortcuts elsewhere. #[test] fn explorer_keys_act_on_its_selection_only_while_hovered() { use crate::explorer::ExplorerTarget; @@ -666,6 +690,7 @@ mod tests { assert_eq!(app.session.pkg.graphs.len(), graphs, "removing a graph undoes"); } + /// Explorer menu actions resolve through their documented UI or engine handler. #[test] fn explorer_menus_name_only_actions_that_exist() { for rows in [EXPLORER_PACKAGE, EXPLORER_FOLDER, EXPLORER_GRAPH] { @@ -823,4 +848,17 @@ mod tests { ctx.set_os(egui::os::OperatingSystem::Windows); assert_eq!(shortcut_label(&ctx, "Ctrl+Shift+E"), "Ctrl+Shift+E"); } + /// A hidden Explorer must not delete its selection using stale hover state. + #[test] + fn review_hidden_explorer_ignores_delete() { + let mut app = app(); + let graphs = app.session.pkg.graphs.len(); + app.ui.explorer.selected = Some(crate::explorer::ExplorerTarget::Graph { document: app.session.document_id, index: 0 }); + app.ui.explorer.hovered = true; + app.ui.dock.close(crate::docking::Panel::Explorer); + + dispatched(egui::Key::Delete, egui::Modifiers::NONE, &mut app); + + assert_eq!(app.session.pkg.graphs.len(), graphs); + } } diff --git a/crates/ui-egui/src/pattern/actions.rs b/crates/ui-egui/src/pattern/actions.rs index 9b3c96b7..83ff7ae9 100644 --- a/crates/ui-egui/src/pattern/actions.rs +++ b/crates/ui-egui/src/pattern/actions.rs @@ -16,7 +16,14 @@ pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option<bool> { return Some(enabled); } match command { - "ui.graph.snapToGrid" | "graph.cook" | "edit.finish" => None, + "ui.graph.snapToGrid" + | "graph.cook" + | "edit.finish" + | "graph.frame.add" + | "graph.comment.add" + | "graph.pin.add" + | "ui.graph.nextPin" + | "ui.graph.previousPin" => None, command if command.starts_with("graph.") || command.starts_with("ui.graph.") @@ -43,6 +50,10 @@ pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool { } pub(super) fn invoke_editor(app: &mut MaterialCraftApp, editor: &mut PatternEditor, command: &str) { + if app.session.annotation_selection.is_some() && matches!(command, "edit.delete" | "edit.deleteRelink") { + app.run(command, serde_json::json!({})); + return; + } if editor_enabled(app, editor, command) != Some(true) { return; } @@ -61,6 +72,9 @@ pub(super) fn invoke_editor(app: &mut MaterialCraftApp, editor: &mut PatternEdit } pub(super) fn editor_enabled(app: &MaterialCraftApp, editor: &PatternEditor, command: &str) -> Option<bool> { + if app.session.annotation_selection.is_some() && matches!(command, "edit.delete" | "edit.deleteRelink") { + return Some(true); + } let target = materialcraft_engine::SelectionTarget::Pattern(editor.node); if let Some(enabled) = crate::graph::wire_actions::enabled(app, command, &editor.selected_wires, Some(&target)) { return Some(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 ba8688e6..b8b1f2c5 100644 --- a/crates/ui-egui/src/pattern/canvas.rs +++ b/crates/ui-egui/src/pattern/canvas.rs @@ -4,7 +4,7 @@ use materialcraft_engine::core::NodeId; use materialcraft_engine::nodes::PortKind; use std::collections::BTreeMap; -use super::{PatternDrag, PatternEditor, geometry}; +use super::{PatternDrag, PatternEditor, geometry, pattern_canvas::PatternCanvas}; use crate::{ MaterialCraftApp, graph::{GraphCamera, PortHit}, @@ -21,13 +21,24 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { 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 }; + let Some(PatternCanvas { geometry, response, camera, frames, comments, pins }) = 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); + app.graph.frames = frames.iter().map(|frame| (frame.id, frame.rect)).collect(); + app.graph.comments = comments.clone(); + app.graph.pins = pins.clone(); + let on_annotation = ui + .input(|input| input.pointer.hover_pos()) + .is_some_and(|pointer| frames.iter().any(|frame| frame.contains(pointer)) || comments.iter().chain(&pins).any(|(_, rect)| rect.contains(pointer))); + super::input::handle(app, &mut editor, ui, &response, &camera, on_annotation); + if editor.drag.is_none() { + crate::graph::annotation_input::handle(app, ui, &camera, &frames, &comments, &pins); + if app.session.annotation_selection.is_some() { + editor.selection.clear(); + editor.selected_wires.clear(); + } + } if let Some(PatternDrag::Wire { node, slot }) = editor.drag && let Some(source) = app.graph.ports.iter().find(|port| { port.node.0 == u64::from(node) @@ -44,11 +55,12 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { app.pattern_editor = Some(editor); } -fn paint(app: &MaterialCraftApp, editor: &mut PatternEditor, ui: &mut Ui) -> Option<(CanvasGeometry, egui::Response, GraphCamera)> { +fn paint(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: &mut Ui) -> Option<PatternCanvas> { + let (bounds, response) = ui.allocate_exact_size(ui.available_size().max(vec2(100.0, 100.0)), Sense::click_and_drag()); + app.graph.view = bounds; 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)); @@ -56,12 +68,18 @@ fn paint(app: &MaterialCraftApp, editor: &mut PatternEditor, ui: &mut Ui) -> Opt let frame_key = GraphCamera::frame_key(ui, bounds) && !crate::shell::modality::Modality::capture(app, ui.ctx()).is_blocked(); if !editor.framed || app.ui.frame_all || frame_key { let selected_only = frame_key && !editor.selection.is_empty(); - let destination = graph + let mut 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)); + if !selected_only { + for frame in &graph.annotations.frames { + destination = + destination.union(Rect::from_min_size(egui::pos2(frame.rect[0], frame.rect[1] - 32.0), vec2(frame.rect[2], frame.rect[3] + 32.0))); + } + } let camera = GraphCamera::fit(bounds, destination); editor.pan = camera.pan; editor.zoom = camera.zoom; @@ -73,12 +91,14 @@ fn paint(app: &MaterialCraftApp, editor: &mut PatternEditor, ui: &mut Ui) -> Opt editor.pan = camera.pan; editor.zoom = camera.zoom; crate::graph::grid::paint(&painter, &camera, bounds); + let frames = crate::graph::annotation_canvas::frames(app, ui, &graph.annotations.frames, &camera); let tokens = Tokens::get(ui.ctx()); let rectangles: BTreeMap<_, _> = graph .nodes .iter() .map(|node| { - let bounds = geometry::bounds(node, editor, snap, selected.contains(&node.id)); + let bounds = geometry::bounds(node, editor, snap, selected.contains(&node.id)) + .translate(crate::graph::annotation_canvas::offset(app, |contents| contents.nodes.contains(&NodeId(u64::from(node.id))))); (node.id, Rect::from_min_max(camera.to_screen(bounds.min), camera.to_screen(bounds.max))) }) .collect(); @@ -140,5 +160,7 @@ fn paint(app: &MaterialCraftApp, editor: &mut PatternEditor, ui: &mut Ui) -> Opt } } - Some((geometry, response, camera)) + let comments = crate::graph::annotation_canvas::comments(app, ui, &graph.annotations.comments, &camera); + let pins = crate::graph::annotation_canvas::pins(app, ui, &graph.annotations.pins, &camera); + Some(PatternCanvas { geometry, response, camera, frames, comments, pins }) } diff --git a/crates/ui-egui/src/pattern/context_menu.rs b/crates/ui-egui/src/pattern/context_menu.rs index e514097f..2c930f9a 100644 --- a/crates/ui-egui/src/pattern/context_menu.rs +++ b/crates/ui-egui/src/pattern/context_menu.rs @@ -11,6 +11,13 @@ pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: & add = PatternNodeKind::ALL.into_iter().find(|kind| kind.native_id() == id); } }); + for (label, entry) in [("Add Comment", "item:comment"), ("Add Frame", "item:frame"), ("Add Navigation pin", "item:pin")] { + if ui.button(tr(label)).clicked() { + app.run("library.add", serde_json::json!({"entry": entry, "at": [editor.menu_at.x, editor.menu_at.y]})); + editor.selection.clear(); + ui.close(); + } + } if ui.button(tr("Add Dot node")).clicked() { add = Some(PatternNodeKind::Dot); ui.close(); diff --git a/crates/ui-egui/src/pattern/input.rs b/crates/ui-egui/src/pattern/input.rs index 3d262b66..e78598b8 100644 --- a/crates/ui-egui/src/pattern/input.rs +++ b/crates/ui-egui/src/pattern/input.rs @@ -4,7 +4,7 @@ use materialcraft_engine::PatternEdit; use super::{PatternDrag, PatternEditor}; use crate::{MaterialCraftApp, graph::GraphCamera}; -pub(super) fn handle(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: &Ui, response: &Response, camera: &GraphCamera) { +pub(super) fn handle(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: &Ui, response: &Response, camera: &GraphCamera, on_annotation: bool) { if crate::graph::gesture::cancelled(ui) { editor.drag = None; return; @@ -21,7 +21,8 @@ pub(super) fn handle(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: 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 on_wire = editor.drag.is_none() + let on_wire = !on_annotation + && editor.drag.is_none() && port.is_none() && node.is_none() && !modifiers.alt @@ -32,7 +33,16 @@ pub(super) fn handle(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: && !(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() && !on_wire && response.hovered() && ui.input(|input| input.pointer.button_pressed(PointerButton::Primary)) { + } else if !on_annotation + && !app.graph.is_dragging() + && editor.drag.is_none() + && !on_wire + && response.hovered() + && ui.input(|input| input.pointer.button_pressed(PointerButton::Primary)) + { + if app.session.annotation_selection.is_some() { + app.run("graph.annotation.select", serde_json::json!({})); + } crate::graph::node_selection::select(&mut editor.selected_wires, None, modifiers); if let Some((id, slot)) = port { if modifiers.alt { @@ -87,6 +97,17 @@ pub(super) fn handle(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: _ => {} } } + if let Some(payload) = crate::widgets::dnd_release::<crate::graph::LibraryDrag>(response) + && let Some(result) = + app.run("library.add", serde_json::json!({"entry": payload.0, "at": [position.x, position.y], "snapToGrid": app.ui.prefs.snap_to_grid})) + { + editor.selection = if app.session.annotation_selection.is_some() { + Vec::new() + } else { + result["result"]["id"].as_u64().and_then(|id| u32::try_from(id).ok()).into_iter().collect() + }; + editor.selected_wires.clear(); + } if response.secondary_clicked() { editor.menu_at = position; if let Some(id) = node diff --git a/crates/ui-egui/src/pattern/mod.rs b/crates/ui-egui/src/pattern/mod.rs index dc56d042..a4ab07ad 100644 --- a/crates/ui-egui/src/pattern/mod.rs +++ b/crates/ui-egui/src/pattern/mod.rs @@ -6,6 +6,7 @@ mod input; pub(crate) mod library; mod node_canvas; mod parameter_value; +mod pattern_canvas; mod pattern_drag; mod pattern_editor; pub(crate) mod properties; diff --git a/crates/ui-egui/src/pattern/pattern_canvas.rs b/crates/ui-egui/src/pattern/pattern_canvas.rs new file mode 100644 index 00000000..7e956afc --- /dev/null +++ b/crates/ui-egui/src/pattern/pattern_canvas.rs @@ -0,0 +1,12 @@ +use crate::graph::{GraphCamera, canvas_geometry::CanvasGeometry, frame_hit::FrameHit}; +use egui::{Rect, Response}; + +/// Geometry and annotation hit targets produced by one FX-Map canvas frame. +pub(super) struct PatternCanvas { + pub geometry: CanvasGeometry, + pub response: Response, + pub camera: GraphCamera, + pub frames: Vec<FrameHit>, + pub comments: Vec<(u64, Rect)>, + pub pins: Vec<(u64, Rect)>, +} diff --git a/crates/ui-egui/src/pattern/pattern_editor.rs b/crates/ui-egui/src/pattern/pattern_editor.rs index ccb1b6cb..2565adfe 100644 --- a/crates/ui-egui/src/pattern/pattern_editor.rs +++ b/crates/ui-egui/src/pattern/pattern_editor.rs @@ -19,6 +19,15 @@ pub struct PatternEditor { } impl PatternEditor { + pub(crate) fn camera(&self) -> crate::state::GraphCamera { + crate::state::GraphCamera { pan: self.pan.into(), zoom: self.zoom } + } + + 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) -> Self { Self { node, diff --git a/crates/ui-egui/src/property/mod.rs b/crates/ui-egui/src/property/mod.rs index da9ae909..9eadab1d 100644 --- a/crates/ui-egui/src/property/mod.rs +++ b/crates/ui-egui/src/property/mod.rs @@ -31,7 +31,7 @@ pub fn title(app: &MaterialCraftApp) -> String { } match EditorTarget::resolve(app) { - EditorTarget::Pattern => return crate::pattern::properties::title(app), + EditorTarget::Pattern if !EditorTarget::annotation_active(app) => return crate::pattern::properties::title(app), EditorTarget::Function if !EditorTarget::annotation_active(app) => { return crate::function::properties::title(app).unwrap_or_else(|| { let name = app.session.graph().ok().filter(|graph| graph.function.is_some()).map_or(tr("Function Graph"), |graph| graph.name.as_str()); @@ -45,6 +45,7 @@ pub fn title(app: &MaterialCraftApp) -> String { let name = match selection { materialcraft_engine::AnnotationSelection::Frame(_) => tr("Frame"), materialcraft_engine::AnnotationSelection::Comment(_) => tr("Comment"), + materialcraft_engine::AnnotationSelection::Pin(_) => tr("Navigation Pin"), }; return format!("{name} - {}", tr("Properties")); } @@ -73,7 +74,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } match EditorTarget::resolve(app) { - EditorTarget::Pattern => { + EditorTarget::Pattern if !EditorTarget::annotation_active(app) => { crate::pattern::properties::show(app, ui); return; } diff --git a/crates/ui-egui/tests/snapshot.rs b/crates/ui-egui/tests/snapshot.rs index afede052..426b0c63 100644 --- a/crates/ui-egui/tests/snapshot.rs +++ b/crates/ui-egui/tests/snapshot.rs @@ -1,3 +1,6 @@ +#[path = "snapshot/graph_items.rs"] +mod graph_items; + #[path = "snapshot/explorer.rs"] mod explorer; @@ -16,6 +19,9 @@ mod embedded_graphs; #[path = "snapshot/library.rs"] mod library; +#[path = "snapshot/menu.rs"] +mod menu; + use std::time::Duration; use egui::vec2; @@ -1379,19 +1385,29 @@ fn embedded_function_toolbar_and_panels_share_the_active_target() { save(&mut harness, &directory, &format!("{definition}-inline-function")); harness.state_mut().ui.library_search = "Sample".into(); settle(&mut harness, 2); - for label in ["Sample gray", "Sample color"] { - assert_eq!(harness.query_all(By::new().label(label)).next().is_some(), definition == "pixel_processor"); + for (label, operation) in [("Sample gray", "samplelum"), ("Sample color", "samplecol")] { + let tile = harness.get(By::new().role(egui::accesskit::Role::ListItem).label(label)); + let position = tile.rect().center(); + + double_click(&mut harness, position); + + assert!(target.current(&harness.state().session).unwrap().nodes.iter().any(|node| node.op == operation)); + materialcraft_ui_egui::menus::invoke(harness.state_mut(), &context, "edit.undo"); + settle(&mut harness, 2); + assert_eq!(harness.state().session.pkg, original); } + save(&mut harness, &directory, &format!("{definition}-library-samplers")); + 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 gray", "Sample color"] { - assert_eq!(harness.query_all(query(label)).next().is_some(), definition == "pixel_processor"); + assert!(harness.query_all(query(label)).next().is_some()); } let labels: Vec<_> = target.available_operations(&harness.state().session).filter(|operation| operation.id != "passthrough").map(|operation| operation.label).collect(); - assert_eq!(labels.len(), if definition == "pixel_processor" { 84 } else { 82 }); + assert_eq!(labels.len(), materialcraft_engine::nodes::function::FUNCTIONS.iter().filter(|operation| operation.id != "passthrough").count()); assert!(harness.query(query("Dot")).is_none()); save(&mut harness, &directory, &format!("{definition}-node-menu")); assert_node_menu_order(&harness, &labels); diff --git a/crates/ui-egui/tests/snapshot/function_library.rs b/crates/ui-egui/tests/snapshot/function_library.rs index 615254ca..212976ce 100644 --- a/crates/ui-egui/tests/snapshot/function_library.rs +++ b/crates/ui-egui/tests/snapshot/function_library.rs @@ -124,3 +124,44 @@ fn bundled_even_count_opens_as_an_editable_arithmetic_tree() { assert_eq!(function.node(function.output.unwrap()).unwrap().op, "ceil"); save(&mut harness, &directory, "even-count-arithmetic-tree"); } + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn samplers_drag_into_both_processor_canvases() { + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + 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})).unwrap()["id"].as_u64().unwrap()); + app.ui.library_search = "Sample".into(); + app.ui.prefs.snap_to_grid = false; + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 5); + harness.key_press_modifiers(egui::Modifiers::CTRL | egui::Modifiers::COMMAND, egui::Key::E); + settle(&mut harness, 4); + let target = FunctionGraphTarget::Parameter { node: owner, parameter: "function".into() }; + let parent_position = harness.state().session.graph().unwrap().node(owner).unwrap().pos; + let parent_count = harness.state().session.graph().unwrap().nodes.len(); + + for (label, operation, offset) in [("Sample gray", "samplelum", vec2(-150.0, 0.0)), ("Sample color", "samplecol", vec2(150.0, 0.0))] { + let before = target.current(&harness.state().session).unwrap().clone(); + + drag(&mut harness, label, offset); + + let function = target.current(&harness.state().session).unwrap(); + assert_eq!(function.nodes.len(), before.nodes.len() + 1, "{definition}: {label}"); + let added = function.nodes.iter().find(|node| !before.nodes.iter().any(|previous| previous.id == node.id)).unwrap(); + assert_eq!(added.op, operation); + harness.get(By::new().role(egui::accesskit::Role::Button).label(label)); + let after = function.clone(); + harness.state_mut().session.undo().unwrap(); + assert_eq!(target.current(&harness.state().session).unwrap(), &before); + harness.state_mut().session.redo().unwrap(); + assert_eq!(target.current(&harness.state().session).unwrap(), &after); + settle(&mut harness, 2); + } + assert_eq!(harness.state().session.graph().unwrap().nodes.len(), parent_count); + assert_eq!(harness.state().session.graph().unwrap().node(owner).unwrap().pos, parent_position); + save(&mut harness, &directory, &format!("library-sampler-drag-{definition}")); + } +} diff --git a/crates/ui-egui/tests/snapshot/graph_items.rs b/crates/ui-egui/tests/snapshot/graph_items.rs new file mode 100644 index 00000000..852ebe61 --- /dev/null +++ b/crates/ui-egui/tests/snapshot/graph_items.rs @@ -0,0 +1,68 @@ +use super::{By, MaterialCraftApp, Queryable, UiState, harness, save, settle}; +use egui::{Event, Key, Modifiers, PointerButton, accesskit::Role, vec2}; +use serde_json::json; + +/// A Library pin can be dropped, renamed, reselected and deleted on every canvas. +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn navigation_pin_library_drop_and_properties_in_every_canvas() { + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + for kind in ["material", "function", "pixel_processor", "value_processor", "fx_map"] { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + if kind == "function" { + app.run("file.new", json!({"kind": "function"})).unwrap(); + } else if kind != "material" { + app.run("graph.node.add", json!({"def": kind})).unwrap(); + materialcraft_ui_egui::menus::invoke(&mut app, &egui::Context::default(), "graph.node.edit"); + } + app.ui.library_category = "Graph items".into(); + app.ui.library_show_other = false; + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 6); + for label in ["Comment", "Dot node", "Frame", "Pin"] { + assert!(harness.query(By::new().role(Role::ListItem).label(label)).is_some(), "{kind}: {label}"); + } + let start = harness.get(By::new().role(Role::ListItem).label("Pin")).rect().center(); + let end = harness.state().graph.view.center() + vec2(130.0, 80.0); + harness.event(Event::PointerMoved(start)); + harness.step(); + harness.event(Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.step(); + for position in [start + vec2(15.0, 0.0), end] { + harness.event(Event::PointerMoved(position)); + harness.step(); + } + harness.event(Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + settle(&mut harness, 4); + let target = harness.state().session.annotation_target.clone(); + assert_eq!(target.items(&harness.state().session).unwrap().pins.len(), 1, "{kind}"); + let input = By::new().role(Role::TextInput).label("Navigation Pin description"); + assert!(harness.query(input.clone()).is_some(), "{kind}"); + assert!(harness.ctx.egui_wants_keyboard_input(), "new pin description must receive focus: {kind}"); + harness.event(Event::ModifiersChanged(Modifiers::COMMAND)); + harness.event(Event::Key { key: Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND }); + harness.step(); + harness.event(Event::Key { key: Key::A, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::COMMAND }); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.event(Event::Text("Review checkpoint".into())); + settle(&mut harness, 3); + assert_eq!(target.items(&harness.state().session).unwrap().pins[0].name, "Review checkpoint", "{kind}"); + save(&mut harness, &directory, &format!("navigation-pin-{kind}")); + + let marker = harness.state().graph.pins[0].1.left_center() + vec2(6.0, 0.0); + harness.event(Event::PointerMoved(marker)); + harness.step(); + for pressed in [true, false] { + harness.event(Event::PointerButton { pos: marker, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + harness.step(); + } + harness.event(Event::Key { key: Key::Delete, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + harness.step(); + harness.event(Event::Key { key: Key::Delete, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }); + settle(&mut harness, 3); + assert!(target.items(&harness.state().session).unwrap().pins.is_empty(), "Delete must remove the selected pin in {kind}"); + harness.state_mut().session.undo().unwrap(); + assert_eq!(target.items(&harness.state().session).unwrap().pins[0].name, "Review checkpoint"); + } +} diff --git a/crates/ui-egui/tests/snapshot/library.rs b/crates/ui-egui/tests/snapshot/library.rs index 7a92bb85..2525483f 100644 --- a/crates/ui-egui/tests/snapshot/library.rs +++ b/crates/ui-egui/tests/snapshot/library.rs @@ -1,14 +1,17 @@ use super::{By, MaterialCraftApp, Queryable, UiState, harness, save, settle, vec2}; use egui::accesskit::Role; +/// Find a category by its accessible tree label. fn tree(label: &str) -> By<'_> { By::new().role(Role::TreeItem).label(label) } +/// Find an entry by its accessible list-item label. fn tile(label: &str) -> By<'_> { By::new().role(Role::ListItem).label(label) } +/// Render categories, search and favorites while exercising a library drag. #[test] #[ignore = "requires an offscreen GPU; run explicitly with --ignored"] fn library_tree_shows_every_category_and_adds_what_the_graph_takes() { @@ -110,6 +113,7 @@ fn library_tree_shows_every_category_and_adds_what_the_graph_takes() { if top == "PBR materials" { save(&mut harness, &directory, "library-categories-open"); } + // Clicking the selected, open category closes it again harness.get(tree(top)).click(); settle(&mut harness, 2); diff --git a/crates/ui-egui/tests/snapshot/menu.rs b/crates/ui-egui/tests/snapshot/menu.rs new file mode 100644 index 00000000..77c05b6a --- /dev/null +++ b/crates/ui-egui/tests/snapshot/menu.rs @@ -0,0 +1,55 @@ +use super::{By, MaterialCraftApp, NodeT, Queryable, UiState, harness, save, settle}; +use egui::accesskit::{Role, Toggled}; + +/// A menu toggle keeps the row neutral and exposes its state with a checkmark. +fn check_menu_toggle(menu: &str, label: &str) { + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + let app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 4); + let button = |label| By::new().role(Role::Button).label(label); + let anchor = if menu == "Tools" { "Compute graph" } else { "Reset layout" }; + let mut fills = Vec::new(); + let mut marks = Vec::new(); + + for checked in [true, false] { + harness.get(button(menu)).click(); + settle(&mut harness, 3); + harness.event(egui::Event::PointerMoved(egui::pos2(800.0, 250.0))); + settle(&mut harness, 3); + let menu_items = harness.get(button(anchor)).parent().unwrap(); + let item = menu_items.get(button(label)); + assert_eq!(item.accesskit_node().toggled(), Some(if checked { Toggled::True } else { Toggled::False })); + let rect = item.rect(); + let image = harness.render().unwrap(); + fills.push(*image.get_pixel((rect.right() - 8.0) as u32, rect.center().y as u32)); + let mut mark = Vec::new(); + for y in (rect.center().y as u32 - 5)..(rect.center().y as u32 + 5) { + for x in (rect.left() as u32 + 3)..(rect.left() as u32 + 19) { + mark.push(*image.get_pixel(x, y)); + } + } + marks.push(mark); + save(&mut harness, &directory, &format!("menu-{}-{}", menu.to_lowercase(), if checked { "checked" } else { "unchecked" })); + harness.get(button(anchor)).parent().unwrap().get(button(label)).click(); + settle(&mut harness, 3); + } + + assert_eq!(fills[0], fills[1], "checked items must not have a persistent row highlight"); + assert_ne!(marks[0], marks[1], "the checkmark must show the toggle state"); +} + +/// Tools uses a checkmark for snapping while the rest of the row stays neutral. +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn tools_menu_uses_checkmarks_for_toggles() { + check_menu_toggle("Tools", "Snap to grid"); +} + +/// Windows uses the same checkmark treatment for visible panels. +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn windows_menu_uses_checkmarks_for_panels() { + check_menu_toggle("Windows", "Explorer"); +} diff --git a/docs/architecture.md b/docs/architecture.md index 83f51364..b02d32e7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -196,7 +196,7 @@ them. Alignment uses the same engine command for all three models, with explicit 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. +Both processor types accept Sample gray and Sample color to read their image inputs. A breadcrumb and parent action return from nested functions, FX-Maps and local graph instances while retaining the parent view and material preview. diff --git a/docs/atomic-workflow.md b/docs/atomic-workflow.md index 9ef2c15c..26c9ef52 100644 --- a/docs/atomic-workflow.md +++ b/docs/atomic-workflow.md @@ -122,8 +122,9 @@ saved files still needs external verification. Function Graphs share the main canvas card geometry and styling, including compact Dot nodes. The Graph, Function Graph and FX-Map Add node menus remain flat and preserve their native catalog -order, also used by the Library. The regular graph menu separates primitives, inputs and output; -Dot is excluded from every Add node list and is added through its separate action. The function -and Pixel Processor menus list 84 operations; Value Processor omits the two samplers. FX-Map lists +order; Library previews are sorted by name. The regular graph menu separates primitives, inputs and output; +Dot is excluded from every Add node list and is added through its separate action. Function +Graph and both processor menus include Sample gray and Sample color. These samplers can also be +dragged from the Library into either processor function. FX-Map lists Quadrant, Switch, Iterate in that order. Type a letter to enable names starting with it while keeping the full list visible; Backspace clears the filter. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index f5051aa4..99cfb373 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -113,8 +113,8 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg | `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, `heightScale` (how far the height output raises the mesh, in mesh radii) and `heightLevel` (the height that stays on the surface; 0 = the relief rises out of it), `normalYFlip` (interpret DirectX normal maps; default false/OpenGL), `transparency` (see through where the alpha is below one: the opacity output, else the base color's alpha), `alphaView` (show the alpha channel) | | `view.3d.loadMesh` | `{path}` shows an OBJ, glTF or GLB mesh (scene `custom`) | | `library.list` | `{filter?, category?}`: every node with ports and parameters | -| `library.tree` | `{filter?, category? (Top or Top/Sub), canvas? (material\|function\|pattern)}`: the Library panel's category tree and its entries. Each entry has `id`, `label`, `category`, `type` (`node`, `comment`, `frame`, `pin`, `instance`, `operation`, `functionInstance`, `pattern`, `bitmap`), the `canvas` that takes it, `missing` when MaterialCraft lacks the library package it needs, and `warning` when it can be added but is incomplete | -| `library.add` | `{entry, at?, snapToGrid?, function?: FunctionGraphTarget}`: add a `library.tree` entry to the open graph (function entries to a Function canvas; FX-Map nodes use `graph.pattern.edit`). Entries with `missing` refuse with the reason | +| `library.tree` | `{filter?, category? (Top or Top/Sub), canvas? (material\|function\|pattern)}`: the Library panel's category tree and its entries. Each entry has `id`, `label`, `category`, `type` (`node`, `comment`, `frame`, `pin`, `instance`, `operation`, `functionInstance`, `pattern`, `bitmap`), the `canvas` that takes it (`any` for shared graph items), `missing` when MaterialCraft lacks the library package it needs, and `warning` when it can be added but is incomplete | +| `library.add` | `{entry, at?, snapToGrid?, function?: FunctionGraphTarget, pattern?: owner node id}`: add a `library.tree` entry to the open graph (function entries to a Function canvas; FX-Map nodes use `graph.pattern.edit`). Entries with `missing` refuse with the reason | | `library.reload` | `{}`: read the SBS library folder again | | `graph.cook` | `{full?, graph?: index}`: cook now and return per-node timings and errors; another material graph of the package cooks at full size into the cache | @@ -122,9 +122,9 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg Every `.sbs` file in the library folder (`assets/sbs`, or `MATERIALCRAFT_SBS_DIR`; installed and browser builds use the bundled `functions.sbs`) loads once per process, and its graphs join every -session's dependencies. Function graphs are listed under Functions, in the sub-category their folder -names (`Functions/colorValues` → Color, `Functions/easings` → Easings); other graphs under the -category in their attributes. A package whose graphs group nodes in titled frames lays the library +session's dependencies. Function graphs are listed under Functions using recognized Tags, then +Category or package-path fallbacks (`Functions/colorValues` → Color, `Functions/easings` → Easings). +Other graphs use the category in their attributes. A package whose graphs group nodes in titled frames lays the library out instead: a frame titled `Top - Sub` (or `Top`) is a Library category, and every node inside it becomes an entry there, `missing` until its package is in the folder. Function frames name only the sub-category. The older category name "SDF functions" reads as MCF functions. @@ -270,12 +270,12 @@ The catalog in `crates/nodes/src/function/catalog.rs` defines all native operati Processors and dynamic parameters use the same function representation. Graph validation and execution use bounded iterative traversal and reject cycles. -`graph.annotation.select {"kind": "frame"|"comment", "id": ...}` selects an annotation. +`graph.annotation.select {"kind": "frame"|"comment"|"pin", "id": ...}` selects an annotation. `graph.frame.edit` accepts `title`, `titleVisible`, `description`, `color` and `rect`. `graph.frame.move {"id": ..., "by": [dx, dy], "snapToGrid": true}` moves enclosed nodes, comments, nested frames and pins together. `graph.comment.edit` accepts `text`, `at` and `size`. `session.inspect` includes annotation selection and the standalone function; `ui.inspect` -includes frame and comment rectangles for synthetic input. +includes frame, comment and pin rectangles for synthetic input. ## Portable materials (TextureCraft) @@ -347,3 +347,19 @@ Bitmap Color space selects sRGB or Linear. `graph.input.bind` accepts `linear: t height and other data maps. Input preview bindings persist in native SBS graph options with the `materialcraft.previewImage.` and `materialcraft.previewLinear.` prefixes; these options describe MaterialCraft editor previews and do not establish external application interoperability. + +### Shared graph items and classification metadata + +The Library sorts previews by their displayed names. Graph items (Comment, Dot node, Frame and +Pin) are available in material, standalone Function, embedded Function and FX-Map canvases. +Dot node appears only in Graph items. To address an embedded canvas, annotation commands and +`library.add` accept `function: FunctionGraphTarget` or `pattern: owner node id`. +`graph.pin.edit {id, description?, at?}` edits a pin's description or position. Selecting a pin +shows its Description field; creating one focuses that field. Delete and undo apply to the +selected pin. `session.inspect` reports `annotationTarget`; `ui.inspect` also reports pin bounds. +Frames, comments and pins are saved in the owning canvas's SBS `GUIObjects` section. + +Function-library conversion preserves Category and Tags, including empty values. Recognized +function tags select Library filters before category-path and package-path fallbacks; multiple +recognized tags can place the function in multiple filters. The tag `Easing` maps to the +`Functions/Easings` filter. This does not implement project-configurable Library filters. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 0d8b1d69..cd51cabb 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -17,7 +17,7 @@ material artists exchange. | Format | Read | Write | Fidelity | Tests | |---|---|---|---|---| -| `.sbs` package (XML), the main format | Yes: atomic filters, library nodes with a MaterialCraft node of the same name (88 of the 491 in a sample that instanced every library node), graph instances, graph inputs/outputs, exposed values, parameters linked to inputs, base parameters, frames, comments, embedded and linked bitmaps and SVGs. Anything else (missing nodes, curve points, gradient keys, function graphs, environment maps) is a Console warning; missing nodes stay as placeholders | Yes: SBS data with bitmaps embedded, plus MaterialCraft's exact copy | Lossless for files MaterialCraft saved (exact copy, guarded by a content hash); placeholders round-trip their SBS data | `formats::sbs::tests`, engine `sbs_is_the_default_save_format_and_mcraft_still_works`, `an_sbs_file_with_missing_nodes_opens_softly` | +| `.sbs` package (XML), the main format | Yes: atomic filters, linked library graphs when their source SBS package is available, graph instances, graph inputs/outputs, exposed values, parameters linked to inputs, base parameters, frames, comments, embedded and linked bitmaps and SVGs. Anything else (missing nodes, curve points, gradient keys, function graphs, environment maps) is a Console warning; missing nodes stay as placeholders | Yes: SBS data with bitmaps embedded, plus MaterialCraft's exact copy | Lossless for files MaterialCraft saved (exact copy, guarded by a content hash); placeholders round-trip their SBS data | `formats::sbs::tests`, engine `sbs_is_the_default_save_format_and_mcraft_still_works`, `an_sbs_file_with_missing_nodes_opens_softly` | | `.mcraft` package (zip: `package.json` + `resources/`), older | Yes | Yes | Lossless (graphs, parameters, frames, comments, pins, exposed inputs, embedded bitmaps) | `formats::tests::package_round_trip`, engine `package_save_and_open_round_trip` | | PNG | Yes (8/16-bit, gray and color) | Yes (8/16-bit) | 16-bit gray round-trips within 1/65535 | `formats::tests::export_every_format` | | JPEG | Yes | Yes (8-bit) | Lossy | same | @@ -41,3 +41,10 @@ roughness, metallic, height, ambient occlusion, opacity) linear. | 2026-11-04 | major | SBS packages become the main project format; `.mcraft` kept | | 2026-11-02 | minor | `.mcmat` portable materials replace the published-archive gap | | 2026-11-02 | major | First version | + +## Canvas annotations + +Frames, comments and navigation pins round-trip in material graphs, standalone functions, +embedded functions and FX-Map graphs. Pin descriptions and positions are preserved. Pin +attachment references (`GUIDependency`) are not modeled. Dynamic functions on unsupported base +parameters, including `pixelsize`, are not imported, so annotations inside them are not retained.