From dbba8b08771e6d75776c6b78a49cd10483377e77 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 19 Nov 2026 02:56:05 -0800 Subject: [PATCH] Add a #[graph] macro for defining subgraph nodes as Rust functions --- .../node_graph/document_node_definitions.rs | 734 +------ .../document_node_derive.rs | 451 ++++- .../document/node_graph/node_inspector.rs | 123 +- .../utility_types/network_interface.rs | 3 +- .../characterization_tests.rs | 2 +- .../network_interface/queries.rs | 33 +- .../utility_types/network_interface/types.rs | 74 - .../messages/portfolio/document_migration.rs | 47 +- .../node_graph_executor/runtime/thumbnails.rs | 17 +- node-graph/README.md | 26 +- .../libraries/core-types/src/registry.rs | 167 ++ node-graph/node-macro/src/codegen.rs | 316 ++- node-graph/node-macro/src/graph.rs | 1744 +++++++++++++++++ node-graph/node-macro/src/lib.rs | 33 + node-graph/node-macro/src/parsing.rs | 57 +- node-graph/node-macro/src/validation.rs | 68 +- node-graph/nodes/gstd/src/lib.rs | 1 + node-graph/nodes/gstd/src/subgraphs.rs | 218 +++ node-graph/preprocessor/src/lib.rs | 7 +- .../guide/graphene/document-migrations.md | 2 +- 20 files changed, 3082 insertions(+), 1041 deletions(-) create mode 100644 node-graph/node-macro/src/graph.rs create mode 100644 node-graph/nodes/gstd/src/subgraphs.rs 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 1e6105eaa4..ff1f0d16c2 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 @@ -5,19 +5,16 @@ use super::node_inspector::{self, ParameterWidgetsInfo, SliderRange}; use super::utility_types::{FrontendNodeType, InputTypeConstraint}; use crate::messages::frontend::IconName; use crate::messages::layout::utility_types::widget_prelude::*; -use crate::messages::portfolio::document::utility_types::network_interface::{ - InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride, -}; +use crate::messages::portfolio::document::utility_types::network_interface::{NodeNetworkInterface, NodeTemplate, NodeTemplateImplementation}; use crate::messages::portfolio::ingest::utility_types::TypeFilter; use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses}; use crate::node_graph_executor::NodeGraphExecutor; use glam::DVec2; use graph_craft::ProtoNodeIdentifier; +use graph_craft::concrete; use graph_craft::document::value::*; use graph_craft::document::*; -use graph_craft::{concrete, list}; -use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType}; -use graphene_std::vector::Vector; +use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType}; use graphene_std::*; use std::collections::{HashMap, VecDeque}; @@ -40,6 +37,11 @@ impl NodeInspectorContext<'_> { let input_inspector_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?; let widget_override = input_inspector_row.widget_override.clone()?; + // Older documents store number and Vec2 widget settings this way, but they come from the definition's parameter + if matches!(widget_override.as_str(), "number" | "vec2") { + return None; + } + let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else { log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override"); return None; @@ -51,11 +53,11 @@ impl NodeInspectorContext<'_> { } /// Input position of the location parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node. -pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = 2; +pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::LocationInput::INDEX; /// Input position of the dimensions parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node. -pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = 3; +pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::DimensionsInput::INDEX; /// Input position of the control path parameter on the "Blend" network node template. -pub const BLEND_PATH_INPUT_INDEX: usize = 4; +pub const BLEND_PATH_INPUT_INDEX: usize = graphene_std::subgraphs::blend::PathInput::INDEX; /// The key used to access definitions for a network node or proto node. /// For proto nodes, this is their [`ProtoNodeIdentifier`]. @@ -107,8 +109,7 @@ pub struct DocumentNodeDefinition { /// Used to create the [`DefinitionIdentifier::Network`] identifier. pub identifier: &'static str, - /// The definition's position in its lineage. Bump it, with a `network` migration, when a change would load existing instances wrongly. - /// Instances store it next to their reference. Proto-node definitions take theirs from the node macro. + /// The definition's position in its lineage, from `version(N)` on its `#[node]` or `#[graph]`. Instances store it next to their reference. pub version: u32, /// The default [`NodeTemplate`] this definition instantiates. @@ -136,529 +137,9 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy HashMap { - let custom = vec![ - DocumentNodeDefinition { - identifier: "Merge", - version: 1, - category: "Graphic", - icon: Some("NodeMerge"), - node_template: NodeTemplate { - implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { - exports: vec![NodeInput::node(NodeId(2), 0)], - nodes: [ - // Primary (bottom) input type coercion - NodeTemplate { - inputs: vec![NodeInput::import(generic!(T), 0)], - implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER), - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -2)), - ..Default::default() - }, - // Secondary (left) input type coercion - NodeTemplate { - inputs: vec![NodeInput::import(generic!(T), 1)], - implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER), - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -1)), - ..Default::default() - }, - NodeTemplate { - call_argument: generic!(T), - inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)], - implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER), - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)), - ..Default::default() - }, - ] - .into_iter() - .enumerate() - .map(|(id, node)| (NodeId(id as u64), node)) - .collect(), - ..Default::default() - }), - inputs: vec![NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(list!(Graphic), true)], - input_metadata: vec![ - ("Base", "The stack of layers below this one, which the content is placed above.").into(), - ("Content", "The artwork this layer adds to the stack as a single item.").into(), - ], - output_names: vec!["Out".to_string()], - output_descriptions: vec!["The stack of layers with this layer's content placed on top.".to_string()], - node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)), - ..Default::default() - }, - description: Cow::Borrowed("Merges the provided content as a new item in the layer's compositing stack."), - inspector: None, - }, - DocumentNodeDefinition { - identifier: "Artboard", - version: 1, - category: "Graphic", - icon: Some("NodeArtboard"), - node_template: NodeTemplate { - implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { - exports: vec![NodeInput::node(NodeId(1), 0)], - nodes: [ - NodeTemplate { - call_argument: generic!(T), - implementation: NodeTemplateImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER), - inputs: vec![ - NodeInput::import(Type::Fn(concrete!(Context).into(), generic!(T).into()), 1), - NodeInput::import(item!(TaggedValue), 2), - NodeInput::import(item!(TaggedValue), 3), - NodeInput::import(item!(TaggedValue), 4), - NodeInput::import(item!(TaggedValue), 5), - ], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -3)), - ..Default::default() - }, - NodeTemplate { - inputs: vec![ - NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0), - NodeInput::node(NodeId(0), 0), - ], - implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER), - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)), - ..Default::default() - }, - ] - .into_iter() - .enumerate() - .map(|(id, node)| (NodeId(id as u64), node)) - .collect(), - ..Default::default() - }), - inputs: vec![ - NodeInput::type_default(list!(Artboard), true), - NodeInput::type_default(list!(Graphic), true), - NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false), - NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false), - NodeInput::value(TaggedValue::Color(Color::WHITE), false), - NodeInput::value(TaggedValue::Bool(true), false), - ], - input_metadata: vec![ - ("Base", "The stack of artboards below this one, which this artboard is placed above.").into(), - ("Content", "Graphics to include within the artboard.").into(), - InputMetadata::with_name_description_override( - "Location", - "Coordinate of the top-left corner of the artboard within the document.", - WidgetOverride::Vec2(Vec2InputSettings { - x: "X".to_string(), - y: "Y".to_string(), - unit: " px".to_string(), - is_integer: true, - ..Default::default() - }), - ), - InputMetadata::with_name_description_override( - "Dimensions", - "Width and height of the artboard within the document.", - WidgetOverride::Vec2(Vec2InputSettings { - x: "W".to_string(), - y: "H".to_string(), - unit: " px".to_string(), - is_integer: true, - ..Default::default() - }), - ), - InputMetadata::with_name_description_override("Background", "Color of the artboard background.", WidgetOverride::Custom("artboard_background".to_string())), - ("Clip", "Whether to cut off the contained content that extends outside the artboard, or keep it visible.").into(), - ], - output_names: vec!["Out".to_string()], - output_descriptions: vec!["The stack of artboards with this artboard placed on top.".to_string()], - node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)), - ..Default::default() - }, - description: Cow::Borrowed("Creates a new Artboard which can be used as a working surface."), - inspector: None, - }, - DocumentNodeDefinition { - identifier: "Blend", - version: 1, - category: "Vector: Deform", - icon: Some("NodeBlend"), - node_template: NodeTemplate { - implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { - exports: vec![NodeInput::node(NodeId(16), 0)], - nodes: [ - // 0: Separate Paths (split the vector into its individual paths) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(vector::separate_paths::IDENTIFIER), - inputs: vec![NodeInput::import(generic!(T), 4)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 0)), - ..Default::default() - }, - // 1: Count (number of subpaths) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(vector::count::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(0), 0)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 2)), - ..Default::default() - }, - // 2: Max (clamp subpath count to at least 1 for empty path case) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(1.), false)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)), - ..Default::default() - }, - // 3: As Number (the integer count enters the network's decimal math) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), - inputs: vec![NodeInput::import(item!(i64), 1)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)), - ..Default::default() - }, - // 4: Multiply (total_instances = count × subpath_count) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(2), 0)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 1)), - ..Default::default() - }, - // 5: Subtract (count - 1, open subpath denominator) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Number(1.), false)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)), - ..Default::default() - }, - // 6: Read Index (current repetition index) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER), - inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::Integer(0), false)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)), - ..Default::default() - }, - // 7: Divide (index / count) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 10)), - ..Default::default() - }, - // 8: Floor (floor(index / count) = subpath index) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(7), 0)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 4)), - ..Default::default() - }, - // 9: Modulo (index % count = local index within subpath) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(math_nodes::modulo::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Bool(true), false)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 7)), - ..Default::default() - }, - // 10: Path Is Closed (check if current subpath is closed) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(vector::path_is_closed::IDENTIFIER), - inputs: vec![NodeInput::import(generic!(T), 4), NodeInput::node(NodeId(8), 0)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 2)), - ..Default::default() - }, - // 11: Switch (closed → count, open → max(count - 1, 1) as denominator) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(math_nodes::switch::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(18), 0)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 12)), - ..Default::default() - }, - // 12: Divide (local_index / denominator = within-subpath fraction) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(9), 0), NodeInput::node(NodeId(11), 0)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 7)), - ..Default::default() - }, - // 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::Number(0.9999999999), false)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)), - ..Default::default() - }, - // 14: Add (subpath_index + clamped fraction = progression) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(math_nodes::add::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(8), 0), NodeInput::node(NodeId(13), 0)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(37, 4)), - ..Default::default() - }, - // 15: Morph (content, progression, reverse, distribution, path) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(vector::morph::IDENTIFIER), - inputs: vec![ - NodeInput::import(generic!(T), 0), - NodeInput::node(NodeId(14), 0), - NodeInput::value(TaggedValue::Bool(false), false), - NodeInput::import(item!(vector::misc::InterpolationDistribution), 3), - NodeInput::import(item!(Vector), 4), - ], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(44, 3)), - ..Default::default() - }, - // 16: Repeat - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(15), 0), NodeInput::node(NodeId(4), 0), NodeInput::import(generic!(T), 2)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(51, 0)), - ..Default::default() - }, - // 17: Max (clamp count to at least 1) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::Number(1.), false)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)), - ..Default::default() - }, - // 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::Number(1.), false)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)), - ..Default::default() - }, - ] - .into_iter() - .enumerate() - .map(|(id, node)| (NodeId(id as u64), node)) - .collect(), - ..Default::default() - }), - inputs: vec![ - NodeInput::type_default(list!(Vector), true), - NodeInput::value(TaggedValue::Integer(10), false), - NodeInput::value(TaggedValue::Bool(Default::default()), false), - NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false), - NodeInput::type_default(item!(Vector), false), - ], - input_metadata: vec![ - ("Content", "The vector objects to create intermediate shapes between.").into(), - ( - "Count", - "The number of shapes spanning from the first object to the last, repeated for each subpath of the control path.", - ) - .into(), - ("Reverse", "Flip the stacking order of the shapes, so the ones nearest the first object are on top.").into(), - ("Distribution", "What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.").into(), - ( - "Path", - "An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.", - ) - .into(), - ], - output_names: vec!["Out".to_string()], - output_descriptions: vec!["The blended shapes, from the first object to the last.".to_string()], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)), - ..Default::default() - }, - description: Cow::Borrowed("Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path."), - inspector: None, - }, - DocumentNodeDefinition { - identifier: "Origins to Polyline", - version: 1, - category: "Vector: Path", - icon: Some("NodeOriginsToPolyline"), - node_template: NodeTemplate { - implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { - exports: vec![NodeInput::node(NodeId(7), 0)], - nodes: [ - // 0: Read Vector - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(context::read_vector::IDENTIFIER), - inputs: vec![NodeInput::value(TaggedValue::None, false)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 1)), - ..Default::default() - }, - // 1: Extract Transform - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::extract_transform::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(0), 0)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 1)), - ..Default::default() - }, - // 2: Decompose Translation - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::decompose_translation::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(1), 0)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 1)), - ..Default::default() - }, - // 3: As Vector (auto-converts the decomposed translation into a single-anchor List) - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(vector::as_vector::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(2), 0)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 1)), - ..Default::default() - }, - // 4: Flatten Vector - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(graphic_nodes::graphic::flatten_vector::IDENTIFIER), - inputs: vec![NodeInput::import(generic!(T), 0)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 0)), - ..Default::default() - }, - // 5: Map - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(graphic::map::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(4), 0), NodeInput::node(NodeId(3), 0)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, 0)), - ..Default::default() - }, - // 6: Combine Paths - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(vector::combine_paths::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(5), 0)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(35, 0)), - ..Default::default() - }, - // 7: Points to Polyline - NodeTemplate { - implementation: NodeTemplateImplementation::ProtoNode(vector::points_to_polyline::IDENTIFIER), - inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::value(TaggedValue::Bool(false), false)], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(42, 0)), - ..Default::default() - }, - ] - .into_iter() - .enumerate() - .map(|(id, node)| (NodeId(id as u64), node)) - .collect(), - ..Default::default() - }), - inputs: vec![NodeInput::type_default(list!(Vector), true)], - input_metadata: vec![("Vector", "The vector objects to connect in order by their origins.").into()], - output_names: vec!["Vector".to_string()], - output_descriptions: vec!["An open polyline with an anchor point at the origin of each object.".to_string()], - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)), - ..Default::default() - }, - description: Cow::Borrowed("Connects the origins of vector objects in order with an open polyline, such as to make a control path for the **Blend** and **Morph** nodes."), - inspector: None, - }, - DocumentNodeDefinition { - identifier: "Load Image", - version: 1, - category: "Data: I/O", - icon: Some("NodeLoadImage"), - node_template: NodeTemplate { - implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { - exports: vec![NodeInput::node(NodeId(1), 0)], - nodes: [ - NodeTemplate { - inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(item!(String), 1)], - implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER), - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)), - ..Default::default() - }, - NodeTemplate { - inputs: vec![NodeInput::node(NodeId(0), 0)], - implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::bytes_to_image::IDENTIFIER), - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)), - ..Default::default() - }, - ] - .into_iter() - .enumerate() - .map(|(id, node)| (NodeId(id as u64), node)) - .collect(), - ..Default::default() - }), - inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String(String::new()), false)], - input_metadata: vec![ - ("Empty", "Has no effect, since the image is loaded from the URL.").into(), - ("URL", "The web address or local asset path of the image to load.").into(), - ], - output_names: vec!["Image".to_string()], - output_descriptions: vec!["The loaded image.".to_string()], - ..Default::default() - }, - description: Cow::Borrowed("Loads an image from a given URL."), - inspector: None, - }, - DocumentNodeDefinition { - identifier: "Regex Find", - version: 1, - category: "String: Regex", - icon: Some("NodeRegexFind"), - node_template: NodeTemplate { - implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { - exports: vec![ - // Primary output: the whole match (String) - NodeInput::node(NodeId(1), 0), - // Secondary output: capture groups (List), each item carries `start`/`end`/`name` attributes from `regex_find` - NodeInput::node(NodeId(2), 0), - ], - nodes: [ - // Node 0: regex_find proto node — returns List of [whole_match, ...capture_groups] - NodeTemplate { - inputs: vec![ - NodeInput::import(item!(String), 0), - NodeInput::import(item!(String), 1), - NodeInput::import(item!(i64), 2), - NodeInput::import(item!(bool), 3), - NodeInput::import(item!(bool), 4), - ], - implementation: NodeTemplateImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER), - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)), - ..Default::default() - }, - // Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them) - NodeTemplate { - inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)], - implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER), - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)), - ..Default::default() - }, - // Node 2: remove_at_index at index 0, returns the capture group items as a List, preserving each item's start/end/name attributes - NodeTemplate { - inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)], - implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER), - node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)), - ..Default::default() - }, - ] - .into_iter() - .enumerate() - .map(|(id, node)| (NodeId(id as u64), node)) - .collect(), - ..Default::default() - }), - inputs: vec![ - NodeInput::value(TaggedValue::String(String::new()), true), - NodeInput::value(TaggedValue::String(String::new()), false), - NodeInput::value(TaggedValue::Integer(0), false), - NodeInput::value(TaggedValue::Bool(false), false), - NodeInput::value(TaggedValue::Bool(false), false), - ], - input_metadata: vec![ - ("String", "The string to search within.").into(), - ("Pattern", "The regular expression pattern to search for.").into(), - ( - "Match Index", - "Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.", - ) - .into(), - ("Case Insensitive", "Match letters regardless of case.").into(), - ("Multiline", "Make `^` and `$` match the start and end of each line, not just the whole string.").into(), - ], - output_names: vec!["Match".to_string(), "Captures".to_string()], - output_descriptions: vec![ - "The whole portion of the string matching the pattern, or empty if there is no match.".to_string(), - "The text matched by each capture group in the pattern, in order.".to_string(), - ], - ..Default::default() - }, - description: Cow::Borrowed( - r#"Finds a portion of the string matching a regular expression pattern. With "Match Index" at its default 0, it selects the first non-overlapping occurrence, but others may be selected. Capture groups, if any, are produced as a list in the "Captures" output."#, - ), - inspector: None, - }, - ]; - - document_node_derive::post_process_nodes(custom) + document_node_derive::derive_definitions() } type NodeInspector = HashMap Vec + Send + Sync>>; @@ -737,91 +218,10 @@ fn static_input_inspector() -> InputInspector { }), ); map.insert( - "number".to_string(), - Box::new(|node_id, index, context| { - let mut number_input = NumberInput::default(); - if let Some(unit) = context - .network_interface - .input_data(&node_id, index, "unit", context.selection_network_path) - .and_then(|value| value.as_str()) - { - number_input = number_input.unit(unit); - } - if let Some(min) = context - .network_interface - .input_data(&node_id, index, "min", context.selection_network_path) - .and_then(|value| value.as_f64()) - { - number_input = number_input.min(min); - } - if let Some(max) = context - .network_interface - .input_data(&node_id, index, "max", context.selection_network_path) - .and_then(|value| value.as_f64()) - { - number_input = number_input.max(max); - } - if let Some(step) = context - .network_interface - .input_data(&node_id, index, "step", context.selection_network_path) - .and_then(|value| value.as_f64()) - { - number_input = number_input.step(step); - } - if let Some(mode) = context.network_interface.input_data(&node_id, index, "mode", context.selection_network_path).map(|value| { - let mode: NumberInputMode = serde_json::from_value(value.clone()).unwrap(); - mode - }) { - number_input = number_input.mode(mode); - } - if let Some(range_min) = context - .network_interface - .input_data(&node_id, index, "range_min", context.selection_network_path) - .and_then(|value| value.as_f64()) - { - number_input = number_input.range_min(Some(range_min)); - } - if let Some(range_max) = context - .network_interface - .input_data(&node_id, index, "range_max", context.selection_network_path) - .and_then(|value| value.as_f64()) - { - number_input = number_input.range_max(Some(range_max)); - } - if let Some(is_integer) = context - .network_interface - .input_data(&node_id, index, "is_integer", context.selection_network_path) - .and_then(|value| value.as_bool()) - { - number_input = number_input.is_integer(is_integer); - } - let blank_assist = context - .network_interface - .input_data(&node_id, index, "blank_assist", context.selection_network_path) - .and_then(|value| value.as_bool()) - .unwrap_or_else(|| { - log::error!("Could not get blank assist when displaying number input for node {node_id}, index {index}"); - true - }); - - Ok(vec![LayoutGroup::row(node_inspector::number_widget( - ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context), - number_input, - ))]) - }), - ); - map.insert( - // The custom number input settings are only available on proto nodes "optional_f64".to_string(), Box::new(|node_id, index, context| { let mut number_input = NumberInput::default(); - // The field is cloned so the lock is released before building the row below, which locks the node metadata again - if let Some(field) = context - .network_interface - .implementation(&node_id, context.selection_network_path) - .and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None }) - .and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned()) - { + if let Some(field) = context.network_interface.field_metadata(&node_id, index, context.selection_network_path) { if let Some(unit) = field.unit { number_input = number_input.unit(unit); } @@ -952,57 +352,6 @@ fn static_input_inspector() -> InputInspector { "type_choice".to_string(), Box::new(|node_id, index, context| Ok(vec![node_inspector::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])), ); - map.insert( - "vec2".to_string(), - Box::new(|node_id, index, context| { - let x = context - .network_interface - .input_data(&node_id, index, "x", context.selection_network_path) - .and_then(|value| value.as_str()) - .unwrap_or_else(|| { - log::error!("Could not get x for vec2 input"); - "" - }) - .to_string(); - let y = context - .network_interface - .input_data(&node_id, index, "y", context.selection_network_path) - .and_then(|value| value.as_str()) - .unwrap_or_else(|| { - log::error!("Could not get y for vec2 input"); - "" - }) - .to_string(); - let unit = context - .network_interface - .input_data(&node_id, index, "unit", context.selection_network_path) - .and_then(|value| value.as_str()) - .unwrap_or_else(|| { - log::error!("Could not get unit for vec2 input"); - "" - }) - .to_string(); - let min = context - .network_interface - .input_data(&node_id, index, "min", context.selection_network_path) - .and_then(|value| value.as_f64()); - let is_integer = context - .network_interface - .input_data(&node_id, index, "is_integer", context.selection_network_path) - .and_then(|value| value.as_bool()) - .unwrap_or_default(); - - Ok(vec![node_inspector::vec2_widget( - ParameterWidgetsInfo::at_index(node_id, index, true, context), - &x, - &y, - &unit, - min, - is_integer, - false, - )]) - }), - ); map.insert( "noise_inspector_scale".to_string(), Box::new(|node_id, index, context| { @@ -1175,6 +524,7 @@ fn static_input_inspector() -> InputInspector { "Y", "", None, + None, false, mandelbrot_to_julia.is_some_and(|percent| percent >= 100.), )]) @@ -1191,6 +541,7 @@ fn static_input_inspector() -> InputInspector { "Y", "", None, + None, false, mandelbrot_to_julia.is_some_and(|percent| percent <= 0.), )]) @@ -1297,6 +648,7 @@ fn static_input_inspector() -> InputInspector { "Y", " px", None, + None, false, false, )]) @@ -1312,6 +664,7 @@ fn static_input_inspector() -> InputInspector { "H", "x", None, + None, false, false, )]) @@ -1432,7 +785,7 @@ fn static_input_inspector() -> InputInspector { "vec2_uv".to_string(), Box::new(|node_id, index, context| { let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context); - Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, false, false)]) + Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, None, false, false)]) }), ); map @@ -1680,6 +1033,18 @@ mod test { use crate::test_utils::test_prelude::*; use graph_craft::document::NodeId; + // A `#[graph]` node with an inner node that has no definition is left out of the catalog with only a logged error + #[test] + fn every_registered_graph_has_a_definition() { + // Released before resolving, since building the catalog locks the registry too + let identifiers: Vec<&str> = graphene_std::registry::GRAPH_METADATA.lock().unwrap().iter().map(|graph| graph.identifier).collect(); + assert!(!identifiers.is_empty(), "the `#[graph]` nodes in `graphene_std::subgraphs` should be registered"); + + for identifier in identifiers { + assert!(resolve_network_node_type(identifier).is_some(), "the '{identifier}' graph should have a definition"); + } + } + #[test] fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() { use glam::{DAffine2, UVec2}; @@ -1820,21 +1185,36 @@ mod test_type_constraints { #[test] fn every_definition_default_value_satisfies_its_constraint() { - let mut violations = Vec::new(); - for definition in super::DOCUMENT_NODE_TYPES.values() { - let name = &definition.node_template.display_name; - let constraints = InputTypeConstraint::constraints_for_all_inputs(&definition.node_template, name); + // Checks a node's inputs against what its implementations accept, then each node inside it, whose values a subgraph's author writes too + fn check(node_template: &NodeTemplate, name: &str, violations: &mut Vec) { + let constraints = InputTypeConstraint::constraints_for_all_inputs(node_template, name); - for (index, (constraint, input)) in constraints.iter().zip(&definition.node_template.inputs).enumerate() { + for (index, (constraint, input)) in constraints.iter().zip(&node_template.inputs).enumerate() { if let Some(value) = input.as_value() && !constraint.accepts_default_value(&value.ty()) { violations.push(format!("{name} input {index}: {} does not satisfy {constraint:?}", value.ty())); } + + let takes_nothing = matches!(constraint, InputTypeConstraint::Limited(types) if !types.is_empty() && types.iter().all(|ty| ty == "()")); + if takes_nothing && matches!(input, NodeInput::Node { .. } | NodeInput::Import { .. }) { + violations.push(format!("{name} input {index}: a wire feeds it, but it takes nothing")); + } + } + + if let NodeTemplateImplementation::Network(network) = &node_template.implementation { + for (node_id, inner) in &network.nodes { + check(inner, &format!("{name}, node {node_id}"), violations); + } } } - assert!(violations.is_empty(), "Default values rejected by their input constraints:\n{}", violations.join("\n")); + let mut violations = Vec::new(); + for definition in super::DOCUMENT_NODE_TYPES.values() { + check(&definition.node_template, &definition.node_template.display_name, &mut violations); + } + + assert!(violations.is_empty(), "Values rejected by their input constraints:\n{}", violations.join("\n")); } #[test] @@ -1851,7 +1231,7 @@ mod test_type_constraints { #[test] fn single_protonode() { - let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist"); + let node_type = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist"); let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name"); all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(glam::DVec2)]); assert!(!constraint[0].satisfies(&concrete!(String))); @@ -1865,7 +1245,7 @@ mod test_type_constraints { #[test] fn single_protonode2() { - let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist"); + let node_type = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist"); let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name"); all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(String)]); assert!(!constraint[0].satisfies(&concrete!(glam::DVec2))); @@ -1874,8 +1254,8 @@ mod test_type_constraints { #[test] fn network() { - let atan_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist"); - let min_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist"); + let atan_definition = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist"); + let min_definition = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist"); let atan_node = atan_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]); let min_node = min_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]); let inner_network = NodeNetworkTemplate { diff --git a/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs b/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs index c85e20d1d1..3091ed556f 100644 --- a/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs +++ b/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs @@ -1,11 +1,17 @@ use super::DocumentNodeDefinition; use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; -use crate::messages::portfolio::document::utility_types::network_interface::{InputMetadata, NodeTemplate, NodeTemplateImplementation, WidgetOverride}; +use crate::messages::portfolio::document::utility_types::network_interface::{ + InputMetadata, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, WidgetOverride, +}; +use glam::IVec2; +use graph_craft::document::value::TaggedValue; +use graph_craft::document::{NodeId, NodeInput}; use graphene_std::registry::*; use graphene_std::*; use std::collections::{HashMap, HashSet}; -pub(super) fn post_process_nodes(custom: Vec) -> HashMap { +/// Generates every definition, from the node macro's metadata for proto nodes and the graph macro's for built-in subgraphs. +pub(super) fn derive_definitions() -> HashMap { let mut definitions_map = HashMap::new(); // Add the protonodes from the macro. @@ -75,16 +81,7 @@ pub(super) fn post_process_nodes(custom: Vec) -> HashMap inputs, call_argument: input_type.clone(), implementation: NodeTemplateImplementation::ProtoNode(id.clone()), - // TODO: Store information for input overrides in the node macro - input_metadata: fields - .iter() - .map(|f| match f.widget_override { - RegistryWidgetOverride::None => (f.name, f.description).into(), - RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Hidden), - RegistryWidgetOverride::String(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::String(str.to_string())), - RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())), - }) - .collect(), + input_metadata: input_metadata(fields), output_names, ..Default::default() }, @@ -96,25 +93,242 @@ pub(super) fn post_process_nodes(custom: Vec) -> HashMap ); } - // Add the hand-written network nodes to the map and add the metadata for their internal protonodes - for mut network_node in custom { - fill_proto_node_metadata(&mut network_node.node_template, &definitions_map); - - // Set the reference to the node identifier - if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation { - network_template.reference = Some(network_node.identifier.to_string()); - // If it is not a merge node, then set the display name to the identifier/reference - if network_node.identifier != "Merge" { - network_node.node_template.display_name = network_node.identifier.to_string(); - } - } - definitions_map.insert(DefinitionIdentifier::Network(network_node.identifier.to_string()), network_node); - } + let graphs = GRAPH_METADATA.lock().unwrap().clone(); + add_graph_definitions(graphs, &mut definitions_map); definitions_map } -/// Recursively fills each nested proto node's editor metadata from its definition, preserving only the authored position. +/// The name, description, and any widget override of each parameter, for a proto node's fields or a graph's imports. +/// The rest of a parameter's widget settings are read from its field when the Inspector draws it. +fn input_metadata(fields: &[FieldMetadata]) -> Vec { + fields + .iter() + .map(|field| { + let (name, description) = (field.name, field.description); + match field.widget_override { + RegistryWidgetOverride::None => (name, description).into(), + RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(name, description, WidgetOverride::Hidden), + RegistryWidgetOverride::String(text) => InputMetadata::with_name_description_override(name, description, WidgetOverride::String(text.to_string())), + RegistryWidgetOverride::Custom(key) => InputMetadata::with_name_description_override(name, description, WidgetOverride::Custom(key.to_string())), + } + }) + .collect() +} + +/// Why a `#[graph]` node has no definition yet, or can't have one. +enum GraphDefinitionError { + /// A node inside it has no definition, which may be another graph not yet added. + MissingNode(String), + /// The graph's wiring is invalid, so it's left out of the catalog. + Invalid(String), +} + +/// Adds the nodes defined as subgraphs by `#[graph]`, each once the definitions of the nodes inside it exist. +fn add_graph_definitions(graphs: Vec, definitions_map: &mut HashMap) { + // Every graph sharing an identifier is left out, so the catalog doesn't depend on registration order + let mut identifier_counts = HashMap::new(); + for graph in &graphs { + *identifier_counts.entry(graph.identifier).or_insert(0) += 1; + } + let mut rejected = HashSet::new(); + let mut pending_graphs: Vec<(GraphMetadata, String)> = graphs + .into_iter() + .filter(|graph| { + let taken = identifier_counts[graph.identifier] > 1; + if taken { + log::error!("The '{}' graph has no definition, since another graph has the same identifier", graph.identifier); + rejected.insert(graph.identifier); + } + !taken + }) + .map(|graph| (graph, String::new())) + .collect(); + + loop { + let pending_count = pending_graphs.len(); + + let mut ready = Vec::new(); + pending_graphs.retain_mut(|(graph, missing)| { + // A graph built on a left-out graph is left out too, rather than embedding another definition of that name + let rejected_inner_graph = graph.nodes.iter().find_map(|node| match node.implementation { + GraphNodeImplementation::Graph(identifier) if rejected.contains(identifier) => Some(identifier), + _ => None, + }); + if let Some(inner_graph) = rejected_inner_graph { + log::error!("The '{}' graph has no definition, since the '{inner_graph}' graph inside it has none", graph.identifier); + rejected.insert(graph.identifier); + return false; + } + + match graph_definition(graph, definitions_map) { + Ok(definition) => { + ready.push(definition); + false + } + Err(GraphDefinitionError::MissingNode(missing_node)) => { + *missing = missing_node; + true + } + Err(GraphDefinitionError::Invalid(reason)) => { + log::error!("The '{}' graph has no definition, since {reason}", graph.identifier); + rejected.insert(graph.identifier); + false + } + } + }); + for definition in ready { + let definition = prepare_network_definition(definition, definitions_map); + definitions_map.insert(DefinitionIdentifier::Network(definition.identifier.to_string()), definition); + } + + if pending_graphs.is_empty() || pending_graphs.len() == pending_count { + break; + } + } + for (graph, missing_node) in pending_graphs { + log::error!("The '{}' graph has no definition, since the '{missing_node}' node inside it has none", graph.identifier); + } +} + +/// Fills a network definition's nested proto node metadata and points its network at the definition. +fn prepare_network_definition(mut network_node: DocumentNodeDefinition, definitions_map: &HashMap) -> DocumentNodeDefinition { + fill_proto_node_metadata(&mut network_node.node_template, definitions_map); + + // Set the reference to the node identifier + if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation { + network_template.reference = Some(network_node.identifier.to_string()); + // If it is not a merge node, then set the display name to the identifier/reference + if network_node.identifier != "Merge" { + network_node.node_template.display_name = network_node.identifier.to_string(); + } + } + + network_node +} + +/// Builds the catalog definition of a node defined as a subgraph by `#[graph]`. +fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap) -> Result { + let mut nodes = HashMap::new(); + for (index, node) in graph.nodes.iter().enumerate() { + // Start from the node's own definition, so each input the graph leaves out matches a new instance of it + let (identifier, name) = match &node.implementation { + GraphNodeImplementation::ProtoNode(identifier) => (DefinitionIdentifier::ProtoNode(identifier.clone()), identifier.as_str().to_string()), + GraphNodeImplementation::Graph(identifier) => (DefinitionIdentifier::Network(identifier.to_string()), identifier.to_string()), + }; + let Some(definition) = definitions_map.get(&identifier) else { + return Err(GraphDefinitionError::MissingNode(name)); + }; + let mut template = definition.default_node_template(); + + if let Some(call_argument) = &node.call_argument { + template.call_argument = call_argument.clone(); + } + template.visible = !node.hidden; + template.locked = node.locked; + template.pinned = node.pinned; + if let Some(display_name) = node.display_name { + template.display_name = display_name.to_string(); + } + + let position = node.position.map_or(IVec2::ZERO, |(x, y)| IVec2::new(x, y)); + template.node_type_metadata = if node.layer { + NodeTypePersistentMetadata::layer(position) + } else { + NodeTypePersistentMetadata::node(position) + }; + + for (input_index, source) in &node.inputs { + let Some(input) = template.inputs.get_mut(*input_index) else { + return Err(GraphDefinitionError::Invalid(format!("its node {index}, '{name}', has no input {input_index} for it to set"))); + }; + + // An input the compiler fills in can't be set, which the macro already prevents for the graphs it builds + if matches!(input, NodeInput::Scope(_) | NodeInput::Reflection(_)) { + return Err(GraphDefinitionError::Invalid(format!( + "it sets input {input_index} of its node {index}, '{name}', which the compiler fills in" + ))); + } + + *input = graph_input(source, input); + } + + nodes.insert(NodeId(index as u64), template); + } + + // Each import starts from its `#[default(...)]` or else its type, as a proto node's parameter does + let inputs = preprocessor::node_inputs(&graph.imports, &NodeIOTypes::empty()); + + let exports = graph.exports.iter().map(|export| graph_input(&export.source, &NodeInput::value(TaggedValue::None, false))).collect(); + + Ok(DocumentNodeDefinition { + identifier: graph.identifier, + version: graph.version, + category: graph.category, + icon: graph.icon, + description: Cow::Borrowed(graph.description), + inspector: None, + node_template: NodeTemplate { + implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { exports, nodes, ..Default::default() }), + inputs, + input_metadata: input_metadata(&graph.imports), + output_names: graph.exports.iter().map(|export| export.name.to_string()).collect(), + output_descriptions: graph.exports.iter().map(|export| export.description.to_string()).collect(), + node_type_metadata: if graph.layer { + NodeTypePersistentMetadata::layer(IVec2::ZERO) + } else { + NodeTypePersistentMetadata::node(IVec2::ZERO) + }, + ..Default::default() + }, + }) +} + +/// The input a graph definition writes, where `default` is what the node's own definition starts that input with. +fn graph_input(source: &GraphInputSource, default: &NodeInput) -> NodeInput { + match source { + GraphInputSource::Node { node, output } => NodeInput::node(NodeId(*node as u64), *output), + GraphInputSource::Import { index, ty } => NodeInput::import(ty.clone(), *index), + GraphInputSource::Value { value, exposed } => { + let ty = match default { + NodeInput::Value { tagged_value, .. } => tagged_value.ty(), + NodeInput::Import { import_type, .. } => import_type.clone(), + _ => generic!(T), + }; + NodeInput::value(graph_value(value, &ty), exposed.unwrap_or(default.is_exposed())) + } + GraphInputSource::Scope(key) => NodeInput::scope(*key), + GraphInputSource::NodePath => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath), + GraphInputSource::SourceId => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId), + } +} + +/// The type of the elements a wire of this type carries, past any `Item`, `List`, or lazy wrapping. +fn element_type(ty: &Type) -> &Type { + let mut element = ty; + while let Type::Item(inner) | Type::List(inner) | Type::Fn(_, inner) = element { + element = inner; + } + element +} + +/// Converts a value written in a graph definition to the type of the input it feeds. +fn graph_value(value: &GraphValue, ty: &Type) -> TaggedValue { + // An integer literal feeds an integer input as an integer, and any other as a number + let is_integer = *element_type(ty) == concrete!(i64); + + match value { + GraphValue::Integer(integer) if is_integer => TaggedValue::Integer(*integer), + GraphValue::Integer(integer) => TaggedValue::Number(*integer as f64), + GraphValue::Number(number) => TaggedValue::Number(*number), + GraphValue::Bool(boolean) => TaggedValue::Bool(*boolean), + GraphValue::String(string) => TaggedValue::String(string.clone()), + GraphValue::Vec2(vec2) => TaggedValue::DVec2(*vec2), + GraphValue::Color(color) => TaggedValue::Color(*color), + } +} + +/// Recursively gives each nested proto node its definition's input and output metadata, and its display name if the network's author gave none. fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &HashMap) { match &mut node_template.implementation { NodeTemplateImplementation::Network(network_template) => { @@ -128,13 +342,190 @@ fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: & return; }; + // A display name, lock, or pin the network's author gave the node is kept let definition_template = &definition.node_template; - node_template.display_name = definition_template.display_name.clone(); + if node_template.display_name.is_empty() { + node_template.display_name = definition_template.display_name.clone(); + } node_template.input_metadata = definition_template.input_metadata.clone(); node_template.output_names = definition_template.output_names.clone(); - node_template.locked = definition_template.locked; - node_template.pinned = definition_template.pinned; + node_template.locked |= definition_template.locked; + node_template.pinned |= definition_template.pinned; } NodeTemplateImplementation::Definition(_) => {} } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type; + + fn number_import() -> FieldMetadata { + FieldMetadata { + name: "Value", + description: "", + internal: false, + exposed: true, + widget_override: RegistryWidgetOverride::None, + value_source: RegistryValueSource::None, + default_colors: None, + default_type: Some(Type::Item(Box::new(concrete!(f64)))), + number_soft_min: None, + number_soft_max: None, + number_hard_min: None, + number_hard_max: None, + number_mode_range: false, + number_display_decimal_places: None, + number_step: None, + unit: None, + multiline: false, + progression: false, + constant: false, + labels: None, + integer: false, + blank_assist: true, + } + } + + /// A graph exporting one node, which is fed by the given inputs. + fn one_node_graph(identifier: &'static str, implementation: GraphNodeImplementation, inputs: Vec<(usize, GraphInputSource)>) -> GraphMetadata { + GraphMetadata { + identifier, + category: "Test", + icon: None, + description: "", + version: 1, + layer: false, + imports: vec![number_import()], + exports: vec![GraphExportMetadata { + name: "Out", + description: "", + source: GraphInputSource::Node { node: 0, output: 0 }, + }], + nodes: vec![GraphNodeMetadata { + implementation, + inputs, + position: None, + layer: false, + display_name: None, + hidden: false, + locked: false, + pinned: false, + call_argument: None, + }], + } + } + + fn from_import() -> Vec<(usize, GraphInputSource)> { + let ty = Type::Item(Box::new(concrete!(f64))); + vec![(0, GraphInputSource::Import { index: 0, ty })] + } + + /// The definitions a test graph builds on: only the As Number proto node. + fn proto_definitions() -> HashMap { + let identifier = DefinitionIdentifier::ProtoNode(math_nodes::as_number::IDENTIFIER); + let definition = resolve_document_node_type(&identifier).expect("As Number should have a definition").clone(); + HashMap::from([(identifier, definition)]) + } + + fn has_graph(definitions_map: &HashMap, identifier: &str) -> bool { + definitions_map.contains_key(&DefinitionIdentifier::Network(identifier.to_string())) + } + + #[test] + fn a_graph_resolves_when_registered_before_a_graph_inside_it() { + let outer = one_node_graph("Test Outer", GraphNodeImplementation::Graph("Test Inner"), from_import()); + let inner = one_node_graph("Test Inner", math_nodes::as_number::IDENTIFIER.into(), from_import()); + + let mut definitions_map = proto_definitions(); + add_graph_definitions(vec![outer, inner], &mut definitions_map); + + assert!(has_graph(&definitions_map, "Test Inner")); + assert!(has_graph(&definitions_map, "Test Outer")); + } + + #[test] + fn a_graph_setting_an_input_its_node_lacks_is_left_out() { + let mut inputs = from_import(); + inputs.push(( + 100, + GraphInputSource::Value { + value: GraphValue::Number(1.), + exposed: None, + }, + )); + let graph = one_node_graph("Test Missing Input", math_nodes::as_number::IDENTIFIER.into(), inputs); + + let mut definitions_map = proto_definitions(); + add_graph_definitions(vec![graph], &mut definitions_map); + + assert!(!has_graph(&definitions_map, "Test Missing Input")); + } + + #[test] + fn graphs_sharing_an_identifier_and_graphs_built_on_them_are_left_out() { + let first = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import()); + let second = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import()); + let dependent = one_node_graph("Test Dependent", GraphNodeImplementation::Graph("Test Twin"), from_import()); + + let mut definitions_map = proto_definitions(); + add_graph_definitions(vec![first, second, dependent], &mut definitions_map); + + assert!(!has_graph(&definitions_map, "Test Twin")); + assert!(!has_graph(&definitions_map, "Test Dependent")); + } + + #[test] + fn an_integer_value_takes_the_type_of_the_input_it_feeds() { + let integer = Type::Item(Box::new(concrete!(i64))); + let number = Type::Item(Box::new(concrete!(f64))); + + assert!(matches!(graph_value(&GraphValue::Integer(3), &integer), TaggedValue::Integer(3))); + assert!(matches!(graph_value(&GraphValue::Integer(3), &number), TaggedValue::Number(value) if value == 3.)); + } + + #[test] + fn imports_start_from_their_default_or_type() { + let unit_primary = FieldMetadata { + default_type: Some(concrete!(())), + ..number_import() + }; + let with_default = FieldMetadata { + value_source: RegistryValueSource::Default("2.5"), + ..number_import() + }; + let graph = GraphMetadata { + imports: vec![unit_primary, with_default], + ..one_node_graph("Test Defaults", math_nodes::as_number::IDENTIFIER.into(), from_import()) + }; + + let mut definitions_map = proto_definitions(); + add_graph_definitions(vec![graph], &mut definitions_map); + let inputs = &definitions_map[&DefinitionIdentifier::Network("Test Defaults".to_string())].node_template.inputs; + + // A `()` primary has nothing to connect, and an exposed parameter's default is parsed by its type + assert!(!inputs[0].is_exposed()); + assert!(matches!(inputs[1].as_value(), Some(TaggedValue::Number(value)) if *value == 2.5)); + assert!(inputs[1].is_exposed()); + } + + #[test] + fn a_graph_nodes_widget_settings_come_from_its_import() { + use crate::messages::prelude::DocumentMessageHandler; + + let node_id = NodeId(1); + let mut document = DocumentMessageHandler::default(); + let artboard = resolve_document_node_type(&DefinitionIdentifier::Network("Artboard".into())).expect("Artboard should exist"); + document.network_interface.insert_node(node_id, artboard.default_node_template(), &[]); + + let location = graphene_std::subgraphs::artboard::LocationInput::INDEX; + let field = document + .network_interface + .field_metadata(&node_id, location, &[]) + .expect("the location input should have its import's settings"); + assert_eq!(field.labels, Some(("X", "Y"))); + assert!(field.integer); + assert!(!document.network_interface.is_internal_input(&node_id, location, &[])); + } +} 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 e566f4afc7..6767e3a647 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs @@ -240,7 +240,7 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec, pub soft_max: Option, @@ -252,6 +252,50 @@ pub(crate) struct ParameterOptions { pub unit: Option<&'static str>, pub display_decimal_places: Option, pub step: Option, + pub labels: Option<(&'static str, &'static str)>, + pub integer: bool, + pub blank_assist: bool, +} + +impl Default for ParameterOptions { + fn default() -> Self { + Self { + soft_min: None, + soft_max: None, + hard_min: None, + hard_max: None, + slider: false, + multiline: false, + progression: false, + unit: None, + display_decimal_places: None, + step: None, + labels: None, + integer: false, + blank_assist: true, + } + } +} + +impl ParameterOptions { + /// The options a proto node's field or a graph's import gives its widget. + pub(crate) fn from_field(field: &graphene_std::registry::FieldMetadata) -> Self { + Self { + soft_min: field.number_soft_min, + soft_max: field.number_soft_max, + hard_min: field.number_hard_min, + hard_max: field.number_hard_max, + slider: field.number_mode_range, + multiline: field.multiline, + progression: field.progression, + unit: field.unit, + display_decimal_places: field.number_display_decimal_places, + step: field.number_step, + labels: field.labels, + integer: field.integer, + blank_assist: field.blank_assist, + } + } } /// The values a range slider's two ends map to linearly and the one its double-click restores, if known. @@ -305,9 +349,12 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type, unit, display_decimal_places, step, + labels, + integer, + blank_assist, } = options; - let mut number_input = NumberInput::default(); + let mut number_input = NumberInput::default().is_integer(integer); if slider { number_input = number_input.mode_range(); } @@ -350,7 +397,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type, } }; - let default_info = ParameterWidgetsInfo::at_index(node_id, index, true, context); + let default_info = ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context); // A type with no widget can only be supplied through the graph, labeled with a placeholder row let unsupported_widgets = |default_info: ParameterWidgetsInfo, type_label: String| { @@ -394,7 +441,10 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type, true => text_area_widget(default_info).into(), false => text_widget(default_info).into(), }, - Some(x) if id_is::(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false), + Some(x) if id_is::(x) => { + let (x_label, y_label) = labels.unwrap_or(("X", "Y")); + vec2_widget(default_info, x_label, y_label, unit.unwrap_or(""), hard_min, hard_max, integer, false) + } Some(x) if id_is::(x) => transform_widget(default_info, unit, &mut extra_widgets), Some(x) if id_is::(x) => color_widget(default_info, ColorInput::default().allow_none(false)), Some(x) if id_is::(x) => color_widget(default_info, ColorInput::default().allow_none(false)), @@ -904,7 +954,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit: } } -pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option, is_integer: bool, disabled: bool) -> LayoutGroup { +pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option, max: Option, is_integer: bool, disabled: bool) -> LayoutGroup { let mut widgets = start_widgets(¶meter_widgets_info); let Some(input) = parameter_widgets_info.input() else { @@ -919,7 +969,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st .label(x) .unit(unit) .min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64))) - .max((1_u64 << f64::MANTISSA_DIGITS) as f64) + .max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64)) .is_integer(is_integer) .disabled(disabled) .on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y)))) @@ -930,7 +980,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st .label(y) .unit(unit) .min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64))) - .max((1_u64 << f64::MANTISSA_DIGITS) as f64) + .max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64)) .is_integer(is_integer) .disabled(disabled) .on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap())))) @@ -945,7 +995,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st .label(x) .unit(unit) .min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64))) - .max((1_u64 << f64::MANTISSA_DIGITS) as f64) + .max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64)) .is_integer(is_integer) .disabled(disabled) .on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value)))) @@ -956,7 +1006,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st .label(y) .unit(unit) .min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64))) - .max((1_u64 << f64::MANTISSA_DIGITS) as f64) + .max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64)) .is_integer(is_integer) .disabled(disabled) .on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap())))) @@ -2798,10 +2848,10 @@ pub(crate) fn grid_inspector(node_id: NodeId, context: &mut NodeInspectorContext ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), NumberInput::default().label("H").min(0.).unit(" px"), )); - let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, false, false); + let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, None, false, false); widgets.extend([spacing, angles]); } else { - let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), false, false); + let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), None, false, false); widgets.push(spacing); } } @@ -3264,40 +3314,20 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect } let row = context.call_widget_override(&node_id, input_index).unwrap_or_else(|| { + let field = context.network_interface.field_metadata(&node_id, input_index, context.selection_network_path); + let options = field.as_ref().map(ParameterOptions::from_field).unwrap_or_default(); + let Some(implementation) = context.network_interface.implementation(&node_id, context.selection_network_path) else { log::error!("Could not get implementation for node {node_id}"); return Vec::new(); }; - let mut options = ParameterOptions::default(); let input_type = match implementation { DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: { // Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below let proto_node_identifier = proto_node_identifier.clone(); - let mut default_type = None; - if let Some(field) = graphene_std::registry::NODE_METADATA - .lock() - .unwrap() - .get(&proto_node_identifier) - .and_then(|metadata| metadata.fields.get(input_index)) - { - options = ParameterOptions { - soft_min: field.number_soft_min, - soft_max: field.number_soft_max, - hard_min: field.number_hard_min, - hard_max: field.number_hard_max, - slider: field.number_mode_range, - multiline: field.multiline, - progression: field.progression, - unit: field.unit, - display_decimal_places: field.number_display_decimal_places, - step: field.number_step, - }; - default_type = field.default_type.clone(); - } - - if let Some(default) = default_type { + if let Some(default) = field.and_then(|field| field.default_type) { break 'early_return default; } @@ -3313,12 +3343,21 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect let Some(input_type) = input_type else { return Vec::new() }; input_type.clone() } - _ => context - .network_interface - .input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path) - .compiled_nested_type() - .cloned() - .unwrap_or(concrete!(())), + _ => { + // A graph import's declared type still picks its widget while its wire's type is unresolved, such as during an error inside the subgraph + let declared_type = field.and_then(|field| field.default_type).map(|declared_type| match declared_type { + Type::Item(element) => *element, + declared_type => declared_type, + }); + + context + .network_interface + .input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path) + .compiled_nested_type() + .cloned() + .or(declared_type) + .unwrap_or(concrete!(())) + } }; inspector_row_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value) @@ -3823,7 +3862,7 @@ pub(crate) fn displace_inspector(node_id: NodeId, context: &mut NodeInspectorCon if !matches!(mode, Some(DisplaceMode::Angle)) { layout.push(color_widget(ParameterWidgetsInfo::new(node_id, XDisplacementInput, true, context), ColorInput::default())); layout.push(color_widget(ParameterWidgetsInfo::new(node_id, YDisplacementInput, true, context), ColorInput::default())); - layout.push(vec2_widget(ParameterWidgetsInfo::new(node_id, OffsetInput, true, context), "X", "Y", " px", None, false, false)); + layout.push(vec2_widget(ParameterWidgetsInfo::new(node_id, OffsetInput, true, context), "X", "Y", " px", None, None, false, false)); } let edge_mode = enum_choice::() diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface.rs b/editor/src/messages/portfolio/document/utility_types/network_interface.rs index a7c35b2994..10a477fb50 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface.rs @@ -59,7 +59,6 @@ use crate::messages::portfolio::document::utility_types::network_interface::reso use crate::messages::portfolio::document::utility_types::text_metrics::text_width; use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire}; use crate::messages::tool::common_functionality::graph_modification_utils; -use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode; use deserialization::deserialize_node_persistent_metadata; use glam::{DAffine2, DVec2, IVec2}; use graph_craft::Type; @@ -74,7 +73,7 @@ use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint use graphene_std::vector::{Vector, VectorModificationType}; use kurbo::BezPath; use memo_network::MemoNetwork; -use serde_json::{Value, json}; +use serde_json::Value; use std::collections::{HashMap, HashSet, VecDeque}; use std::hash::Hash; use std::ops::Deref; 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 9d3e468e78..3fcb123ef9 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 @@ -2613,7 +2613,7 @@ async fn shaking_a_node_spliced_in_by_a_secondary_input_keeps_the_dot_on_its_wir // Numbers to Vec2 hides its primary input, so it takes the flow by its first exposed input instead let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; let shaken = editor - .create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER), 10, 0) + .create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER), 10, 0) .await; let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await; let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await; 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 588217afab..b238e43b00 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 @@ -1,9 +1,6 @@ use super::*; use std::hash::{Hash, Hasher}; -/// Index of the Artboard definition's Clip input, which must match the input order authored in document_node_definitions.rs. -pub(crate) const ARTBOARD_CLIP_INPUT_INDEX: usize = 5; - impl NodeNetworkInterface { /// Runs a query against a resolved [`NetworkView`], logging any error at this message-boundary wrapper and mapping it to None. pub(crate) fn query<'a, 'p, T>(&'a self, network_path: &'p [NodeId], caller: &str, query: impl FnOnce(NetworkView<'a, 'p>) -> Result) -> Option { @@ -829,17 +826,27 @@ impl NodeNetworkInterface { self.view(network_path).ok().and_then(|view| view.persistent_input_metadata(node_id, index).ok()) } - /// Whether the input is internal state of its proto node (named with a leading `_`), which is never exposed to the graph. + /// Whether the input is internal state of its node (named with a leading `_`), which is never exposed to the graph. pub fn is_internal_input(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> bool { - let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) else { - return false; - }; - let Ok(node_metadata) = graphene_std::registry::NODE_METADATA.lock() else { return false }; + self.field_metadata(node_id, index, network_path).is_some_and(|field| field.internal) + } - node_metadata - .get(proto_node_identifier) - .and_then(|metadata| metadata.fields.get(index)) - .is_some_and(|field| field.internal) + /// The metadata the node macro records for a proto node's parameter, or the `#[graph]` macro for a graph node's import. + /// A graph node's input has it only while it still has that import's name, since an edited subgraph can reorder its imports. + pub fn field_metadata(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> Option { + if let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) { + let node_metadata = graphene_std::registry::NODE_METADATA.lock().ok()?; + return node_metadata.get(proto_node_identifier)?.fields.get(index).cloned(); + } + + let Some(DefinitionIdentifier::Network(identifier)) = self.reference(node_id, network_path) else { + return None; + }; + let input_name = self.persistent_input_metadata(node_id, index, network_path)?.input_name.clone(); + + let graphs = graphene_std::registry::GRAPH_METADATA.lock().ok()?; + let field = graphs.iter().find(|graph| graph.identifier == identifier)?.imports.get(index)?; + (field.name == input_name).then(|| field.clone()) } /// The description stored for a node's output, or else for a proto node, the doc comment on its field in the struct a multi-output node returns. @@ -1079,7 +1086,7 @@ impl NodeNetworkInterface { /// Whether the artboard layer clips the content inside it to its bounds. fn artboard_clips_content(&self, artboard: LayerNodeIdentifier) -> bool { self.document_node(&artboard.to_node(), &[]) - .and_then(|artboard| artboard.inputs.get(ARTBOARD_CLIP_INPUT_INDEX)) + .and_then(|artboard| artboard.inputs.get(graphene_std::subgraphs::artboard::ClipInput::INDEX)) .is_some_and(|clip_input| matches!(clip_input, NodeInput::Value { tagged_value, .. } if tagged_value.clone().deref() == &TaggedValue::Bool(true))) } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/types.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/types.rs index caaf3489c3..352d759544 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/types.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/types.rs @@ -773,51 +773,11 @@ impl PartialEq for DocumentNodeMetadata { } } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -pub struct NumberInputSettings { - pub unit: Option, - pub min: Option, - pub max: Option, - pub step: Option, - pub mode: NumberInputMode, - pub range_min: Option, - pub range_max: Option, - pub is_integer: bool, - pub blank_assist: bool, -} - -impl Default for NumberInputSettings { - fn default() -> Self { - NumberInputSettings { - unit: None, - min: None, - max: None, - step: None, - mode: NumberInputMode::default(), - range_min: None, - range_max: None, - is_integer: false, - blank_assist: true, - } - } -} - -#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] -pub struct Vec2InputSettings { - pub x: String, - pub y: String, - pub unit: String, - pub min: Option, - pub is_integer: bool, -} - #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum WidgetOverride { None, Hidden, String(String), - Number(NumberInputSettings), - Vec2(Vec2InputSettings), Custom(String), } @@ -854,40 +814,6 @@ impl InputPersistentMetadata { self.input_data.insert("string_inspector".to_string(), Value::String(string_inspector)); self.widget_override = Some("string".to_string()); } - WidgetOverride::Number(mut number_inspector) => { - if let Some(unit) = number_inspector.unit.take() { - self.input_data.insert("unit".to_string(), json!(unit)); - } - if let Some(min) = number_inspector.min.take() { - self.input_data.insert("min".to_string(), json!(min)); - } - if let Some(max) = number_inspector.max.take() { - self.input_data.insert("max".to_string(), json!(max)); - } - if let Some(step) = number_inspector.step.take() { - self.input_data.insert("step".to_string(), json!(step)); - } - if let Some(range_min) = number_inspector.range_min.take() { - self.input_data.insert("range_min".to_string(), json!(range_min)); - } - if let Some(range_max) = number_inspector.range_max.take() { - self.input_data.insert("range_max".to_string(), json!(range_max)); - } - self.input_data.insert("mode".to_string(), json!(number_inspector.mode)); - self.input_data.insert("is_integer".to_string(), Value::Bool(number_inspector.is_integer)); - self.input_data.insert("blank_assist".to_string(), Value::Bool(number_inspector.blank_assist)); - self.widget_override = Some("number".to_string()); - } - WidgetOverride::Vec2(vec2_inspector) => { - self.input_data.insert("x".to_string(), json!(vec2_inspector.x)); - self.input_data.insert("y".to_string(), json!(vec2_inspector.y)); - self.input_data.insert("unit".to_string(), json!(vec2_inspector.unit)); - self.input_data.insert("is_integer".to_string(), Value::Bool(vec2_inspector.is_integer)); - if let Some(min) = vec2_inspector.min { - self.input_data.insert("min".to_string(), json!(min)); - } - self.widget_override = Some("vec2".to_string()); - } WidgetOverride::Custom(lambda_name) => { self.widget_override = Some(lambda_name); } diff --git a/editor/src/messages/portfolio/document_migration.rs b/editor/src/messages/portfolio/document_migration.rs index 7bf6c03b87..d47ab7d93b 100644 --- a/editor/src/messages/portfolio/document_migration.rs +++ b/editor/src/messages/portfolio/document_migration.rs @@ -472,9 +472,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[ ], }, // The old 'Vec2 Value' node took separate X and Y inputs, a role now filled by 'Numbers to Vec2', while the new 'Vec2 Value' node takes a single vec2 input. - // Old references (including these older aliases) are remapped here to `vec_2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node. + // Old references (including these older aliases) are remapped here to `vec2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node. NodeReplacement { - node: graphene_std::math_nodes::vec_2_value::IDENTIFIER, + node: graphene_std::math_nodes::vec2_value::IDENTIFIER, aliases: &[ "graphene_math_nodes::Vec2ValueNode", "graphene_core::ops::ConstructVector2", @@ -484,7 +484,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[ ], }, NodeReplacement { - node: graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER, + node: graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER, aliases: &["math_nodes::CombineVec2Node"], }, // ================================ @@ -1576,8 +1576,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_ // A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one. // Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths. let split_wrapper_replacements = [ - ("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER), - ("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER), + ("Split Vec2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER), + ("Split Vector2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER), ("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER), ]; for (old_reference, new_identifier) in split_wrapper_replacements { @@ -1641,7 +1641,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_ let DocumentNodeImplementation::ProtoNode(protonode_id) = &node.implementation else { return None }; let name = protonode_id.as_str().split('<').next().unwrap_or_default(); if EXTRACT_XY.contains(&name) { - Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY")) + Some((*node_id, path, graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER, "Extract XY")) } else if EXTRACT_CHANNEL.contains(&name) { Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel")) } else { @@ -2931,8 +2931,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId], // Convert the old 'Vec2 Value' node, identified by its leftover 3-input shape with separate X and Y inputs, // into the 'Numbers to Vec2' node which now fills that role (the new 'Vec2 Value' node instead takes a single vec2 input) - if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec_2_value::IDENTIFIER) && inputs_count == 3 { - let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER); + if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec2_value::IDENTIFIER) && inputs_count == 3 { + let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER); let mut node_template = resolve_document_node_type(&numbers_to_vec2_reference)?.default_node_template(); document.network_interface.replace_implementation(node_id, network_path, &mut node_template); @@ -5230,7 +5230,11 @@ mod tests { let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else { panic!("Blend should be a network node") }; - let count_conversion = network_template.nodes.get_mut(&NodeId(3)).expect("Blend should have a count conversion node"); + let (&count_conversion_id, count_conversion) = network_template + .nodes + .iter_mut() + .find(|(_, node)| node.inputs.iter().any(|input| matches!(input, NodeInput::Import { import_index: 1, .. }))) + .expect("Blend should have a count conversion node"); count_conversion.implementation = NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::floor::IDENTIFIER); count_conversion.inputs = vec![NodeInput::import(item!(f64), 1)]; document.network_interface.insert_node(node_id, node_template, &[]); @@ -5247,7 +5251,7 @@ mod tests { panic!("Blend should stay a network node") }; assert_eq!( - inner.nodes[&shipped_node_id("Blend", NodeId(3))].implementation, + inner.nodes[&shipped_node_id("Blend", count_conversion_id)].implementation, DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::as_number::IDENTIFIER) ); } @@ -5264,7 +5268,11 @@ mod tests { let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else { panic!("Blend should be a network node") }; - let edited_subtract = network_template.nodes.get_mut(&NodeId(5)).expect("Blend should have an open-path denominator node"); + let (&edited_subtract_id, edited_subtract) = network_template + .nodes + .iter_mut() + .find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::subtract::IDENTIFIER)) + .expect("Blend should have an open-path denominator node"); edited_subtract.inputs[1] = NodeInput::value(TaggedValue::Number(42.), false); document.network_interface.insert_node(node_id, node_template, &[]); @@ -5274,7 +5282,7 @@ mod tests { let (DocumentNodeImplementation::Definition(definition), Some(inner)) = (implementation, document.network_interface.document_network().implementation_network(implementation)) else { panic!("Blend should stay a network node") }; - let edited_subtract = derived_node_id(*definition, NodeId(5)); + let edited_subtract = derived_node_id(*definition, edited_subtract_id); assert_eq!(inner.nodes[&edited_subtract].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(42.))); } @@ -5356,8 +5364,15 @@ mod tests { let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else { panic!("Regex Find should be a network node") }; - network_template.nodes.get_mut(&NodeId(0)).expect("Regex Find should have a find node").inputs[2] = NodeInput::import(item!(f64), 2); - network_template.nodes.get_mut(&NodeId(1)).expect("Regex Find should have an item-at-index node").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false); + let inner_node_id = |identifier: graphene_std::ProtoNodeIdentifier| { + let implementation = NodeTemplateImplementation::ProtoNode(identifier); + network_template.nodes.iter().find(|(_, node)| node.implementation == implementation).map(|(&id, _)| id) + }; + let find_id = inner_node_id(graphene_std::text_nodes::regex::regex_find::IDENTIFIER).expect("Regex Find should have a find node"); + let item_at_index_id = inner_node_id(graphene_std::graphic::item_at_index::IDENTIFIER).expect("Regex Find should have an item-at-index node"); + + network_template.nodes.get_mut(&find_id).expect("the find node should exist").inputs[2] = NodeInput::import(item!(f64), 2); + network_template.nodes.get_mut(&item_at_index_id).expect("the item-at-index node should exist").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false); document.network_interface.insert_node(node_id, node_template, &[]); migrate(&mut document); @@ -5371,9 +5386,9 @@ mod tests { let Some(inner) = document.network_interface.document_network().implementation_network(&node.implementation) else { panic!("Regex Find should stay a network node") }; - assert_eq!(inner.nodes[&shipped_node_id("Regex Find", NodeId(0))].inputs.get(2), Some(&NodeInput::import(item!(i64), 2))); + assert_eq!(inner.nodes[&shipped_node_id("Regex Find", find_id)].inputs.get(2), Some(&NodeInput::import(item!(i64), 2))); assert_eq!( - inner.nodes[&shipped_node_id("Regex Find", NodeId(1))].inputs.get(1).and_then(|input| input.as_value()).cloned(), + inner.nodes[&shipped_node_id("Regex Find", item_at_index_id)].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Integer(0)) ); } diff --git a/editor/src/node_graph_executor/runtime/thumbnails.rs b/editor/src/node_graph_executor/runtime/thumbnails.rs index a98734f0f8..c206a92196 100644 --- a/editor/src/node_graph_executor/runtime/thumbnails.rs +++ b/editor/src/node_graph_executor/runtime/thumbnails.rs @@ -398,7 +398,8 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] { #[cfg(test)] mod tests { - use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, shipped_node_id}; + use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type; + use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, NodeTemplateImplementation, shipped_node_id}; use crate::test_utils::test_prelude::*; use glam::UVec2; use graph_craft::document::NodeId; @@ -429,8 +430,20 @@ mod tests { editor.draw_rect(0., 0., 10., 10.).await; let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node(); + // The node adding Merge's content to the stack + let Some(NodeTemplateImplementation::Network(merge_network)) = resolve_network_node_type("Merge").map(|merge| &merge.node_template.implementation) else { + panic!("Merge should be a network node") + }; + let Some((&extend_id, _)) = merge_network + .nodes + .iter() + .find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER)) + else { + panic!("Merge should extend the stack with its content") + }; + compile_and_run(&mut editor).await; - let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", NodeId(2)))]); + let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", extend_id))]); assert!(merge_content.is_some(), "The Merge layer's content should be compiled"); assert_eq!( editor.runtime.thumbnails.sources.get(&layer).copied(), diff --git a/node-graph/README.md b/node-graph/README.md index 31247534b1..40287aea30 100644 --- a/node-graph/README.md +++ b/node-graph/README.md @@ -32,7 +32,7 @@ pub struct DocumentNodeDefinition { } ``` -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`. +None of these definitions are written by hand. 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`. A built-in node made from a subgraph has its definition generated from the `graph` macro (see [Creating a node from a subgraph](#creating-a-node-from-a-subgraph)), keyed by its name. ## Inspector @@ -127,7 +127,29 @@ fn opacity( ## Additional Macro Options -The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `unit`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, while `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`. +The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `step`, `display_decimal_places`, `unit`, `integer`, `labels`, `blank_assist`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, `#[display_decimal_places(2)]` sets how many decimal places a number's widget shows, `#[integer]` makes a number or Vec2 widget take only integers, `#[labels("W", "H")]` names a Vec2 widget's two fields, and `#[blank_assist(false)]` drops the space a widget leaves for its assist area. `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`. + +## Creating a node from a subgraph + +A node built from other nodes uses the `graph` macro, which registers the subgraph as a catalog definition. It takes `category`, `icon`, `name`, and `version` as `node` does, plus `layer` for a node that starts as a layer. Unlike a proto node's, a graph's name (or the title derived from its function name) is also its catalog identifier, which documents store. The function's parameters are the subgraph's imports, which are parsed like a proto node's parameters and take the same value and widget attributes. On an import, `#[hard]` bounds the Inspector widget without clamping a value wired into it. `out!(...)` names the exports. In the body, `>>` feeds its left side into the primary input of the node on its right, every other parameter is named in the call, and a bare name feeds the binding or import of that name into the parameter of the same name. State methods after a call, each written once, set the node's position in grid units (`.at(x, y)`), its display name (`.named("…")`), its flags (`.layer()`, `.hidden()`, `.locked()`, and `.pinned()`), and its call argument (`.call_argument::()`, or `impl Any` for a generic one). An output's name after the call or a binding, like `.captures`, wires from that output instead of the primary one, and goes after any state methods. The body ends with one value per export, as a final expression or with `return`. This is the Load Image node as it exists in `node-graph/nodes/gstd/src/subgraphs.rs`: + +```rs +/// Loads an image from a given URL. +#[node_macro::graph(category("Data: I/O"), icon("NodeLoadImage"))] +pub fn load_image( + _: (), + /// The web address or local asset path of the image to load. + #[name("URL")] + url: Item, +) -> out!( + /// The loaded image. + image, +) { + load_resource(url).at(0, 0) >> bytes_to_image().at(7, 0) +} +``` + +Each node, parameter, and output name resolves through the module the `node` or `graph` macro generates for that node, named after its function, so a misspelled one is reported where it's written. The module's `PARAMETER_COUNT` lets the macro reject `>>` into a node with no parameters. Proto nodes don't name their outputs in that module, so only a graph's outputs can be chosen by name. Every input a call leaves out keeps the default from the node's own definition. ## Executing a document `NodeNetwork` diff --git a/node-graph/libraries/core-types/src/registry.rs b/node-graph/libraries/core-types/src/registry.rs index 6413e87862..0851492b48 100644 --- a/node-graph/libraries/core-types/src/registry.rs +++ b/node-graph/libraries/core-types/src/registry.rs @@ -60,6 +60,12 @@ pub struct FieldMetadata { pub progression: bool, /// Whether the input must be fed by a value known at compile time, from `#[constant]`. pub constant: bool, + /// The X and Y labels of a Vec2 parameter's widget, from `#[labels("W", "H")]`. + pub labels: Option<(&'static str, &'static str)>, + /// Whether a number or Vec2 parameter's widget only takes integers, from `#[integer]`. Integer types always do. + pub integer: bool, + /// Whether the widget leaves room for the assist area beside it, which `#[blank_assist(false)]` turns off. + pub blank_assist: bool, } #[derive(Clone, Debug)] @@ -222,6 +228,167 @@ pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::ne pub static NODE_METADATA: LazyLock>> = LazyLock::new(|| Mutex::new(HashMap::new())); +/// Every node defined as a subgraph by the `#[graph]` macro, in registration order. +pub static GRAPH_METADATA: LazyLock>> = LazyLock::new(|| Mutex::new(Vec::new())); + +/// A node defined as a subgraph by `#[graph]`, which the editor turns into a catalog definition alongside the proto nodes. +#[derive(Clone, Debug)] +pub struct GraphMetadata { + /// The definition's identifier and display name. + pub identifier: &'static str, + pub category: &'static str, + pub icon: Option<&'static str>, + pub description: &'static str, + /// The declaration version from `#[graph(version(N))]`, starting at 1. + pub version: u32, + /// Whether a new instance starts as a layer, from `#[graph(layer)]`. + pub layer: bool, + /// The subgraph's imports, which become the inputs of each instance, described like a proto node's parameters. + /// Each one's `default_type` is the type it was declared with. + pub imports: Vec, + pub exports: Vec, + /// The nodes inside the subgraph, where each node's position in this list is its ID. + pub nodes: Vec, +} + +#[derive(Clone, Debug)] +pub struct GraphExportMetadata { + pub name: &'static str, + pub description: &'static str, + pub source: GraphInputSource, +} + +/// A node inside a subgraph defined by `#[graph]`. +#[derive(Clone, Debug)] +pub struct GraphNodeMetadata { + pub implementation: GraphNodeImplementation, + /// The inputs the definition sets, by index. Every other input keeps the default from the node's own definition. + pub inputs: Vec<(usize, GraphInputSource)>, + /// The absolute position in grid units, from `.at(x, y)`. + pub position: Option<(i32, i32)>, + /// From `.layer()`. + pub layer: bool, + /// From `.named("…")`. + pub display_name: Option<&'static str>, + /// From `.hidden()`. + pub hidden: bool, + /// From `.locked()`. + pub locked: bool, + /// From `.pinned()`. + pub pinned: bool, + /// From `.call_argument::()`. + pub call_argument: Option, +} + +/// What a node inside a subgraph is an instance of. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum GraphNodeImplementation { + ProtoNode(ProtoNodeIdentifier), + /// Another node defined by `#[graph]`, named by its identifier. + Graph(&'static str), +} + +impl From for GraphNodeImplementation { + fn from(identifier: ProtoNodeIdentifier) -> Self { + Self::ProtoNode(identifier) + } +} + +impl From<&'static str> for GraphNodeImplementation { + fn from(identifier: &'static str) -> Self { + Self::Graph(identifier) + } +} + +/// What feeds an input, or an export, of a subgraph defined by `#[graph]`. +#[derive(Clone, Debug)] +pub enum GraphInputSource { + /// The output of another node in the subgraph, by its position in [`GraphMetadata::nodes`]. + Node { node: usize, output: usize }, + /// One of the subgraph's imports, with the type its wire records. + Import { index: usize, ty: Type }, + /// A value. Without an exposure, the input keeps the one from the node's own definition. + Value { value: GraphValue, exposed: Option }, + /// A scope input, from `scope("…")`. + Scope(&'static str), + /// The document path of the node, from `reflect(NodePath)`. + NodePath, + /// The source ID of the node, from `reflect(SourceId)`. + SourceId, +} + +/// A value written in a subgraph definition. The editor converts it to the type of the input it feeds. +#[derive(Clone, Debug, PartialEq)] +pub enum GraphValue { + /// A number written without a fractional part, which feeds an integer input as an integer and any other as a number. + Integer(i64), + Number(f64), + Bool(bool), + String(String), + Vec2(glam::DVec2), + Color(Color), +} + +impl GraphValue { + pub fn vec2(x: f64, y: f64) -> Self { + Self::Vec2(glam::DVec2::new(x, y)) + } + + /// An opaque color from `rgb(0xRRGGBB)`. + pub fn rgb(hex: u32) -> Self { + let [_, red, green, blue] = hex.to_be_bytes(); + Self::Color(crate::color::SRGBA8::new(red, green, blue, 255).into()) + } + + /// A color with alpha from `rgba(0xRRGGBBAA)`. + pub fn rgba(hex: u32) -> Self { + let [red, green, blue, alpha] = hex.to_be_bytes(); + Self::Color(crate::color::SRGBA8::new(red, green, blue, alpha).into()) + } +} + +impl From<&str> for GraphValue { + fn from(value: &str) -> Self { + Self::String(value.to_string()) + } +} + +impl From for GraphValue { + fn from(value: String) -> Self { + Self::String(value) + } +} + +impl From for GraphValue { + fn from(value: bool) -> Self { + Self::Bool(value) + } +} + +impl From for GraphValue { + fn from(value: f64) -> Self { + Self::Number(value) + } +} + +impl From for GraphValue { + fn from(value: i64) -> Self { + Self::Integer(value) + } +} + +impl From for GraphValue { + fn from(value: glam::DVec2) -> Self { + Self::Vec2(value) + } +} + +impl From for GraphValue { + fn from(value: Color) -> Self { + Self::Color(value) + } +} + /// All multi-output proto nodes (those returning a [`Destructure`] struct), keyed by their identifier. /// Snapshotted on first access, which must happen after startup registration of the node metadata completes. pub static MULTI_OUTPUT_NODES: LazyLock> = LazyLock::new(|| { diff --git a/node-graph/node-macro/src/codegen.rs b/node-graph/node-macro/src/codegen.rs index 7cd9bd37a8..2c5b75c625 100644 --- a/node-graph/node-macro/src/codegen.rs +++ b/node-graph/node-macro/src/codegen.rs @@ -3,6 +3,7 @@ use convert_case::{Case, Casing}; use proc_macro2::TokenStream as TokenStream2; use quote::{ToTokens, format_ident, quote, quote_spanned}; use std::sync::atomic::AtomicU64; +use syn::ext::IdentExt; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::token::Comma; @@ -112,15 +113,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn let data_field_names: Vec<_> = data_fields.iter().map(|f| &f.pat_ident.ident).collect(); // Only regular fields have input names/descriptions (for UI) - let input_names: Vec<_> = regular_fields - .iter() - .map(|f| &f.name) - .zip(regular_field_names.iter()) - .map(|zipped| match zipped { - (Some(name), _) => name.value(), - (_, name) => name.to_string().to_case(Case::Title), - }) - .collect(); + let input_names: Vec<_> = regular_fields.iter().map(|field| parameter_display_name(field)).collect(); // The primary input is not a parameter, so generators can name their unused one `_primary` without it becoming internal let input_internal = regular_field_names @@ -174,56 +167,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn }) .collect(); - // Only regular fields have UI metadata (data fields are internal state) - let widget_override: Vec<_> = regular_fields - .iter() - .map(|field| match &field.widget_override { - ParsedWidgetOverride::None => quote!(RegistryWidgetOverride::None), - ParsedWidgetOverride::Hidden => quote!(RegistryWidgetOverride::Hidden), - ParsedWidgetOverride::String(lit_str) => quote!(RegistryWidgetOverride::String(#lit_str)), - ParsedWidgetOverride::Custom(lit_str) => quote!(RegistryWidgetOverride::Custom(#lit_str)), - }) - .collect(); - - let value_sources: Vec<_> = regular_fields - .iter() - .map(|field| match field.ty.value_source() { - ParsedValueSource::Default(data) => { - // Check if the data is a string literal by parsing the token stream - let data_str = data.to_string(); - if data_str.starts_with('"') && data_str.ends_with('"') && data_str.len() >= 2 { - quote!(RegistryValueSource::Default(#data)) - } else { - quote!(RegistryValueSource::Default(stringify!(#data))) - } - } - ParsedValueSource::Scope(data) => { - if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(_), .. }) = data.as_ref() { - quote!(RegistryValueSource::Scope(#data)) - } else { - quote!(RegistryValueSource::Scope(#data.as_static_str())) - } - } - ParsedValueSource::SourceId => quote!(RegistryValueSource::SourceId), - ParsedValueSource::NodePath => quote!(RegistryValueSource::NodePath), - _ => quote!(RegistryValueSource::None), - }) - .collect(); - - let default_colors: Vec<_> = regular_fields - .iter() - .map(|field| match field.ty.regular() { - Some(RegularParsedField { - value_source: ParsedValueSource::Default(data), - .. - }) => match color_constant_paths(data) { - Some(paths) => quote!(Some(&[#(#paths),*])), - None => quote!(None), - }, - _ => quote!(None), - }) - .collect(); - let default_types: Vec<_> = regular_fields .iter() .enumerate() @@ -270,64 +213,12 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn }) .collect(); - let bound_values = |select: fn(&RegularParsedField) -> &Option| -> Vec<_> { - regular_fields - .iter() - .map(|field| match field.ty.regular() { - Some(regular) => select(regular).as_ref().map_or(quote!(None), |bound| quote!(Some(#bound))), - None => quote!(None), - }) - .collect() - }; - let number_soft_min_values = bound_values(|field| &field.number_soft_min); - let number_soft_max_values = bound_values(|field| &field.number_soft_max); - let number_hard_min_values = bound_values(|field| &field.number_hard_min); - let number_hard_max_values = bound_values(|field| &field.number_hard_max); - let number_mode_range_values: Vec<_> = regular_fields + // Only regular fields have UI metadata (data fields are internal state) + let field_metadata: Vec<_> = regular_fields .iter() - .map(|field| match field.ty.regular() { - Some(RegularParsedField { number_mode_range, .. }) => quote!(#number_mode_range), - None => quote!(false), - }) - .collect(); - let number_display_decimal_places: Vec<_> = regular_fields - .iter() - .map(|field| field.number_display_decimal_places.as_ref().map_or(quote!(None), |i| quote!(Some(#i)))) - .collect(); - let number_step: Vec<_> = regular_fields.iter().map(|field| field.number_step.as_ref().map_or(quote!(None), |i| quote!(Some(#i)))).collect(); - - let unit_suffix: Vec<_> = regular_fields.iter().map(|field| field.unit.as_ref().map_or(quote!(None), |i| quote!(Some(#i)))).collect(); - let multiline: Vec<_> = regular_fields - .iter() - .map(|field| { - let multiline = field.multiline; - quote!(#multiline) - }) - .collect(); - let progression: Vec<_> = regular_fields - .iter() - .map(|field| { - let progression = field.progression; - quote!(#progression) - }) - .collect(); - let constant: Vec<_> = regular_fields - .iter() - .map(|field| { - let constant = field.constant; - quote!(#constant) - }) - .collect(); - - let exposed: Vec<_> = regular_fields - .iter() - .map(|field| match field.ty.regular() { - Some(RegularParsedField { exposed, .. }) => quote!(#exposed), - None => { - let exposed = !field.is_environment(); - quote!(#exposed) - } - }) + .zip(&input_internal) + .zip(&default_types) + .map(|((field, internal), default_type)| field_metadata_tokens(field, *internal, default_type, core_types)) .collect(); // Only eval regular fields (data fields are accessed directly as self.field_name) @@ -858,7 +749,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn Some(cfg) => quote!(#[cfg(#cfg)]), None => quote!(), }; - let node_input_accessor = generate_node_input_references(parsed, &field_idents, core_types, &identifier, &cfg); + let parameter_idents: Vec<_> = regular_fields.iter().filter(|field| !field.is_environment()).map(|field| &field.pat_ident).collect(); + let node_input_accessor = generate_node_input_references(parsed, ¶meter_idents, core_types, &identifier, &cfg); let mapped_node_impl = match (&mapped_struct_where_clause, &mapped_eval_impl) { (Some(mapped_where_clause), Some(mapped_eval)) => quote! { @@ -1009,7 +901,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn use gcore::{Node, NodeIOTypes, concrete, fn_type, ProtoNodeIdentifier, WasmNotSync, NodeIO, ContextFeature}; use gcore::value::ClonedNode; use gcore::ops::TypeNode; - use gcore::registry::{NodeMetadata, FieldMetadata, NODE_REGISTRY, NODE_METADATA, DynAnyNode, DowncastBothNode, TypeErasedBox, PanicNode, RegistryValueSource, RegistryWidgetOverride}; + use gcore::registry::{NodeMetadata, NODE_REGISTRY, NODE_METADATA, DynAnyNode, DowncastBothNode, TypeErasedBox, PanicNode}; use gcore::ctor::ctor; // Use the types specified in the implementation @@ -1056,31 +948,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn }, version: #version, output_fields: #output_fields, - fields: vec![ - #( - FieldMetadata { - name: #input_names, - widget_override: #widget_override, - description: #input_descriptions, - internal: #input_internal, - exposed: #exposed, - value_source: #value_sources, - default_colors: #default_colors, - default_type: #default_types, - number_soft_min: #number_soft_min_values, - number_soft_max: #number_soft_max_values, - number_hard_min: #number_hard_min_values, - number_hard_max: #number_hard_max_values, - number_mode_range: #number_mode_range_values, - number_display_decimal_places: #number_display_decimal_places, - number_step: #number_step, - unit: #unit_suffix, - multiline: #multiline, - progression: #progression, - constant: #constant, - }, - )* - ], + fields: vec![#(#field_metadata,)*], }; NODE_METADATA.lock().unwrap().insert(#identifier(), metadata); } @@ -1088,6 +956,131 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn }) } +/// The display name an identifier derives, in Title Case. +pub(crate) fn derived_display_name(ident: &Ident) -> String { + // A lone `_` comes out of the case conversion as a space + ident.unraw().to_string().to_case(Case::Title).trim().to_string() +} + +/// The name a parameter shows in the UI: its `#[name("…")]`, or else its identifier in Title Case. +pub(crate) fn parameter_display_name(field: &ParsedField) -> String { + match &field.name { + Some(name) => name.value(), + None => derived_display_name(&field.pat_ident.ident), + } +} + +/// The symbol naming a parameter or output in a node's module, like `CountInput` for the `count` parameter. +pub(crate) fn symbol_name(ident: &Ident, suffix: &str) -> Ident { + format_ident!("{}{suffix}", ident.unraw().to_string().to_case(Case::Pascal), span = ident.span()) +} + +/// Generated code for `Some(value)` or `None`, by full path so no name in the author's module can stand in for either. +pub(crate) fn option_tokens(value: Option) -> TokenStream2 { + match value { + Some(value) => quote!(::core::option::Option::Some(#value)), + None => quote!(::core::option::Option::None), + } +} + +/// The registry's `FieldMetadata` for a parameter, shared by proto node fields and graph imports, which differ only in +/// how they work out whether it's internal state and which type its default is built from. +pub(crate) fn field_metadata_tokens(field: &ParsedField, internal: bool, default_type: &TokenStream2, core_types: &TokenStream2) -> TokenStream2 { + let registry = quote!(#core_types::registry); + + let name = parameter_display_name(field); + let description = &field.description; + let exposed = match field.ty.regular() { + Some(regular) => regular.exposed, + None => !field.is_environment(), + }; + + let widget_override = match &field.widget_override { + ParsedWidgetOverride::None => quote!(#registry::RegistryWidgetOverride::None), + ParsedWidgetOverride::Hidden => quote!(#registry::RegistryWidgetOverride::Hidden), + ParsedWidgetOverride::String(text) => quote!(#registry::RegistryWidgetOverride::String(#text)), + ParsedWidgetOverride::Custom(key) => quote!(#registry::RegistryWidgetOverride::Custom(#key)), + }; + + // A string literal default keeps its contents, and any other expression is stringified for the editor to parse by type + let value_source = match field.ty.value_source() { + ParsedValueSource::Default(data) => { + let data_string = data.to_string(); + if data_string.starts_with('"') && data_string.ends_with('"') && data_string.len() >= 2 { + quote!(#registry::RegistryValueSource::Default(#data)) + } else { + quote!(#registry::RegistryValueSource::Default(::core::stringify!(#data))) + } + } + ParsedValueSource::Scope(data) => { + if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(_), .. }) = data.as_ref() { + quote!(#registry::RegistryValueSource::Scope(#data)) + } else { + quote!(#registry::RegistryValueSource::Scope(#data.as_static_str())) + } + } + ParsedValueSource::SourceId => quote!(#registry::RegistryValueSource::SourceId), + ParsedValueSource::NodePath => quote!(#registry::RegistryValueSource::NodePath), + ParsedValueSource::None => quote!(#registry::RegistryValueSource::None), + }; + + let default_colors = match field.ty.regular() { + Some(RegularParsedField { + value_source: ParsedValueSource::Default(data), + .. + }) => option_tokens(color_constant_paths(data).map(|paths| quote!(&[#(#paths),*]))), + _ => option_tokens(None), + }; + + let regular = field.ty.regular(); + let bound = |select: fn(&RegularParsedField) -> &Option| option_tokens(regular.and_then(|regular| select(regular).as_ref()).map(ToTokens::to_token_stream)); + let number_soft_min = bound(|regular| ®ular.number_soft_min); + let number_soft_max = bound(|regular| ®ular.number_soft_max); + let number_hard_min = bound(|regular| ®ular.number_hard_min); + let number_hard_max = bound(|regular| ®ular.number_hard_max); + let number_mode_range = regular.is_some_and(|regular| regular.number_mode_range); + + let number_display_decimal_places = option_tokens(field.number_display_decimal_places.as_ref().map(ToTokens::to_token_stream)); + let number_step = option_tokens(field.number_step.as_ref().map(ToTokens::to_token_stream)); + let unit = option_tokens(field.unit.as_ref().map(ToTokens::to_token_stream)); + let labels = option_tokens(field.labels.as_ref().map(|(x, y)| quote!((#x, #y)))); + let ParsedField { + multiline, + progression, + constant, + integer, + blank_assist, + .. + } = field; + + quote! { + #registry::FieldMetadata { + name: #name, + description: #description, + internal: #internal, + exposed: #exposed, + widget_override: #widget_override, + value_source: #value_source, + default_colors: #default_colors, + default_type: #default_type, + number_soft_min: #number_soft_min, + number_soft_max: #number_soft_max, + number_hard_min: #number_hard_min, + number_hard_max: #number_hard_max, + number_mode_range: #number_mode_range, + number_display_decimal_places: #number_display_decimal_places, + number_step: #number_step, + unit: #unit, + multiline: #multiline, + progression: #progression, + constant: #constant, + labels: #labels, + integer: #integer, + blank_assist: #blank_assist, + } + } +} + /// The `Color::*` constant paths making up a default expression, when it consists solely of them (the form used by color and gradient parameter defaults). fn color_constant_paths(tokens: &TokenStream2) -> Option> { use syn::parse::Parser; @@ -1108,26 +1101,25 @@ fn color_constant_paths(tokens: &TokenStream2) -> Option> { .collect() } -/// Generates the per-parameter symbol types used to reference this node's inputs. -fn generate_node_input_references(parsed: &ParsedNodeFn, field_idents: &[&PatIdent], core_types: &TokenStream2, identifier: &Ident, cfg: &TokenStream2) -> TokenStream2 { - let inputs_module_name = format_ident!("{}", parsed.struct_name.to_string().to_case(Case::Snake)); +/// Generates the module named after the node's function, holding its identifier, its parameter count, and a symbol for each parameter. +/// The inputs the compiler fills in come after the parameters and get no symbol, so a graph can't name one. +fn generate_node_input_references(parsed: &ParsedNodeFn, parameter_idents: &[&PatIdent], core_types: &TokenStream2, identifier: &Ident, cfg: &TokenStream2) -> TokenStream2 { + let inputs_module_name = &parsed.fn_name; - let mut generated_input_accessor = Vec::new(); - if !parsed.attributes.flags.skip_impl { - for (input_index, input_ident) in field_idents.iter().enumerate() { - // TODO: figure out a better name that doesn't conflict with so many types - let struct_name = format_ident!("{}Input", input_ident.ident.to_string().to_case(Case::Pascal)); - - // Every parameter gets a plain unit struct: the symbol used across the codebase to name this input - generated_input_accessor.push(quote! { - pub struct #struct_name; - impl #core_types::NodeParameter for #struct_name { - const NODE_IDENTIFIER: #core_types::ProtoNodeIdentifier = #inputs_module_name::IDENTIFIER; - const INDEX: usize = #input_index; - } - }); + // Every parameter gets a plain unit struct: the symbol used across the codebase to name this input + let generated_input_accessor = parameter_idents.iter().enumerate().map(|(input_index, input_ident)| { + // TODO: figure out a better name that doesn't conflict with so many types + let struct_name = symbol_name(&input_ident.ident, "Input"); + quote! { + pub struct #struct_name; + impl #core_types::NodeParameter for #struct_name { + const NODE_IDENTIFIER: #core_types::ProtoNodeIdentifier = #inputs_module_name::IDENTIFIER; + const INDEX: usize = #input_index; + } } - } + }); + + let parameter_count = parameter_idents.len(); quote! { #cfg @@ -1136,6 +1128,8 @@ fn generate_node_input_references(parsed: &ParsedNodeFn, field_idents: &[&PatIde /// The `ProtoNodeIdentifier` of this node without any generics attached to it pub const IDENTIFIER: #core_types::ProtoNodeIdentifier = #identifier(); + /// How many parameters this node has, which come before the inputs the compiler fills in. + pub const PARAMETER_COUNT: usize = #parameter_count; #(#generated_input_accessor)* } } diff --git a/node-graph/node-macro/src/graph.rs b/node-graph/node-macro/src/graph.rs new file mode 100644 index 0000000000..c6027f774f --- /dev/null +++ b/node-graph/node-macro/src/graph.rs @@ -0,0 +1,1744 @@ +//! The `#[graph]` macro, which defines a node as a subgraph written in the graph text format's Rust syntax. +//! +//! The function's parameters become the subgraph's imports, `out!(...)` names its exports, and the body wires nodes +//! together with `>>`. The macro checks the body's shape, then generates code that registers the subgraph's metadata at +//! startup, as the node macro does for proto nodes. Each node, parameter, and output name resolves through the per-node +//! module the node macro (or this macro) generates, so rustc reports a misspelled name at the token the author wrote. + +use crate::codegen::{NODE_ID, derived_display_name, field_metadata_tokens, option_tokens, symbol_name}; +use crate::crate_ident::CrateIdent; +use crate::parsing::{ParsedField, ParsedFieldType, parse_field}; +use crate::validation::{validate_name_isnt_a_value_helper, validate_parameters}; +use convert_case::{Case, Casing}; +use proc_macro2::{Span, TokenStream as TokenStream2}; +use quote::{ToTokens, format_ident, quote, quote_spanned}; +use std::collections::HashMap; +use syn::ext::IdentExt; +use syn::parse::{ParseStream, Parser}; +use syn::spanned::Spanned; +use syn::{Attribute, BinOp, Error, Expr, ExprCall, ExprMethodCall, FnArg, Ident, Item, ItemFn, Lit, LitInt, LitStr, Meta, Pat, ReturnType, Stmt, Token, Type, UnOp}; + +/// The calls a graph body reads as values or input sources rather than as nodes, so no node can share one's name. +pub(crate) const VALUE_HELPERS: &[&str] = &["rgb", "rgba", "scope", "reflect", "exposed", "unexposed"]; + +/// The parameter attributes an import takes, which are those describing its value and widget rather than a proto node's implementation. +const IMPORT_ATTRIBUTES: &[&str] = &[ + "doc", + "name", + "expose", + "default", + "widget", + "unit", + "hard", + "soft", + "range", + "step", + "display_decimal_places", + "multiline", + "progression", + "labels", + "integer", + "blank_assist", +]; + +pub fn new_graph_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result { + let function: ItemFn = syn::parse2(item)?; + let attributes = parse_graph_attributes(attr); + + // The symbols naming the graph stay defined while it has errors, so those errors don't also break every use of it + let display_name = attributes.as_ref().ok().and_then(|attributes| attributes.display_name.as_ref()); + let symbols = symbol_module(&function, &graph_identifier(&function.sig.ident, display_name)); + proc_macro_error3::set_dummy(symbols.clone()); + + let crate_ident = CrateIdent::default(); + let core_types = crate_ident.gcore()?.clone(); + + let graph = match attributes.and_then(|attributes| Graph::parse(&function, attributes, &core_types)) { + Ok(graph) => graph, + Err(error) => { + let error = error.to_compile_error(); + return Ok(quote!(#error #symbols)); + } + }; + validate_parameters(&graph.imports.iter().map(|import| import.field.clone()).collect::>()); + validate_name_isnt_a_value_helper(&function.sig.ident); + + Ok(graph.generate(&function, &core_types, symbols)) +} + +/// The attributes inside `#[graph(...)]`. +#[derive(Default)] +struct GraphAttributes { + category: Option, + icon: Option, + display_name: Option, + version: Option, + layer: bool, +} + +fn parse_graph_attributes(attr: TokenStream2) -> syn::Result { + let mut attributes = GraphAttributes::default(); + + let parser = syn::meta::parser(|meta| { + let string_argument = |meta: &syn::meta::ParseNestedMeta| -> syn::Result { + let content; + syn::parenthesized!(content in meta.input); + content.parse() + }; + let repeated = |name: &str| meta.error(format!("Multiple '{name}' attributes are not allowed")); + + if meta.path.is_ident("category") { + if attributes.category.is_some() { + return Err(repeated("category")); + } + attributes.category = Some(string_argument(&meta)?); + } else if meta.path.is_ident("icon") { + if attributes.icon.is_some() { + return Err(repeated("icon")); + } + attributes.icon = Some(string_argument(&meta)?); + } else if meta.path.is_ident("name") { + if attributes.display_name.is_some() { + return Err(repeated("name")); + } + attributes.display_name = Some(string_argument(&meta)?); + } else if meta.path.is_ident("version") { + if attributes.version.is_some() { + return Err(repeated("version")); + } + let content; + syn::parenthesized!(content in meta.input); + let literal: LitInt = content.parse()?; + let version: u32 = literal.base10_parse()?; + if version == 0 { + return Err(Error::new_spanned(literal, "Versions start at 1")); + } + attributes.version = Some(version); + } else if meta.path.is_ident("layer") { + if attributes.layer { + return Err(repeated("layer")); + } + attributes.layer = true; + } else { + return Err(meta.error("Unknown `#[graph]` attribute. Expected `category(\"…\")`, `icon(\"…\")`, `name(\"…\")`, `version(N)`, or `layer`")); + } + Ok(()) + }); + parser.parse2(attr)?; + + if attributes.category.is_none() { + return Err(Error::new(Span::call_site(), "A `#[graph]` needs a category, like `#[graph(category(\"Vector: Deform\"))]`")); + } + + Ok(attributes) +} + +/// The `///` lines of an item, each trimmed and joined by line breaks. +fn doc_comment(attributes: &[Attribute]) -> String { + attributes + .iter() + .filter_map(|attribute| { + let Meta::NameValue(name_value) = &attribute.meta else { return None }; + if !name_value.path.is_ident("doc") { + return None; + } + let Expr::Lit(expression) = &name_value.value else { return None }; + let Lit::Str(text) = &expression.lit else { return None }; + Some(text.value().trim().to_string()) + }) + .collect::>() + .join("\n") + .trim() + .to_string() +} + +/// The `Type` expression for a type written in a signature. +fn type_tokens(ty: &Type, core_types: &TokenStream2) -> syn::Result { + let span = ty.span(); + + match ty { + Type::Tuple(tuple) if tuple.elems.is_empty() => Ok(quote_spanned!(span=> #core_types::concrete!(()))), + Type::Paren(inner) => type_tokens(&inner.elem, core_types), + Type::FnPtr(function) => { + if function.inputs.len() > 1 || function.variadic.is_some() || function.abi.is_some() || function.unsafety.is_some() || function.lifetimes.is_some() { + return Err(Error::new_spanned(function, "A function type takes at most one input, like `fn(Context) -> Item`")); + } + + let input = match function.inputs.first() { + Some(input) => type_tokens(&input.ty, core_types)?, + None => quote!(#core_types::concrete!(())), + }; + let output = match &function.output { + ReturnType::Type(_, output) => type_tokens(output.as_ref(), core_types)?, + ReturnType::Default => quote!(#core_types::concrete!(())), + }; + Ok(quote_spanned!(span=> #core_types::Type::Fn(::std::boxed::Box::new(#input), ::std::boxed::Box::new(#output)))) + } + // Nothing matches a graph's generic types by name, so every `impl Any` takes the same one + Type::ImplTrait(_) if is_any_type(ty) => Ok(quote_spanned!(span=> #core_types::generic!(T))), + Type::ImplTrait(_) => Err(Error::new_spanned(ty, "A generic type is written `impl Any`")), + Type::Path(path) if path.qself.is_none() => { + let Some(last) = path.path.segments.last() else { + return Ok(quote_spanned!(span=> #core_types::concrete!(#ty))); + }; + + if is_lone_capital(path) { + return Err(Error::new_spanned(ty, format!("A generic type is written `impl Any`, rather than a name like `{}`", last.ident))); + } + let name = last.ident.to_string(); + + // The element type recurses, so a generic element like the one in `List` stays generic + if matches!(name.as_str(), "Item" | "List") + && let syn::PathArguments::AngleBracketed(arguments) = &last.arguments + { + let [syn::GenericArgument::Type(element)] = arguments.args.iter().collect::>().as_slice() else { + return Err(Error::new_spanned(arguments, format!("`{name}` takes one element type, like `{name}`"))); + }; + let element = type_tokens(element, core_types)?; + + return Ok(match name.as_str() { + "Item" => quote_spanned!(span=> #core_types::Type::Item(::std::boxed::Box::new(#element))), + _ => quote_spanned!(span=> #core_types::Type::List(::std::boxed::Box::new(#element))), + }); + } + + Ok(quote_spanned!(span=> #core_types::concrete!(#ty))) + } + _ => Ok(quote_spanned!(span=> #core_types::concrete!(#ty))), + } +} + +/// The graph's identifier and display name, from `#[graph(name("…"))]` or else its function name in Title Case. +fn graph_identifier(ident: &Ident, display_name: Option<&LitStr>) -> String { + match display_name { + Some(name) => name.value(), + None => ident.unraw().to_string().to_case(Case::Pascal).to_case(Case::Title), + } +} + +/// The `#[cfg(...)]` attributes on the function, which apply to everything generated from it. +fn cfg_attributes(function: &ItemFn) -> Vec<&Attribute> { + function.attrs.iter().filter(|attribute| attribute.path().is_ident("cfg")).collect() +} + +/// The module named after the graph, holding its identifier, its parameter count, and the symbols naming its inputs and outputs. +fn symbol_module(function: &ItemFn, identifier: &str) -> TokenStream2 { + let visibility = &function.vis; + let ident = &function.sig.ident; + let cfg_attributes = cfg_attributes(function); + let module_doc = format!("The identifier, parameter, and output symbols of the **{identifier}** graph."); + let parameter_count = function.sig.inputs.len(); + + let parameter_structs = function.sig.inputs.iter().enumerate().filter_map(|(index, argument)| { + let FnArg::Typed(typed) = argument else { return None }; + let Pat::Ident(pattern) = &*typed.pat else { return None }; + + let struct_name = symbol_name(&pattern.ident, "Input"); + Some(quote! { + pub struct #struct_name; + impl #struct_name { + /// Position of this parameter among the graph's inputs. + pub const INDEX: usize = #index; + } + }) + }); + + // A signature with errors names no outputs, and `Graph::parse` reports the errors + let exports = parse_exports(&function.sig.output).unwrap_or_default(); + let output_structs = exports.iter().enumerate().map(|(index, export)| { + let struct_name = symbol_name(&export.ident, "Output"); + quote! { + pub struct #struct_name; + impl #struct_name { + /// Position of this export among the graph's outputs. + pub const INDEX: usize = #index; + } + } + }); + + quote! { + #(#cfg_attributes)* + #[doc = #module_doc] + #visibility mod #ident { + /// The graph's identifier in the node catalog. + pub const IDENTIFIER: &str = #identifier; + /// How many parameters (imports) the graph has. + pub const PARAMETER_COUNT: usize = #parameter_count; + + #(#parameter_structs)* + + #(#output_structs)* + } + } +} + +/// One of the subgraph's imports, from a function parameter. +struct Import { + ident: Ident, + field: ParsedField, + /// The type the import was declared with, which the wires from it record. + ty: TokenStream2, + /// The import's `FieldMetadata`, built as the node macro builds a proto node parameter's. + metadata: TokenStream2, +} + +/// One of the subgraph's exports, from a name in `out!(...)`. +struct Export { + ident: Ident, + name: String, + description: String, +} + +/// What feeds an input or export, as the macro tracks it while reading the body. +#[derive(Clone)] +enum Feed { + /// A node's output, chosen by name like `.captures`, or else its primary output. + Node { + node: usize, + output: Option, + }, + Import { + index: usize, + ty: Option, + }, + Value { + value: TokenStream2, + exposed: Option, + }, + /// The scope key, as a string literal or a node module's `IDENTIFIER`, as `#[scope(...)]` takes it. + Scope(Expr), + NodePath, + SourceId, +} + +/// Which input of a node a definition sets. +enum Slot { + Primary, + Named(Ident), +} + +/// A node created by a call in the body. +struct Node { + /// The module the node macro (or this macro) generates for the called node, which names its identifier and parameters. + module: syn::Path, + inputs: Vec<(Slot, Feed)>, + primary_span: Option, + position: Option<(i32, i32)>, + layer: bool, + display_name: Option, + hidden: bool, + locked: bool, + pinned: bool, + call_argument: Option, +} + +struct Graph { + ident: Ident, + identifier: String, + attributes: GraphAttributes, + description: String, + imports: Vec, + exports: Vec, + nodes: Vec, + export_sources: Vec, + /// Items written after the `return`, such as constants, which the generated code keeps in scope for the values that use them. + items: Vec, +} + +/// Reads the body, building the subgraph's nodes and wires. +struct BodyReader<'a> { + core_types: &'a TokenStream2, + /// The function name of the graph being read, which its body can't call. + graph_ident: &'a Ident, + imports: &'a [Import], + bindings: HashMap, + nodes: Vec, +} + +impl Graph { + fn parse(function: &ItemFn, attributes: GraphAttributes, core_types: &TokenStream2) -> syn::Result { + let signature = &function.sig; + if let Some(asyncness) = &signature.asyncness { + return Err(Error::new_spanned(asyncness, "A graph can't be `async`, since the nodes inside it decide how they run")); + } + if !signature.generics.params.is_empty() { + return Err(Error::new_spanned(&signature.generics, "A graph doesn't declare generics. Write a generic type as `impl Any`")); + } + if let Some(where_clause) = &signature.generics.where_clause { + return Err(Error::new_spanned(where_clause, "A graph can't have a `where` clause")); + } + if signature.constness.is_some() || !matches!(signature.safety, syn::Safety::Default) || signature.abi.is_some() { + return Err(Error::new_spanned(signature.fn_token, "A graph is written as a plain `fn`")); + } + + // Any other attribute would be dropped, since the function itself isn't emitted + if let Some(attribute) = function.attrs.iter().find(|attribute| !attribute.path().is_ident("doc") && !attribute.path().is_ident("cfg")) { + return Err(Error::new_spanned(attribute, "Only doc comments and `#[cfg(...)]` apply to a graph")); + } + + let ident = function.sig.ident.clone(); + let identifier = graph_identifier(&ident, attributes.display_name.as_ref()); + let description = doc_comment(&function.attrs); + + let imports = function + .sig + .inputs + .iter() + .enumerate() + .map(|(index, argument)| parse_import(index, argument, core_types)) + .collect::>>()?; + + let exports = parse_exports(&function.sig.output)?; + + let mut reader = BodyReader { + core_types, + graph_ident: &ident, + imports: &imports, + bindings: HashMap::new(), + nodes: Vec::new(), + }; + + let mut export_sources = None; + let mut items = Vec::new(); + let statements = &function.block.stmts; + for (index, statement) in statements.iter().enumerate() { + match statement { + Stmt::Local(local) => { + if export_sources.is_some() { + return Err(Error::new_spanned(local, "Bindings go before the `return`, and only definitions and data go after it")); + } + reader.read_binding(local)?; + } + Stmt::Expr(Expr::Return(return_expression), _) => { + if export_sources.is_some() { + return Err(Error::new_spanned(return_expression, "A graph has one `return`")); + } + let Some(returned) = &return_expression.expr else { + return Err(Error::new_spanned(return_expression, "Return the export values, like `return card;`")); + }; + export_sources = Some(reader.read_exports(returned, &exports)?); + } + Stmt::Item(Item::Fn(nested)) => { + return Err(Error::new_spanned( + &nested.sig.ident, + "Nested graph definitions aren't supported yet, so define this graph beside the one using it", + )); + } + Stmt::Item(item) => items.push(item.clone()), + // A final expression without a semicolon gives the exports, as it returns a value in Rust + Stmt::Expr(expression, None) if index + 1 == statements.len() => { + if export_sources.is_some() { + return Err(Error::new_spanned(expression, "A graph gives its exports once, with `return` or a final expression")); + } + export_sources = Some(reader.read_exports(expression, &exports)?); + } + Stmt::Expr(expression, _) => { + return Err(Error::new_spanned(expression, "Each statement in a graph is a `let` binding or the exports it returns")); + } + Stmt::Macro(statement) => { + return Err(Error::new_spanned(statement, "Macros aren't supported in a graph body")); + } + } + } + + let Some(export_sources) = export_sources else { + return Err(Error::new_spanned( + &function.sig.ident, + "A graph ends its body with one value per export, as a final expression or with `return`", + )); + }; + let nodes = reader.nodes; + + Ok(Self { + ident, + identifier, + attributes, + description, + imports, + exports, + nodes, + export_sources, + items, + }) + } + + fn generate(&self, function: &ItemFn, core_types: &TokenStream2, symbols: TokenStream2) -> TokenStream2 { + let Self { + ident, + identifier, + attributes, + description, + imports, + exports, + nodes, + export_sources, + items, + } = self; + + let cfg_attributes = cfg_attributes(function); + let category = attributes.category.as_ref().map(LitStr::value).unwrap_or_default(); + let icon = option_tokens(attributes.icon.as_ref().map(ToTokens::to_token_stream)); + let version = attributes.version.unwrap_or(1); + let layer = attributes.layer; + + let import_tokens = imports.iter().map(|import| &import.metadata); + + let export_tokens = exports.iter().zip(export_sources).map(|(export, source)| { + let Export { name, description, .. } = export; + let source = source_tokens(source, imports, nodes, core_types); + quote! { + #core_types::registry::GraphExportMetadata { + name: #name, + description: #description, + source: #source, + } + } + }); + + let node_tokens = nodes.iter().map(|node| node_tokens(node, imports, nodes, core_types)); + let primary_input_checks = nodes.iter().map(|node| primary_input_checks(node, core_types)); + + let module_name = format_ident!("_{}_graph", ident); + let metadata_name = format_ident!("_{}_graph_metadata", ident); + let registry_name = format_ident!( + "__node_registry_{}_{}Graph", + NODE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst), + ident.unraw().to_string().to_case(Case::Pascal) + ); + + quote! { + // Built in the module the graph is written in, so the paths its body uses resolve as written. The generated + // code names everything by full path, so the author's names can't stand in for what it refers to. + #(#cfg_attributes)* + #[doc(hidden)] + fn #metadata_name() -> #core_types::registry::GraphMetadata { + #(#items)* + #(#primary_input_checks)* + + #core_types::registry::GraphMetadata { + identifier: #identifier, + category: #category, + icon: #icon, + description: #description, + version: #version, + layer: #layer, + imports: ::std::vec![#(#import_tokens,)*], + exports: ::std::vec![#(#export_tokens,)*], + nodes: ::std::vec![#(#node_tokens,)*], + } + } + + #(#cfg_attributes)* + #[doc(hidden)] + mod #module_name { + use #core_types as gcore; + use gcore::ctor::ctor; + + #[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = gcore::ctor))] + pub(super) fn register_graph() { + gcore::registry::GRAPH_METADATA.lock().unwrap().push(super::#metadata_name()); + } + } + + // On Wasm, `ctor` isn't available, so JS invokes this exported shim to register the graph + #(#cfg_attributes)* + #[cfg(target_family = "wasm")] + #[unsafe(no_mangle)] + extern "C" fn #registry_name() { + #module_name::register_graph(); + } + + #symbols + } + } +} + +fn parse_import(index: usize, argument: &FnArg, core_types: &TokenStream2) -> syn::Result { + let FnArg::Typed(typed) = argument else { + return Err(Error::new_spanned(argument, "A graph's imports are named parameters, like `content: List`")); + }; + let is_unit = matches!(&*typed.ty, Type::Tuple(tuple) if tuple.elems.is_empty()); + + // A primary import that takes nothing can go unnamed as `_: ()`, since nothing can wire into it + let pattern = match &*typed.pat { + Pat::Ident(pattern) => pattern.clone(), + Pat::Wild(wild) if index == 0 && is_unit => syn::PatIdent { + attrs: wild.attrs.clone(), + by_ref: None, + mutability: None, + ident: wild.underscore_token.into(), + subpat: None, + }, + _ => { + return Err(Error::new_spanned( + &typed.pat, + "Name each import with an identifier, or write `_: ()` for a primary import that takes nothing", + )); + } + }; + if let Some(problem) = binding_pattern_problem(&pattern) { + return Err(Error::new_spanned(&pattern, format!("An import is a plain name, {problem}"))); + } + let ident = pattern.ident.clone(); + + for attribute in &typed.attrs { + let attribute_name = attribute.path().get_ident().map(Ident::to_string).unwrap_or_default(); + if !IMPORT_ATTRIBUTES.contains(&attribute_name.as_str()) { + return Err(Error::new_spanned(attribute, format!("Unknown import attribute `#[{}]`", attribute.path().to_token_stream()))); + } + } + + let field = parse_field(pattern, (*typed.ty).clone(), &typed.attrs)?; + if matches!(field.ty, ParsedFieldType::Node(_)) { + return Err(Error::new_spanned(&typed.ty, "An import is a value, rather than an `impl Node`")); + } + + let ty = type_tokens(&typed.ty, core_types)?; + + // Like a proto node parameter, an import carries a ranked wire, except a primary import that takes nothing + if !(is_ranked_type(&typed.ty) || (index == 0 && is_unit)) { + let message = match is_unit { + true => "Only the primary import can be `()`, since it means the graph takes nothing there", + false => "An import's type is an `Item` or `List`, like `width: Item`, or `()` for a primary import that takes nothing", + }; + return Err(Error::new_spanned(&typed.ty, message)); + } + + // A parameter named with a leading `_` is internal state, except the primary one, as for a proto node + let internal = index > 0 && ident.to_string().starts_with('_'); + let metadata = field_metadata_tokens(&field, internal, &option_tokens(Some(ty.clone())), core_types); + + Ok(Import { ident, field, ty, metadata }) +} + +/// `impl Any`, which is how a graph writes a generic type. +fn is_any_type(ty: &Type) -> bool { + let Type::ImplTrait(impl_trait) = ty else { return false }; + let [syn::TypeParamBound::Trait(bound)] = impl_trait.bounds.iter().collect::>().as_slice() else { + return false; + }; + bound.maybe.is_none() && bound.lifetimes.is_none() && bound.path.segments.last().is_some_and(|last| last.ident == "Any" && last.arguments.is_none()) +} + +/// A lone capital letter, like `T`, which Rust would use to name a generic type. +fn is_lone_capital(path: &syn::TypePath) -> bool { + let Some(segment) = path.path.segments.first().filter(|_| path.path.segments.len() == 1) else { + return false; + }; + let name = segment.ident.to_string(); + path.qself.is_none() && segment.arguments.is_none() && name.len() == 1 && name.chars().all(|character| character.is_ascii_uppercase()) +} + +/// Whether a type is a ranked wire (an `Item` or `List`), or a generic or lazy one, which resolves to a ranked wire. +fn is_ranked_type(ty: &Type) -> bool { + match ty { + Type::Paren(inner) => is_ranked_type(&inner.elem), + Type::FnPtr(_) => true, + Type::ImplTrait(_) => is_any_type(ty), + Type::Path(path) => path.path.segments.last().is_some_and(|last| last.ident == "Item" || last.ident == "List"), + _ => false, + } +} + +/// What makes a binding or import pattern more than a plain name, which a graph has no use for. +fn binding_pattern_problem(pattern: &syn::PatIdent) -> Option<&'static str> { + if pattern.by_ref.is_some() { + Some("without `ref`") + } else if pattern.mutability.is_some() { + Some("without `mut`") + } else if pattern.subpat.is_some() { + Some("without an `@` pattern") + } else { + None + } +} + +/// Reads the names in `-> out!(...)`, each with its optional `///` description and `#[name("…")]`. +fn parse_exports(output: &ReturnType) -> syn::Result> { + let ReturnType::Type(_, ty) = output else { + return Err(Error::new(output.span(), "Name the graph's exports, like `-> out!(out)`")); + }; + let Type::Macro(type_macro) = &**ty else { + return Err(Error::new_spanned(ty, "Name the graph's exports with `out!(...)`, like `-> out!(out)`")); + }; + if !type_macro.mac.path.is_ident("out") { + return Err(Error::new_spanned(&type_macro.mac.path, "Name the graph's exports with `out!(...)`")); + } + + let parser = |input: ParseStream| { + let mut exports = Vec::new(); + while !input.is_empty() { + let attributes = input.call(Attribute::parse_outer)?; + if input.peek(Token![_]) { + let underscore: Token![_] = input.parse()?; + return Err(Error::new(underscore.span, "A hidden primary export isn't supported yet")); + } + let ident: Ident = input.call(Ident::parse_any)?; + + let mut name = None; + for attribute in &attributes { + if attribute.path().is_ident("name") { + if name.is_some() { + return Err(Error::new_spanned(attribute, "Multiple 'name' attributes are not allowed")); + } + name = Some(attribute.parse_args::()?.value()); + } else if !attribute.path().is_ident("doc") { + return Err(Error::new_spanned(attribute, "Unknown export attribute")); + } + } + let name = name.unwrap_or_else(|| derived_display_name(&ident)); + + exports.push(Export { + ident, + name, + description: doc_comment(&attributes), + }); + + if input.is_empty() { + break; + } + input.parse::()?; + } + Ok(exports) + }; + + let exports = parser.parse2(type_macro.mac.tokens.clone())?; + if exports.is_empty() { + return Err(Error::new_spanned(type_macro, "Name at least one export")); + } + Ok(exports) +} + +impl BodyReader<'_> { + fn read_binding(&mut self, local: &syn::Local) -> syn::Result<()> { + let Pat::Ident(pattern) = &local.pat else { + return Err(Error::new_spanned(&local.pat, "Bind each node to a plain name, like `let spacing = ...;`")); + }; + if let Some(problem) = binding_pattern_problem(pattern) { + return Err(Error::new_spanned(pattern, format!("Bind each node to a plain name, {problem}"))); + } + let Some(initializer) = &local.init else { + return Err(Error::new_spanned(local, "Give each binding a value")); + }; + if let Some((else_token, _)) = &initializer.diverge { + return Err(Error::new_spanned(else_token, "A binding names a node, so it has no `else`")); + } + if !local.attrs.is_empty() { + return Err(Error::new_spanned(&local.attrs[0], "Put node state after the call, like `.at(x, y)`, rather than as an attribute")); + } + + let name = pattern.ident.to_string(); + if self.bindings.contains_key(&name) || self.imports.iter().any(|import| import.ident == pattern.ident) { + return Err(Error::new_spanned(&pattern.ident, format!("`{name}` is already the name of a binding or import"))); + } + + let source = self.read(&initializer.expr)?; + self.bindings.insert(name, source); + Ok(()) + } + + fn read_exports(&mut self, returned: &Expr, exports: &[Export]) -> syn::Result> { + let values: Vec<&Expr> = match returned { + Expr::Tuple(tuple) => tuple.elems.iter().collect(), + single => vec![single], + }; + + if values.len() != exports.len() { + let message = format!("The graph names {} exports in `out!(...)`, but returns {} values", exports.len(), values.len()); + return Err(Error::new_spanned(returned, message)); + } + + values + .into_iter() + .map(|value| match self.read(value)? { + Feed::Import { .. } | Feed::Scope(_) => Err(Error::new_spanned(value, "An export can't come straight from an import or scope yet, so pass it through a node first")), + feed => Ok(feed), + }) + .collect() + } + + /// Reads an expression, creating any nodes it calls, and returns what its result feeds. + fn read(&mut self, expression: &Expr) -> syn::Result { + match expression { + Expr::Paren(inner) => self.read(&inner.expr), + Expr::Group(inner) => self.read(&inner.expr), + Expr::Path(path) if path.qself.is_none() => { + if let Some(ident) = path.path.get_ident() { + let name = ident.to_string(); + if let Some(source) = self.bindings.get(&name) { + return Ok(source.clone()); + } + if let Some(index) = self.imports.iter().position(|import| *ident == import.ident) { + return Ok(Feed::Import { index, ty: None }); + } + if name == "None" { + return Err(Error::new_spanned(ident, "Type defaults like `None` aren't supported yet, so leave the input out to keep its default")); + } + + // A name in capitals is a constant, used as a value + let is_constant = name.chars().any(|character| character.is_ascii_uppercase()) && !name.chars().any(|character| character.is_ascii_lowercase()); + if !is_constant { + return Err(Error::new_spanned(ident, format!("`{name}` isn't a binding or import. Call a node with parentheses, like `{name}()`"))); + } + } + Ok(self.value(expression)) + } + Expr::Lit(_) | Expr::Unary(syn::ExprUnary { op: UnOp::Neg(_), .. }) => self.literal(expression), + Expr::Array(array) => { + let numbers = array.elems.iter().map(number_literal).collect::>>(); + match numbers.as_deref() { + Some([x, y]) => { + let core_types = self.core_types; + Ok(Feed::Value { + value: quote_spanned!(array.span()=> #core_types::registry::GraphValue::vec2(#x, #y)), + exposed: None, + }) + } + _ => Err(Error::new_spanned( + array, + "Several wires into one input aren't supported until variadic inputs land, and a value array is a two-number Vec2", + )), + } + } + Expr::Cast(cast) => { + let Feed::Import { index, .. } = self.read(&cast.expr)? else { + return Err(Error::new_spanned(cast, "Only an import can be cast, to set the type its wire records")); + }; + Ok(Feed::Import { + index, + ty: Some(type_tokens(&cast.ty, self.core_types)?), + }) + } + Expr::Call(call) => self.read_call(call), + Expr::MethodCall(method_call) => self.read_state(method_call), + Expr::Binary(binary) if matches!(binary.op, BinOp::Shr(_)) => { + let upstream = self.read(&binary.left)?; + let (node, output) = self.read_node(&binary.right)?; + + // A binding on the right is a node made earlier, which the left side may already be fed by + if let Feed::Node { node: upstream_node, .. } = upstream + && self.is_fed_by(upstream_node, node) + { + return Err(Error::new_spanned(binary, "This wire makes a loop, since the node on the right already feeds the left side")); + } + + let node_entry = &mut self.nodes[node]; + if let Some(previous) = node_entry.primary_span { + let mut error = Error::new_spanned(&binary.right, "This node's primary input is already fed. Several wires into one input are written together as an array"); + error.combine(Error::new(previous, "It's fed here")); + return Err(error); + } + node_entry.primary_span = Some(binary.left.span()); + node_entry.inputs.push((Slot::Primary, upstream)); + + Ok(Feed::Node { node, output }) + } + Expr::Binary(binary) => Err(Error::new_spanned( + binary, + "Graphs use only `>>`, which feeds its left side into the next node. Do math with nodes, like `multiply(multiplicand = 2)`", + )), + Expr::Field(field) => self.read_output(field), + _ => Err(Error::new_spanned(expression, "This expression isn't part of the graph syntax")), + } + } + + /// Whether `node` is `source` or feeds it through any chain of wires. O(n) in the nodes upstream of `node`. + fn is_fed_by(&self, node: usize, source: usize) -> bool { + let mut visited = vec![false; self.nodes.len()]; + let mut stack = vec![node]; + + while let Some(current) = stack.pop() { + if current == source { + return true; + } + if std::mem::replace(&mut visited[current], true) { + continue; + } + stack.extend(self.nodes[current].inputs.iter().filter_map(|(_, feed)| match feed { + Feed::Node { node, .. } => Some(*node), + _ => None, + })); + } + + false + } + + /// Reads the right side of `>>`, which must be a node (a call, or a binding naming one) and may choose one of its outputs. + fn read_node(&mut self, expression: &Expr) -> syn::Result<(usize, Option)> { + match self.read(expression)? { + Feed::Node { node, output } => Ok((node, output)), + _ => Err(Error::new_spanned(expression, "The right side of `>>` is a node, like `fill()`, or a binding naming one")), + } + } + + /// Reads the choice of one of a node's outputs by name, like `.captures`. + fn read_output(&mut self, field: &syn::ExprField) -> syn::Result { + let syn::Member::Named(output) = &field.member else { + return Err(Error::new_spanned(&field.member, "Choose an output by its name, like `.captures`")); + }; + + match self.read(&field.base)? { + Feed::Node { node, output: None } => Ok(Feed::Node { node, output: Some(output.clone()) }), + Feed::Node { output: Some(_), .. } => Err(Error::new_spanned(output, "An output is already chosen here")), + _ => Err(Error::new_spanned(&field.base, "Only a node has outputs to choose from")), + } + } + + fn literal(&self, expression: &Expr) -> syn::Result { + let core_types = self.core_types; + let span = expression.span(); + + // The input an integer feeds sets its type, which a suffix would contradict + let integer = match expression { + Expr::Lit(syn::ExprLit { lit: Lit::Int(integer), .. }) => Some(integer), + Expr::Unary(syn::ExprUnary { expr, .. }) => match &**expr { + Expr::Lit(syn::ExprLit { lit: Lit::Int(integer), .. }) => Some(integer), + _ => None, + }, + _ => None, + }; + if let Some(integer) = integer + && !integer.suffix().is_empty() + { + return Err(Error::new_spanned(integer, "Write the integer without a type suffix, since the input it feeds sets its type")); + } + + let value = match expression { + Expr::Lit(literal) => match &literal.lit { + Lit::Int(_) => quote_spanned!(span=> #core_types::registry::GraphValue::Integer(#expression)), + Lit::Float(_) => quote_spanned!(span=> #core_types::registry::GraphValue::Number(#expression)), + Lit::Bool(_) => quote_spanned!(span=> #core_types::registry::GraphValue::Bool(#expression)), + Lit::Str(_) => quote_spanned!(span=> #core_types::registry::GraphValue::String(::std::string::String::from(#expression))), + _ => return Err(Error::new_spanned(literal, "Unsupported literal")), + }, + Expr::Unary(unary) => match &*unary.expr { + Expr::Lit(syn::ExprLit { lit: Lit::Int(_), .. }) => quote_spanned!(span=> #core_types::registry::GraphValue::Integer(#expression)), + Expr::Lit(syn::ExprLit { lit: Lit::Float(_), .. }) => quote_spanned!(span=> #core_types::registry::GraphValue::Number(#expression)), + _ => return Err(Error::new_spanned(unary, "Only a number can be negated")), + }, + _ => return Err(Error::new_spanned(expression, "Unsupported literal")), + }; + + Ok(Feed::Value { value, exposed: None }) + } + + /// A constant or other Rust expression used as a value. + fn value(&self, expression: &Expr) -> Feed { + let core_types = self.core_types; + Feed::Value { + value: quote_spanned!(expression.span()=> #core_types::registry::GraphValue::from(#expression)), + exposed: None, + } + } + + fn read_call(&mut self, call: &ExprCall) -> syn::Result { + let Expr::Path(function) = &*call.func else { + return Err(Error::new_spanned(&call.func, "Call a node by its name, like `fill()`")); + }; + let module = function.path.clone(); + + // Value helpers, which build values and input sources rather than nodes + if let Some(name) = module.get_ident().map(Ident::to_string) { + let core_types = self.core_types; + let single_argument = || -> syn::Result<&Expr> { + match call.args.iter().collect::>().as_slice() { + [argument] => Ok(argument), + _ => Err(Error::new_spanned(call, format!("`{name}(...)` takes one argument"))), + } + }; + + match name.as_str() { + "rgb" | "rgba" => { + let hex = single_argument()?; + + // `rgb` takes six hex digits, and a larger literal would lose its top byte + if name == "rgb" + && let Expr::Lit(syn::ExprLit { lit: Lit::Int(literal), .. }) = hex + && literal.base10_parse::().is_ok_and(|value| value > 0xFF_FFFF) + { + return Err(Error::new_spanned(hex, "`rgb(...)` takes six hex digits, like `rgb(0xE85D75)`. Use `rgba(...)` to give an alpha too")); + } + + let constructor = format_ident!("{name}"); + return Ok(Feed::Value { + value: quote_spanned!(call.span()=> #core_types::registry::GraphValue::#constructor(#hex)), + exposed: None, + }); + } + "scope" => return Ok(Feed::Scope(single_argument()?.clone())), + "reflect" => { + let argument = single_argument()?; + let Expr::Path(reflected) = argument else { + return Err(Error::new_spanned(argument, "Reflect `NodePath` or `SourceId`")); + }; + return match reflected.path.get_ident().map(Ident::to_string).as_deref() { + Some("NodePath") => Ok(Feed::NodePath), + Some("SourceId") => Ok(Feed::SourceId), + _ => Err(Error::new_spanned(argument, "Reflect `NodePath` or `SourceId`")), + }; + } + "exposed" | "unexposed" => { + let Feed::Value { value, .. } = self.read(single_argument()?)? else { + return Err(Error::new_spanned(call, format!("`{name}(...)` wraps a value"))); + }; + return Ok(Feed::Value { + value, + exposed: Some(name == "exposed"), + }); + } + _ => {} + } + } + + if module.get_ident() == Some(self.graph_ident) { + return Err(Error::new_spanned(&call.func, "A graph can't contain itself")); + } + + // Read each named argument before creating the node, so the nodes feeding it come first + let mut inputs: Vec<(Slot, Feed)> = Vec::new(); + for argument in &call.args { + let (parameter, value) = match argument { + Expr::Assign(assignment) => { + let parameter = match &*assignment.left { + Expr::Path(parameter) => parameter.path.get_ident(), + _ => None, + }; + let Some(parameter) = parameter else { + return Err(Error::new_spanned(&assignment.left, "Name the parameter, like `weight = 6`")); + }; + (parameter.clone(), &*assignment.right) + } + // The shorthand `progression` feeds the binding or import of that name into the parameter of the same name + Expr::Path(shorthand) if shorthand.path.get_ident().is_some() => (shorthand.path.segments[0].ident.clone(), argument), + _ => return Err(Error::new_spanned(argument, "Name each argument, like `weight = 6`, or write a bare name for the shorthand")), + }; + + if let Some((Slot::Named(previous), _)) = inputs.iter().find(|(slot, _)| matches!(slot, Slot::Named(named) if *named == parameter)) { + let mut error = Error::new_spanned( + ¶meter, + format!("`{parameter}` is already set in this call. Several wires into one input are written together as an array"), + ); + error.combine(Error::new_spanned(previous, "It's set here")); + return Err(error); + } + + inputs.push((Slot::Named(parameter), self.read(value)?)); + } + + self.nodes.push(Node { + module, + inputs, + primary_span: None, + position: None, + layer: false, + display_name: None, + hidden: false, + locked: false, + pinned: false, + call_argument: None, + }); + Ok(Feed::Node { + node: self.nodes.len() - 1, + output: None, + }) + } + + /// Reads a node state method after a call, like `.at(x, y)` or `.hidden()`. + fn read_state(&mut self, method_call: &ExprMethodCall) -> syn::Result { + let mut receiver = &*method_call.receiver; + while let Expr::Paren(syn::ExprParen { expr: inner, .. }) | Expr::Group(syn::ExprGroup { expr: inner, .. }) = receiver { + receiver = inner; + } + + if matches!(receiver, Expr::Field(_)) { + return Err(Error::new_spanned( + &method_call.method, + "Node state goes before the output it chooses, like `regex_find().at(0, 0).captures`", + )); + } + if !matches!(receiver, Expr::Call(_) | Expr::MethodCall(_)) { + return Err(Error::new_spanned(&method_call.method, "Node state goes directly after the call it modifies, not on a binding")); + } + + let source = self.read(receiver)?; + let Feed::Node { node, .. } = source else { + return Err(Error::new_spanned(&method_call.method, "Node state goes after a node call")); + }; + + let arguments: Vec<&Expr> = method_call.args.iter().collect(); + let method = method_call.method.to_string(); + let no_arguments = |arguments: &[&Expr]| { + if arguments.is_empty() { + Ok(()) + } else { + Err(Error::new_spanned(&method_call.args, format!("`.{method}()` takes no arguments"))) + } + }; + + // Only `.call_argument::<...>()` takes a type + if method != "call_argument" + && let Some(turbofish) = &method_call.turbofish + { + return Err(Error::new_spanned(turbofish, format!("`.{method}()` takes no type"))); + } + + let core_types = self.core_types; + let entry = &mut self.nodes[node]; + + // Each piece of state is set once, as each `#[graph(...)]` attribute is + let already_set = match method.as_str() { + "at" => entry.position.is_some(), + "layer" => entry.layer, + "hidden" => entry.hidden, + "locked" => entry.locked, + "pinned" => entry.pinned, + "named" => entry.display_name.is_some(), + "call_argument" => entry.call_argument.is_some(), + _ => false, + }; + if already_set { + return Err(Error::new_spanned(&method_call.method, format!("`.{method}()` is already set on this node"))); + } + + match method.as_str() { + "at" => { + let [x, y] = arguments.as_slice() else { + return Err(Error::new_spanned(method_call, "Give a position in grid units, like `.at(-50, 8)`")); + }; + entry.position = Some((grid_coordinate(x)?, grid_coordinate(y)?)); + } + "layer" => { + no_arguments(&arguments)?; + entry.layer = true; + } + "hidden" => { + no_arguments(&arguments)?; + entry.hidden = true; + } + "locked" => { + no_arguments(&arguments)?; + entry.locked = true; + } + "pinned" => { + no_arguments(&arguments)?; + entry.pinned = true; + } + "named" => { + let [Expr::Lit(syn::ExprLit { lit: Lit::Str(name), .. })] = arguments.as_slice() else { + return Err(Error::new_spanned(method_call, "Give a display name, like `.named(\"Candle spacing\")`")); + }; + entry.display_name = Some(name.clone()); + } + "call_argument" => { + no_arguments(&arguments)?; + let Some(turbofish) = &method_call.turbofish else { + return Err(Error::new_spanned(method_call, "Name the call argument's type, like `.call_argument::()`")); + }; + let [syn::GenericArgument::Type(ty)] = turbofish.args.iter().collect::>().as_slice() else { + return Err(Error::new_spanned(turbofish, "Name one call argument type, like `.call_argument::()`")); + }; + entry.call_argument = Some(type_tokens(ty, core_types)?); + } + _ => { + return Err(Error::new_spanned( + &method_call.method, + format!("Unknown node state `.{method}()`. Parameters go inside the call's parentheses, like `node({method} = ...)`"), + )); + } + } + + Ok(source) + } +} + +fn grid_coordinate(expression: &Expr) -> syn::Result { + let (negative, literal) = match expression { + Expr::Unary(syn::ExprUnary { op: UnOp::Neg(_), expr, .. }) => (true, &**expr), + other => (false, other), + }; + let Expr::Lit(syn::ExprLit { lit: Lit::Int(integer), .. }) = literal else { + return Err(Error::new_spanned(expression, "Positions are integers in grid units")); + }; + if !integer.suffix().is_empty() { + return Err(Error::new_spanned(integer, "Write the position without a type suffix")); + } + let magnitude: i32 = integer.base10_parse()?; + Ok(if negative { -magnitude } else { magnitude }) +} + +/// A number literal, possibly negative, as an `f64` expression. +fn number_literal(expression: &Expr) -> Option { + match expression { + Expr::Lit(syn::ExprLit { lit: Lit::Int(integer), .. }) if integer.suffix().is_empty() => { + let value = integer.base10_parse::().ok()?; + Some(quote!(#value)) + } + Expr::Lit(syn::ExprLit { lit: Lit::Float(float), .. }) => Some(quote!(#float)), + Expr::Unary(syn::ExprUnary { op: UnOp::Neg(_), expr, .. }) => number_literal(expr).map(|number| quote!(-#number)), + _ => None, + } +} + +fn source_tokens(source: &Feed, imports: &[Import], nodes: &[Node], core_types: &TokenStream2) -> TokenStream2 { + match source { + Feed::Node { node, output } => { + let output = match output { + // A misspelled output is reported at the name the author wrote + Some(output) => { + let module = &nodes[*node].module; + let struct_name = symbol_name(output, "Output"); + quote_spanned!(output.span()=> #module::#struct_name::INDEX) + } + None => quote!(0), + }; + quote!(#core_types::registry::GraphInputSource::Node { node: #node, output: #output }) + } + Feed::Import { index, ty } => { + let ty = ty.clone().unwrap_or_else(|| imports[*index].ty.clone()); + quote!(#core_types::registry::GraphInputSource::Import { index: #index, ty: #ty }) + } + Feed::Value { value, exposed } => { + let exposed = option_tokens(exposed.map(|exposed| quote!(#exposed))); + quote!(#core_types::registry::GraphInputSource::Value { value: #value, exposed: #exposed }) + } + // A string literal is the key itself, and anything else is an identifier, as for `#[scope(...)]` + Feed::Scope(key @ Expr::Lit(syn::ExprLit { lit: Lit::Str(_), .. })) => quote!(#core_types::registry::GraphInputSource::Scope(#key)), + Feed::Scope(key) => quote!(#core_types::registry::GraphInputSource::Scope(#key.as_static_str())), + Feed::NodePath => quote!(#core_types::registry::GraphInputSource::NodePath), + Feed::SourceId => quote!(#core_types::registry::GraphInputSource::SourceId), + } +} + +/// The index of the input a slot names, from the symbols in the called node's module. +fn input_index(module: &syn::Path, slot: &Slot, core_types: &TokenStream2) -> TokenStream2 { + match slot { + // A node's primary input is its first, since the inputs the compiler fills in follow the parameters + Slot::Primary => quote!(0), + Slot::Named(parameter) => { + let struct_name = symbol_name(parameter, "Input"); + quote_spanned! {parameter.span()=> + { + #[allow(unused_imports)] + use #core_types::NodeParameter as _; + #module::#struct_name::INDEX + } + } + } + } +} + +/// Compile-time checks that a node `>>` feeds has a primary input, and that no argument names that input too. +fn primary_input_checks(node: &Node, core_types: &TokenStream2) -> TokenStream2 { + if node.primary_span.is_none() { + return TokenStream2::new(); + } + + let module = &node.module; + let node_name = module.segments.last().map(|segment| segment.ident.to_string()).unwrap_or_default(); + let no_parameters = format!("`{node_name}` has no parameters, so `>>` has no input to feed"); + let has_primary = quote_spanned! {module.span()=> + const _: () = assert!(#module::PARAMETER_COUNT > 0, #no_parameters); + }; + + let primary = input_index(&node.module, &Slot::Primary, core_types); + let checks = node.inputs.iter().filter_map(|(slot, _)| { + let Slot::Named(parameter) = slot else { return None }; + let named = input_index(&node.module, slot, core_types); + let message = format!("`{parameter}` is the primary input, which `>>` already feeds, so it's set twice"); + Some(quote_spanned! {parameter.span()=> + const _: () = assert!(#named != #primary, #message); + }) + }); + quote!(#has_primary #(#checks)*) +} + +fn node_tokens(node: &Node, imports: &[Import], nodes: &[Node], core_types: &TokenStream2) -> TokenStream2 { + let Node { + module, + inputs, + position, + layer, + display_name, + hidden, + locked, + pinned, + call_argument, + .. + } = node; + + // A misspelled node or parameter is reported at the name the author wrote + let implementation = quote_spanned!(module.span()=> #core_types::registry::GraphNodeImplementation::from(#module::IDENTIFIER)); + let inputs = inputs.iter().map(|(slot, source)| { + let index = input_index(module, slot, core_types); + let source = source_tokens(source, imports, nodes, core_types); + quote!((#index, #source)) + }); + + let position = option_tokens(position.map(|(x, y)| quote!((#x, #y)))); + let display_name = option_tokens(display_name.as_ref().map(ToTokens::to_token_stream)); + let call_argument = option_tokens(call_argument.clone()); + + quote! { + #core_types::registry::GraphNodeMetadata { + implementation: #implementation, + inputs: ::std::vec![#(#inputs,)*], + position: #position, + layer: #layer, + display_name: #display_name, + hidden: #hidden, + locked: #locked, + pinned: #pinned, + call_argument: #call_argument, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::codegen::parameter_display_name; + + fn parse(function: ItemFn) -> syn::Result { + let attributes = parse_graph_attributes(quote!(category("Test"))).expect("the attributes should parse"); + Graph::parse(&function, attributes, "e!(core_types)) + } + + fn error_message(function: ItemFn) -> String { + match parse(function) { + Ok(_) => panic!("the graph should be rejected"), + Err(error) => error.to_string(), + } + } + + #[test] + fn reads_chains_named_arguments_shorthand_and_state() { + let graph = parse(syn::parse_quote! { + /// Outlines its content. + fn outlined(content: List, #[unit(" px")] width: Item) -> out!(out) { + let thickness = width >> multiply(multiplicand = 2).at(1, 2); + return content >> stroke(weight = thickness, width).hidden(); + } + }) + .expect("the graph should parse"); + + assert_eq!(graph.identifier, "Outlined"); + assert_eq!(graph.description, "Outlines its content."); + assert_eq!(graph.imports.iter().map(|import| parameter_display_name(&import.field)).collect::>(), ["Content", "Width"]); + assert_eq!(graph.nodes.len(), 2); + + let (multiply, stroke) = (&graph.nodes[0], &graph.nodes[1]); + assert_eq!(multiply.position, Some((1, 2))); + assert!(stroke.hidden); + assert!(matches!(&stroke.inputs[0], (Slot::Named(name), Feed::Node { node: 0, .. }) if name == "weight")); + assert!(matches!(&stroke.inputs[1], (Slot::Named(name), Feed::Import { index: 1, .. }) if name == "width")); + assert!(matches!(&stroke.inputs[2], (Slot::Primary, Feed::Import { index: 0, .. }))); + } + + #[test] + fn a_final_expression_gives_the_exports_as_return_does() { + for function in [ + syn::parse_quote! { + fn outlined(content: List) -> out!(out) { + return content >> stroke(weight = 2); + } + }, + syn::parse_quote! { + fn outlined(content: List) -> out!(out) { + content >> stroke(weight = 2) + } + }, + ] { + let graph = parse(function).expect("the graph should parse"); + assert_eq!(graph.nodes.len(), 1); + assert!(matches!(graph.export_sources.as_slice(), [Feed::Node { node: 0, .. }])); + } + } + + #[test] + fn rejects_exports_given_twice() { + let message = error_message(syn::parse_quote! { + fn twice(content: List) -> out!(out) { + return content >> stroke(); + content >> stroke() + } + }); + assert!(message.contains("exports once"), "{message}"); + } + + #[test] + fn rejects_a_parameter_set_twice() { + let message = error_message(syn::parse_quote! { + fn twice(content: List) -> out!(out) { + return content >> stroke(weight = 1, weight = 2); + } + }); + assert!(message.contains("already set"), "{message}"); + } + + #[test] + fn rejects_a_primary_input_fed_twice() { + let message = error_message(syn::parse_quote! { + fn twice(content: List) -> out!(out) { + let outline = stroke(); + let lower = content >> outline; + return content >> outline; + } + }); + assert!(message.contains("already fed"), "{message}"); + } + + #[test] + fn rejects_unknown_node_state() { + let message = error_message(syn::parse_quote! { + fn state(content: List) -> out!(out) { + return content >> stroke().weight(2); + } + }); + assert!(message.contains("Unknown node state"), "{message}"); + } + + #[test] + fn rejects_a_return_that_doesnt_match_the_exports() { + let message = error_message(syn::parse_quote! { + fn mismatch(content: List) -> out!(first, second) { + return content; + } + }); + assert!(message.contains("2 exports"), "{message}"); + } + + #[test] + fn rejects_an_export_straight_from_an_import() { + let message = error_message(syn::parse_quote! { + fn passthrough(content: List) -> out!(out) { + let alias = content; + return alias; + } + }); + assert!(message.contains("straight from an import"), "{message}"); + } + + #[test] + fn rejects_a_suffixed_integer() { + let message = error_message(syn::parse_quote! { + fn suffixed(content: List) -> out!(out) { + return content >> stroke(weight = -2_i64); + } + }); + assert!(message.contains("without a type suffix"), "{message}"); + } + + #[test] + fn rejects_type_arguments_it_would_drop() { + let list = error_message(syn::parse_quote! { + fn extra(content: List) -> out!(out) { + return content >> stroke(); + } + }); + assert!(list.contains("takes one element type"), "{list}"); + + let state = error_message(syn::parse_quote! { + fn extra(content: List) -> out!(out) { + return content >> stroke().hidden::(); + } + }); + assert!(state.contains("takes no type"), "{state}"); + } + + #[test] + fn rejects_repeated_attributes_and_a_zero_version() { + let attribute_error = |attributes: TokenStream2| match parse_graph_attributes(attributes) { + Ok(_) => panic!("the attributes should be rejected"), + Err(error) => error.to_string(), + }; + + let repeated = attribute_error(quote!(category("A"), category("B"))); + assert!(repeated.contains("Multiple 'category'"), "{repeated}"); + + let zero = attribute_error(quote!(category("A"), version(0))); + assert!(zero.contains("Versions start at 1"), "{zero}"); + } + + #[test] + fn rejects_signatures_a_graph_cant_have() { + let asynchronous = error_message(syn::parse_quote! { + async fn later(content: List) -> out!(out) { + return content >> stroke(); + } + }); + assert!(asynchronous.contains("can't be `async`"), "{asynchronous}"); + + let generic = error_message(syn::parse_quote! { + fn generic(content: List) -> out!(out) { + return content >> stroke(); + } + }); + assert!(generic.contains("doesn't declare generics"), "{generic}"); + } + + #[test] + fn rejects_proto_node_only_attributes_on_an_import() { + let message = error_message(syn::parse_quote! { + fn constant(#[constant] content: List) -> out!(out) { + return content >> stroke(); + } + }); + assert!(message.contains("Unknown import attribute `#[constant]`"), "{message}"); + } + + #[test] + fn reads_outputs_chosen_by_name() { + let graph = parse(syn::parse_quote! { + fn digits(text: Item) -> out!(first, runs, run_count) { + let found = regex_find(string = text).at(1, 0); + let runs = text >> regex_find().captures; + return (found.r#match, runs, found.captures >> count()); + } + }) + .expect("the graph should parse"); + + let chosen = |feed: &Feed| match feed { + Feed::Node { node, output } => (*node, output.as_ref().map(Ident::to_string)), + _ => panic!("the feed should be a node"), + }; + assert_eq!(chosen(&graph.export_sources[0]), (0, Some("r#match".into()))); + assert_eq!(chosen(&graph.export_sources[1]), (1, Some("captures".into()))); + assert_eq!(chosen(&graph.export_sources[2]), (2, None)); + + assert!(matches!(&graph.nodes[1].inputs[0], (Slot::Primary, Feed::Import { index: 0, .. }))); + assert_eq!(chosen(&graph.nodes[2].inputs[0].1), (0, Some("captures".into()))); + } + + #[test] + fn rejects_outputs_chosen_wrongly() { + let numbered = error_message(syn::parse_quote! { + fn numbered(text: Item) -> out!(out) { + return text >> regex_find().1; + } + }); + assert!(numbered.contains("by its name"), "{numbered}"); + + let twice = error_message(syn::parse_quote! { + fn twice(text: Item) -> out!(out) { + return text >> regex_find().captures.groups; + } + }); + assert!(twice.contains("already chosen"), "{twice}"); + + let import = error_message(syn::parse_quote! { + fn import(text: Item) -> out!(out) { + return text.length >> count(); + } + }); + assert!(import.contains("Only a node has outputs"), "{import}"); + + let state = error_message(syn::parse_quote! { + fn state(text: Item) -> out!(out) { + return text >> regex_find().captures.at(1, 2); + } + }); + assert!(state.contains("before the output it chooses"), "{state}"); + } + + #[test] + fn rejects_a_wire_that_makes_a_loop() { + let around = error_message(syn::parse_quote! { + fn looped(content: List) -> out!(out) { + let outline = stroke(); + let shadow = outline >> blur(); + return shadow >> outline; + } + }); + assert!(around.contains("makes a loop"), "{around}"); + + let itself = error_message(syn::parse_quote! { + fn looped(content: List) -> out!(out) { + let outline = stroke(); + return outline >> outline; + } + }); + assert!(itself.contains("makes a loop"), "{itself}"); + } + + #[test] + fn rejects_a_graph_that_contains_itself() { + let message = error_message(syn::parse_quote! { + fn outlined(content: List) -> out!(out) { + return content >> outlined(); + } + }); + assert!(message.contains("can't contain itself"), "{message}"); + } + + #[test] + fn rejects_state_set_twice() { + let message = error_message(syn::parse_quote! { + fn twice(content: List) -> out!(out) { + return content >> stroke().at(1, 2).at(3, 4); + } + }); + assert!(message.contains("`.at()` is already set"), "{message}"); + } + + #[test] + fn reads_state_after_a_parenthesized_call() { + let graph = parse(syn::parse_quote! { + fn grouped(content: List) -> out!(out) { + return content >> (stroke()).hidden(); + } + }) + .expect("the graph should parse"); + assert!(graph.nodes[0].hidden); + } + + #[test] + fn rejects_bindings_and_imports_that_arent_plain_names() { + let binding = error_message(syn::parse_quote! { + fn mutable(content: List) -> out!(out) { + let mut outline = content >> stroke(); + return outline; + } + }); + assert!(binding.contains("without `mut`"), "{binding}"); + + let diverging = error_message(syn::parse_quote! { + fn diverging(content: List) -> out!(out) { + let outline = content >> stroke() else { return }; + return outline; + } + }); + assert!(diverging.contains("no `else`"), "{diverging}"); + + let import = error_message(syn::parse_quote! { + fn mutable(mut content: List) -> out!(out) { + return content >> stroke(); + } + }); + assert!(import.contains("without `mut`"), "{import}"); + } + + #[test] + fn reads_an_unnamed_primary_import_that_takes_nothing() { + let graph = parse(syn::parse_quote! { + fn generated(_: (), seed: Item) -> out!(out) { + return random(seed); + } + }) + .expect("the graph should parse"); + assert_eq!(parameter_display_name(&graph.imports[0].field), ""); + + let named_elsewhere = error_message(syn::parse_quote! { + fn generated(content: List, _: ()) -> out!(out) { + return content >> stroke(); + } + }); + assert!(named_elsewhere.contains("Name each import"), "{named_elsewhere}"); + } + + #[test] + fn reads_generic_types_written_as_impl_any() { + let graph = parse(syn::parse_quote! { + fn generic(content: impl Any, items: List) -> out!(out) { + return content >> passthrough().call_argument::(); + } + }) + .expect("the graph should parse"); + assert!(graph.imports[0].ty.to_string().contains("generic")); + assert!(graph.imports[1].ty.to_string().contains("generic")); + + let named = error_message(syn::parse_quote! { + fn generic(content: T) -> out!(out) { + return content >> passthrough(); + } + }); + assert!(named.contains("written `impl Any`"), "{named}"); + + let other_trait = error_message(syn::parse_quote! { + fn generic(content: impl Clone) -> out!(out) { + return content >> passthrough(); + } + }); + assert!(other_trait.contains("written `impl Any`"), "{other_trait}"); + } + + #[test] + fn rejects_imports_that_arent_ranked() { + let unranked = error_message(syn::parse_quote! { + fn unranked(content: List, count: i64) -> out!(out) { + return content >> repeat(count); + } + }); + assert!(unranked.contains("`Item` or `List`"), "{unranked}"); + + let unit = error_message(syn::parse_quote! { + fn unit(content: List, nothing: ()) -> out!(out) { + return content >> stroke(); + } + }); + assert!(unit.contains("Only the primary import can be `()`"), "{unit}"); + } + + #[test] + fn rejects_values_the_macro_would_misread() { + let suffixed_position = error_message(syn::parse_quote! { + fn suffixed(content: List) -> out!(out) { + return content >> stroke().at(5_i32, 0); + } + }); + assert!(suffixed_position.contains("position without a type suffix"), "{suffixed_position}"); + + let alpha_in_rgb = error_message(syn::parse_quote! { + fn translucent(content: List) -> out!(out) { + return content >> fill(paint = rgb(0xE85D7580)); + } + }); + assert!(alpha_in_rgb.contains("six hex digits"), "{alpha_in_rgb}"); + + let type_default = error_message(syn::parse_quote! { + fn unpainted(content: List) -> out!(out) { + return content >> fill(paint = None); + } + }); + assert!(type_default.contains("Type defaults like `None`"), "{type_default}"); + } + + #[test] + fn reads_a_scope_named_by_a_node_identifier() { + let graph = parse(syn::parse_quote! { + fn scoped(content: List) -> out!(out) { + return content >> stroke(weight = scope(editor_api::IDENTIFIER)); + } + }) + .expect("the graph should parse"); + assert!(matches!(&graph.nodes[0].inputs[0], (Slot::Named(_), Feed::Scope(Expr::Path(_))))); + } + + #[test] + fn rejects_attributes_a_graph_would_drop() { + let message = error_message(syn::parse_quote! { + #[allow(dead_code)] + fn kept(content: List) -> out!(out) { + return content >> stroke(); + } + }); + assert!(message.contains("Only doc comments and `#[cfg(...)]`"), "{message}"); + + let export_names = error_message(syn::parse_quote! { + fn named(content: List) -> out!(#[name("A")] #[name("B")] out) { + return content >> stroke(); + } + }); + assert!(export_names.contains("Multiple 'name'"), "{export_names}"); + } + + #[test] + fn rejects_state_on_a_binding() { + let message = error_message(syn::parse_quote! { + fn state(content: List) -> out!(out) { + let outline = content >> stroke(); + return outline.hidden(); + } + }); + assert!(message.contains("not on a binding"), "{message}"); + } +} diff --git a/node-graph/node-macro/src/lib.rs b/node-graph/node-macro/src/lib.rs index b988d7d3af..1466bf70a9 100644 --- a/node-graph/node-macro/src/lib.rs +++ b/node-graph/node-macro/src/lib.rs @@ -5,6 +5,7 @@ mod codegen; mod crate_ident; mod derive_choice_type; mod destructure; +mod graph; mod parsing; mod validation; @@ -16,6 +17,38 @@ pub fn node(attr: TokenStream, item: TokenStream) -> TokenStream { parsing::new_node_fn(attr.into(), item.into()).unwrap_or_else(|err| err.to_compile_error()).into() } +/// Defines a node as a subgraph of other nodes, the way `#[node]` defines a proto node. +/// +/// The function's parameters are the subgraph's imports, parsed like a proto node's parameters, so they take the same +/// value and widget attributes. On an import, `#[hard]` bounds the widget without clamping a wired value. +/// `out!(...)` names its exports. The body binds nodes with `let`, wires them with `>>` (which feeds its left side +/// into the primary input of the node on its right), and ends with `return`, giving one value per export. Every +/// parameter is named in a call, and a bare name feeds the binding or import of that name to the parameter of the same +/// name. Node state goes in methods after the call, each written once: `.at(x, y)`, `.layer()`, `.hidden()`, `.locked()`, +/// `.pinned()`, `.named("…")`, and `.call_argument::()`. After those, an output's name like `.captures` wires from that +/// output of the node, which also works on a binding. +/// +/// ```ignore +/// /// Outlines its content. +/// #[node_macro::graph(category("Vector: Style"))] +/// pub fn outlined( +/// content: List, +/// /// Outline thickness. +/// #[unit(" px")] +/// width: Item, +/// ) -> out!( +/// /// The outlined content. +/// out, +/// ) { +/// return content >> stroke(weight = width).at(7, 0); +/// } +/// ``` +#[proc_macro_error] +#[proc_macro_attribute] +pub fn graph(attr: TokenStream, item: TokenStream) -> TokenStream { + graph::new_graph_fn(attr.into(), item.into()).unwrap_or_else(|err| err.to_compile_error()).into() +} + /// Derives `Destructure` for a struct returned by a multi-output node, making each of its `Item` or `List` fields an output connector. /// /// A node function returning such a struct (rather than an `Item` or `List`) becomes a multi-output node. The preprocessor diff --git a/node-graph/node-macro/src/parsing.rs b/node-graph/node-macro/src/parsing.rs index fd8aa03d68..39ed07a32f 100644 --- a/node-graph/node-macro/src/parsing.rs +++ b/node-graph/node-macro/src/parsing.rs @@ -137,6 +137,10 @@ pub struct ParsedField { pub progression: bool, pub constant: bool, pub is_data_field: bool, + /// The X and Y labels of a Vec2 widget, from `#[labels("W", "H")]`. + pub labels: Option<(LitStr, LitStr)>, + pub integer: bool, + pub blank_assist: bool, } impl ParsedField { @@ -170,6 +174,9 @@ impl ParsedField { progression: false, constant: false, is_data_field: false, + labels: None, + integer: false, + blank_assist: true, } } @@ -319,8 +326,8 @@ impl ToTokens for NumberBound { /// Unlike a Rust range there is no `..=` form, `..` is purely this attribute DSL's bounds operator. #[derive(Clone, Debug)] pub struct NumberRange { - start: Option, - end: Option, + pub(crate) start: Option, + pub(crate) end: Option, } impl Parse for NumberRange { @@ -819,7 +826,8 @@ fn parse_node_implementations(attr: &Attribute, name: &Ident) -> syn:: }) } -fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Result { +/// Parses a parameter and its attributes, for a proto node's field or a graph's import. +pub(crate) fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Result { let ident = &pat_ident.ident; // Checks for the #[data] attribute, indicating that this is a data field rather than an input parameter to the node. @@ -1004,6 +1012,22 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul }) .transpose()?; + // `#[labels("W", "H")]` names a Vec2 widget's two fields, and `#[integer]` makes a number or Vec2 widget take only integers + let labels = extract_attribute(attrs, "labels") + .map(|attr| { + let labels: Vec = attr.parse_args_with(Punctuated::::parse_terminated)?.into_iter().collect(); + let [x, y] = <[LitStr; 2]>::try_from(labels).map_err(|_| Error::new_spanned(attr, "Give a Vec2 widget two labels, like `#[labels(\"W\", \"H\")]`"))?; + Ok::<_, Error>((x, y)) + }) + .transpose()?; + let integer = extract_attribute(attrs, "integer").is_some(); + + // `#[blank_assist(false)]` drops the space a widget leaves for the assist area beside it + let blank_assist = extract_attribute(attrs, "blank_assist") + .map(|attr| attr.parse_args::().map(|enabled| enabled.value)) + .transpose()? + .unwrap_or(true); + let (is_node, node_input_type, node_output_type) = parse_node_type(&ty); let description = attrs .iter() @@ -1062,6 +1086,9 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul progression, constant, is_data_field, + labels, + integer, + blank_assist, }) } else { let implementations = extract_attribute(attrs, "implementations") @@ -1114,6 +1141,9 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul progression, constant, is_data_field, + labels, + integer, + blank_assist, }) } } @@ -1413,6 +1443,9 @@ mod tests { progression: false, constant: false, is_data_field: false, + labels: None, + integer: false, + blank_assist: true, }], body: TokenStream2::new(), description: String::from("Multi\nLine\n"), @@ -1475,6 +1508,9 @@ mod tests { progression: false, constant: false, is_data_field: false, + labels: None, + integer: false, + blank_assist: true, }, ParsedField { pat_ident: pat_ident("translate"), @@ -1499,6 +1535,9 @@ mod tests { progression: false, constant: false, is_data_field: false, + labels: None, + integer: false, + blank_assist: true, }, ], body: TokenStream2::new(), @@ -1562,6 +1601,9 @@ mod tests { progression: false, constant: false, is_data_field: false, + labels: None, + integer: false, + blank_assist: true, }], body: TokenStream2::new(), description: "Test\n".into(), @@ -1628,6 +1670,9 @@ mod tests { progression: false, constant: false, is_data_field: false, + labels: None, + integer: false, + blank_assist: true, }], body: TokenStream2::new(), description: String::new(), @@ -1697,6 +1742,9 @@ mod tests { progression: false, constant: false, is_data_field: false, + labels: None, + integer: false, + blank_assist: true, }], body: TokenStream2::new(), description: String::new(), @@ -1791,6 +1839,9 @@ mod tests { progression: false, constant: false, is_data_field: false, + labels: None, + integer: false, + blank_assist: true, }], body: TokenStream2::new(), description: String::new(), diff --git a/node-graph/node-macro/src/validation.rs b/node-graph/node-macro/src/validation.rs index 0cdab673a4..887f43dcb2 100644 --- a/node-graph/node-macro/src/validation.rs +++ b/node-graph/node-macro/src/validation.rs @@ -1,22 +1,22 @@ -use crate::parsing::{Implementation, NodeOutputTier, NodeParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, output_payload, output_tier}; +use crate::graph::VALUE_HELPERS; +use crate::parsing::{Implementation, NodeOutputTier, NodeParsedField, ParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, output_payload, output_tier}; use proc_macro_error3::{abort_if_dirty, emit_error}; use quote::quote; use syn::spanned::Spanned; -use syn::{GenericParam, Type}; +use syn::{GenericParam, Ident, Type}; pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> { let validators: &[fn(&ParsedNodeFn)] = &[ // Add more validators here as needed validate_implementations_for_generics, validate_implementations_row_counts, - validate_primary_input_expose, - validate_min_max, - validate_range_slider_bounds, + |parsed| validate_parameters(&parsed.fields), validate_no_item_parameters, validate_element_wise, validate_ranked_inputs, validate_async, validate_non_parameters_trail, + |parsed| validate_name_isnt_a_value_helper(&parsed.fn_name), ]; for validator in validators { @@ -28,6 +28,20 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> { Ok(()) } +/// A graph body reads a call to a value helper like `rgb(...)` as a value, so a node or graph of that name couldn't be called there. +pub(crate) fn validate_name_isnt_a_value_helper(name: &Ident) { + if let Some(message) = value_helper_name_violation(name) { + emit_error!(name.span(), "{}", message); + } +} + +fn value_helper_name_violation(name: &Ident) -> Option { + let name = name.to_string(); + VALUE_HELPERS + .contains(&name.as_str()) + .then(|| format!("A node can't be named `{name}`, since graphs use that name for a value helper")) +} + fn validate_no_item_parameters(parsed: &ParsedNodeFn) { if parsed.attributes.flags.skip_impl { return; @@ -291,8 +305,15 @@ fn is_unit_type(ty: &Type) -> bool { matches!(ty, Type::Tuple(tuple) if tuple.elems.is_empty()) } -fn validate_min_max(parsed: &ParsedNodeFn) { - for field in &parsed.fields { +/// The checks on a node's parameters, shared by proto node fields and graph imports, where the first is the primary input. +pub(crate) fn validate_parameters(fields: &[ParsedField]) { + validate_primary_input_expose(fields); + validate_min_max(fields); + validate_range_slider_bounds(fields); +} + +fn validate_min_max(fields: &[ParsedField]) { + for field in fields { if let Some(RegularParsedField { number_hard_max, number_hard_min, @@ -351,8 +372,8 @@ fn validate_min_max(parsed: &ParsedNodeFn) { /// A `#[range]` slider needs a defined extent on both ends. The extent comes from `#[soft]` when present, /// otherwise it falls back to `#[hard]`, so each end must be covered by at least one of the two attributes. -fn validate_range_slider_bounds(parsed: &ParsedNodeFn) { - for field in &parsed.fields { +fn validate_range_slider_bounds(fields: &[ParsedField]) { + for field in fields { if let Some(RegularParsedField { number_mode_range: true, number_soft_min, @@ -384,8 +405,8 @@ fn validate_range_slider_bounds(parsed: &ParsedNodeFn) { } } -fn validate_primary_input_expose(parsed: &ParsedNodeFn) { - if let Some(field) = parsed.fields.first() +fn validate_primary_input_expose(fields: &[ParsedField]) { + if let Some(field) = fields.first() && let Some(RegularParsedField { exposed: true, .. }) = field.ty.regular() { let pat_ident = &field.pat_ident; @@ -394,7 +415,7 @@ fn validate_primary_input_expose(parsed: &ParsedNodeFn) { "Unnecessary #[expose] attribute on primary input `{}`. Primary inputs are always exposed.", pat_ident.ident; help = "You can safely remove the #[expose] attribute from this field."; - note = "The function's second argument, `{}`, is the node's primary input and it's always exposed by default", pat_ident.ident + note = "`{}` is the node's primary input, which is always exposed by default", pat_ident.ident ); } } @@ -462,7 +483,7 @@ fn validate_async(parsed: &ParsedNodeFn) { } /// The arguments that aren't parameters, which are `#[data]` state and the inputs the compiler fills in, go after the parameters. -/// That keeps the primary input at index 0, where the editor's chain flow and other nodes feeding the primary input expect it. +/// That keeps the primary input at index 0, where the editor's chain flow and a graph's `>>` expect it. fn validate_non_parameters_trail(parsed: &ParsedNodeFn) { if let Some((span, message)) = non_parameter_order_violation(parsed) { emit_error!(span, "{}", message); @@ -475,7 +496,7 @@ fn non_parameter_order_violation(parsed: &ParsedNodeFn) -> Option<(proc_macro2:: let (parameter, non_parameter) = (¶meter.pat_ident, &non_parameter.pat_ident.ident); let message = format!( - "The parameter `{}` comes after `{non_parameter}`, which isn't a parameter. Move `{non_parameter}` after the parameters: `#[data]` state and the inputs the compiler fills in (`#[scope]`, `#[source_id]`, and `#[node_path]`) go last, so the primary input is always the node's first input, which is the one the editor's chain flow feeds.", + "The parameter `{}` comes after `{non_parameter}`, which isn't a parameter. Move `{non_parameter}` after the parameters: `#[data]` state and the inputs the compiler fills in (`#[scope]`, `#[source_id]`, and `#[node_path]`) go last, so the primary input is always the node's first input, which is the one the editor's chain flow and a graph's `>>` feed.", parameter.ident ); Some((parameter.span(), message)) @@ -727,6 +748,25 @@ mod tests { assert_eq!(only_non_parameters, None); } + #[test] + fn a_node_named_like_a_value_helper_is_rejected() { + let named = |input: TokenStream| value_helper_name_violation(&parse_node_fn(quote::quote!(category("Test")), input).expect("The test node fn should parse").fn_name); + + let message = named(quote::quote!( + fn rgb(_: impl Ctx, value: Item) -> Item { + value + } + )); + assert!(message.is_some_and(|message| message.contains("can't be named `rgb`"))); + + let other = named(quote::quote!( + fn tint(_: impl Ctx, value: Item) -> Item { + value + } + )); + assert_eq!(other, None); + } + fn row_count_violations(input: TokenStream) -> Vec { let parsed = parse_node_fn(quote::quote!(category("Test")), input).expect("The test node fn should parse"); implementations_row_count_violations(&parsed).into_iter().map(|(_, message)| message).collect() diff --git a/node-graph/nodes/gstd/src/lib.rs b/node-graph/nodes/gstd/src/lib.rs index 07a342bd95..2a319dc9a2 100644 --- a/node-graph/nodes/gstd/src/lib.rs +++ b/node-graph/nodes/gstd/src/lib.rs @@ -5,6 +5,7 @@ pub mod render_background; pub mod render_cache; pub mod render_node; pub mod render_pixel_preview; +pub mod subgraphs; pub mod text; pub use blending_nodes; pub use brush_nodes as brush; diff --git a/node-graph/nodes/gstd/src/subgraphs.rs b/node-graph/nodes/gstd/src/subgraphs.rs new file mode 100644 index 0000000000..ad024acceb --- /dev/null +++ b/node-graph/nodes/gstd/src/subgraphs.rs @@ -0,0 +1,218 @@ +use crate::artboard::create_artboard; +use crate::context::{read_index, read_vector}; +use crate::graphic::{as_graphic, extend, flatten_vector, into_group, item_at_index, map, remove_at_index}; +use crate::platform_application_io::{bytes_to_image, load_resource}; +use crate::vector::misc::InterpolationDistribution; +use crate::vector::{as_vector, combine_paths, count, morph, path_is_closed, points_to_polyline, separate_paths}; +use crate::{Artboard, Color, Graphic, Vector}; +use glam::DVec2; +use math_nodes::{add, as_number, divide, floor, max, modulo, multiply, subtract, switch}; +use repeat_nodes::repeat; +use transform_nodes::{decompose_translation, extract_transform}; + +/// Merges the provided content as a new item in the layer's compositing stack. +#[node_macro::graph(category("Graphic"), icon("NodeMerge"), layer)] +pub fn merge( + /// The stack of layers below this one, which the content is placed above. + base: List, + /// The artwork this layer adds to the stack as a single item. + #[expose] + content: List, +) -> out!( + /// The stack of layers with this layer's content placed on top. + out, +) { + let grouped = content >> into_group().at(-7, -1); + base >> as_graphic().at(-7, -2) >> extend(new = grouped).at(0, -2) +} + +/// Creates a new Artboard which can be used as a working surface. +#[node_macro::graph(category("Graphic"), icon("NodeArtboard"), layer)] +pub fn artboard( + /// The stack of artboards below this one, which this artboard is placed above. + base: List, + /// Graphics to include within the artboard. + #[expose] + content: List, + /// Coordinate of the top-left corner of the artboard within the document. + #[labels("X", "Y")] + #[unit(" px")] + #[integer] + location: Item, + /// Width and height of the artboard within the document. + #[labels("W", "H")] + #[unit(" px")] + #[integer] + #[default(1920., 1080.)] + dimensions: Item, + /// Color of the artboard background. + #[widget(ParsedWidgetOverride::Custom = "artboard_background")] + #[default(Color::WHITE)] + background: Item, + /// Whether to cut off the contained content that extends outside the artboard, or keep it visible. + #[default(true)] + clip: Item, +) -> out!( + /// The stack of artboards with this artboard placed on top. + out, +) { + let board = create_artboard(content, location, dimensions, background, clip).at(-7, -3); + base >> extend(new = board).at(0, -4) +} + +/// Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path. +#[node_macro::graph(category("Vector: Deform"), icon("NodeBlend"))] +pub fn blend( + /// The vector objects to create intermediate shapes between. + content: List, + /// The number of shapes spanning from the first object to the last, repeated for each subpath of the control path. + #[default(10)] + count: Item, + /// Flip the stacking order of the shapes, so the ones nearest the first object are on top. + reverse: Item, + /// What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced. + distribution: Item, + /// An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight. + path: Item, +) -> out!( + /// The blended shapes, from the first object to the last. + out, +) { + // Each clamps to at least 1, which also covers an empty control path + let shapes_per_path = count >> as_number().at(2, 13) >> max(other_value = 1).at(9, 13); + let path_count = path >> separate_paths().at(2, 0) >> count().at(2, 2) >> max(other_value = 1).at(9, 2); + + // Split the repetition index into which subpath it's on and where along that subpath + let index = read_index().at(2, 7); + let path_index = index >> divide(denominator = shapes_per_path).at(16, 10) >> floor().at(23, 4); + let local_index = index >> modulo(modulus = shapes_per_path).at(16, 7); + + // A closed subpath spaces its shapes by the count, and an open one by one fewer (at least 1) so its last shape lands on the end + let open_spacing = shapes_per_path >> subtract(subtrahend = 1).at(16, 14) >> max(other_value = 1).at(23, 14); + let spacing = path >> path_is_closed(index = path_index).at(30, 2) >> switch(if_true = shapes_per_path, if_false = open_spacing).at(30, 12); + + // Scaling just below 1 keeps the last shape from overflowing into the next subpath + let fraction = local_index >> divide(denominator = spacing).at(23, 7) >> multiply(multiplicand = 0.9999999999).at(30, 7); + let progression = path_index >> add(addend = fraction).at(37, 4); + + let total = shapes_per_path >> multiply(multiplicand = path_count).at(16, 1); + content >> morph(progression, distribution, path).at(44, 3) >> repeat(count = total, reverse).at(51, 0) +} + +/// Connects the origins of vector objects in order with an open polyline, such as to make a control path for the **Blend** and **Morph** nodes. +#[node_macro::graph(category("Vector: Path"), icon("NodeOriginsToPolyline"), name("Origins to Polyline"))] +pub fn origins_to_polyline( + /// The vector objects to connect in order by their origins. + vector: List, +) -> out!( + /// An open polyline with an anchor point at the origin of each object. + vector, +) { + // Each object's origin, read from the item being mapped, as a single-anchor vector + let origin = read_vector().at(0, 1) >> extract_transform().at(7, 1) >> decompose_translation().at(14, 1) >> as_vector().at(21, 1); + + vector >> flatten_vector().at(21, 0) >> map(mapped = origin).at(28, 0) >> combine_paths().at(35, 0) >> points_to_polyline(closed = false).at(42, 0) +} + +/// Loads an image from a given URL. +#[node_macro::graph(category("Data: I/O"), icon("NodeLoadImage"))] +pub fn load_image( + _: (), + /// The web address or local asset path of the image to load. + #[name("URL")] + url: Item, +) -> out!( + /// The loaded image. + image, +) { + load_resource(url).at(0, 0) >> bytes_to_image().at(7, 0) +} + +/// Finds a portion of the string matching a regular expression pattern. With "Match Index" at its default 0, it selects the first non-overlapping occurrence, but others may be selected. Capture groups, if any, are produced as a list in the "Captures" output. +#[node_macro::graph(category("String: Regex"), icon("NodeRegexFind"))] +pub fn regex_find( + /// The string to search within. + string: Item, + /// The regular expression pattern to search for. + pattern: Item, + /// Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match. + match_index: Item, + /// Match letters regardless of case. + case_insensitive: Item, + /// Make `^` and `$` match the start and end of each line, not just the whole string. + multiline: Item, +) -> out!( + /// The whole portion of the string matching the pattern, or empty if there is no match. + r#match, + /// The text matched by each capture group in the pattern, in order. + captures, +) { + // The whole match, then each capture group, where each item carries `start`, `end`, and `name` attributes + let found = string >> text_nodes::regex::regex_find(pattern, match_index, case_insensitive, multiline).at(0, 0); + + let whole_match = found >> item_at_index(index = 0).at(8, 0); + let capture_groups = found >> remove_at_index(index = 0).at(8, 2); + + (whole_match, capture_groups) +} + +#[cfg(test)] +mod tests { + use super::*; + use core_types::registry::GraphInputSource; + + /// Finds the capture groups of a pattern. + #[node_macro::graph(category("Test"))] + fn regex_captures(string: Item, pattern: Item) -> out!(captures) { + return string >> regex_find(pattern).captures; + } + + #[test] + fn an_output_chosen_by_name_wires_from_that_output() { + let graph = _regex_captures_graph_metadata(); + assert!(matches!(graph.exports[0].source, GraphInputSource::Node { node: 0, output: 1 })); + } + + /// Puts its content on a board, setting every piece of node state. + #[node_macro::graph(category("Test"))] + fn boarded(content: List) -> out!(out) { + return create_artboard(content, background = rgb(0x102030), clip = exposed(false)) + .named("Board") + .hidden() + .locked() + .pinned() + .layer() + .call_argument::() + .at(3, -4); + } + + #[test] + fn node_state_and_values_reach_the_metadata() { + use core_types::NodeParameter; + use core_types::registry::GraphValue; + + let graph = _boarded_graph_metadata(); + let node = &graph.nodes[0]; + assert_eq!(node.display_name, Some("Board")); + assert!(node.hidden && node.locked && node.pinned && node.layer); + assert_eq!(node.position, Some((3, -4))); + assert!(matches!(node.call_argument, Some(core_types::Type::Generic(_)))); + + let source = |index: usize| &node.inputs.iter().find(|(input_index, _)| *input_index == index).expect("the input should be set").1; + assert!(matches!(source(create_artboard::ContentInput::INDEX), GraphInputSource::Import { index: 0, .. })); + assert!(matches!( + source(create_artboard::BackgroundInput::INDEX), + GraphInputSource::Value { + value: GraphValue::Color(_), + exposed: None + } + )); + assert!(matches!( + source(create_artboard::ClipInput::INDEX), + GraphInputSource::Value { + value: GraphValue::Bool(false), + exposed: Some(true) + } + )); + } +} diff --git a/node-graph/preprocessor/src/lib.rs b/node-graph/preprocessor/src/lib.rs index 3622d65394..4a81108d8c 100644 --- a/node-graph/preprocessor/src/lib.rs +++ b/node-graph/preprocessor/src/lib.rs @@ -416,7 +416,8 @@ pub fn node_inputs(fields: &[registry::FieldMetadata], first_node_io: &NodeIOTyp return NodeInput::value(TaggedValue::None, true); }; let ty = ty.clone().normalize_rank(); - let exposed = if index == 0 { ty != fn_type!(Context, ()) } else { field.exposed }; + // A `()` primary has nothing to connect, whether it's a proto node's lazy input or a graph's import + let exposed = if index == 0 { ty != fn_type!(Context, ()) && ty != concrete!(()) } else { field.exposed }; match &field.value_source { RegistryValueSource::None => {} @@ -543,7 +544,7 @@ mod destructure_tests { fn vec2_to_numbers_network() -> NodeNetwork { let vec2_to_numbers = DocumentNode { inputs: vec![NodeInput::value(TaggedValue::DVec2(DVec2::new(3., 5.)), false)], - implementation: DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER), + implementation: DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER), ..Default::default() }; multi_output_into_add_network(vec2_to_numbers, [1, 2]) @@ -561,7 +562,7 @@ mod destructure_tests { #[test] fn multi_output_node_expands_into_generated_destructure_network() { - let vec2_to_numbers_identifier = graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER; + let vec2_to_numbers_identifier = graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER; let destructure = registry::MULTI_OUTPUT_NODES .get(&vec2_to_numbers_identifier) .expect("Vec2 to Numbers should be registered as a multi-output node"); diff --git a/website/content/volunteer/guide/graphene/document-migrations.md b/website/content/volunteer/guide/graphene/document-migrations.md index 5d3f12bb43..0dd933a15a 100644 --- a/website/content/volunteer/guide/graphene/document-migrations.md +++ b/website/content/volunteer/guide/graphene/document-migrations.md @@ -219,7 +219,7 @@ Writing to any other node fails, since another anchor's run may be editing it. ### Network definitions -Some built-in nodes, like Merge and Artboard, are subgraphs. Each instance holds its own copy of a network defined in `document_node_definitions.rs`, and stores the definition's identifier and `version` next to it. Bump `version` on the `DocumentNodeDefinition` when instances saved before your change would load wrongly, and register a migration from the old version with the `network` prefix: +Some built-in nodes, like Merge and Artboard, are subgraphs. Each is defined by a `#[graph]` function in `node-graph/nodes/gstd/src/subgraphs.rs`, and instances store the definition's identifier and `version` next to their copy of its network. Bump the version with `#[graph(..., version(N))]` when instances saved before your change would load wrongly, and register a migration from the old version with the `network` prefix: ```rust rename!(network "Artboard"@1 => @2);