diff --git a/assets/sbs/all_nodes.resources/test.bmp b/assets/sbs/all_nodes.resources/test.bmp
deleted file mode 100644
index 5a54b4a..0000000
Binary files a/assets/sbs/all_nodes.resources/test.bmp and /dev/null differ
diff --git a/assets/sbs/all_nodes.sbs b/assets/sbs/all_nodes.sbs
deleted file mode 100644
index dbb7cdb..0000000
--- a/assets/sbs/all_nodes.sbs
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/assets/sbs/functions.sbs b/assets/sbs/functions.sbs
index 0294f74..c9713d3 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 0000000..93b3af6
--- /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 c3f43bc..84addc0 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 1810508..b02cfa3 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 d0275a8..d1c47bc 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 5825eca..e72f6df 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 8385ca6..cd3b686 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 0000000..255ff67
--- /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 acc9729..51ccc34 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -60,6 +60,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::explorer_clipboard_commands::specs());
v.extend(crate::graph_instance_commands::specs());
v.extend(crate::function_library_commands::specs());
+ v.extend(crate::node_library_commands::specs());
v.extend(crate::node_info_commands::specs());
v.extend(crate::atomic_sample_commands::specs());
v.extend(crate::material_cmds::specs());
@@ -76,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());
@@ -100,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;
}
@@ -116,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 103091e..ca0113e 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 60321be..7dc7e10 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 a4672d4..47cf604 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 5e7f8c1..644b3ac 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/function_library.rs b/crates/engine/src/function_library.rs
index ad55a8b..072707f 100644
--- a/crates/engine/src/function_library.rs
+++ b/crates/engine/src/function_library.rs
@@ -1,21 +1,2 @@
-use materialcraft_core::Package;
-use std::{collections::BTreeMap, sync::Arc};
-
+/// The bundled function library every session loads (see `node_library`)
pub(crate) const STANDARD_PACKAGE: &str = "sbs://functions.sbs";
-
-pub(crate) struct FunctionLibrary {
- pub packages: BTreeMap>,
- pub warnings: Vec,
-}
-
-pub(crate) fn load() -> Result {
- let bytes = materialcraft_formats::sbs::library::read(STANDARD_PACKAGE)?;
- let mut read =
- materialcraft_formats::sbs::read_sbs(&bytes, STANDARD_PACKAGE, &crate::file_cmds::linked_files(STANDARD_PACKAGE)).map_err(|error| error.to_string())?;
- crate::linked_files::normalize_references(&mut read.pkg, STANDARD_PACKAGE);
- read.warnings.extend(crate::linked_files::load(&mut read.pkg));
-
- let mut packages = std::mem::take(&mut read.pkg.dependencies);
- packages.insert(STANDARD_PACKAGE.into(), Arc::new(read.pkg));
- Ok(FunctionLibrary { packages, warnings: read.warnings })
-}
diff --git a/crates/engine/src/graph_cmds.rs b/crates/engine/src/graph_cmds.rs
index 9f0954e..ecf8077 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 {
@@ -22,9 +22,15 @@ pub(crate) fn specs() -> Vec {
})
}),
cmd!("graph.format", "Output format", [], None, "{format: u8|u16|f16|f32, graph?, document?}", always, format),
- cmd!("graph.cook", "Compute graph", [], None, "{full?: bool} cooks now; returns per-node timings and errors", has_graph, cook),
- cmd!("graph.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.cook",
+ "Compute graph",
+ [],
+ None,
+ "{full?: bool, graph?: index (another graph of the package cooks at full size into the cache)} cooks now; returns per-node timings and errors",
+ has_graph,
+ cook
+ ),
cmd!(
"graph.exposed.add",
"Expose parameter",
@@ -153,8 +159,19 @@ fn format(s: &mut Session, p: &J) -> Result {
}
fn cook(s: &mut Session, p: &J) -> Result {
- let cooked = if boolp(p, "full") == Some(true) { s.cook_full(s.graph) } else { s.cook().clone() };
- let g = s.graph()?;
+ let index = match p.get("graph").filter(|graph| !graph.is_null()) {
+ None => s.graph,
+ Some(graph) => {
+ let index = graph.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad("graph.cook", "`graph` is a graph index"))?;
+ let graph = s.pkg.graph(index)?;
+ if graph.function.is_some() {
+ return Err(bad("graph.cook", "a Function Graph has no outputs to compute"));
+ }
+ index
+ }
+ };
+ let cooked = if index != s.graph || boolp(p, "full") == Some(true) { s.cook_full(index) } else { s.cook().clone() };
+ let g = s.pkg.graph(index)?;
Ok(json!({
"ms": cooked.ms,
"nodes": cooked.nodes.iter().map(|(id, r)| {
@@ -175,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 27c64b6..71942eb 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 bacdf62..31c0ae1 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;
@@ -11,6 +14,9 @@ mod folder_property_commands;
pub use explorer_clipboard::ExplorerClipboard;
mod function_library;
mod function_library_commands;
+pub mod node_library;
+mod node_library_commands;
+pub use node_library::{LibraryCanvas, LibraryEntry, LibraryItem, NodeLibrary};
mod function_variable;
mod function_variable_commands;
mod function_variables;
@@ -99,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 01fad15..f0038f3 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
new file mode 100644
index 0000000..24bf9be
--- /dev/null
+++ b/crates/engine/src/node_library.rs
@@ -0,0 +1,458 @@
+//! 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 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 std::collections::{BTreeMap, BTreeSet};
+use std::sync::{Arc, Mutex};
+
+/// The library tree in display order: top-level categories and their sub-categories. The UI adds
+/// Favorites above it
+pub const CATEGORIES: &[(&str, &[&str])] = &[
+ ("Graph items", &[]),
+ ("Atomic nodes", &[]),
+ ("FxMap nodes", &[]),
+ ("Function nodes", &["Constant", "Vector", "Variables", "Samplers", "Cast", "Operator", "Logical", "Comparison", "Function", "Control"]),
+ ("Texture generators", &["Noises", "Patterns"]),
+ ("Filters", &["Adjustments", "Blending", "Blurs", "Channels", "Effects", "Normal map", "Tiling", "Transforms"]),
+ ("Material filters", &["1-click", "Effects", "Transforms", "Blending", "PBR utilities", "Scan processing"]),
+ ("Mesh-based generators", &["Mask generators", "Weathering", "Utilities"]),
+ ("Spline & Path tools", &["Spline tools", "Path tools"]),
+ ("MCF functions", &["Primitives", "Operators", "Transforms"]),
+ ("Functions", &["Color", "Comparison", "Constant", "Conversion", "Maths", "Parity", "Random", "Transformation", "Various", "Easings"]),
+ ("3D view", &["HDRI environments", "HDRI tools"]),
+ ("PBR materials", &["Bricks", "Concrete", "Fabric", "Ground", "Metal", "Paper", "Pavement", "Tiles", "Wood", "Stone"]),
+ ("Values", &["Constant"]),
+];
+
+/// Older layouts name categories MaterialCraft has renamed: (old, current)
+const RENAMED: &[(&str, &str)] = &[("SDF functions", "MCF functions")];
+
+/// Words that place a material in a sub-category when its layout frame names only the top level
+const SUB_KEYWORDS: &[(&str, &str, &[&str])] = &[
+ ("PBR materials", "Bricks", &["brick"]),
+ ("PBR materials", "Concrete", &["concrete", "cement"]),
+ ("PBR materials", "Fabric", &["fabric", "cloth", "textile", "leather"]),
+ ("PBR materials", "Ground", &["ground", "gravel", "soil", "sand", "dirt", "grass", "mud"]),
+ ("PBR materials", "Metal", &["metal", "steel", "iron", "copper", "rust"]),
+ ("PBR materials", "Paper", &["paper", "cardboard"]),
+ ("PBR materials", "Pavement", &["pavement", "paving", "cobble", "asphalt"]),
+ ("PBR materials", "Tiles", &["tile"]),
+ ("PBR materials", "Wood", &["wood", "plank", "bark"]),
+ ("PBR materials", "Stone", &["stone", "rock", "marble", "granite"]),
+];
+
+/// Everything loaded from the library folder
+#[derive(Debug, Default)]
+pub struct NodeLibrary {
+ /// Library packages (layouts excluded) and their own dependencies, by `sbs://` path
+ pub packages: BTreeMap>,
+ /// The `sbs://` files that laid the library out
+ pub layouts: Vec,
+ pub warnings: Vec,
+ placements: Vec,
+}
+
+static SHARED: Mutex