diff --git a/document/migrations/core/src/view.rs b/document/migrations/core/src/view.rs index 638fd1950e2..3b72ab220a1 100644 --- a/document/migrations/core/src/view.rs +++ b/document/migrations/core/src/view.rs @@ -1,5 +1,7 @@ -use crate::{Compiler, Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector}; +use crate::{Compiler, Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector, encode}; +use document_graph_storage::attributes::attr::node::REFLECTION_METADATA; use document_graph_storage::{Implementation, InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp}; +use serde::Serialize; use std::ops::Deref; /// Which part of the registry around an anchor a view reads or edits. A migration's footprint is the union of its views' regions. @@ -329,6 +331,16 @@ impl Inputs { self.origins.push(None); } + /// Add a slot the compiler fills in with what `metadata` names, a frozen mirror value such as the node's path. + pub fn push_reflection(&mut self, metadata: T) { + let mut slot = new_slot(NodeInput::Reflection); + slot.attributes.set(REFLECTION_METADATA, encode(&metadata), TimeStamp::ORIGIN); + + self.edited = true; + self.slots.push(slot); + self.origins.push(None); + } + pub fn remove(&mut self, index: u32) { if !self.check(index, self.slots.len()) { return; diff --git a/document/migrations/nodes/src/lib.rs b/document/migrations/nodes/src/lib.rs index df036483b28..a72966d217f 100644 --- a/document/migrations/nodes/src/lib.rs +++ b/document/migrations/nodes/src/lib.rs @@ -4,3 +4,4 @@ mod graphene_core; mod math_nodes; mod raster_nodes; +mod vector_nodes; diff --git a/document/migrations/nodes/src/vector_nodes/mod.rs b/document/migrations/nodes/src/vector_nodes/mod.rs new file mode 100644 index 00000000000..d3785a39851 --- /dev/null +++ b/document/migrations/nodes/src/vector_nodes/mod.rs @@ -0,0 +1,4 @@ +//! Migrations of the nodes in `vector_nodes`. + +mod path_from_path_network; +mod renames; diff --git a/document/migrations/nodes/src/vector_nodes/path_from_path_network.rs b/document/migrations/nodes/src/vector_nodes/path_from_path_network.rs new file mode 100644 index 00000000000..bf39a10334f --- /dev/null +++ b/document/migrations/nodes/src/vector_nodes/path_from_path_network.rs @@ -0,0 +1,49 @@ +use migration_core::{Inputs, migration}; +use serde::Serialize; + +/// Frozen mirror of the `DocumentNodeMetadata` variant this migration uses. +#[derive(Serialize)] +enum Reflected { + DocumentNodePath, +} + +/// The Path subgraph became the node it held, which takes the instance's inputs and is given its own path as that node was. +#[migration(network "Path"@1 => "vector_nodes::vector_modification_nodes::PathNode"@2)] +pub fn path_from_path_network(inputs: &mut Inputs) { + inputs.push_reflection(Reflected::DocumentNodePath); +} + +#[cfg(test)] +mod tests { + use super::*; + use document_graph_storage::NodeInput; + use document_graph_storage::attributes::attr::node::REFLECTION_METADATA; + use migration_core::{decl, literal}; + use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo}; + + fn contract() -> SourceContract { + SourceContract::new(2, |random, _slot| literal(random.below(10) as f64)) + } + + #[test] + fn rewrites_history() { + check_commutation(&PathFromPathNetwork, &contract()); + check_undo(&PathFromPathNetwork, &contract()); + } + + #[test] + fn collapses_into_the_node_and_gives_it_its_path() { + let (content, modification) = (literal(1.), literal(2.)); + + let mut fixture = Fixture::new(&PathFromPathNetwork); + let (path, network) = fixture.add_network(decl!(network "Path"@1), vec![content.clone(), modification.clone()]); + let migrated = fixture.migrate(&PathFromPathNetwork).unwrap(); + + assert_eq!(fixture.declaration_of(&migrated, path), Some(decl!("vector_nodes::vector_modification_nodes::PathNode"@2))); + assert!(!migrated.networks.contains_key(&network)); + assert_eq!(fixture.inputs(&migrated, path), [content, modification, NodeInput::Reflection]); + + let own_path = &migrated.node_instances[&path].inputs()[2]; + assert_eq!(own_path.attributes.get_typed::(REFLECTION_METADATA).as_deref(), Some("DocumentNodePath")); + } +} diff --git a/document/migrations/nodes/src/vector_nodes/renames.rs b/document/migrations/nodes/src/vector_nodes/renames.rs new file mode 100644 index 00000000000..2a8844dbf4a --- /dev/null +++ b/document/migrations/nodes/src/vector_nodes/renames.rs @@ -0,0 +1,5 @@ +//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are. + +use migration_core::rename; + +rename!("vector_nodes::vector_modification_nodes::PathModifyNode"@1 => "vector_nodes::vector_modification_nodes::PathNode"@2); diff --git a/document/migrations/runner/tests/node_migrations/examples.rs b/document/migrations/runner/tests/node_migrations/examples.rs index f902e7e23c7..64425fe1ce4 100644 --- a/document/migrations/runner/tests/node_migrations/examples.rs +++ b/document/migrations/runner/tests/node_migrations/examples.rs @@ -33,6 +33,18 @@ pub fn opacity_toggles(inputs: &mut Inputs) { inputs.push(literal(Tagged::Number(100.))); } +/// Frozen mirror of the `DocumentNodeMetadata` variant the migration below uses. +#[derive(Serialize)] +pub enum Reflected { + DocumentNodePath, +} + +/// Gives the node its own path. +#[migration("vector_nodes::bounding_box"@1 => @2)] +pub fn bounding_box_own_path(inputs: &mut Inputs) { + inputs.push_reflection(Reflected::DocumentNodePath); +} + pub const ROTATION: u32 = 2; /// Rotation is now stored in degrees. diff --git a/document/migrations/runner/tests/node_migrations/main.rs b/document/migrations/runner/tests/node_migrations/main.rs index 4e7bcfab596..73e00f26f9c 100644 --- a/document/migrations/runner/tests/node_migrations/main.rs +++ b/document/migrations/runner/tests/node_migrations/main.rs @@ -5,8 +5,9 @@ mod networks; mod registration; mod rewrite; +use document_graph_storage::attributes::attr::node::REFLECTION_METADATA; use document_graph_storage::{NodeId, NodeInput, ROOT_NETWORK, Registry}; -use examples::{AngleBetweenDegrees, Axis, ExtractXyToSplit, OpacityToggles, ROTATION, Tagged, TransformDegrees}; +use examples::{AngleBetweenDegrees, Axis, BoundingBoxOwnPath, ExtractXyToSplit, OpacityToggles, ROTATION, Tagged, TransformDegrees}; use migration_core::{decl, literal, literal_of}; use migration_runner::RunnerError; use migration_runner::testing::{Fixture, registered}; @@ -57,6 +58,19 @@ fn opacity_toggles_build_the_target_layout() { assert_eq!(fixture.declaration_of(&migrated, opacity), Some(decl!("blending_nodes::opacity"@2))); } +#[test] +fn reflection_input_stores_what_it_reflects() { + let mut fixture = Fixture::new(&BoundingBoxOwnPath); + let bounding_box = fixture.add(decl!("vector_nodes::bounding_box"@1), vec![literal(Tagged::Number(1.))]); + + let migrated = fixture.migrate(&BoundingBoxOwnPath).unwrap(); + + let slots = migrated.node_instances[&bounding_box].inputs(); + assert_eq!(slots.len(), 2); + assert_eq!(slots[1].input, NodeInput::Reflection); + assert_eq!(slots[1].attributes.get_typed::(REFLECTION_METADATA).as_deref(), Some("DocumentNodePath")); +} + #[test] fn transform_converts_a_literal_rotation() { let mut fixture = Fixture::new(&TransformDegrees); diff --git a/document/migrations/runner/tests/node_migrations/registration.rs b/document/migrations/runner/tests/node_migrations/registration.rs index 061d22fcb69..636d558916e 100644 --- a/document/migrations/runner/tests/node_migrations/registration.rs +++ b/document/migrations/runner/tests/node_migrations/registration.rs @@ -30,6 +30,7 @@ fn every_migration_registers_once() { decl!("order::static_late"@1), decl!("transform_nodes::transform"@1), decl!("vector_nodes::angle_between"@1), + decl!("vector_nodes::bounding_box"@1), decl!("vector_nodes::extract_xy"@1), decl!("vector_nodes::split_vec2"@2), ]; diff --git a/document/migrations/runner/tests/node_migrations/rewrite.rs b/document/migrations/runner/tests/node_migrations/rewrite.rs index 2a754a619cd..0586577d054 100644 --- a/document/migrations/runner/tests/node_migrations/rewrite.rs +++ b/document/migrations/runner/tests/node_migrations/rewrite.rs @@ -1,6 +1,6 @@ //! The history properties of `migration_runner::testing` on the examples. -use crate::examples::{AngleBetweenDegrees, Axis, ExtractXyToSplit, OpacityToggles, Tagged, TransformDegrees}; +use crate::examples::{AngleBetweenDegrees, Axis, BoundingBoxOwnPath, ExtractXyToSplit, OpacityToggles, Tagged, TransformDegrees}; use migration_core::{decl, literal}; use migration_runner::testing::{Random, SourceContract, check_commutation, check_undo, registered}; @@ -18,6 +18,11 @@ fn opacity_toggles_commute() { check_commutation(&OpacityToggles, &numbers(2)); } +#[test] +fn bounding_box_own_path_commutes() { + check_commutation(&BoundingBoxOwnPath, &numbers(1)); +} + #[test] fn transform_degrees_commutes() { check_commutation(&TransformDegrees, &numbers(3)); diff --git a/editor/src/messages/clipboard/clipboard_message_handler.rs b/editor/src/messages/clipboard/clipboard_message_handler.rs index 7d6cd6d420c..eee639d666b 100644 --- a/editor/src/messages/clipboard/clipboard_message_handler.rs +++ b/editor/src/messages/clipboard/clipboard_message_handler.rs @@ -1,7 +1,7 @@ use crate::consts::DEFAULT_STROKE_WIDTH; use crate::messages::portfolio::document::SelectionParts; use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn; -use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type; +use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::network_interface; use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes; @@ -429,7 +429,7 @@ impl MessageHandler> for Clipboard let mut layers = Vec::new(); for (_, new_vector, transform) in paths { - let Some(node_type) = resolve_network_node_type("Path") else { + let Some(node_type) = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER) else { error!("Path node does not exist"); continue; }; diff --git a/editor/src/messages/portfolio/document/graph_operation/utility_types.rs b/editor/src/messages/portfolio/document/graph_operation/utility_types.rs index bdd2f1802ee..5ee73fe9159 100644 --- a/editor/src/messages/portfolio/document/graph_operation/utility_types.rs +++ b/editor/src/messages/portfolio/document/graph_operation/utility_types.rs @@ -137,7 +137,9 @@ impl<'a> ModifyInputsContext<'a> { self.network_interface.move_node_to_chain_start(&smooth_anchors_id, layer, &[], self.import); // Add Path node to chain start (closest to the Merge node) - let path = resolve_network_node_type("Path").expect("Path node does not exist").default_node_template(); + let path = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER) + .expect("Path node does not exist") + .default_node_template(); let path_id = NodeId::new(); self.network_interface.insert_node(path_id, path, &[]); self.network_interface.move_node_to_chain_start(&path_id, layer, &[], self.import); @@ -150,7 +152,7 @@ impl<'a> ModifyInputsContext<'a> { let (vector, paths) = Vector::from_bezpath(&bezpath); let modification = Box::new(VectorModification::create_from_vector(&vector, &paths)); - let shape = resolve_network_node_type("Path") + let shape = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER) .expect("Path node does not exist") .node_template_input_override([None, Some(NodeInput::value(TaggedValue::VectorModification(modification), false))]); let shape_id = NodeId::new(); @@ -410,7 +412,7 @@ impl<'a> ModifyInputsContext<'a> { // If inserting a 'Path' node, insert a 'Combine Paths' node if the type is `Graphic`. // TODO: Allow the 'Path' node to operate on `List` data by utilizing the reference (index or ID?) for each item. - if node_definition.identifier == "Path" { + if *reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER) { let layer_input_type = self.network_interface.input_type(&InputConnector::layer_secondary_input(output_layer.to_node()), &[]); if layer_input_type.compiled_element_name().as_deref() == Some("Graphic") { let Some(combine_paths_definition) = resolve_proto_node_type(graphene_std::vector_nodes::combine_paths::IDENTIFIER) else { @@ -994,7 +996,7 @@ impl<'a> ModifyInputsContext<'a> { } pub fn vector_modify(&mut self, modification_type: VectorModificationType) { - let Some(path_node_id) = self.existing_network_node_id("Path", true) else { + let Some(path_node_id) = self.existing_proto_node_id(graphene_std::vector::path::IDENTIFIER, true) else { return; }; self.network_interface.vector_modify(&path_node_id, modification_type); 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 24fc64af1e7..d3daee0c602 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 @@ -769,56 +769,6 @@ fn document_node_definitions() -> HashMap MessageHandler> for NodeG NodeGraphMessage::AddPathNode => { if let Some(layer) = make_path_editable_is_allowed(network_interface) { responses.add(NodeGraphMessage::CreateNodeInLayerWithTransaction { - node_type: DefinitionIdentifier::Network("Path".into()), + node_type: DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER), layer, }); responses.add(EventMessage::SelectionChanged); diff --git a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs index 8540d739156..863a3360a04 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs @@ -3143,8 +3143,8 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect } else { let number_of_inputs = context.network_interface.number_of_inputs(&node_id, context.selection_network_path); for input_index in 1..number_of_inputs { - // Hide inputs that are connected to a scope - if let Some(NodeInput::Scope(_)) = context + // Hide inputs that are connected to a scope or filled in by the compiler + if let Some(NodeInput::Scope(_) | NodeInput::Reflection(_)) = context .network_interface .input_from_connector(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path) { diff --git a/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs b/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs index 79a9a6f5847..0a9d2c8a3c6 100644 --- a/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs +++ b/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs @@ -872,7 +872,7 @@ async fn demo_artwork_vector_modifications_still_apply() { let document = editor.active_document(); let network = &document.network_interface; - let path_definition = DefinitionIdentifier::Network("Path".into()); + let path_definition = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER); let mut path_layers = 0; let mut any_curve = false; diff --git a/editor/src/messages/portfolio/document/utility_types/document_metadata.rs b/editor/src/messages/portfolio/document/utility_types/document_metadata.rs index d3168788ccc..d4566965378 100644 --- a/editor/src/messages/portfolio/document/utility_types/document_metadata.rs +++ b/editor/src/messages/portfolio/document/utility_types/document_metadata.rs @@ -131,7 +131,7 @@ impl DocumentMetadata { let mut use_local = true; let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, network_interface); - let identifier = DefinitionIdentifier::Network("Path".into()); + let identifier = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER); if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&identifier) && let Some(&source) = self.first_element_source_ids.get(&layer.to_node()) && !network_interface 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 8d4bc1de97c..5b537d04921 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 @@ -62,6 +62,19 @@ impl NodeNetworkInterface { layer_paths } + /// The path of every node in the document's networks made from the definition. + pub fn node_paths_with_reference(&self, reference: &DefinitionIdentifier) -> Vec> { + let mut node_paths = Vec::new(); + self.for_each_network(&mut |network_path, network_metadata| { + for node_id in network_metadata.persistent_metadata.node_metadata.keys() { + if self.reference(node_id, network_path).as_ref() == Some(reference) { + node_paths.push([network_path, &[*node_id]].concat()); + } + } + }); + node_paths + } + fn for_each_layer(&self, visit: &mut impl FnMut(&[NodeId], NodeId)) { self.for_each_network(&mut |network_path, network_metadata| { for (node_id, node_metadata) in &network_metadata.persistent_metadata.node_metadata { diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/resolved_types.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/resolved_types.rs index ac50e5acdd3..5c29530c200 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/resolved_types.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/resolved_types.rs @@ -768,25 +768,48 @@ mod tests { #[tokio::test] async fn subgraph_inputs_look_through_type_preserving_nodes() { use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; - use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; + use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector}; use crate::test_utils::test_prelude::*; let mut editor = EditorTestUtils::create(); editor.new_document().await; - let path_node_id = editor.create_node_by_name(DefinitionIdentifier::Network("Path".into())).await; + let merge = editor.create_node_by_name_at(DefinitionIdentifier::Network("Merge".into()), 0, 0).await; - // The Path subgraph's content goes through a Monitor node, which accepts most types, before the node that needs a vector - let content_types = editor - .active_document() - .network_interface - .potential_valid_input_types(&InputConnector::node_at_index(path_node_id, 0), &[]) - .iter() - .map(ToString::to_string) - .collect::>(); - assert!(content_types.iter().any(|ty| ty == "Vector"), "Path's content should accept a vector, found {content_types:?}"); + // A new import feeding a Memoize, which accepts most types, before a Path that needs a vector + editor.enter_editable_network(merge).await; + let memoize = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::memo::memoize::IDENTIFIER), -20, 10).await; + let path = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER), -10, 10).await; + editor + .handle_message(NodeGraphMessage::CreateWire { + output_connector: OutputConnector::node(memoize, 0), + input_connector: InputConnector::node_at_index(path, 0), + }) + .await; + let import_index = editor.active_document().network_interface.number_of_imports(&[merge]); + editor + .handle_message(NodeGraphMessage::AddImportAndConnect { + import_index, + input_connector: InputConnector::node_at_index(memoize, 0), + }) + .await; + + let network_interface = &editor.active_document().network_interface; + let type_names = |input_connector: &InputConnector, network_path: &[super::NodeId]| { + network_interface + .potential_valid_input_types(input_connector, network_path) + .iter() + .map(ToString::to_string) + .collect::>() + }; + + let memoize_types = type_names(&InputConnector::node_at_index(memoize, 0), &[merge]); + assert!(memoize_types.iter().any(|ty| ty == "Color"), "Memoize itself should accept a color, found {memoize_types:?}"); + + let content_types = type_names(&InputConnector::node_at_index(merge, import_index), &[]); + assert!(content_types.iter().any(|ty| ty == "Vector"), "the input should accept a vector, found {content_types:?}"); assert!( !content_types.iter().any(|ty| ty == "Color"), - "Path's content should not accept a color just because its Monitor does, found {content_types:?}" + "the input should not accept a color just because its Memoize does, found {content_types:?}" ); } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/structure.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/structure.rs index ac020869b1a..f6bb3d14375 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/structure.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/structure.rs @@ -6,7 +6,7 @@ impl NodeNetworkInterface { pub fn compute_modified_vector(&self, layer: LayerNodeIdentifier) -> Option { let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self); - if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into())) + if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER)) && let Some(geometry) = self.document_metadata.vector_modify.get(&path_node) { let mut modified = geometry.clone(); @@ -28,7 +28,7 @@ impl NodeNetworkInterface { /// (e.g. the pre-solidified centerline for a Solidify Stroke layer) and otherwise do nothing. pub fn upstream_path_node_vector(&self, layer: LayerNodeIdentifier) -> Option { let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self); - graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))?; + graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER))?; self.compute_modified_vector(layer) } diff --git a/editor/src/messages/portfolio/document_migration.rs b/editor/src/messages/portfolio/document_migration.rs index 477329d0057..45c7c83a63a 100644 --- a/editor/src/messages/portfolio/document_migration.rs +++ b/editor/src/messages/portfolio/document_migration.rs @@ -944,8 +944,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[ aliases: &["graphene_core::vector::PathLengthNode"], }, NodeReplacement { - node: graphene_std::vector::path_modify::IDENTIFIER, + node: graphene_std::vector::path::IDENTIFIER, aliases: &[ + "vector_nodes::vector_modification_nodes::PathModifyNode", "graphene_core::vector::vector_modification_nodes::PathModifyNode", "graphene_core::vector::vector_data::modification::PathModifyNode", "graphene_core::vector::vector_modification::PathModifyNode", @@ -1370,6 +1371,28 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_ } } + // The "Path" wrapper network was replaced with the `path` proto node directly. Convert old `Network("Path")` instances to the proto node, forwarding the Content and Modification inputs. + // Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer Path's network impl orphans its child paths. + let path_wrappers: Vec<(NodeId, Vec)> = document + .network_interface + .document_network() + .recursive_nodes() + .filter_map(|(node_id, _, path)| (document.network_interface.reference(node_id, &path) == Some(DefinitionIdentifier::Network("Path".into()))).then_some((*node_id, path))) + .collect(); + for (node_id, network_path) in &path_wrappers { + let new_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER); + let Some(definition) = resolve_document_node_type(&new_reference) else { continue }; + let mut node_template = definition.default_node_template(); + document.network_interface.replace_implementation(node_id, network_path, &mut node_template); + let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else { + continue; + }; + + for (index, input) in old_inputs.into_iter().take(2).enumerate() { + document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path); + } + } + // The Merge and Artboard networks no longer pass their content through a Monitor node, since thumbnails are found from the layers themselves. // Pre-pass for the same reason as the Brush, Transform, and Image migrations above: rebuilding the network orphans its child paths. let monitored_layers: Vec<(NodeId, Vec, DefinitionIdentifier)> = document @@ -3463,7 +3486,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId], // SVG-import legacy Path nodes baked their geometry at non-exposed input 0; move it to input 1 (the modern slot for VectorModification). // For exposed input 0, any baked value is unused at runtime, so just reset it. - if reference == DefinitionIdentifier::Network("Path".into()) { + if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER) { let input_0 = node.inputs.first()?; if let NodeInput::Value { tagged_value, exposed } = input_0 && let TaggedValue::VectorModification(modification) = &**tagged_value diff --git a/editor/src/messages/tool/common_functionality/edit_target.rs b/editor/src/messages/tool/common_functionality/edit_target.rs index bdf5ab34c2e..1fa8f01e2fd 100644 --- a/editor/src/messages/tool/common_functionality/edit_target.rs +++ b/editor/src/messages/tool/common_functionality/edit_target.rs @@ -78,7 +78,7 @@ impl EditTarget { /// The Path node, which vector edits insert beside a layer with vector content when it's missing. pub fn path() -> Self { - Self::network_node("Path", Insertion::BesideVectorLayer) + Self::proto_node(graphene_std::vector::path::IDENTIFIER, Insertion::BesideVectorLayer) } /// The Fill node, which paint edits insert under any Stroke node beside a layer with vector content when it's missing. diff --git a/editor/src/messages/tool/common_functionality/graph_modification_utils.rs b/editor/src/messages/tool/common_functionality/graph_modification_utils.rs index 54a8fc447ac..1d3a222f470 100644 --- a/editor/src/messages/tool/common_functionality/graph_modification_utils.rs +++ b/editor/src/messages/tool/common_functionality/graph_modification_utils.rs @@ -23,7 +23,11 @@ pub fn find_spline(document: &DocumentMessageHandler, layer: LayerNodeIdentifier .network_interface .upstream_flow_back_from_nodes([layer.to_node()].to_vec(), &[], FlowType::HorizontalFlow) .map(|node_id| (document.network_interface.reference(&node_id, &[]), node_id)) - .take_while(|(reference, _)| reference.as_ref().is_some_and(|node_ref| node_ref != &DefinitionIdentifier::Network("Path".into()))) + .take_while(|(reference, _)| { + reference + .as_ref() + .is_some_and(|node_ref| node_ref != &DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER)) + }) .find(|(reference, _)| { reference .as_ref() @@ -115,7 +119,7 @@ pub fn merge_layers(document: &DocumentMessageHandler, first_layer: LayerNodeIde // Add a path node after the combine paths node let path_node_id = NodeId::new(); - let path_node = document_node_definitions::resolve_network_node_type("Path") + let path_node = document_node_definitions::resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER) .expect("Failed to create path node") .default_node_template(); responses.add(NodeGraphMessage::InsertNode { diff --git a/editor/src/messages/tool/common_functionality/utility_functions.rs b/editor/src/messages/tool/common_functionality/utility_functions.rs index de6cac5e0b5..8e4aedcdb8e 100644 --- a/editor/src/messages/tool/common_functionality/utility_functions.rs +++ b/editor/src/messages/tool/common_functionality/utility_functions.rs @@ -635,7 +635,8 @@ pub fn make_path_editable_is_allowed(network_interface: &mut NodeNetworkInterfac // Must not already have an existing Path node, in the right-most part of the layer chain, which has an empty set of modifications // (otherwise users could repeatedly keep running this command and stacking up empty Path nodes) - if let Some(TaggedValue::VectorModification(modifications)) = NodeGraphLayer::new(first_layer, network_interface).find_input(&DefinitionIdentifier::Network("Path".into()), 1) + if let Some(TaggedValue::VectorModification(modifications)) = + NodeGraphLayer::new(first_layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER), 1) && modifications.is_empty() { return None; diff --git a/editor/src/messages/tool/tool_messages/freehand_tool.rs b/editor/src/messages/tool/tool_messages/freehand_tool.rs index df5839a16cb..bea5a216295 100644 --- a/editor/src/messages/tool/tool_messages/freehand_tool.rs +++ b/editor/src/messages/tool/tool_messages/freehand_tool.rs @@ -1,6 +1,6 @@ use super::tool_prelude::*; use crate::consts::SNAP_POINT_TOLERANCE; -use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type; +use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type; use crate::messages::portfolio::document::overlays::utility_functions::open_path_endpoint_overlays; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; @@ -312,7 +312,7 @@ impl Fsm for FreehandToolFsmState { let parent = document.new_layer_bounding_artboard(input, viewport); - let node_type = resolve_network_node_type("Path").expect("Path node does not exist"); + let node_type = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER).expect("Path node does not exist"); let node = node_type.default_node_template(); let nodes = vec![(NodeId(0), node)]; @@ -454,7 +454,7 @@ mod test_freehand { .filter_map(|layer| { let graph_layer = NodeGraphLayer::new(layer, &document.network_interface); // Only get layers with path nodes - let _ = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))?; + let _ = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER))?; let vector = document.network_interface.compute_modified_vector(layer)?; let transform = document.metadata().transform_to_viewport(layer); diff --git a/editor/src/messages/tool/tool_messages/path_tool.rs b/editor/src/messages/tool/tool_messages/path_tool.rs index 83df250a1bc..76c8a58e7b4 100644 --- a/editor/src/messages/tool/tool_messages/path_tool.rs +++ b/editor/src/messages/tool/tool_messages/path_tool.rs @@ -6,7 +6,7 @@ use crate::consts::{ }; use crate::messages::input_mapper::utility_types::macros::action_shortcut_manual; use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn; -use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type; +use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type; use crate::messages::portfolio::document::overlays::utility_functions::{path_overlays, selected_segments}; use crate::messages::portfolio::document::overlays::utility_types::{DrawHandles, OverlayContext}; use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier}; @@ -2859,7 +2859,7 @@ impl Fsm for PathToolFsmState { let layer = if shape_editor.selected_shape_state.contains_key(&layer) { layer } else { - let Some(node_type) = resolve_network_node_type("Path") else { + let Some(node_type) = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER) else { error!("Could not resolve node type for Path"); continue; }; diff --git a/editor/src/messages/tool/tool_messages/pen_tool.rs b/editor/src/messages/tool/tool_messages/pen_tool.rs index 84caadd18a6..892c36ff05d 100644 --- a/editor/src/messages/tool/tool_messages/pen_tool.rs +++ b/editor/src/messages/tool/tool_messages/pen_tool.rs @@ -1,7 +1,7 @@ use super::tool_prelude::*; use crate::consts::{COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_05, HIDE_HANDLE_DISTANCE, SEGMENT_OVERLAY_SIZE}; use crate::messages::input_mapper::utility_types::pointer::MouseKeys; -use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type; +use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type; use crate::messages::portfolio::document::overlays::utility_functions::path_overlays; use crate::messages::portfolio::document::overlays::utility_types::{DrawHandles, OverlayContext}; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; @@ -1434,7 +1434,7 @@ impl PenToolData { } // New path layer - let node_type = resolve_network_node_type("Path").expect("Path node does not exist"); + let node_type = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER).expect("Path node does not exist"); let nodes = vec![(NodeId(0), node_type.default_node_template())]; let parent = document.new_layer_bounding_artboard(input, viewport); @@ -2526,7 +2526,7 @@ mod test_pen_tool { /// The single Pen-drawn path layer and its vector, or `None` once the layer has been undone away. fn drawn_path(editor: &EditorTestUtils) -> Option<(LayerNodeIdentifier, VectorGeometry)> { let document = editor.active_document(); - let path_identifier = DefinitionIdentifier::Network("Path".into()); + let path_identifier = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER); let mut path_layers = document .metadata() .all_layers() diff --git a/editor/src/messages/tool/tool_messages/spline_tool.rs b/editor/src/messages/tool/tool_messages/spline_tool.rs index 9fb89b04db6..45c060a6c30 100644 --- a/editor/src/messages/tool/tool_messages/spline_tool.rs +++ b/editor/src/messages/tool/tool_messages/spline_tool.rs @@ -1,7 +1,7 @@ use super::tool_prelude::*; use crate::consts::{DRAG_THRESHOLD, PATH_JOIN_THRESHOLD, SNAP_POINT_TOLERANCE}; use crate::messages::input_mapper::utility_types::pointer::MouseKeys; -use crate::messages::portfolio::document::node_graph::document_node_definitions::{resolve_network_node_type, resolve_proto_node_type}; +use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type; use crate::messages::portfolio::document::overlays::utility_functions::open_path_endpoint_overlays; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; @@ -442,7 +442,7 @@ impl Fsm for SplineToolFsmState { let parent = document.new_layer_bounding_artboard(input, viewport); - let path_node_type = resolve_network_node_type("Path").expect("Path node does not exist"); + let path_node_type = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER).expect("Path node does not exist"); let path_node = path_node_type.default_node_template(); let spline_node_type = resolve_proto_node_type(graphene_std::vector::spline::IDENTIFIER).expect("Spline node does not exist"); let spline_node = spline_node_type.node_template_input_override([Some(NodeInput::node(NodeId(1), 0))]); diff --git a/editor/src/node_graph_executor.rs b/editor/src/node_graph_executor.rs index d65879c6cc1..44dd518293a 100644 --- a/editor/src/node_graph_executor.rs +++ b/editor/src/node_graph_executor.rs @@ -1,7 +1,8 @@ use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus}; +use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError; use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView; -use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; +use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface}; use crate::messages::prelude::*; use glam::{DAffine2, DVec2, UVec2}; use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue}; @@ -10,12 +11,12 @@ use graph_craft::proto::GraphErrors; use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation}; use graphene_std::bounds::RenderBoundingBox; use graphene_std::color::SRGBA8; -use graphene_std::list::List; +use graphene_std::list::{Item, List}; use graphene_std::raster::{CPU, Raster}; use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box}; use graphene_std::transform::Footprint; -use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, paths_from_list_row_attributes}; -use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic}; +use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes}; +use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter}; use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta; use std::any::Any; use std::sync::Arc; @@ -38,7 +39,6 @@ pub struct ExecutionResponse { responses: VecDeque, /// The layers whose thumbnails the runtime let go of, which it renders anew if they have content to show again. dropped_thumbnails: Vec, - vector_modify: HashMap, /// The latest result of each observation. observations: HashMap, } @@ -48,6 +48,8 @@ pub struct ExecutionResponse { pub enum ObservationKey { /// The node the Data panel inspects. DataPanel, + /// The content of a 'Path' node, which is the geometry the Pen and Path tools edit. + PathContent(NodeId), // TODO: Eventually remove this document upgrade code /// The "Fill" node whose geometry a gradient migration measures. FillMeasurement, @@ -258,7 +260,7 @@ impl NodeGraphExecutor { resources, previewed: Vec::new(), layers: document.network_interface.layer_paths(), - observations: HashMap::new(), + observations: self.observations(&document.network_interface), })) .map_err(|e| e.to_string())?; Ok(instrumented) @@ -288,7 +290,7 @@ impl NodeGraphExecutor { resources, previewed, layers, - observations: self.observations(), + observations: self.observations(&document.network_interface), })) .map_err(|e| e.to_string())?; } else if inspected_node_changed { @@ -314,8 +316,9 @@ impl NodeGraphExecutor { } /// Every observation a graph update of the document starts with. - fn observations(&self) -> HashMap { - self.data_panel_observation().map(|observation| (ObservationKey::DataPanel, observation)).into_iter().collect() + fn observations(&self, network_interface: &NodeNetworkInterface) -> HashMap { + let data_panel = self.data_panel_observation().map(|observation| (ObservationKey::DataPanel, observation)); + data_panel.into_iter().chain(path_content_observations(network_interface)).collect() } /// Adds an evaluate request for whatever current network is cached. @@ -483,7 +486,7 @@ impl NodeGraphExecutor { resources, previewed, layers: document.network_interface.layer_paths(), - observations: self.observations(), + observations: self.observations(&document.network_interface), })) .map_err(|e| e.to_string())?; let execution_id = self.queue_execution(render_config); @@ -518,7 +521,6 @@ impl NodeGraphExecutor { result, responses: existing_responses, dropped_thumbnails, - vector_modify, mut observations, } = *execution_response; all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied()); @@ -645,7 +647,7 @@ impl NodeGraphExecutor { None => responses.add(response), } } - document.network_interface.update_vector_modify(vector_modify); + document.network_interface.update_vector_modify(path_contents(&observations)); match (node_graph_output, execution_context.export_config) { (Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses), @@ -1179,6 +1181,37 @@ fn measure_fill_geometry(data: &Arc) -> Option<(DAffine2, None } +fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator { + let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER)); + + path_nodes.into_iter().filter_map(|node_path| { + let key = ObservationKey::PathContent(*node_path.last()?); + let observation = Observation { + node_path, + connector: ObservedConnector::Input(path::ContentInput::INDEX), + overrides: ContextOverrides::default(), + }; + Some((key, observation)) + }) +} + +/// The incoming geometry of each 'Path' node, read from its observed content. +fn path_contents(observations: &HashMap) -> HashMap { + observations + .iter() + .filter_map(|(key, result)| { + let ObservationKey::PathContent(path_node) = *key else { return None }; + let value = result.data.as_ref()?; + + let geometry = match value.downcast_ref::>() { + Some(list) => VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()), + None => VectorGeometry::from_item(value.downcast_ref::>()?), + }; + Some((path_node, geometry)) + }) + .collect() +} + // Re-export for usage by tests in other modules #[cfg(test)] pub use test::Instrumented; @@ -1224,8 +1257,9 @@ mod test { monitor_node_ids.push(path.clone()); path.pop(); - // A None value is a unit wire with nothing to record and no Monitor row, so its slot stays a dead path that introspects as absent - if matches!(input, NodeInput::Value { tagged_value, .. } if matches!(&**tagged_value, graph_craft::document::value::TaggedValue::None)) { + // A None value has nothing to record and a reflection must stay on the node it describes, so such a slot stays a dead path that introspects as absent + let is_none = matches!(input, NodeInput::Value { tagged_value, .. } if matches!(&**tagged_value, graph_craft::document::value::TaggedValue::None)); + if is_none || matches!(input, NodeInput::Reflection(_)) { continue; } diff --git a/editor/src/node_graph_executor/runtime.rs b/editor/src/node_graph_executor/runtime.rs index b1748b90958..ad302392091 100644 --- a/editor/src/node_graph_executor/runtime.rs +++ b/editor/src/node_graph_executor/runtime.rs @@ -11,15 +11,12 @@ use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler}; use graph_craft::proto::GraphErrors; use graphene_hash::CacheHash; use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture}; -use graphene_std::list::{Item, List}; -use graphene_std::memo::IORecord; use graphene_std::ops::ConvertAsync; #[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))] use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle}; use graphene_std::raster_types::Raster; use graphene_std::runtime::AsyncRuntime; use graphene_std::vector::style::RenderMode; -use graphene_std::vector::{Vector, VectorGeometry, paths_from_list_row_attributes}; use graphene_std::{Context, NodeError, Poll}; use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta}; use interpreted_executor::util::wrap_network_in_scope; @@ -57,7 +54,6 @@ pub struct NodeRuntime { resources: ResourceRegistry, node_graph_errors: GraphErrors, node_graph_warnings: GraphErrors, - monitor_nodes: Vec<(Vec, NodeId)>, thumbnails: Thumbnails, observer: Observer, /// Whether an observation changed since its results were last sent. @@ -65,9 +61,6 @@ pub struct NodeRuntime { preprocessor: preprocessor::Preprocessor, - vector_modify: HashMap, - vector_evaluations: HashMap, - /// Cached surface for Wasm viewport rendering (reused across frames) #[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))] wasm_canvas_cache: CanvasSurfaceHandle, @@ -155,15 +148,12 @@ impl NodeRuntime { node_graph_errors: Vec::new(), node_graph_warnings: Vec::new(), - monitor_nodes: Vec::new(), thumbnails: Thumbnails::new(), observer: Observer::default(), observations_changed: false, preprocessor: preprocessor::Preprocessor::new(), - vector_modify: Default::default(), - vector_evaluations: Default::default(), #[cfg(all(target_family = "wasm", feature = "gpu"))] wasm_canvas_cache: CanvasSurfaceHandle::new(), #[cfg(all(target_family = "wasm", feature = "gpu"))] @@ -376,7 +366,6 @@ impl NodeRuntime { result: ExecutionResult::Panic(payload), responses: VecDeque::new(), dropped_thumbnails: Vec::new(), - vector_modify: HashMap::new(), observations: HashMap::new(), }; self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); @@ -388,7 +377,7 @@ impl NodeRuntime { async fn respond(&mut self, execution_id: u64, result: ExecutionResult) { let mut responses = VecDeque::new(); - let dropped_thumbnails = self.process_monitor_nodes(&mut responses).await; + let dropped_thumbnails = self.update_thumbnails(&mut responses).await; let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref()); let response = ExecutionResponse { @@ -396,7 +385,6 @@ impl NodeRuntime { result, responses, dropped_thumbnails, - vector_modify: self.vector_modify.clone(), observations, }; self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); @@ -429,12 +417,6 @@ impl NodeRuntime { Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)), }; self.node_graph_warnings = warnings; - self.monitor_nodes = proto_network - .nodes - .iter() - .filter(|(_, node)| node.identifier == graphene_std::memo::monitor::IDENTIFIER) - .map(|(id, node)| (node.original_location.path.clone().unwrap_or_default(), *id)) - .collect(); assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?"); let result = self.executor.update(proto_network).map_err(|(types, e)| { @@ -465,41 +447,9 @@ impl NodeRuntime { EvaluationErrors(errors.into()) } - /// Updates state data, giving back the layers whose thumbnails were dropped because they no longer have content to show. - async fn process_monitor_nodes(&mut self, responses: &mut VecDeque) -> Vec { + /// Renders the stale thumbnails, giving back the layers whose thumbnails were dropped because they no longer have content to show. + async fn update_thumbnails(&mut self, responses: &mut VecDeque) -> Vec { let dropped_thumbnails = self.thumbnails.drop_sourceless(); - - for (monitor_node_path, _) in &self.monitor_nodes { - let Some(parent_network_node_id) = monitor_parent_node(monitor_node_path) else { - warn!("Monitor node has invalid node id"); - continue; - }; - - if !records_vector(&self.executor, monitor_node_path) { - continue; - } - let tree = self.executor.tree(); - let Ok(content_node) = tree.input_node(monitor_node_path, 0) else { continue }; - let Ok(Some(context)) = tree.last_context(content_node) else { continue }; - let context_hash = context_hash(&context); - if self.vector_evaluations.get(&parent_network_node_id) == Some(&(content_node, context_hash)) { - continue; - } - - let Some(output) = tree.evaluate(content_node, &context).ok().and_then(evaluated_output) else { - continue; - }; - let geometry = if let Some(list) = output.downcast_ref::>() { - VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()) - } else if let Some(item) = output.downcast_ref::>() { - VectorGeometry::from_item(item) - } else { - continue; - }; - self.vector_modify.insert(parent_network_node_id, geometry); - self.vector_evaluations.insert(parent_network_node_id, (content_node, context_hash)); - } - self.thumbnails.render_stale(&self.executor, &self.editor_api, responses).await; dropped_thumbnails @@ -514,18 +464,6 @@ impl ExecutionResult { } } -/// The layer a monitor node belongs to, since monitor nodes sit within the network of the document node they monitor. -fn monitor_parent_node(monitor_node_path: &[NodeId]) -> Option { - monitor_node_path.len().checked_sub(2).and_then(|index| monitor_node_path.get(index)).copied() -} - -fn records_vector(executor: &DynamicExecutor, monitor_node_path: &[NodeId]) -> bool { - // TODO: Tell this from the monitor node's type once the types the borrow tree records can be compared with concrete ones - executor - .introspect(monitor_node_path) - .is_ok_and(|data| data.is::>>() || data.is::>>()) -} - fn evaluated_output(poll: Poll) -> Option { match poll { Poll::Final(output) | Poll::Partial(output) => Some(output), diff --git a/node-graph/libraries/core-types/src/registry.rs b/node-graph/libraries/core-types/src/registry.rs index 0858d6c0d41..53747cb9751 100644 --- a/node-graph/libraries/core-types/src/registry.rs +++ b/node-graph/libraries/core-types/src/registry.rs @@ -76,6 +76,7 @@ pub enum RegistryValueSource { Default(&'static str), Scope(&'static str), SourceId, + NodePath, } #[derive(Clone, Debug)] diff --git a/node-graph/node-macro/src/codegen.rs b/node-graph/node-macro/src/codegen.rs index 697b8525526..1449657c13d 100644 --- a/node-graph/node-macro/src/codegen.rs +++ b/node-graph/node-macro/src/codegen.rs @@ -205,6 +205,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn } } ParsedValueSource::SourceId => quote!(RegistryValueSource::SourceId), + ParsedValueSource::NodePath => quote!(RegistryValueSource::NodePath), _ => quote!(RegistryValueSource::None), }) .collect(); diff --git a/node-graph/node-macro/src/parsing.rs b/node-graph/node-macro/src/parsing.rs index 1b47931935c..1e671ac92d7 100644 --- a/node-graph/node-macro/src/parsing.rs +++ b/node-graph/node-macro/src/parsing.rs @@ -81,6 +81,7 @@ pub enum ParsedValueSource { Default(TokenStream2), Scope(Box), SourceId, + NodePath, } // #[widget(ParsedWidgetOverride::Hidden)] @@ -174,10 +175,10 @@ impl ParsedField { } } - /// Whether the field is environment rather than an argument: `#[data]` state or a `#[scope]`-injected wire. + /// Whether the field is environment rather than an argument: `#[data]` state, a `#[scope]`-injected wire, or a `#[source_id]` or `#[node_path]` value the compiler fills in. /// Environment fields never classify the node, never supply the element-wise frame, and broadcast by clone. pub(crate) fn is_environment(&self) -> bool { - self.is_data_field || matches!(self.ty.value_source(), ParsedValueSource::Scope(_) | ParsedValueSource::SourceId) + self.is_data_field || matches!(self.ty.value_source(), ParsedValueSource::Scope(_) | ParsedValueSource::SourceId | ParsedValueSource::NodePath) } } @@ -879,6 +880,9 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul // Gives a synchronous node its `SourceId`, as async nodes get it, so it can bump its own generation let source_id = extract_attribute(attrs, "source_id").is_some(); + // Gives a node the path of the document node it was placed as + let node_path = extract_attribute(attrs, "node_path").is_some(); + // Validate data field attributes if is_data_field { if default_value.is_some() { @@ -905,6 +909,18 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul if source_id { return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot have #[source_id] attribute")); } + if node_path { + return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot have #[node_path] attribute")); + } + } + if source_id && node_path { + return Err(Error::new_spanned(&pat_ident, "Cannot have both `source_id` and `node_path` attributes")); + } + if exposed && (source_id || node_path) { + return Err(Error::new_spanned( + &pat_ident, + "Inputs the compiler fills in (#[source_id] or #[node_path]) cannot be exposed (#[expose]). They aren't set in the graph", + )); } if exposed && ident.to_string().starts_with('_') { return Err(Error::new_spanned( @@ -916,9 +932,11 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul let value_source = match (default_value, scope) { (Some(_), Some(_)) => return Err(Error::new_spanned(&pat_ident, "Cannot have both `default` and `scope` attributes")), (Some(_), _) | (_, Some(_)) if source_id => return Err(Error::new_spanned(&pat_ident, "`source_id` cannot have a `default` or `scope` attribute")), + (Some(_), _) | (_, Some(_)) if node_path => return Err(Error::new_spanned(&pat_ident, "`node_path` cannot have a `default` or `scope` attribute")), (Some(default_value), _) => ParsedValueSource::Default(default_value), (_, Some(scope)) => ParsedValueSource::Scope(Box::new(scope)), _ if source_id => ParsedValueSource::SourceId, + _ if node_path => ParsedValueSource::NodePath, _ => ParsedValueSource::None, }; @@ -1880,6 +1898,24 @@ mod tests { parse_node_fn(attr, input).unwrap(); } + #[test] + #[should_panic(expected = "Inputs the compiler fills in (#[source_id] or #[node_path]) cannot be exposed (#[expose])")] + fn test_exposed_node_path() { + let attr = quote!(category("Invalid")); + let input = quote!( + fn invalid_node( + _: impl Ctx, + content: Item, + #[expose] + #[node_path] + node_path: Item, + ) -> Item { + content + } + ); + parse_node_fn(attr, input).unwrap(); + } + #[test] #[should_panic(expected = "Unsupported attribute in `node`")] fn test_unsupported_attribute() { diff --git a/node-graph/nodes/vector/src/vector_modification_nodes.rs b/node-graph/nodes/vector/src/vector_modification_nodes.rs index b311c7ff290..797411ec5a4 100644 --- a/node-graph/nodes/vector/src/vector_modification_nodes.rs +++ b/node-graph/nodes/vector/src/vector_modification_nodes.rs @@ -1,16 +1,22 @@ -use core_types::list::{ATTR_GEOMETRY_CACHE, Item, List, NodeIdPath}; +use core_types::list::{ATTR_GEOMETRY_CACHE, Item, NodeIdPath}; use core_types::transform::BakeTransform; -use core_types::uuid::NodeId; use core_types::{ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_TRANSFORM, Ctx}; use glam::{DAffine2, DVec2}; use graphic_types::Vector; use vector_types::kurbo::BezPath; use vector_types::vector::{GeometryCache, VectorModification, edit_item_geometry, ensure_paths_attribute, shared_paths_from_item_attributes}; -/// Applies a differential modification to a vector path, associating changes made by the Pen and Path tools to indices of edited points and segments. -#[node_macro::node(category(""), memoize)] -fn path_modify(_ctx: impl Ctx, vector: Item, modification: Item>, node_path: Item) -> Item { - let mut vector = vector; +/// Holds the edits made with the Pen and Path tools, applying them to the incoming shape. +#[node_macro::node(category("Vector: Geometry"), icon("NodePath"), memoize, version(2))] +fn path( + _ctx: impl Ctx, + /// The original shape that edits made with the Pen and Path tools are applied to. + content: Item, + /// The edits made with the Pen and Path tools, stored as changes to points and segments. + modification: Item>, + #[node_path] node_path: Item, +) -> Item { + let mut vector = content; let modification = modification.into_element(); // Moving points leaves the paths as they are, so they stay shared with the incoming geometry instead of being copied @@ -39,16 +45,10 @@ fn path_modify(_ctx: impl Ctx, vector: Item, modification: Item(ATTR_EDITOR_CLICK_TARGET); - // Set the path to the encapsulating subgraph (drop our own trailing entry from `node_path`), - // matching the `path_of_subgraph` proto so editor tools can route data back to the parent layer. - let node_path = node_path.into_element().0; - let subgraph_path: List = { - let len = node_path.len(); - node_path.into_iter().take(len.saturating_sub(1)).collect() - }; - let existing = vector.attribute_cloned_or_default::(ATTR_EDITOR_LAYER_PATH).0; - let layer_path = if existing.is_empty() { subgraph_path } else { existing }; - vector.set_attribute(ATTR_EDITOR_LAYER_PATH, NodeIdPath(layer_path)); + // Trace a vector no layer has claimed back to this node for the editor's tools + if vector.attribute_cloned_or_default::(ATTR_EDITOR_LAYER_PATH).0.is_empty() { + vector.set_attribute(ATTR_EDITOR_LAYER_PATH, node_path.into_element()); + } vector } @@ -67,7 +67,7 @@ fn bake_transform(_ctx: impl Ctx, #[implement #[cfg(test)] mod tests { use super::*; - use core_types::list::{ATTR_ID, ATTR_PATHS}; + use core_types::list::{ATTR_ID, ATTR_PATHS, List}; use vector_types::vector::{CurveType, PointId, SegmentId, VectorModificationType, paths_from_item_attributes, push_path}; // A lone loop fills by its contour alone, so it keeps the direction it was drawn in even when that winds backwards @@ -81,7 +81,7 @@ mod tests { bezpath.close_path(); let drawn = Vector::item_from_bezpath(&bezpath); - let modified = path_modify((), drawn.clone(), Item::default(), Item::default()); + let modified = path((), drawn.clone(), Item::default(), Item::default()); assert_eq!(paths_from_item_attributes(&modified), paths_from_item_attributes(&drawn)); } @@ -106,7 +106,7 @@ mod tests { let mut modification = VectorModification::default(); modification.modify(&VectorModificationType::ApplyPointDelta { point: hub, delta: DVec2::X }); - let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()); + let modified = path((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()); let first_path = |item: &Item| paths_from_item_attributes(item).unwrap().element(0).unwrap().0.iter_element_values().copied().collect::>(); assert_eq!(first_path(&drawn), [0, 1, 2, 3, 0]); @@ -125,7 +125,7 @@ mod tests { let mut modification = VectorModification::default(); modification.modify(&VectorModificationType::ApplyPointDelta { point: corner, delta: DVec2::X }); - let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()); + let modified = path((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()); assert_eq!(modified.element().0.element(1), Some(&DVec2::new(11., 0.))); assert!(std::ptr::eq(paths_from_item_attributes(&drawn).unwrap(), paths_from_item_attributes(&modified).unwrap())); @@ -149,7 +149,7 @@ mod tests { }); for modification in [VectorModification::default(), adds_a_point] { - let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()); + let modified = path((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()); assert_eq!(paths_from_item_attributes(&modified).map(List::len), Some(0)); assert_eq!( diff --git a/node-graph/preprocessor/src/lib.rs b/node-graph/preprocessor/src/lib.rs index f9336a14fd3..83a982f6d82 100644 --- a/node-graph/preprocessor/src/lib.rs +++ b/node-graph/preprocessor/src/lib.rs @@ -426,6 +426,7 @@ pub fn node_inputs(fields: &[registry::FieldMetadata], first_node_io: &NodeIOTyp } RegistryValueSource::Scope(data) => return NodeInput::scope(*data), RegistryValueSource::SourceId => return NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId), + RegistryValueSource::NodePath => return NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath), }; // A ranked `Item` type prefers a bare `T` value (promoted at resolution), since bare values drive the Inspector widgets diff --git a/website/content/volunteer/guide/graphene/document-migrations.md b/website/content/volunteer/guide/graphene/document-migrations.md index fd9baa7cddd..de52d7aa06e 100644 --- a/website/content/volunteer/guide/graphene/document-migrations.md +++ b/website/content/volunteer/guide/graphene/document-migrations.md @@ -84,13 +84,15 @@ You ask for what you need through the function's parameters, in any order. The f | `&Node` | The anchor before migration | `id()`, `inputs()`, and the stored node's other accessors | | `&Graph` | The anchor's network before migration | `node(id)`, `declaration(id)`, `consumers(output)` | | `Option<&dyn Compiler>` | What only the compiler can tell about the state before migration, see [Asking the compiler](#asking-the-compiler) | `input_type(node, slot)` | -| `&mut Inputs` | The anchor's input slots | `set`, `insert`, `push`, `remove`, `truncate`, `len` | +| `&mut Inputs` | The anchor's input slots | `set`, `insert`, `push`, `push_reflection`, `remove`, `truncate`, `len` | | `&mut Upstream` | Nodes feeding the anchor | `add_node`, `add_node_keyed`, `remove_node` | | `&mut Downstream` | Whatever reads the anchor's outputs | `consumers`, `add_node`, `add_node_keyed`, `connect` | | `&mut Target` | Which declaration the anchor becomes, see [Choosing a target](#choosing-a-target) | `set` | Reads always see the old document. `node.inputs()` returns the old layout however many edits you've made, and nodes you add never show up in `consumers`. `Inputs` edits apply in order to the layout being built. After `inputs.insert(1, ...)`, later `Inputs` calls see the old slot 1 as slot 2. `node.inputs()[1]` is still the old slot 1. +An input the compiler fills in, like a node's own path, is added with `inputs.push_reflection(...)`, which takes a frozen mirror of the `DocumentNodeMetadata` variant it reflects. + ### Values A migration has to keep working after the code around it changes, so it can't use live types like `TaggedValue`. Declare an enum with only the variants you read or write, named the same as in `TaggedValue`: