diff --git a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs index 25452666e57..e31c24ac752 100644 --- a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs +++ b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs @@ -139,18 +139,6 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy HashMap { let custom = vec![ - DocumentNodeDefinition { - identifier: "Custom Node", - version: 1, - category: "Routing", - icon: Some("NodeCustomNode"), - node_template: NodeTemplate { - implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()), - ..Default::default() - }, - description: Cow::Borrowed("An empty node network you can use to create your own custom nodes."), - inspector: None, - }, DocumentNodeDefinition { identifier: "Merge", version: 1, diff --git a/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs b/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs index 92cf866c4c5..1c1a7421bdd 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs @@ -45,6 +45,11 @@ pub enum NodeGraphMessage { xy: Option<(i32, i32)>, add_transaction: bool, }, + /// Adds a subgraph with nothing in it, at the given grid position or else in view, and selects it. + CreateEmptySubgraph { + node_id: Option, + xy: Option<(i32, i32)>, + }, CreateWire { output_connector: OutputConnector, input_connector: InputConnector, @@ -383,6 +388,7 @@ impl NodeGraphMessage { | Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path), Self::AddNodes { .. } | Self::CreateNodeFromContextMenu { .. } + | Self::CreateEmptySubgraph { .. } | Self::CreateWire { .. } | Self::CreateWires { .. } | Self::ConnectUpstreamOutputToInput { .. } diff --git a/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs b/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs index 13abc789bd0..497e2de9266 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs @@ -5,13 +5,14 @@ use crate::messages::input_mapper::utility_types::macros::{action_shortcut, acti use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::portfolio::document::document_message_handler::navigation_controls; use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext; -use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type}; +use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type}; use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic}; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView; use crate::messages::portfolio::document::utility_types::misc::GroupFolderType; use crate::messages::portfolio::document::utility_types::network_interface::{ - self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint, TransactionStatus, + self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTemplate, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint, + TransactionStatus, }; use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry}; use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire}; @@ -422,6 +423,23 @@ impl<'a> MessageHandler> for NodeG }); responses.add(NodeGraphMessage::SendGraph); } + NodeGraphMessage::CreateEmptySubgraph { node_id, xy } => { + let node_id = node_id.unwrap_or_else(NodeId::new); + let (x, y) = xy.unwrap_or_else(|| { + network_interface + .node_graph_ptz(breadcrumb_network_path) + .map_or((0, 0), |ptz| ((-ptz.pan.x / GRID_SIZE as f64) as i32, (-ptz.pan.y / GRID_SIZE as f64) as i32)) + }); + + responses.add(DocumentMessage::AddTransaction); + responses.add(NodeGraphMessage::InsertNode { + node_id, + node_template: Box::new(NodeTemplate::empty_subgraph()), + }); + responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x, y }); + responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }); + responses.add(NodeGraphMessage::SendGraph); + } NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => { let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else { log::error!("Failed to find upstream node for downstream_input"); @@ -769,24 +787,19 @@ impl<'a> MessageHandler> for NodeG } } - // Use the network interface to add a default node, then set the imports, exports, paste the nodes inside, and connect them to the imports/exports + // Add an empty subgraph, then set its imports and exports, paste the nodes inside, and connect them to the imports and exports let encapsulating_node_id = NodeId::new(); - let mut default_node_template = resolve_network_node_type("Custom Node").expect("Custom Node should exist").default_node_template(); + let mut subgraph_template = NodeTemplate::empty_subgraph(); let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else { log::error!("Could not get center of selected_nodes"); return; }; let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32); - default_node_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1)); + subgraph_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1)); responses.add(DocumentMessage::AddTransaction); responses.add(NodeGraphMessage::InsertNode { node_id: encapsulating_node_id, - node_template: Box::new(default_node_template), - }); - responses.add(NodeGraphMessage::SetDisplayNameImpl { - node_id: encapsulating_node_id, - network_path: selection_network_path.to_vec(), - alias: "Untitled Node".to_string(), + node_template: Box::new(subgraph_template), }); responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id }); @@ -3426,6 +3439,13 @@ impl NodeGraphMessageHandler { }) .disabled(read_only) .widget_instance(), + Separator::new(SeparatorStyle::Related).widget_instance(), + TextButton::new("New Custom Node") + .tooltip_label("New Custom Node") + .tooltip_description("Add an empty subgraph, which can be entered to build a node of your own out of other nodes.") + .on_update(|_| NodeGraphMessage::CreateEmptySubgraph { node_id: None, xy: None }.into()) + .disabled(read_only) + .widget_instance(), // Separator::new(SeparatorStyle::Unrelated).widget_instance(), // diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/catalog_tests.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/catalog_tests.rs index e7dcdd522c9..9f855676bf8 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/catalog_tests.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/catalog_tests.rs @@ -1,4 +1,4 @@ -use super::template::NodeTemplateImplementation; +use super::template::{NodeTemplate, NodeTemplateImplementation}; use super::{InputConnector, OutputConnector, catalog}; use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type}; use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd; @@ -308,7 +308,7 @@ async fn undoing_the_unlock_of_an_open_catalog_node_shows_it_read_only_again() { async fn undoing_the_creation_of_an_open_subgraph_leaves_it() { let mut editor = EditorTestUtils::create(); editor.new_document().await; - let subgraph = editor.create_node_by_name(DefinitionIdentifier::Network("Custom Node".to_string())).await; + let subgraph = editor.create_empty_subgraph_at(0, 0).await; editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await; assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]); @@ -349,7 +349,7 @@ async fn a_subgraph_holding_a_catalog_node_pastes_into_a_document_without_it() { let custom = NodeId::new(); let blend = NodeId::new(); let interface = &mut editor.active_document_mut().network_interface; - interface.insert_node(custom, resolve_network_node_type("Custom Node").expect("Custom Node").default_node_template(), &[]); + interface.insert_node(custom, NodeTemplate::empty_subgraph(), &[]); interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]); let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else { panic!("the Blend should name a table entry") diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs index 1635bb39688..03637dd42e0 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs @@ -3119,7 +3119,7 @@ async fn imports_and_exports_keep_just_a_grid_cell_from_a_dot() { let mut editor = EditorTestUtils::create(); editor.new_document().await; - let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await; + let subgraph = editor.create_empty_subgraph_at(0, 0).await; let path = [subgraph]; editor.enter_editable_network(subgraph).await; @@ -3506,7 +3506,7 @@ async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire /// Opens a new subgraph with one node inside, which is all that lies between its import and its export. async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) { - let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await; + let subgraph = editor.create_empty_subgraph_at(0, 0).await; editor.enter_editable_network(subgraph).await; editor.handle_message(NodeGraphMessage::AddImport).await; editor.handle_message(NodeGraphMessage::AddPrimaryExport).await; @@ -4041,18 +4041,30 @@ async fn a_session_preview_of_a_removed_node_is_dropped() { ); } +#[tokio::test] +async fn a_new_subgraph_is_its_own_definition() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let subgraph = editor.create_empty_subgraph_at(0, 0).await; + let network_interface = &editor.active_document().network_interface; + assert!(matches!(network_interface.implementation(&subgraph, &[]), Some(DocumentNodeImplementation::Definition(_)))); + assert_eq!(network_interface.reference(&subgraph, &[]), None, "it shouldn't name a catalog definition"); + assert_eq!(network_interface.display_name(&subgraph, &[]), "Subgraph"); +} + #[tokio::test] async fn cannot_preview_node_without_outputs() { let mut editor = EditorTestUtils::create(); editor.new_document().await; - let custom_node = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await; + let subgraph = editor.create_empty_subgraph_at(0, 0).await; let network_interface = &mut editor.active_document_mut().network_interface; - assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0); + assert_eq!(network_interface.number_of_outputs(&subgraph, &[]), 0); // Attempting to toggle preview on a node without outputs should not enable previewing - network_interface.toggle_preview(custom_node, &[]); + network_interface.toggle_preview(subgraph, &[]); assert_eq!(network_interface.previewing(&[]), Previewing::No); } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/queries.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/queries.rs index d7c3fa89d0c..588217afab9 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/queries.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/queries.rs @@ -802,7 +802,7 @@ impl NodeNetworkInterface { self.query(network_path, "reference", |view| view.reference(node_id)).flatten() } - /// The icon of the node's definition, or the Custom Node icon when its definition has none or can't be found. + /// The icon of the node's definition, or the generic subgraph icon when its definition has none or can't be found. pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str { self.reference(node_id, network_path) .and_then(|reference| resolve_document_node_type(&reference)?.icon) @@ -875,16 +875,16 @@ impl NodeNetworkInterface { node.set_widget_override(index, widget_override); } - /// Returns the display name of the node. If the display name is empty, it will return "Untitled Node" or "Untitled Layer" depending on the node type. + /// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed. pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String { self.query(network_path, "display_name", |view| Ok(view.display_name(node_id))) - .unwrap_or_else(|| "Custom Node".to_string()) + .unwrap_or_else(|| "Subgraph".to_string()) } /// The uneditable name in the Inspector which represents the function name of the node implementation. pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String { self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id))) - .unwrap_or_else(|| "Custom Node".to_string()) + .unwrap_or_else(|| "Subgraph".to_string()) } pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool { diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs index efcdbba810c..e1cd2eedecc 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs @@ -38,6 +38,14 @@ pub struct NodeTemplate { } impl NodeTemplate { + /// A new subgraph with nothing in it, which names no definition since it becomes its own entry in the document's definitions table. + pub fn empty_subgraph() -> Self { + Self { + implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()), + ..Default::default() + } + } + /// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`]. pub fn input(&self, _parameter: P) -> Option<&NodeInput> { self.inputs.get(P::INDEX) diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/view.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/view.rs index 0d7dd78cb4c..99e869a6c72 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/view.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/view.rs @@ -169,7 +169,7 @@ impl<'a, 'p> NetworkView<'a, 'p> { .ok() .flatten() .map(|identifier| identifier.implementation_name_from_identifier()) - .unwrap_or("Custom Node".to_string()) + .unwrap_or("Subgraph".to_string()) } /// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed. diff --git a/editor/src/messages/portfolio/document_migration.rs b/editor/src/messages/portfolio/document_migration.rs index 39ce8155e00..32e66acb566 100644 --- a/editor/src/messages/portfolio/document_migration.rs +++ b/editor/src/messages/portfolio/document_migration.rs @@ -1295,7 +1295,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_ } // The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present. - // Some old documents store it as a Custom Node subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way. + // Some old documents store it as a subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way. // Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths. let transform_layers: Vec<(NodeId, Vec, usize)> = document .network_interface @@ -1771,6 +1771,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_ }) .collect(); + migrate_custom_node_subgraphs(document); + // Apply upgrades to each unmodified node, except those inside the read-only built-in subgraphs let nodes = document .network_interface @@ -4045,6 +4047,25 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne Some(()) } +/// Gives each subgraph made from the removed Custom Node definition, from the catalog or by merging selected nodes, no reference and no default name, like one made with the New Custom Node button. +/// Instances can share a definitions table entry holding the reference, so all of them are found before any is changed. +fn migrate_custom_node_subgraphs(document: &mut DocumentMessageHandler) { + let custom_node = Some(DefinitionIdentifier::Network("Custom Node".into())); + let subgraphs: Vec<(NodeId, Vec)> = document + .network_interface + .document_network() + .recursive_nodes() + .filter(|(node_id, _, path)| document.network_interface.reference(node_id, path) == custom_node) + .map(|(node_id, _, path)| (*node_id, path)) + .collect(); + + for (node_id, network_path) in subgraphs { + reset_default_display_name(document, &node_id, &network_path, "Custom Node"); + reset_default_display_name(document, &node_id, &network_path, "Untitled Node"); + document.network_interface.set_reference(&node_id, &network_path, None); + } +} + /// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula. fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) { let math_f_nodes: Vec<(NodeId, Vec)> = document @@ -4597,6 +4618,45 @@ mod tests { assert!(errors.is_empty(), "opening the document logged errors: {errors:?}"); } + #[tokio::test] + async fn opening_custom_node_subgraphs_drops_their_reference_and_default_names() { + use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation; + use crate::messages::portfolio::document_storage_io::load_legacy_document; + use crate::test_utils::test_prelude::*; + use graph_craft::application_io::resource::HashMapResourceStorage; + + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let from_catalog = editor.create_empty_subgraph_at(0, 0).await; + let document = editor.active_document_mut(); + let Some(DocumentNodeImplementation::Definition(shared)) = document.network_interface.implementation(&from_catalog, &[]).cloned() else { + panic!("the subgraph should name a definitions table entry") + }; + + // A second instance of the same table entry, named as Merge Selected Nodes named the subgraphs it made + let from_merging = NodeId::new(); + let instance = NodeTemplate { + implementation: NodeTemplateImplementation::Definition(shared), + ..Default::default() + }; + document.network_interface.insert_node(from_merging, instance, &[]); + document.network_interface.set_reference(&from_catalog, &[], Some("Custom Node".into())); + document.network_interface.set_display_name(&from_catalog, "Custom Node".into(), &[]); + document.network_interface.set_display_name(&from_merging, "Untitled Node".into(), &[]); + let serialized = document.serialize_document(); + + let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open"); + let interface = &opened.network_interface; + for node_id in [from_catalog, from_merging] { + assert!( + matches!(interface.implementation(&node_id, &[]), Some(DocumentNodeImplementation::Definition(_))), + "the subgraph should still exist" + ); + assert_eq!(interface.reference(&node_id, &[]), None); + assert_eq!(interface.display_name(&node_id, &[]), "Subgraph"); + } + } + #[tokio::test] async fn a_rasterize_node_on_the_export_compiles() { use crate::test_utils::test_prelude::*; diff --git a/editor/src/test_utils.rs b/editor/src/test_utils.rs index 2b02058927a..bf4fde6a37c 100644 --- a/editor/src/test_utils.rs +++ b/editor/src/test_utils.rs @@ -423,6 +423,17 @@ impl EditorTestUtils { self.create_node(node_type, Some((x, y))).await } + /// Adds an empty subgraph at the grid position, as the graph's New Custom Node button does. + pub async fn create_empty_subgraph_at(&mut self, x: i32, y: i32) -> NodeId { + let node_id = NodeId::new(); + self.handle_message(NodeGraphMessage::CreateEmptySubgraph { + node_id: Some(node_id), + xy: Some((x, y)), + }) + .await; + node_id + } + async fn create_node(&mut self, node_type: DefinitionIdentifier, xy: Option<(i32, i32)>) -> NodeId { let node_id = NodeId::new(); self.handle_message(NodeGraphMessage::CreateNodeFromContextMenu { diff --git a/node-graph/README.md b/node-graph/README.md index 01a82ab0c03..31247534b13 100644 --- a/node-graph/README.md +++ b/node-graph/README.md @@ -32,7 +32,7 @@ pub struct DocumentNodeDefinition { } ``` -Only the definitions of nodes built from a nested network, such as the empty "Custom Node", are written by hand in that file. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`. +Only the definitions of built-in nodes made from a nested network are written by hand in that file. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`. ## Inspector diff --git a/tools/node-docs/src/utility.rs b/tools/node-docs/src/utility.rs index 311d009dc3b..e459828bebb 100644 --- a/tools/node-docs/src/utility.rs +++ b/tools/node-docs/src/utility.rs @@ -6,7 +6,7 @@ pub const OMIT_HIDDEN: bool = true; pub fn category_description(category: &str) -> &str { match category { "Value" => "Nodes in this category supply data values of common types such as numbers, colors, gradients, booleans, and strings.", - "Routing" => "Nodes in this category direct how data flows through the graph, such as switching between inputs, repeating steps on a result, wrapping nodes into a custom subgraph, and caching results.", + "Routing" => "Nodes in this category direct how data flows through the graph, such as switching between inputs, repeating steps on a result, and caching results.", "Transform" => "Nodes in this category move, rotate, scale, and skew graphical content, read and combine the transformation matrices that place it, and arrange items by packing them into rows or columns.", "Graphic" => "Nodes in this category compose graphical content of any kind, such as merging layers, making artboards and groups, blending and clipping, repeating and mirroring copies, and flattening nested groups.", "Vector: Style" => "Nodes in this category apply fill and stroke styles to alter the appearance of vector graphics.",