Compare commits

...
Author SHA1 Message Date
Dennis Kobert c54608c12d Refactor node graph macro 2026-11-30 17:51:01 +01:00
22 changed files with 2439 additions and 2138 deletions

No files matched your search

Generated
+13
View File
@@ -2534,6 +2534,18 @@ dependencies = [
"smallvec", "smallvec",
] ]
[[package]]
name = "graph-text"
version = "0.0.0"
dependencies = [
"convert_case 0.12.0",
"core-types",
"glam",
"log",
"proc-macro2",
"syn 3.0.9",
]
[[package]] [[package]]
name = "graphene-animation" name = "graphene-animation"
version = "0.0.0" version = "0.0.0"
@@ -2664,6 +2676,7 @@ dependencies = [
"futures", "futures",
"glam", "glam",
"graph-craft", "graph-craft",
"graph-text",
"graphene-application-io", "graphene-application-io",
"graphene-canvas-utils", "graphene-canvas-utils",
"graphene-core", "graphene-core",
+1
View File
@@ -93,6 +93,7 @@ graphene-application-io = { path = "node-graph/libraries/application-io" }
graphene-resource = { path = "node-graph/libraries/resources" } graphene-resource = { path = "node-graph/libraries/resources" }
graphene-animation = { path = "node-graph/libraries/animation" } graphene-animation = { path = "node-graph/libraries/animation" }
core-types = { path = "node-graph/libraries/core-types" } core-types = { path = "node-graph/libraries/core-types" }
graph-text = { path = "node-graph/libraries/graph-text" }
raster-types = { path = "node-graph/libraries/raster-types" } raster-types = { path = "node-graph/libraries/raster-types" }
vector-types = { path = "node-graph/libraries/vector-types" } vector-types = { path = "node-graph/libraries/vector-types" }
graphic-types = { path = "node-graph/libraries/graphic-types" } graphic-types = { path = "node-graph/libraries/graphic-types" }
@@ -53,11 +53,13 @@ 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. /// 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 = graphene_std::subgraphs::artboard::LocationInput::INDEX; pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = 2;
/// 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. /// 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 = graphene_std::subgraphs::artboard::DimensionsInput::INDEX; pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = 3;
/// Input position of the clip parameter on the "Artboard" layer template.
pub const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
/// Input position of the control path parameter on the "Blend" network node template. /// Input position of the control path parameter on the "Blend" network node template.
pub const BLEND_PATH_INPUT_INDEX: usize = graphene_std::subgraphs::blend::PathInput::INDEX; pub const BLEND_PATH_INPUT_INDEX: usize = 4;
/// The key used to access definitions for a network node or proto node. /// The key used to access definitions for a network node or proto node.
/// For proto nodes, this is their [`ProtoNodeIdentifier`]. /// For proto nodes, this is their [`ProtoNodeIdentifier`].
@@ -986,18 +988,29 @@ mod test {
use crate::test_utils::test_prelude::*; use crate::test_utils::test_prelude::*;
use graph_craft::document::NodeId; 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 // A graph text node with an inner node that has no definition is left out of the catalog with only a logged error
#[test] #[test]
fn every_registered_graph_has_a_definition() { fn every_registered_graph_has_a_definition() {
// Released before resolving, since building the catalog locks the registry too let sources = graphene_std::registry::GRAPH_SOURCES.lock().unwrap().len();
let identifiers: Vec<&str> = graphene_std::registry::GRAPH_METADATA.lock().unwrap().iter().map(|graph| graph.identifier).collect(); let graphs = &*graphene_std::graph_text::GRAPHS;
assert!(!identifiers.is_empty(), "the `#[graph]` nodes in `graphene_std::subgraphs` should be registered"); assert!(!graphs.is_empty(), "the graphs in `graphene_std` should be registered");
assert_eq!(graphs.len(), sources, "every registered graph should resolve");
for identifier in identifiers { for graph in graphs {
assert!(resolve_network_node_type(identifier).is_some(), "the '{identifier}' graph should have a definition"); assert!(resolve_network_node_type(graph.identifier).is_some(), "the '{}' graph should have a definition", graph.identifier);
} }
} }
#[test]
fn input_index_constants_match_the_graphs() {
use graphene_std::graph_text::import_index;
assert_eq!(import_index("Artboard", "location"), Some(super::ARTBOARD_LOCATION_INPUT_INDEX));
assert_eq!(import_index("Artboard", "dimensions"), Some(super::ARTBOARD_DIMENSIONS_INPUT_INDEX));
assert_eq!(import_index("Artboard", "clip"), Some(super::ARTBOARD_CLIP_INPUT_INDEX));
assert_eq!(import_index("Blend", "path"), Some(super::BLEND_PATH_INPUT_INDEX));
}
#[test] #[test]
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() { fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
use glam::{DAffine2, UVec2}; use glam::{DAffine2, UVec2};
@@ -93,8 +93,7 @@ pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNode
); );
} }
let graphs = GRAPH_METADATA.lock().unwrap().clone(); add_graph_definitions(graph_text::GRAPHS.clone(), &mut definitions_map);
add_graph_definitions(graphs, &mut definitions_map);
definitions_map definitions_map
} }
@@ -116,7 +115,7 @@ fn input_metadata(fields: &[FieldMetadata]) -> Vec<InputMetadata> {
.collect() .collect()
} }
/// Why a `#[graph]` node has no definition yet, or can't have one. /// Why a graph text node has no definition yet, or can't have one.
enum GraphDefinitionError { enum GraphDefinitionError {
/// A node inside it has no definition, which may be another graph not yet added. /// A node inside it has no definition, which may be another graph not yet added.
MissingNode(String), MissingNode(String),
@@ -124,7 +123,7 @@ enum GraphDefinitionError {
Invalid(String), Invalid(String),
} }
/// Adds the nodes defined as subgraphs by `#[graph]`, each once the definitions of the nodes inside it exist. /// Adds the nodes defined as subgraphs in graph text, each once the definitions of the nodes inside it exist.
fn add_graph_definitions(graphs: Vec<GraphMetadata>, definitions_map: &mut HashMap<DefinitionIdentifier, DocumentNodeDefinition>) { fn add_graph_definitions(graphs: Vec<GraphMetadata>, definitions_map: &mut HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
// Every graph sharing an identifier is left out, so the catalog doesn't depend on registration order // Every graph sharing an identifier is left out, so the catalog doesn't depend on registration order
let mut identifier_counts = HashMap::new(); let mut identifier_counts = HashMap::new();
@@ -207,7 +206,7 @@ fn prepare_network_definition(mut network_node: DocumentNodeDefinition, definiti
network_node network_node
} }
/// Builds the catalog definition of a node defined as a subgraph by `#[graph]`. /// Builds the catalog definition of a node defined as a subgraph in graph text.
fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> Result<DocumentNodeDefinition, GraphDefinitionError> { fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> Result<DocumentNodeDefinition, GraphDefinitionError> {
let mut nodes = HashMap::new(); let mut nodes = HashMap::new();
for (index, node) in graph.nodes.iter().enumerate() { for (index, node) in graph.nodes.iter().enumerate() {
@@ -221,9 +220,6 @@ fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionI
}; };
let mut template = definition.default_node_template(); 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.visible = !node.hidden;
template.locked = node.locked; template.locked = node.locked;
template.pinned = node.pinned; template.pinned = node.pinned;
@@ -231,7 +227,7 @@ fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionI
template.display_name = display_name.to_string(); template.display_name = display_name.to_string();
} }
let position = node.position.map_or(IVec2::ZERO, |(x, y)| IVec2::new(x, y)); let position = IVec2::from(node.position);
template.node_type_metadata = if node.layer { template.node_type_metadata = if node.layer {
NodeTypePersistentMetadata::layer(position) NodeTypePersistentMetadata::layer(position)
} else { } else {
@@ -243,14 +239,14 @@ fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionI
return Err(GraphDefinitionError::Invalid(format!("its node {index}, '{name}', has no input {input_index} for it to set"))); 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 // An input the compiler fills in can't be set
if matches!(input, NodeInput::Scope(_) | NodeInput::Reflection(_)) { if matches!(input, NodeInput::Scope(_) | NodeInput::Reflection(_)) {
return Err(GraphDefinitionError::Invalid(format!( return Err(GraphDefinitionError::Invalid(format!(
"it sets input {input_index} of its node {index}, '{name}', which the compiler fills in" "it sets input {input_index} of its node {index}, '{name}', which the compiler fills in"
))); )));
} }
*input = graph_input(source, input); *input = graph_input(source, input).map_err(|reason| GraphDefinitionError::Invalid(format!("input {input_index} of its node {index}, '{name}', is invalid: {reason}")))?;
} }
nodes.insert(NodeId(index as u64), template); nodes.insert(NodeId(index as u64), template);
@@ -259,7 +255,12 @@ fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionI
// Each import starts from its `#[default(...)]` or else its type, as a proto node's parameter does // 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 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(); let exports = graph
.exports
.iter()
.map(|export| graph_input(&export.source, &NodeInput::value(TaggedValue::None, false)))
.collect::<Result<_, _>>()
.map_err(GraphDefinitionError::Invalid)?;
Ok(DocumentNodeDefinition { Ok(DocumentNodeDefinition {
identifier: graph.identifier, identifier: graph.identifier,
@@ -285,41 +286,39 @@ fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionI
} }
/// The input a graph definition writes, where `default` is what the node's own definition starts that input with. /// 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 { /// A value must have the type of that default, if it has one.
match source { fn graph_input(source: &GraphInputSource, default: &NodeInput) -> Result<NodeInput, String> {
Ok(match source {
GraphInputSource::Node { node, output } => NodeInput::node(NodeId(*node as u64), *output), GraphInputSource::Node { node, output } => NodeInput::node(NodeId(*node as u64), *output),
GraphInputSource::Import { index, ty } => NodeInput::import(ty.clone(), *index), GraphInputSource::Import { index, ty } => NodeInput::import(ty.clone(), *index),
GraphInputSource::Value { value, exposed } => { GraphInputSource::Value { value, exposed } => {
let ty = match default { let value = graph_value(value);
NodeInput::Value { tagged_value, .. } => tagged_value.ty(), if let NodeInput::Value { tagged_value, .. } = default
NodeInput::Import { import_type, .. } => import_type.clone(), && **tagged_value != TaggedValue::None
_ => generic!(T), && element_type(&tagged_value.ty()) != element_type(&value.ty())
}; {
NodeInput::value(graph_value(value, &ty), exposed.unwrap_or(default.is_exposed())) return Err(format!("its value `{value:?}` doesn't have the input's type, `{:?}`", tagged_value.ty()));
}
NodeInput::value(value, exposed.unwrap_or(default.is_exposed()))
} }
GraphInputSource::Scope(key) => NodeInput::scope(*key), GraphInputSource::Scope(key) => NodeInput::scope(*key),
GraphInputSource::NodePath => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath), GraphInputSource::NodePath => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath),
GraphInputSource::SourceId => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId), 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. /// The type of the elements a wire of this type carries, past any `Item`, `List`, or lazy wrapping.
fn element_type(ty: &Type) -> &Type { fn element_type(ty: &Type) -> Type {
let mut element = ty; let mut element = ty;
while let Type::Item(inner) | Type::List(inner) | Type::Fn(_, inner) = element { while let Type::Item(inner) | Type::List(inner) | Type::Fn(_, inner) = element {
element = inner; element = inner;
} }
element element.clone()
} }
/// Converts a value written in a graph definition to the type of the input it feeds. fn graph_value(value: &GraphValue) -> TaggedValue {
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 { match value {
GraphValue::Integer(integer) if is_integer => TaggedValue::Integer(*integer), GraphValue::Integer(integer) => TaggedValue::Integer(*integer),
GraphValue::Integer(integer) => TaggedValue::Number(*integer as f64),
GraphValue::Number(number) => TaggedValue::Number(*number), GraphValue::Number(number) => TaggedValue::Number(*number),
GraphValue::Bool(boolean) => TaggedValue::Bool(*boolean), GraphValue::Bool(boolean) => TaggedValue::Bool(*boolean),
GraphValue::String(string) => TaggedValue::String(string.clone()), GraphValue::String(string) => TaggedValue::String(string.clone()),
@@ -364,6 +363,7 @@ mod tests {
fn number_import() -> FieldMetadata { fn number_import() -> FieldMetadata {
FieldMetadata { FieldMetadata {
name: "Value", name: "Value",
identifier: "value",
description: "", description: "",
internal: false, internal: false,
exposed: true, exposed: true,
@@ -392,6 +392,7 @@ mod tests {
fn one_node_graph(identifier: &'static str, implementation: GraphNodeImplementation, inputs: Vec<(usize, GraphInputSource)>) -> GraphMetadata { fn one_node_graph(identifier: &'static str, implementation: GraphNodeImplementation, inputs: Vec<(usize, GraphInputSource)>) -> GraphMetadata {
GraphMetadata { GraphMetadata {
identifier, identifier,
path: identifier,
category: "Test", category: "Test",
icon: None, icon: None,
description: "", description: "",
@@ -400,19 +401,19 @@ mod tests {
imports: vec![number_import()], imports: vec![number_import()],
exports: vec![GraphExportMetadata { exports: vec![GraphExportMetadata {
name: "Out", name: "Out",
identifier: "out",
description: "", description: "",
source: GraphInputSource::Node { node: 0, output: 0 }, source: GraphInputSource::Node { node: 0, output: 0 },
}], }],
nodes: vec![GraphNodeMetadata { nodes: vec![GraphNodeMetadata {
implementation, implementation,
inputs, inputs,
position: None, position: (0, 0),
layer: false, layer: false,
display_name: None, display_name: None,
hidden: false, hidden: false,
locked: false, locked: false,
pinned: false, pinned: false,
call_argument: None,
}], }],
} }
} }
@@ -436,7 +437,7 @@ mod tests {
#[test] #[test]
fn a_graph_resolves_when_registered_before_a_graph_inside_it() { 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 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 inner = one_node_graph("Test Inner", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
let mut definitions_map = proto_definitions(); let mut definitions_map = proto_definitions();
add_graph_definitions(vec![outer, inner], &mut definitions_map); add_graph_definitions(vec![outer, inner], &mut definitions_map);
@@ -455,7 +456,7 @@ mod tests {
exposed: None, exposed: None,
}, },
)); ));
let graph = one_node_graph("Test Missing Input", math_nodes::as_number::IDENTIFIER.into(), inputs); let graph = one_node_graph("Test Missing Input", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), inputs);
let mut definitions_map = proto_definitions(); let mut definitions_map = proto_definitions();
add_graph_definitions(vec![graph], &mut definitions_map); add_graph_definitions(vec![graph], &mut definitions_map);
@@ -465,8 +466,8 @@ mod tests {
#[test] #[test]
fn graphs_sharing_an_identifier_and_graphs_built_on_them_are_left_out() { 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 first = one_node_graph("Test Twin", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
let second = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import()); let second = one_node_graph("Test Twin", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
let dependent = one_node_graph("Test Dependent", GraphNodeImplementation::Graph("Test Twin"), from_import()); let dependent = one_node_graph("Test Dependent", GraphNodeImplementation::Graph("Test Twin"), from_import());
let mut definitions_map = proto_definitions(); let mut definitions_map = proto_definitions();
@@ -477,12 +478,12 @@ mod tests {
} }
#[test] #[test]
fn an_integer_value_takes_the_type_of_the_input_it_feeds() { fn a_value_must_have_the_type_of_the_input_it_feeds() {
let integer = Type::Item(Box::new(concrete!(i64))); let number_input = NodeInput::value(TaggedValue::Number(0.), false);
let number = Type::Item(Box::new(concrete!(f64))); let value = |value| GraphInputSource::Value { value, exposed: None };
assert!(matches!(graph_value(&GraphValue::Integer(3), &integer), TaggedValue::Integer(3))); assert!(graph_input(&value(GraphValue::Integer(3)), &number_input).is_err());
assert!(matches!(graph_value(&GraphValue::Integer(3), &number), TaggedValue::Number(value) if value == 3.)); assert!(matches!(graph_input(&value(GraphValue::Number(3.)), &number_input), Ok(NodeInput::Value { .. })));
} }
#[test] #[test]
@@ -497,7 +498,7 @@ mod tests {
}; };
let graph = GraphMetadata { let graph = GraphMetadata {
imports: vec![unit_primary, with_default], imports: vec![unit_primary, with_default],
..one_node_graph("Test Defaults", math_nodes::as_number::IDENTIFIER.into(), from_import()) ..one_node_graph("Test Defaults", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import())
}; };
let mut definitions_map = proto_definitions(); let mut definitions_map = proto_definitions();
@@ -519,7 +520,7 @@ mod tests {
let artboard = resolve_document_node_type(&DefinitionIdentifier::Network("Artboard".into())).expect("Artboard should exist"); 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(), &[]); document.network_interface.insert_node(node_id, artboard.default_node_template(), &[]);
let location = graphene_std::subgraphs::artboard::LocationInput::INDEX; let location = graphene_std::graph_text::import_index("Artboard", "location").expect("Artboard should have a location import");
let field = document let field = document
.network_interface .network_interface
.field_metadata(&node_id, location, &[]) .field_metadata(&node_id, location, &[])
@@ -1,4 +1,5 @@
use super::*; use super::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::ARTBOARD_CLIP_INPUT_INDEX;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
impl NodeNetworkInterface { impl NodeNetworkInterface {
@@ -831,7 +832,7 @@ impl NodeNetworkInterface {
self.field_metadata(node_id, index, network_path).is_some_and(|field| field.internal) self.field_metadata(node_id, index, network_path).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. /// The metadata the node macro records for a proto node's parameter, or graph text describes 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. /// 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<graphene_std::registry::FieldMetadata> { pub fn field_metadata(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> Option<graphene_std::registry::FieldMetadata> {
if let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) { if let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) {
@@ -844,8 +845,7 @@ impl NodeNetworkInterface {
}; };
let input_name = self.persistent_input_metadata(node_id, index, network_path)?.input_name.clone(); 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 = graphene_std::graph_text::GRAPHS.iter().find(|graph| graph.identifier == identifier)?.imports.get(index)?;
let field = graphs.iter().find(|graph| graph.identifier == identifier)?.imports.get(index)?;
(field.name == input_name).then(|| field.clone()) (field.name == input_name).then(|| field.clone())
} }
@@ -1086,7 +1086,7 @@ impl NodeNetworkInterface {
/// Whether the artboard layer clips the content inside it to its bounds. /// Whether the artboard layer clips the content inside it to its bounds.
fn artboard_clips_content(&self, artboard: LayerNodeIdentifier) -> bool { fn artboard_clips_content(&self, artboard: LayerNodeIdentifier) -> bool {
self.document_node(&artboard.to_node(), &[]) self.document_node(&artboard.to_node(), &[])
.and_then(|artboard| artboard.inputs.get(graphene_std::subgraphs::artboard::ClipInput::INDEX)) .and_then(|artboard| artboard.inputs.get(ARTBOARD_CLIP_INPUT_INDEX))
.is_some_and(|clip_input| matches!(clip_input, NodeInput::Value { tagged_value, .. } if tagged_value.clone().deref() == &TaggedValue::Bool(true))) .is_some_and(|clip_input| matches!(clip_input, NodeInput::Value { tagged_value, .. } if tagged_value.clone().deref() == &TaggedValue::Bool(true)))
} }
+26 -15
View File
@@ -32,7 +32,7 @@ pub struct DocumentNodeDefinition {
} }
``` ```
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. 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 its graph text (see [Creating a node from a subgraph](#creating-a-node-from-a-subgraph)), keyed by its name.
## Inspector ## Inspector
@@ -131,25 +131,36 @@ The macro invocation can be extended with additional attributes. The currently s
## Creating a node from a subgraph ## 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::<Footprint>()`, 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`: A node built from other nodes is written in graph text, a Rust-like syntax parsed at runtime by the `graph-text` crate. Built-in graphs are registered with the `core_types::graph!` macro, which only records the text and where it's written. This is the Load Image node as it exists in `node-graph/nodes/gstd/src/subgraphs.rs`:
```rs ```rs
/// Loads an image from a given URL. graph! {
#[node_macro::graph(category("Data: I/O"), icon("NodeLoadImage"))] #![syntax(1)]
pub fn load_image( use graphene_std::platform_application_io::{bytes_to_image@1, load_resource@1};
_: (),
/// The web address or local asset path of the image to load. /// Loads an image from a given URL.
#[name("URL")] #[category("Data: I/O"), icon("NodeLoadImage")]
url: Item<String>, fn load_image@1(
) -> out!( _,
/// The loaded image. /// The web address or local asset path of the image to load.
image, #[name("URL")]
) { url,
load_resource(url).at(0, 0) >> bytes_to_image().at(7, 0) ) -> (
/// The loaded image.
image,
) {
load_resource(url) >> bytes_to_image()
}
} }
``` ```
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. The text starts with its syntax version, `#![syntax(1)]`. The `use` section names each node by its identifier's module path and function name, at the declaration version it was written for, and `as` renames one. A graph's own version follows its name, like `load_image@1`. The graph's attributes are `category`, `icon`, `name`, and `layer`, and its name (or the title derived from its function name) is its catalog identifier, which documents store.
The function's parameters are the subgraph's imports, written without types, and `_` is a primary import that takes nothing. An import inherits its type, default, description, and widget settings from the inner parameter of its own name that it feeds, or else from the first one, and its attributes override those: `name`, `expose`, `default`, `widget`, `unit`, `hard`, `soft`, `range`, `step`, `display_decimal_places`, `multiline`, `progression`, `labels`, `integer`, and `blank_assist`. The exports are named in parentheses after `->`.
In the body, `let` binds a node, `>>` 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. A value has the type it's written with, so `1` is an integer and `1.` a number, and `#[exposed]` before an argument exposes its value. State methods after a call, each written once, set the node's display name (`.named("…")`) and flags (`.layer()`, `.hidden()`, `.locked()`, and `.pinned()`). Nodes are placed left of the node they feed, so positions are only written to adjust that, with `.offset(x, y)` or `.at(x, y)` in grid units. A graph's output name after a call or binding, like `.captures`, wires from that output instead of the primary one. The body ends with one value per export.
The `every_graph_resolves` test in `subgraphs.rs` reports any graph whose text doesn't resolve, with the place it's written. Every input a call leaves out keeps the default from the node's own definition.
## Executing a document `NodeNetwork` ## Executing a document `NodeNetwork`
+55 -74
View File
@@ -35,6 +35,8 @@ pub struct NodeFlags {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct FieldMetadata { pub struct FieldMetadata {
pub name: &'static str, pub name: &'static str,
/// The parameter's name in the node function, which graph text uses to set it.
pub identifier: &'static str,
pub description: &'static str, pub description: &'static str,
/// Whether the parameter is internal state of its node (named with a leading `_`), which is never exposed to the graph. /// Whether the parameter is internal state of its node (named with a leading `_`), which is never exposed to the graph.
pub internal: bool, pub internal: bool,
@@ -228,23 +230,61 @@ pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::ne
pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new())); pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
/// Every node defined as a subgraph by the `#[graph]` macro, in registration order. /// The graph text of every `graph!` invocation, in registration order.
pub static GRAPH_METADATA: LazyLock<Mutex<Vec<GraphMetadata>>> = LazyLock::new(|| Mutex::new(Vec::new())); pub static GRAPH_SOURCES: LazyLock<Mutex<Vec<GraphSource>>> = 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. /// The text of one `graph!` invocation and where it's written, for error messages.
#[derive(Clone, Debug)]
pub struct GraphSource {
/// The module the graph is defined in, which qualifies its name in `use` paths.
pub module_path: &'static str,
pub file: &'static str,
pub line: u32,
pub column: u32,
pub text: &'static str,
}
/// Registers graph text as a built-in subgraph node, which the editor turns into a catalog definition.
///
/// Each invocation registers itself under a symbol named after its crate, line, and column, so two invocations at the
/// same line and column in different files of one crate fail to link.
#[macro_export]
macro_rules! graph {
($($source:tt)*) => {
const _: () = {
use $crate as gcore;
use gcore::ctor::ctor;
#[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = gcore::ctor))]
#[unsafe(export_name = concat!("__node_registry_graph_", env!("CARGO_CRATE_NAME"), "_", line!(), "_", column!()))]
extern "C" fn register_graph() {
gcore::registry::GRAPH_SOURCES.lock().unwrap().push(gcore::registry::GraphSource {
module_path: module_path!(),
file: file!(),
line: line!(),
column: column!(),
text: stringify!($($source)*),
});
}
};
};
}
/// A node defined as a subgraph in graph text, which the editor turns into a catalog definition alongside the proto nodes.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct GraphMetadata { pub struct GraphMetadata {
/// The definition's identifier and display name. /// The definition's identifier and display name.
pub identifier: &'static str, pub identifier: &'static str,
/// The module path and function name that `use` paths in graph text name the graph by.
pub path: &'static str,
pub category: &'static str, pub category: &'static str,
pub icon: Option<&'static str>, pub icon: Option<&'static str>,
pub description: &'static str, pub description: &'static str,
/// The declaration version from `#[graph(version(N))]`, starting at 1. /// The declaration version from `fn name@N`, starting at 1.
pub version: u32, pub version: u32,
/// Whether a new instance starts as a layer, from `#[graph(layer)]`. /// Whether a new instance starts as a layer, from `#[layer]`.
pub layer: bool, pub layer: bool,
/// The subgraph's imports, which become the inputs of each instance, described like a proto node's parameters. /// 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<FieldMetadata>, pub imports: Vec<FieldMetadata>,
pub exports: Vec<GraphExportMetadata>, pub exports: Vec<GraphExportMetadata>,
/// The nodes inside the subgraph, where each node's position in this list is its ID. /// The nodes inside the subgraph, where each node's position in this list is its ID.
@@ -254,53 +294,36 @@ pub struct GraphMetadata {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct GraphExportMetadata { pub struct GraphExportMetadata {
pub name: &'static str, pub name: &'static str,
/// The export's name in graph text, which chooses it as an output.
pub identifier: &'static str,
pub description: &'static str, pub description: &'static str,
pub source: GraphInputSource, pub source: GraphInputSource,
} }
/// A node inside a subgraph defined by `#[graph]`. /// A node inside a subgraph defined in graph text.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct GraphNodeMetadata { pub struct GraphNodeMetadata {
pub implementation: GraphNodeImplementation, pub implementation: GraphNodeImplementation,
/// The inputs the definition sets, by index. Every other input keeps the default from the node's own definition. /// The inputs the definition sets, by index. Every other input keeps the default from the node's own definition.
pub inputs: Vec<(usize, GraphInputSource)>, pub inputs: Vec<(usize, GraphInputSource)>,
/// The absolute position in grid units, from `.at(x, y)`. /// The position in grid units.
pub position: Option<(i32, i32)>, pub position: (i32, i32),
/// From `.layer()`.
pub layer: bool, pub layer: bool,
/// From `.named("…")`.
pub display_name: Option<&'static str>, pub display_name: Option<&'static str>,
/// From `.hidden()`.
pub hidden: bool, pub hidden: bool,
/// From `.locked()`.
pub locked: bool, pub locked: bool,
/// From `.pinned()`.
pub pinned: bool, pub pinned: bool,
/// From `.call_argument::<T>()`.
pub call_argument: Option<Type>,
} }
/// What a node inside a subgraph is an instance of. /// What a node inside a subgraph is an instance of.
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub enum GraphNodeImplementation { pub enum GraphNodeImplementation {
ProtoNode(ProtoNodeIdentifier), ProtoNode(ProtoNodeIdentifier),
/// Another node defined by `#[graph]`, named by its identifier. /// Another subgraph node, named by its identifier.
Graph(&'static str), Graph(&'static str),
} }
impl From<ProtoNodeIdentifier> for GraphNodeImplementation { /// What feeds an input, or an export, of a subgraph defined in graph text.
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)] #[derive(Clone, Debug)]
pub enum GraphInputSource { pub enum GraphInputSource {
/// The output of another node in the subgraph, by its position in [`GraphMetadata::nodes`]. /// The output of another node in the subgraph, by its position in [`GraphMetadata::nodes`].
@@ -317,10 +340,10 @@ pub enum GraphInputSource {
SourceId, SourceId,
} }
/// A value written in a subgraph definition. The editor converts it to the type of the input it feeds. /// A value written in graph text, whose type is set by how it's written.
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub enum GraphValue { pub enum GraphValue {
/// A number written without a fractional part, which feeds an integer input as an integer and any other as a number. /// A number written without a fractional part.
Integer(i64), Integer(i64),
Number(f64), Number(f64),
Bool(bool), Bool(bool),
@@ -347,48 +370,6 @@ impl GraphValue {
} }
} }
impl From<&str> for GraphValue {
fn from(value: &str) -> Self {
Self::String(value.to_string())
}
}
impl From<String> for GraphValue {
fn from(value: String) -> Self {
Self::String(value)
}
}
impl From<bool> for GraphValue {
fn from(value: bool) -> Self {
Self::Bool(value)
}
}
impl From<f64> for GraphValue {
fn from(value: f64) -> Self {
Self::Number(value)
}
}
impl From<i64> for GraphValue {
fn from(value: i64) -> Self {
Self::Integer(value)
}
}
impl From<glam::DVec2> for GraphValue {
fn from(value: glam::DVec2) -> Self {
Self::Vec2(value)
}
}
impl From<Color> for GraphValue {
fn from(value: Color) -> Self {
Self::Color(value)
}
}
/// All multi-output proto nodes (those returning a [`Destructure`] struct), keyed by their identifier. /// 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. /// Snapshotted on first access, which must happen after startup registration of the node metadata completes.
pub static MULTI_OUTPUT_NODES: LazyLock<HashMap<ProtoNodeIdentifier, DestructureMetadata>> = LazyLock::new(|| { pub static MULTI_OUTPUT_NODES: LazyLock<HashMap<ProtoNodeIdentifier, DestructureMetadata>> = LazyLock::new(|| {
@@ -0,0 +1,26 @@
[package]
name = "graph-text"
description = "Parses the graph text format, which defines subgraph nodes in a Rust-like syntax"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[dependencies]
# Local dependencies
core-types = { workspace = true }
# Workspace dependencies
syn = { workspace = true }
proc-macro2 = { workspace = true }
glam = { workspace = true }
convert_case = { workspace = true }
log = { workspace = true }
@@ -0,0 +1,106 @@
//! The default placement of a graph's nodes, relative to the nodes they feed.
/// How far apart, in grid units, a node is placed from the node it feeds.
const COLUMN_WIDTH: i32 = 7;
/// A node's wires and its written placement, as the layout reads them.
pub struct LayoutNode {
/// The node feeding the primary input.
pub primary: Option<usize>,
/// The nodes feeding the other inputs, in the order they're written.
pub secondaries: Vec<usize>,
/// The absolute position from `.at(x, y)`, which replaces the default one.
pub at: Option<(i32, i32)>,
/// The nudge from `.offset(x, y)`, added to the default position.
pub offset: (i32, i32),
}
/// Places each node in the column left of the first node it feeds. A node feeding a primary input shares that node's row,
/// and one feeding another input goes in a new row below everything placed so far. Each export's node starts a new row.
pub fn layout(nodes: &[LayoutNode], roots: &[usize]) -> Vec<(i32, i32)> {
let mut placement = Placement {
nodes,
positions: vec![None; nodes.len()],
bottom: None,
};
for &root in roots {
let row = placement.next_row();
placement.place(root, 0, row);
}
for node in 0..nodes.len() {
let row = placement.next_row();
placement.place(node, 0, row);
}
placement.positions.into_iter().map(Option::unwrap_or_default).collect()
}
struct Placement<'a> {
nodes: &'a [LayoutNode],
positions: Vec<Option<(i32, i32)>>,
/// The lowest row used so far.
bottom: Option<i32>,
}
impl Placement<'_> {
fn next_row(&self) -> i32 {
self.bottom.map_or(0, |bottom| bottom + 1)
}
fn place(&mut self, node: usize, x: i32, y: i32) {
if self.positions[node].is_some() {
return;
}
let LayoutNode { primary, secondaries, at, offset } = &self.nodes[node];
let (x, y) = at.unwrap_or((x + offset.0, y + offset.1));
self.positions[node] = Some((x, y));
self.bottom = Some(self.bottom.map_or(y, |bottom| bottom.max(y)));
if let Some(primary) = primary {
self.place(*primary, x - COLUMN_WIDTH, y);
}
for &secondary in secondaries {
let row = self.next_row();
self.place(secondary, x - COLUMN_WIDTH, row);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn node(primary: Option<usize>, secondaries: Vec<usize>) -> LayoutNode {
LayoutNode {
primary,
secondaries,
at: None,
offset: (0, 0),
}
}
#[test]
fn chains_run_left_and_side_inputs_go_below() {
// Merge: `base >> as_graphic() >> extend(new = content >> into_group())`
let nodes = [node(None, vec![]), node(None, vec![]), node(Some(0), vec![1])];
assert_eq!(layout(&nodes, &[2]), [(-7, 0), (-7, 1), (0, 0)]);
}
#[test]
fn written_placement_moves_a_node_and_its_upstream() {
let mut offset = node(None, vec![]);
offset.offset = (0, 2);
let mut at = node(Some(0), vec![]);
at.at = Some((10, -4));
assert_eq!(layout(&[offset, at], &[1]), [(3, -2), (10, -4)]);
}
#[test]
fn each_export_and_unexported_node_starts_a_new_row() {
let nodes = [node(None, vec![]), node(None, vec![]), node(None, vec![])];
assert_eq!(layout(&nodes, &[0, 1]), [(0, 0), (0, 1), (0, 2)]);
}
}
+122
View File
@@ -0,0 +1,122 @@
//! Graph text, which defines a subgraph node in a Rust-like syntax that is parsed at runtime.
//!
//! Built-in graphs are written in `core_types::graph!` invocations, which register their text at startup.
mod layout;
mod resolve;
mod syntax;
use core_types::ProtoNodeIdentifier;
use core_types::registry::{GRAPH_SOURCES, GraphMetadata, GraphSource, NODE_METADATA, NodeMetadata};
use resolve::{Context, ResolveError};
use std::collections::HashMap;
use std::fmt;
use std::sync::LazyLock;
pub use syntax::SYNTAX_VERSION;
/// Every registered graph that resolves, in registration order. Resolved on first access, which must happen after
/// startup registration of the nodes and graphs completes. Each graph that fails is left out and its error logged.
pub static GRAPHS: LazyLock<Vec<GraphMetadata>> = LazyLock::new(|| {
let sources = GRAPH_SOURCES.lock().map(|sources| sources.clone()).unwrap_or_default();
let Ok(proto_nodes) = NODE_METADATA.lock() else {
log::error!("The node metadata is poisoned, so no graph resolves");
return Vec::new();
};
let (graphs, errors) = resolve_sources(&sources, &proto_nodes);
for error in errors {
log::error!("{error}");
}
graphs
});
/// The position of a registered graph's import, by the graph's identifier and the import's name.
pub fn import_index(graph: &str, import: &str) -> Option<usize> {
GRAPHS.iter().find(|metadata| metadata.identifier == graph)?.imports.iter().position(|field| field.identifier == import)
}
/// An error in graph text, with the place it's written.
#[derive(Debug)]
pub struct GraphTextError {
pub message: String,
pub file: &'static str,
pub line: u32,
pub column: u32,
/// The graph text from the error onward, which locates it within the text.
pub excerpt: String,
}
impl fmt::Display for GraphTextError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}:{}:{}: {} (at `{}`)", self.file, self.line, self.column, self.message, self.excerpt)
}
}
impl GraphTextError {
fn new(source: &GraphSource, error: syn::Error) -> Vec<Self> {
error
.into_iter()
.map(|error| {
let start = error.span().start();
let excerpt = source
.text
.lines()
.nth(start.line.saturating_sub(1))
.map(|line| line.chars().skip(start.column).take(40).collect::<String>())
.unwrap_or_default();
Self {
message: error.to_string(),
file: source.file,
line: source.line,
column: source.column,
excerpt: excerpt.trim().to_string(),
}
})
.collect()
}
}
/// Parses and resolves graph sources. A graph using another one resolves once that one has, whatever the order.
pub fn resolve_sources(sources: &[GraphSource], proto_nodes: &HashMap<ProtoNodeIdentifier, NodeMetadata>) -> (Vec<GraphMetadata>, Vec<GraphTextError>) {
let mut errors = Vec::new();
let mut pending = Vec::new();
for source in sources {
match syn::parse_str::<syntax::Source>(source.text) {
Ok(parsed) => pending.push((source, parsed, None)),
Err(error) => errors.extend(GraphTextError::new(source, error)),
}
}
let mut graphs = Vec::new();
loop {
let pending_count = pending.len();
let mut still_pending = Vec::new();
for (source, parsed, _) in pending {
let context = Context { proto_nodes, graphs: &graphs };
match resolve::resolve(&parsed, source.module_path, &context) {
Ok(graph) => graphs.push(graph),
Err(ResolveError::Invalid(error)) => errors.extend(GraphTextError::new(source, error)),
Err(ResolveError::Unresolved(error)) => still_pending.push((source, parsed, Some(error))),
}
}
pending = still_pending;
if pending.is_empty() || pending.len() == pending_count {
break;
}
}
for (source, _, error) in pending {
if let Some(error) = error {
errors.extend(GraphTextError::new(source, error));
}
}
(graphs, errors)
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,749 @@
//! Resolves parsed graph text against the registered nodes and graphs, producing the graph's `GraphMetadata`.
use crate::layout::{LayoutNode, layout};
use crate::syntax::{Attribute, Expression, GraphItem, Import, Source, StateKind, Use, ValueKind, doc_comment};
use convert_case::{Case, Casing};
use core_types::registry::{
FieldMetadata, GraphExportMetadata, GraphInputSource, GraphMetadata, GraphNodeImplementation, GraphNodeMetadata, GraphValue, NodeMetadata, RegistryValueSource, RegistryWidgetOverride,
};
use core_types::{ProtoNodeIdentifier, Type, concrete, generic};
use proc_macro2::Span;
use std::collections::{HashMap, HashSet};
use syn::ext::IdentExt;
use syn::parse::{ParseStream, Parser};
use syn::{Error, Ident, LitBool, LitInt, LitStr, Token};
/// The registered nodes and the graphs resolved so far, which graph text can use.
pub struct Context<'a> {
pub proto_nodes: &'a HashMap<ProtoNodeIdentifier, NodeMetadata>,
pub graphs: &'a [GraphMetadata],
}
pub enum ResolveError {
/// A used name matches nothing yet, which may be a graph that resolves later.
Unresolved(Error),
Invalid(Error),
}
impl From<Error> for ResolveError {
fn from(error: Error) -> Self {
Self::Invalid(error)
}
}
/// What a used name refers to.
#[derive(Clone, Copy)]
enum Target<'a> {
ProtoNode(&'a ProtoNodeIdentifier, &'a NodeMetadata),
Graph(&'a GraphMetadata),
}
impl<'a> Target<'a> {
fn parameters(&self) -> &'a [FieldMetadata] {
match self {
Self::ProtoNode(_, metadata) => &metadata.fields,
Self::Graph(graph) => &graph.imports,
}
}
fn implementation(&self) -> GraphNodeImplementation {
match self {
Self::ProtoNode(identifier, _) => GraphNodeImplementation::ProtoNode((*identifier).clone()),
Self::Graph(graph) => GraphNodeImplementation::Graph(graph.identifier),
}
}
}
/// What feeds an input or export while the body is read.
#[derive(Clone)]
enum Feed {
/// A node's output, chosen by name, or else its primary output.
Node {
node: usize,
output: Option<usize>,
},
Import(usize),
Value {
value: GraphValue,
exposed: Option<bool>,
},
Scope(String),
NodePath,
SourceId,
}
struct Node<'a> {
target: Target<'a>,
name: Ident,
inputs: Vec<(usize, Feed)>,
states: Vec<StateKind>,
}
struct Resolver<'a> {
context: &'a Context<'a>,
graph_path: String,
uses: HashMap<String, &'a Use>,
used: HashSet<String>,
imports: &'a [Import],
bindings: HashMap<String, Feed>,
nodes: Vec<Node<'a>>,
/// The parameters of the inner inputs each import feeds, in the order they're written.
import_consumers: Vec<Vec<FieldMetadata>>,
}
/// Resolves a parsed graph text, given the module path its graph is defined in.
pub fn resolve(source: &Source, module_path: &str, context: &Context) -> Result<GraphMetadata, ResolveError> {
let graph = &source.graph;
let graph_path = format!("{module_path}::{}", graph.name);
let mut uses = HashMap::new();
for entry in &source.uses {
let local_name = entry.local_name();
if uses.insert(local_name.to_string(), entry).is_some() {
return Err(Error::new(local_name.span(), format!("`{local_name}` is used twice. Rename one with `as`")).into());
}
}
let mut resolver = Resolver {
context,
graph_path,
uses,
used: HashSet::new(),
imports: &graph.imports,
bindings: HashMap::new(),
nodes: Vec::new(),
import_consumers: vec![Vec::new(); graph.imports.len()],
};
for binding in &graph.bindings {
let name = binding.name.to_string();
if resolver.bindings.contains_key(&name) || resolver.import_index(&binding.name).is_some() {
return Err(Error::new(binding.name.span(), format!("`{name}` is already the name of a binding or import")).into());
}
let feed = resolver.read(&binding.value)?;
resolver.bindings.insert(name, feed);
}
let export_feeds = resolver.read_exports(&graph.result, graph.exports.len())?;
if let Some(unused) = source.uses.iter().find(|entry| !resolver.used.contains(&entry.local_name().to_string())) {
return Err(Error::new(unused.local_name().span(), format!("`{}` is used but never called", unused.local_name())).into());
}
resolver.build(graph, module_path, export_feeds)
}
impl<'a> Resolver<'a> {
fn import_index(&self, name: &Ident) -> Option<usize> {
self.imports.iter().position(|import| import.name.as_ref() == Some(name))
}
fn read(&mut self, expression: &'a Expression) -> Result<Feed, ResolveError> {
match expression {
Expression::Name(name) => {
if let Some(feed) = self.bindings.get(&name.to_string()) {
return Ok(feed.clone());
}
if let Some(index) = self.import_index(name) {
return Ok(Feed::Import(index));
}
Err(Error::new(name.span(), format!("`{name}` isn't a binding or import. Call a node with parentheses, like `{name}()`")).into())
}
Expression::Value(value) => Ok(Feed::Value {
value: match &value.kind {
ValueKind::Integer(integer) => GraphValue::Integer(*integer),
ValueKind::Number(number) => GraphValue::Number(*number),
ValueKind::Bool(boolean) => GraphValue::Bool(*boolean),
ValueKind::String(string) => GraphValue::String(string.clone()),
ValueKind::Vec2(x, y) => GraphValue::vec2(*x, *y),
},
exposed: None,
}),
Expression::Call(call) => self.read_call(call),
Expression::Feed { upstream, downstream, span } => {
let upstream_feed = self.read(upstream)?;
let Feed::Node { node, output } = self.read(downstream)? else {
return Err(Error::new(downstream.span(), "The right side of `>>` is a node, like `fill()`, or a binding naming one").into());
};
if let Feed::Node { node: upstream_node, .. } = upstream_feed
&& self.is_fed_by(upstream_node, node)
{
return Err(Error::new(*span, "This wire makes a loop, since the node on the right already feeds the left side").into());
}
let entry = &self.nodes[node];
if entry.target.parameters().is_empty() {
return Err(Error::new(entry.name.span(), format!("`{}` has no parameters, so `>>` has no input to feed", entry.name)).into());
}
if entry.inputs.iter().any(|(index, _)| *index == 0) {
let primary = &entry.target.parameters()[0];
let message = format!("The primary input of `{}`, `{}`, is already fed, so `>>` can't feed it too", entry.name, primary.identifier);
return Err(Error::new(*span, message).into());
}
self.connect(node, 0, upstream_feed);
Ok(Feed::Node { node, output })
}
Expression::Output { node, output } => {
let Feed::Node { node, output: None } = self.read(node)? else {
return Err(Error::new(output.span(), "Only a node has outputs to choose from, and only one can be chosen").into());
};
let Target::Graph(graph) = self.nodes[node].target else {
return Err(Error::new(output.span(), "Only a graph's outputs can be chosen by name").into());
};
let name = output.unraw().to_string();
let Some(index) = graph.exports.iter().position(|export| export.identifier == name) else {
return Err(Error::new(output.span(), format!("`{}` has no output named `{name}`", self.nodes[node].name)).into());
};
Ok(Feed::Node { node, output: Some(index) })
}
Expression::Tuple { span, .. } => Err(Error::new(*span, "A tuple only gives a graph's exports, as its final expression").into()),
}
}
fn read_exports(&mut self, result: &'a Expression, export_count: usize) -> Result<Vec<Feed>, ResolveError> {
let values: Vec<&Expression> = match result {
Expression::Tuple { elements, .. } => elements.iter().collect(),
single => vec![single],
};
if values.len() != export_count {
return Err(Error::new(result.span(), format!("The graph names {export_count} exports, but ends with {} values", values.len())).into());
}
values
.into_iter()
.map(|value| match self.read(value)? {
Feed::Import(_) | Feed::Scope(_) => Err(Error::new(value.span(), "An export can't come straight from an import or scope yet, so pass it through a node first").into()),
feed => Ok(feed),
})
.collect()
}
/// Whether `node` is `source` or feeds it through any chain of wires.
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
}
fn connect(&mut self, node: usize, input: usize, feed: Feed) {
if let Feed::Import(import) = feed {
let parameter = self.nodes[node].target.parameters()[input].clone();
self.import_consumers[import].push(parameter);
}
self.nodes[node].inputs.push((input, feed));
}
fn read_call(&mut self, call: &'a crate::syntax::Call) -> Result<Feed, ResolveError> {
let name = call.name.to_string();
if let Some(feed) = self.read_value_helper(call)? {
return Ok(feed);
}
let target = self.target(&call.name)?;
self.used.insert(name);
let mut inputs = Vec::new();
for argument in &call.arguments {
let parameter = match (&argument.parameter, &argument.value) {
(Some(parameter), _) => parameter,
(None, Expression::Name(shorthand)) => shorthand,
(None, value) => return Err(Error::new(value.span(), "Name each argument, like `weight = 6`, or write a bare name for the shorthand").into()),
};
let Some(index) = target.parameters().iter().position(|field| parameter == field.identifier) else {
return Err(Error::new(parameter.span(), format!("`{}` has no parameter named `{parameter}`", call.name)).into());
};
if inputs.iter().any(|(existing, _)| *existing == index) {
return Err(Error::new(parameter.span(), format!("`{parameter}` is already set in this call")).into());
}
let mut feed = self.read(&argument.value)?;
for attribute in &argument.attributes {
if attribute.name != "exposed" {
return Err(Error::new(attribute.name.span(), format!("Unknown argument attribute `#[{}]`", attribute.name)).into());
}
attribute.flag()?;
let Feed::Value { exposed, .. } = &mut feed else {
return Err(Error::new(attribute.name.span(), "Only a value can be exposed").into());
};
*exposed = Some(true);
}
inputs.push((index, feed));
}
self.nodes.push(Node {
target,
name: call.name.clone(),
inputs: Vec::new(),
states: call.states.iter().map(|state| state.kind.clone()).collect(),
});
let node = self.nodes.len() - 1;
for (index, feed) in inputs {
self.connect(node, index, feed);
}
Ok(Feed::Node { node, output: None })
}
/// Reads a call to `rgb`, `rgba`, `scope`, or `reflect`, which build values and input sources rather than nodes.
fn read_value_helper(&self, call: &crate::syntax::Call) -> Result<Option<Feed>, ResolveError> {
let name = call.name.to_string();
if !matches!(name.as_str(), "rgb" | "rgba" | "scope" | "reflect") {
return Ok(None);
}
let [argument] = call.arguments.as_slice() else {
return Err(Error::new(call.name.span(), format!("`{name}(...)` takes one argument")).into());
};
if let Some(state) = call.states.first() {
return Err(Error::new(state.span, format!("`{name}(...)` is a value, so it has no node state")).into());
}
if argument.parameter.is_some() || !argument.attributes.is_empty() {
return Err(Error::new(call.name.span(), format!("`{name}(...)` takes a plain argument")).into());
}
let value = &argument.value;
let feed = match (name.as_str(), value) {
("rgb", Expression::Value(crate::syntax::Value { kind: ValueKind::Integer(hex), .. })) if (0..=0xFF_FFFF).contains(hex) => Feed::Value {
value: GraphValue::rgb(*hex as u32),
exposed: None,
},
("rgb", _) => return Err(Error::new(value.span(), "`rgb(...)` takes six hex digits, like `rgb(0xE85D75)`. Use `rgba(...)` to give an alpha too").into()),
("rgba", Expression::Value(crate::syntax::Value { kind: ValueKind::Integer(hex), .. })) if (0..=0xFFFF_FFFF).contains(hex) => Feed::Value {
value: GraphValue::rgba(*hex as u32),
exposed: None,
},
("rgba", _) => return Err(Error::new(value.span(), "`rgba(...)` takes eight hex digits, like `rgba(0xE85D75FF)`").into()),
("scope", Expression::Value(crate::syntax::Value { kind: ValueKind::String(key), .. })) => Feed::Scope(key.clone()),
("scope", _) => return Err(Error::new(value.span(), "`scope(...)` takes the scope's key as a string").into()),
(_, Expression::Name(reflected)) if reflected == "NodePath" => Feed::NodePath,
(_, Expression::Name(reflected)) if reflected == "SourceId" => Feed::SourceId,
_ => return Err(Error::new(value.span(), "Reflect `NodePath` or `SourceId`").into()),
};
Ok(Some(feed))
}
/// The node or graph a called name refers to, through the `use` section.
fn target(&self, name: &Ident) -> Result<Target<'a>, ResolveError> {
let Some(entry) = self.uses.get(&name.to_string()) else {
return Err(Error::new(name.span(), format!("`{name}` isn't used. Add it to the `use` section, like `use path::{name}@1;`")).into());
};
let module_path = entry.module_path();
let proto_identifier = ProtoNodeIdentifier::with_owned_string(format!("{module_path}::{}Node", entry.name.to_string().to_case(Case::Pascal)));
if let Some((identifier, metadata)) = self.context.proto_nodes.get_key_value(&proto_identifier) {
check_version(entry, metadata.version)?;
return Ok(Target::ProtoNode(identifier, metadata));
}
let graph_path = format!("{module_path}::{}", entry.name);
if graph_path == self.graph_path {
return Err(Error::new(name.span(), "A graph can't contain itself").into());
}
if let Some(graph) = self.context.graphs.iter().find(|graph| graph.path == graph_path) {
check_version(entry, graph.version)?;
return Ok(Target::Graph(graph));
}
Err(ResolveError::Unresolved(Error::new(entry.name.span(), format!("No node or graph is named `{graph_path}`"))))
}
fn build(self, graph: &GraphItem, module_path: &str, export_feeds: Vec<Feed>) -> Result<GraphMetadata, ResolveError> {
let attributes = GraphAttributes::read(&graph.attributes)?;
let imports = graph
.imports
.iter()
.zip(&self.import_consumers)
.enumerate()
.map(|(index, (import, consumers))| import_metadata(index, import, consumers))
.collect::<syn::Result<Vec<_>>>()?;
let import_types: Vec<Type> = imports.iter().map(import_wire_type).collect();
let source = |feed: &Feed| match feed {
Feed::Node { node, output } => GraphInputSource::Node {
node: *node,
output: output.unwrap_or(0),
},
Feed::Import(index) => GraphInputSource::Import {
index: *index,
ty: import_types[*index].clone(),
},
Feed::Value { value, exposed } => GraphInputSource::Value {
value: value.clone(),
exposed: *exposed,
},
Feed::Scope(key) => GraphInputSource::Scope(leak(key.clone())),
Feed::NodePath => GraphInputSource::NodePath,
Feed::SourceId => GraphInputSource::SourceId,
};
let layout_nodes: Vec<LayoutNode> = self
.nodes
.iter()
.map(|node| {
let upstream = |input: &(usize, Feed)| match input.1 {
Feed::Node { node, .. } => Some(node),
_ => None,
};
LayoutNode {
primary: node.inputs.iter().filter(|input| input.0 == 0).find_map(upstream),
secondaries: node.inputs.iter().filter(|input| input.0 != 0).filter_map(upstream).collect(),
at: node.states.iter().find_map(|state| match state {
StateKind::At(x, y) => Some((*x, *y)),
_ => None,
}),
offset: node
.states
.iter()
.find_map(|state| match state {
StateKind::Offset(x, y) => Some((*x, *y)),
_ => None,
})
.unwrap_or_default(),
}
})
.collect();
let roots: Vec<usize> = export_feeds
.iter()
.filter_map(|feed| match feed {
Feed::Node { node, .. } => Some(*node),
_ => None,
})
.collect();
let positions = layout(&layout_nodes, &roots);
let nodes = self
.nodes
.iter()
.zip(positions)
.map(|(node, position)| GraphNodeMetadata {
implementation: node.target.implementation(),
inputs: node.inputs.iter().map(|(index, feed)| (*index, source(feed))).collect(),
position,
layer: node.states.contains(&StateKind::Layer),
display_name: node.states.iter().find_map(|state| match state {
StateKind::Named(name) => Some(leak(name.clone())),
_ => None,
}),
hidden: node.states.contains(&StateKind::Hidden),
locked: node.states.contains(&StateKind::Locked),
pinned: node.states.contains(&StateKind::Pinned),
})
.collect();
let exports = graph
.exports
.iter()
.zip(&export_feeds)
.map(|(export, feed)| {
let mut name = None;
for attribute in &export.attributes {
match attribute.name.to_string().as_str() {
"doc" => {}
"name" => set_once(&mut name, attribute, attribute.string()?)?,
other => return Err(Error::new(attribute.name.span(), format!("Unknown export attribute `#[{other}]`"))),
}
}
Ok(GraphExportMetadata {
name: leak(name.unwrap_or_else(|| derived_display_name(&export.name))),
identifier: leak(export.name.unraw().to_string()),
description: leak(doc_comment(&export.attributes)),
source: source(feed),
})
})
.collect::<syn::Result<Vec<_>>>()?;
let identifier = attributes.display_name.unwrap_or_else(|| graph.name.unraw().to_string().to_case(Case::Pascal).to_case(Case::Title));
Ok(GraphMetadata {
identifier: leak(identifier),
path: leak(format!("{module_path}::{}", graph.name)),
category: leak(attributes.category),
icon: attributes.icon.map(leak),
description: leak(doc_comment(&graph.attributes)),
version: graph.version,
layer: attributes.layer,
imports,
exports,
nodes,
})
}
}
fn check_version(entry: &Use, version: u32) -> syn::Result<()> {
if entry.version == version {
return Ok(());
}
Err(Error::new(entry.name.span(), format!("`{}` is at version {version}, not {}", entry.name, entry.version)))
}
/// Strings in the registry's metadata live for the whole program, which holds for graphs resolved once at startup.
fn leak(string: String) -> &'static str {
Box::leak(string.into_boxed_str())
}
/// The display name an identifier derives, in Title Case.
fn derived_display_name(ident: &Ident) -> String {
ident.unraw().to_string().to_case(Case::Title).trim().to_string()
}
fn set_once<T>(slot: &mut Option<T>, attribute: &Attribute, value: T) -> syn::Result<()> {
if slot.is_some() {
return Err(Error::new(attribute.name.span(), format!("Multiple `{}` attributes are not allowed", attribute.name)));
}
*slot = Some(value);
Ok(())
}
struct GraphAttributes {
category: String,
icon: Option<String>,
display_name: Option<String>,
layer: bool,
}
impl GraphAttributes {
fn read(attributes: &[Attribute]) -> syn::Result<Self> {
let (mut category, mut icon, mut display_name, mut layer) = (None, None, None, None);
for attribute in attributes {
match attribute.name.to_string().as_str() {
"doc" => {}
"category" => set_once(&mut category, attribute, attribute.string()?)?,
"icon" => set_once(&mut icon, attribute, attribute.string()?)?,
"name" => set_once(&mut display_name, attribute, attribute.string()?)?,
"layer" => {
attribute.flag()?;
set_once(&mut layer, attribute, true)?;
}
other => {
return Err(Error::new(
attribute.name.span(),
format!("Unknown graph attribute `#[{other}]`. Expected `category(\"…\")`, `icon(\"…\")`, `name(\"…\")`, or `layer`"),
));
}
}
}
let Some(category) = category else {
return Err(Error::new(Span::call_site(), "A graph needs a category, like `#[category(\"Vector: Deform\")]`"));
};
Ok(Self {
category,
icon,
display_name,
layer: layer.unwrap_or_default(),
})
}
}
/// A parameter description with nothing set, which an import starts from when it feeds no input.
pub(crate) fn blank_field() -> FieldMetadata {
FieldMetadata {
name: "",
identifier: "",
description: "",
internal: false,
exposed: false,
widget_override: RegistryWidgetOverride::None,
value_source: RegistryValueSource::None,
default_colors: None,
default_type: None,
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,
}
}
/// An import's parameter description, inherited from an inner input it feeds and overridden by its own attributes.
/// That input is the one whose parameter has the import's name, or else the first one fed.
fn import_metadata(index: usize, import: &Import, consumers: &[FieldMetadata]) -> syn::Result<FieldMetadata> {
let Some(name) = &import.name else {
if let Some(attribute) = import.attributes.first() {
return Err(Error::new(attribute.name.span(), "An unused primary import takes no attributes"));
}
return Ok(FieldMetadata {
default_type: Some(concrete!(())),
..blank_field()
});
};
let identifier = name.unraw().to_string();
let inherited = consumers.iter().find(|consumer| consumer.identifier == identifier).or(consumers.first());
let mut field = FieldMetadata {
identifier: leak(identifier.clone()),
exposed: false,
internal: index > 0 && identifier.starts_with('_'),
constant: false,
..inherited.cloned().unwrap_or_else(blank_field)
};
let mut display_name = None;
let mut seen = HashSet::new();
for attribute in &import.attributes {
let attribute_name = attribute.name.to_string();
if attribute_name != "doc" && !seen.insert(attribute_name.clone()) {
return Err(Error::new(attribute.name.span(), format!("Multiple `{attribute_name}` attributes are not allowed")));
}
apply_import_attribute(&mut field, &mut display_name, attribute)?;
}
field.name = leak(display_name.unwrap_or_else(|| derived_display_name(name)));
let description = doc_comment(&import.attributes);
if !description.is_empty() {
field.description = leak(description);
}
Ok(field)
}
fn apply_import_attribute(field: &mut FieldMetadata, display_name: &mut Option<String>, attribute: &Attribute) -> syn::Result<()> {
let arguments = || attribute.list();
match attribute.name.to_string().as_str() {
"doc" => {}
"name" => *display_name = Some(attribute.string()?),
"expose" => {
attribute.flag()?;
field.exposed = true;
}
"default" => {
let tokens = arguments()?;
field.default_type = default_type(&tokens, field.default_type.take());
field.value_source = RegistryValueSource::Default(leak(tokens.to_string()));
field.default_colors = None;
}
"widget" => {
field.widget_override = (|input: ParseStream| {
let kind: Ident = input.parse()?;
let text = || -> syn::Result<&'static str> {
input.parse::<Token![=]>()?;
Ok(leak(input.parse::<LitStr>()?.value()))
};
match kind.to_string().as_str() {
"Hidden" => Ok(RegistryWidgetOverride::Hidden),
"String" => Ok(RegistryWidgetOverride::String(text()?)),
"Custom" => Ok(RegistryWidgetOverride::Custom(text()?)),
_ => Err(Error::new(kind.span(), "A widget is `Hidden`, `String = \"…\"`, or `Custom = \"…\"`")),
}
})
.parse2(arguments()?)?;
}
"unit" => field.unit = Some(leak(attribute.string()?)),
"hard" => (field.number_hard_min, field.number_hard_max) = parse_bounds.parse2(arguments()?)?,
"soft" => (field.number_soft_min, field.number_soft_max) = parse_bounds.parse2(arguments()?)?,
"range" => {
attribute.flag()?;
field.number_mode_range = true;
}
"step" => field.number_step = Some(parse_number.parse2(arguments()?)?),
"display_decimal_places" => field.number_display_decimal_places = Some(syn::parse2::<LitInt>(arguments()?)?.base10_parse()?),
"multiline" => {
attribute.flag()?;
field.multiline = true;
}
"progression" => {
attribute.flag()?;
field.progression = true;
}
"integer" => {
attribute.flag()?;
field.integer = true;
}
"labels" => {
field.labels = Some(
(|input: ParseStream| {
let x: LitStr = input.parse()?;
input.parse::<Token![,]>()?;
let y: LitStr = input.parse()?;
Ok((leak(x.value()), leak(y.value())))
})
.parse2(arguments()?)?,
);
}
"blank_assist" => field.blank_assist = syn::parse2::<LitBool>(arguments()?)?.value,
other => return Err(Error::new(attribute.name.span(), format!("Unknown import attribute `#[{other}]`"))),
}
Ok(())
}
/// The type a `#[default(...)]` is parsed as: a literal's own type, or else the bare element of the inherited type.
fn default_type(tokens: &proc_macro2::TokenStream, inherited: Option<Type>) -> Option<Type> {
if let Ok(literal) = syn::parse2::<crate::syntax::Value>(tokens.clone()) {
return Some(match literal.kind {
ValueKind::Integer(_) => concrete!(i64),
ValueKind::Number(_) => concrete!(f64),
ValueKind::Bool(_) => concrete!(bool),
ValueKind::String(_) => concrete!(String),
ValueKind::Vec2(..) => concrete!(glam::DVec2),
});
}
match inherited {
Some(Type::Item(element)) => Some(*element),
other => other,
}
}
/// The type an import's wire records, ranked as an `Item` when its default is a bare element.
fn import_wire_type(field: &FieldMetadata) -> Type {
match &field.default_type {
Some(ty @ (Type::Item(_) | Type::List(_) | Type::Fn(..) | Type::Generic(_))) => ty.clone(),
Some(unit) if *unit == concrete!(()) => unit.clone(),
Some(element) => Type::Item(Box::new(element.clone())),
None => generic!(T),
}
}
fn parse_number(input: ParseStream) -> syn::Result<f64> {
let negative = input.peek(Token![-]);
if negative {
input.parse::<Token![-]>()?;
}
let magnitude: f64 = match input.parse::<syn::Lit>()? {
syn::Lit::Int(integer) => integer.base10_parse()?,
syn::Lit::Float(float) => float.base10_parse()?,
other => return Err(Error::new(other.span(), "Expected a number")),
};
Ok(if negative { -magnitude } else { magnitude })
}
/// Reads `a..b`, where either end may be left out.
fn parse_bounds(input: ParseStream) -> syn::Result<(Option<f64>, Option<f64>)> {
let start = if input.peek(Token![..]) { None } else { Some(parse_number(input)?) };
input.parse::<Token![..]>()?;
let end = if input.is_empty() { None } else { Some(parse_number(input)?) };
Ok((start, end))
}
@@ -0,0 +1,780 @@
//! The grammar of graph text, parsed with syn from the tokens of a `graph!` invocation or a clipboard string.
use proc_macro2::{Span, TokenStream};
use syn::ext::IdentExt;
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{Error, Ident, Lit, LitInt, LitStr, Token, braced, bracketed, parenthesized};
/// The syntax version this parser reads, from the `#![syntax(N)]` header.
pub const SYNTAX_VERSION: u32 = 1;
/// A whole graph text: its header, its `use` section, and the graph it defines.
pub struct Source {
pub uses: Vec<Use>,
pub graph: GraphItem,
}
/// One node or graph named by the `use` section, like `math_nodes::add@1`.
pub struct Use {
pub module: Vec<Ident>,
pub name: Ident,
pub version: u32,
pub alias: Option<Ident>,
}
impl Use {
/// The name the body calls it by.
pub fn local_name(&self) -> &Ident {
self.alias.as_ref().unwrap_or(&self.name)
}
pub fn module_path(&self) -> String {
self.module.iter().map(Ident::to_string).collect::<Vec<_>>().join("::")
}
}
/// An attribute item like `category("Graphic")`, `layer`, or `doc = "…"`. One `#[...]` can hold several, separated by commas.
pub struct Attribute {
pub name: Ident,
pub arguments: AttributeArguments,
}
pub enum AttributeArguments {
None,
List(TokenStream),
Value(Lit),
}
impl Attribute {
/// The parenthesized arguments, or an error naming the attribute if it has none.
pub fn list(&self) -> syn::Result<TokenStream> {
match &self.arguments {
AttributeArguments::List(tokens) => Ok(tokens.clone()),
_ => Err(Error::new(self.name.span(), format!("`{}` takes arguments in parentheses", self.name))),
}
}
/// An error unless the attribute is written without arguments.
pub fn flag(&self) -> syn::Result<()> {
match &self.arguments {
AttributeArguments::None => Ok(()),
_ => Err(Error::new(self.name.span(), format!("`{}` takes no arguments", self.name))),
}
}
pub fn string(&self) -> syn::Result<String> {
syn::parse2::<LitStr>(self.list()?).map(|literal| literal.value())
}
}
pub struct GraphItem {
pub attributes: Vec<Attribute>,
pub name: Ident,
pub version: u32,
pub imports: Vec<Import>,
pub exports: Vec<Export>,
pub bindings: Vec<Binding>,
/// The final expression, which gives one value per export.
pub result: Expression,
}
pub struct Import {
pub attributes: Vec<Attribute>,
/// The import's name, or `None` for an unused primary import written `_`.
pub name: Option<Ident>,
}
pub struct Export {
pub attributes: Vec<Attribute>,
pub name: Ident,
}
pub struct Binding {
pub name: Ident,
pub value: Expression,
}
pub enum Expression {
Name(Ident),
Value(Value),
Call(Call),
/// `upstream >> downstream`, which feeds the upstream into the downstream node's primary input.
Feed {
upstream: Box<Expression>,
downstream: Box<Expression>,
span: Span,
},
/// A node's output chosen by name, like `.captures`.
Output {
node: Box<Expression>,
output: Ident,
},
Tuple {
elements: Vec<Expression>,
span: Span,
},
}
impl Expression {
pub fn span(&self) -> Span {
match self {
Self::Name(name) => name.span(),
Self::Value(value) => value.span,
Self::Call(call) => call.name.span(),
Self::Feed { span, .. } | Self::Tuple { span, .. } => *span,
Self::Output { output, .. } => output.span(),
}
}
}
pub struct Value {
pub kind: ValueKind,
pub span: Span,
}
pub enum ValueKind {
Integer(i64),
Number(f64),
Bool(bool),
String(String),
Vec2(f64, f64),
}
pub struct Call {
pub name: Ident,
pub arguments: Vec<Argument>,
pub states: Vec<State>,
}
pub struct Argument {
pub attributes: Vec<Attribute>,
/// The parameter set by `parameter = value`, or `None` for a positional argument, which for a node is the shorthand `name`.
pub parameter: Option<Ident>,
pub value: Expression,
}
/// A node state method after a call, like `.offset(0, 2)`.
pub struct State {
pub kind: StateKind,
pub span: Span,
}
#[derive(Clone, PartialEq)]
pub enum StateKind {
At(i32, i32),
Offset(i32, i32),
Named(String),
Hidden,
Locked,
Pinned,
Layer,
}
impl Parse for Source {
fn parse(input: ParseStream) -> syn::Result<Self> {
parse_header(input)?;
let mut uses = Vec::new();
while input.peek(Token![use]) {
uses.extend(parse_use(input)?);
}
let graph = input.parse()?;
if !input.is_empty() {
return Err(input.error("Graph text defines one graph"));
}
Ok(Self { uses, graph })
}
}
/// Reads `#![syntax(N)]`, which every graph text starts with.
fn parse_header(input: ParseStream) -> syn::Result<()> {
if !(input.peek(Token![#]) && input.peek2(Token![!])) {
return Err(input.error(format!("Graph text starts with its syntax version, like `#![syntax({SYNTAX_VERSION})]`")));
}
input.parse::<Token![#]>()?;
input.parse::<Token![!]>()?;
let content;
bracketed!(content in input);
let name: Ident = content.parse()?;
if name != "syntax" {
return Err(Error::new(name.span(), "The header is `#![syntax(N)]`"));
}
let arguments;
parenthesized!(arguments in content);
let literal: LitInt = arguments.parse()?;
let version: u32 = literal.base10_parse()?;
if version != SYNTAX_VERSION {
return Err(Error::new(literal.span(), format!("Syntax version {version} isn't supported, only {SYNTAX_VERSION} is")));
}
Ok(())
}
/// Reads `use path::name@N;` or `use path::{a@N, b@N as c};`.
fn parse_use(input: ParseStream) -> syn::Result<Vec<Use>> {
let use_token: Token![use] = input.parse()?;
let mut module = Vec::new();
let entries = loop {
if input.peek(syn::token::Brace) {
let content;
braced!(content in input);
break Punctuated::<UseEntry, Token![,]>::parse_terminated(&content)?.into_iter().collect::<Vec<_>>();
}
let segment: Ident = input.parse()?;
if input.peek(Token![::]) {
input.parse::<Token![::]>()?;
module.push(segment);
} else {
break vec![UseEntry::parse_after_name(segment, input)?];
}
};
input.parse::<Token![;]>()?;
if module.is_empty() {
return Err(Error::new(use_token.span, "Name a node by its full path, like `use math_nodes::add@1;`"));
}
Ok(entries
.into_iter()
.map(|entry| Use {
module: module.clone(),
name: entry.name,
version: entry.version,
alias: entry.alias,
})
.collect())
}
struct UseEntry {
name: Ident,
version: u32,
alias: Option<Ident>,
}
impl UseEntry {
fn parse_after_name(name: Ident, input: ParseStream) -> syn::Result<Self> {
let version = parse_version(input)?;
let alias = if input.peek(Token![as]) {
input.parse::<Token![as]>()?;
Some(input.parse()?)
} else {
None
};
Ok(Self { name, version, alias })
}
}
impl Parse for UseEntry {
fn parse(input: ParseStream) -> syn::Result<Self> {
let name = input.parse()?;
Self::parse_after_name(name, input)
}
}
/// Reads `@N`, the version a node or graph is declared or used at.
fn parse_version(input: ParseStream) -> syn::Result<u32> {
if !input.peek(Token![@]) {
return Err(input.error("Give the version, like `@1`"));
}
input.parse::<Token![@]>()?;
let literal: LitInt = input.parse()?;
if !literal.suffix().is_empty() {
return Err(Error::new(literal.span(), "Write the version without a type suffix"));
}
let version: u32 = literal.base10_parse()?;
if version == 0 {
return Err(Error::new(literal.span(), "Versions start at 1"));
}
Ok(version)
}
/// Reads any number of `#[...]` groups, each holding comma-separated attribute items.
fn parse_attributes(input: ParseStream) -> syn::Result<Vec<Attribute>> {
let mut attributes = Vec::new();
while input.peek(Token![#]) && !input.peek2(Token![!]) {
input.parse::<Token![#]>()?;
let content;
bracketed!(content in input);
while !content.is_empty() {
let name = content.call(Ident::parse_any)?;
let arguments = if content.peek(syn::token::Paren) {
let arguments;
parenthesized!(arguments in content);
AttributeArguments::List(arguments.parse()?)
} else if content.peek(Token![=]) {
content.parse::<Token![=]>()?;
AttributeArguments::Value(content.parse()?)
} else {
AttributeArguments::None
};
attributes.push(Attribute { name, arguments });
if content.is_empty() {
break;
}
content.parse::<Token![,]>()?;
}
}
Ok(attributes)
}
/// The `///` lines among the attributes, each trimmed and joined by line breaks.
pub fn doc_comment(attributes: &[Attribute]) -> String {
attributes
.iter()
.filter(|attribute| attribute.name == "doc")
.filter_map(|attribute| match &attribute.arguments {
AttributeArguments::Value(Lit::Str(text)) => Some(text.value().trim().to_string()),
_ => None,
})
.collect::<Vec<_>>()
.join("\n")
.trim()
.to_string()
}
impl Parse for GraphItem {
fn parse(input: ParseStream) -> syn::Result<Self> {
let attributes = parse_attributes(input)?;
input.parse::<Token![fn]>()?;
let name: Ident = input.parse()?;
let version = parse_version(input)?;
let parameters;
parenthesized!(parameters in input);
let imports = Punctuated::<Import, Token![,]>::parse_terminated(&parameters)?.into_iter().collect();
input.parse::<Token![->]>()?;
let exports: Vec<Export> = if input.peek(syn::token::Paren) {
let content;
parenthesized!(content in input);
Punctuated::<Export, Token![,]>::parse_terminated(&content)?.into_iter().collect()
} else {
vec![input.parse()?]
};
if exports.is_empty() {
return Err(Error::new(name.span(), "Name at least one export, like `-> (out)`"));
}
let body;
braced!(body in input);
let mut bindings = Vec::new();
while body.peek(Token![let]) {
bindings.push(body.parse()?);
}
if body.is_empty() {
return Err(Error::new(name.span(), "A graph ends its body with one value per export"));
}
let result = parse_expression(&body)?;
if body.peek(Token![;]) {
return Err(body.error("The graph ends with its exports, written without a semicolon"));
}
if !body.is_empty() {
return Err(body.error("Each statement in a graph is a `let` binding, followed by the exports it ends with"));
}
Ok(Self {
attributes,
name,
version,
imports,
exports,
bindings,
result,
})
}
}
impl Parse for Import {
fn parse(input: ParseStream) -> syn::Result<Self> {
let attributes = parse_attributes(input)?;
let name = if input.peek(Token![_]) {
input.parse::<Token![_]>()?;
None
} else {
Some(input.parse()?)
};
if input.peek(Token![:]) {
return Err(input.error("Imports take no type, since it's inferred from the inputs they feed"));
}
Ok(Self { attributes, name })
}
}
impl Parse for Export {
fn parse(input: ParseStream) -> syn::Result<Self> {
let attributes = parse_attributes(input)?;
let name = input.call(Ident::parse_any)?;
Ok(Self { attributes, name })
}
}
impl Parse for Binding {
fn parse(input: ParseStream) -> syn::Result<Self> {
input.parse::<Token![let]>()?;
let name = input.parse()?;
input.parse::<Token![=]>()?;
let value = parse_expression(input)?;
input.parse::<Token![;]>()?;
Ok(Self { name, value })
}
}
impl Parse for Expression {
fn parse(input: ParseStream) -> syn::Result<Self> {
parse_expression(input)
}
}
/// Reads a chain of `>>`, which binds loosest and groups from the left.
fn parse_expression(input: ParseStream) -> syn::Result<Expression> {
let mut expression = parse_postfix(input)?;
while input.peek(Token![>>]) {
let token: Token![>>] = input.parse()?;
let downstream = parse_postfix(input)?;
expression = Expression::Feed {
upstream: Box::new(expression),
downstream: Box::new(downstream),
span: token.span(),
};
}
Ok(expression)
}
/// Reads a primary expression followed by node state methods and output choices.
fn parse_postfix(input: ParseStream) -> syn::Result<Expression> {
let mut expression = parse_primary(input)?;
while input.peek(Token![.]) && !input.peek(Token![..]) {
input.parse::<Token![.]>()?;
let name = input.call(Ident::parse_any)?;
if !input.peek(syn::token::Paren) {
if matches!(expression, Expression::Output { .. }) {
return Err(Error::new(name.span(), "An output is already chosen here"));
}
expression = Expression::Output {
node: Box::new(expression),
output: name,
};
continue;
}
let arguments;
parenthesized!(arguments in input);
let call = match &mut expression {
Expression::Call(call) => call,
Expression::Output { .. } => {
return Err(Error::new(name.span(), "Node state goes before the output it chooses, like `regex_find().at(0, 0).captures`"));
}
_ => return Err(Error::new(name.span(), "Node state goes directly after the call it modifies, not on a binding")),
};
let state = parse_state(&name, &arguments)?;
if call.states.iter().any(|existing| std::mem::discriminant(&existing.kind) == std::mem::discriminant(&state.kind)) {
return Err(Error::new(name.span(), format!("`.{name}()` is already set on this node")));
}
call.states.push(state);
}
Ok(expression)
}
fn parse_state(name: &Ident, arguments: ParseStream) -> syn::Result<State> {
let method = name.to_string();
let no_arguments = || match arguments.is_empty() {
true => Ok(()),
false => Err(arguments.error(format!("`.{method}()` takes no arguments"))),
};
let coordinates = || -> syn::Result<(i32, i32)> {
let x = parse_grid_coordinate(arguments)?;
arguments.parse::<Token![,]>()?;
let y = parse_grid_coordinate(arguments)?;
if !arguments.is_empty() {
return Err(arguments.error("Give two coordinates in grid units"));
}
Ok((x, y))
};
let kind = match method.as_str() {
"at" => {
let (x, y) = coordinates()?;
StateKind::At(x, y)
}
"offset" => {
let (x, y) = coordinates()?;
StateKind::Offset(x, y)
}
"named" => {
let display_name: LitStr = arguments.parse()?;
StateKind::Named(display_name.value())
}
"hidden" => no_arguments().map(|_| StateKind::Hidden)?,
"locked" => no_arguments().map(|_| StateKind::Locked)?,
"pinned" => no_arguments().map(|_| StateKind::Pinned)?,
"layer" => no_arguments().map(|_| StateKind::Layer)?,
_ => {
return Err(Error::new(
name.span(),
format!("Unknown node state `.{method}()`. Parameters go inside the call's parentheses, like `node({method} = ...)`"),
));
}
};
Ok(State { kind, span: name.span() })
}
fn parse_grid_coordinate(input: ParseStream) -> syn::Result<i32> {
let negative = input.peek(Token![-]);
if negative {
input.parse::<Token![-]>()?;
}
let literal: LitInt = input.parse().map_err(|error| Error::new(error.span(), "Positions are integers in grid units"))?;
if !literal.suffix().is_empty() {
return Err(Error::new(literal.span(), "Write the position without a type suffix"));
}
let magnitude: i32 = literal.base10_parse()?;
Ok(if negative { -magnitude } else { magnitude })
}
fn parse_primary(input: ParseStream) -> syn::Result<Expression> {
let span = input.span();
if input.peek(syn::token::Paren) {
let content;
parenthesized!(content in input);
let elements = Punctuated::<Expression, Token![,]>::parse_terminated(&content)?;
if elements.is_empty() {
return Err(Error::new(span, "Empty parentheses aren't part of the graph syntax"));
}
if elements.len() == 1 && !elements.trailing_punct() {
return Ok(elements.into_iter().next().expect("there is one element"));
}
return Ok(Expression::Tuple {
elements: elements.into_iter().collect(),
span,
});
}
if input.peek(syn::token::Bracket) {
let content;
bracketed!(content in input);
let numbers = Punctuated::<Value, Token![,]>::parse_terminated(&content)?;
let components: Vec<f64> = numbers
.iter()
.filter_map(|number| match number.kind {
ValueKind::Number(number) => Some(number),
ValueKind::Integer(integer) => Some(integer as f64),
_ => None,
})
.collect();
let [x, y] = components.as_slice() else {
return Err(Error::new(span, "A value array is a two-number Vec2, like `[1., 2.]`"));
};
return Ok(Expression::Value(Value { kind: ValueKind::Vec2(*x, *y), span }));
}
if input.peek(Lit) || input.peek(Token![-]) {
return input.parse().map(Expression::Value);
}
if input.peek(Ident) {
let name: Ident = input.parse()?;
if !input.peek(syn::token::Paren) {
return Ok(Expression::Name(name));
}
let content;
parenthesized!(content in input);
let arguments = Punctuated::<Argument, Token![,]>::parse_terminated(&content)?.into_iter().collect();
return Ok(Expression::Call(Call { name, arguments, states: Vec::new() }));
}
Err(input.error("This isn't part of the graph syntax"))
}
impl Parse for Value {
fn parse(input: ParseStream) -> syn::Result<Self> {
let span = input.span();
let negative = input.peek(Token![-]);
if negative {
input.parse::<Token![-]>()?;
}
let literal: Lit = input.parse()?;
let kind = match &literal {
Lit::Int(integer) => {
if !integer.suffix().is_empty() {
return Err(Error::new(integer.span(), "Write the integer without a type suffix. Its type is `i64`"));
}
let value: i64 = integer.base10_parse()?;
ValueKind::Integer(if negative { -value } else { value })
}
Lit::Float(float) => {
if !float.suffix().is_empty() {
return Err(Error::new(float.span(), "Write the number without a type suffix. Its type is `f64`"));
}
let value: f64 = float.base10_parse()?;
ValueKind::Number(if negative { -value } else { value })
}
Lit::Bool(boolean) if !negative => ValueKind::Bool(boolean.value),
Lit::Str(string) if !negative => ValueKind::String(string.value()),
_ if negative => return Err(Error::new(literal.span(), "Only a number can be negated")),
_ => return Err(Error::new(literal.span(), "Unsupported literal")),
};
Ok(Self { kind, span })
}
}
impl Parse for Argument {
fn parse(input: ParseStream) -> syn::Result<Self> {
let attributes = parse_attributes(input)?;
let parameter = if input.peek(Ident) && input.peek2(Token![=]) && !input.peek2(Token![==]) {
let parameter = input.parse()?;
input.parse::<Token![=]>()?;
Some(parameter)
} else {
None
};
let value = parse_expression(input)?;
Ok(Self { attributes, parameter, value })
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(text: &str) -> syn::Result<Source> {
syn::parse_str(text)
}
fn error_message(text: &str) -> String {
match parse(text) {
Ok(_) => panic!("the graph text should be rejected"),
Err(error) => error.to_string(),
}
}
#[test]
fn reads_the_header_uses_and_graph() {
let source = parse(
r#"
#![syntax(1)]
use graphic_nodes::graphic::{as_graphic@1, extend@2 as append};
use graphic_nodes::graphic::into_group@1;
/// Merges content.
#[category("Graphic"), layer]
fn merge@3(base, #[expose] content) -> (out) {
let grouped = content >> into_group();
base >> as_graphic() >> append(new = grouped)
}
"#,
)
.expect("the graph text should parse");
let uses: Vec<String> = source.uses.iter().map(|entry| format!("{}::{}@{}", entry.module_path(), entry.local_name(), entry.version)).collect();
assert_eq!(
uses,
["graphic_nodes::graphic::as_graphic@1", "graphic_nodes::graphic::append@2", "graphic_nodes::graphic::into_group@1"]
);
let graph = &source.graph;
assert_eq!(graph.name, "merge");
assert_eq!(graph.version, 3);
assert_eq!(doc_comment(&graph.attributes), "Merges content.");
assert_eq!(graph.imports.len(), 2);
assert_eq!(graph.bindings.len(), 1);
assert!(matches!(graph.result, Expression::Feed { .. }));
}
#[test]
fn reads_state_values_and_outputs() {
let source = parse(
r#"
#![syntax(1)]
use a::b::{f@1, g@1};
fn state@1(_, x) -> (match, other) {
let node = f(#[exposed] flag = false, offset = -2.5, size = [1, -2.], count = 3, label = "text", x).named("N").offset(0, -2).hidden();
(node.match, node >> g())
}
"#,
)
.expect("the graph text should parse");
let graph = &source.graph;
assert!(graph.imports[0].name.is_none());
assert_eq!(graph.exports[0].name, "match");
let Expression::Call(call) = &graph.bindings[0].value else {
panic!("the binding should be a call")
};
let kinds: Vec<StateKind> = call.states.iter().map(|state| state.kind.clone()).collect();
assert!(kinds == [StateKind::Named("N".into()), StateKind::Offset(0, -2), StateKind::Hidden]);
assert!(matches!(call.arguments[1].value, Expression::Value(Value { kind: ValueKind::Number(-2.5), .. })));
assert!(matches!(call.arguments[2].value, Expression::Value(Value { kind: ValueKind::Vec2(1., -2.), .. })));
assert!(matches!(call.arguments[3].value, Expression::Value(Value { kind: ValueKind::Integer(3), .. })));
assert!(call.arguments[5].parameter.is_none());
let Expression::Tuple { elements, .. } = &graph.result else {
panic!("the result should be a tuple")
};
assert!(matches!(&elements[0], Expression::Output { output, .. } if output == "match"));
}
#[test]
fn rejects_text_without_a_supported_header() {
assert!(error_message("fn a@1() -> (out) { b() }").contains("starts with its syntax version"));
assert!(error_message("#![syntax(2)] fn a@1() -> (out) { b() }").contains("isn't supported"));
}
#[test]
fn rejects_unversioned_and_unqualified_names() {
assert!(error_message("#![syntax(1)] use a::b; fn a@1() -> (out) { b() }").contains("Give the version"));
assert!(error_message("#![syntax(1)] use b@1; fn a@1() -> (out) { b() }").contains("full path"));
assert!(error_message("#![syntax(1)] fn a() -> (out) { b() }").contains("Give the version"));
assert!(error_message("#![syntax(1)] fn a@0() -> (out) { b() }").contains("start at 1"));
}
#[test]
fn rejects_typed_imports_and_suffixed_literals() {
assert!(error_message("#![syntax(1)] fn a@1(x: Item<f64>) -> (out) { b(x) }").contains("take no type"));
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b(c = 1_u32) }").contains("without a type suffix"));
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b(c = 1.5_f32) }").contains("without a type suffix"));
}
#[test]
fn rejects_misplaced_state() {
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { let n = b(); n.hidden() }").contains("not on a binding"));
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().out.hidden() }").contains("before the output"));
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().hidden().hidden() }").contains("already set"));
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().weight(2) }").contains("Unknown node state"));
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().at(1.5, 2) }").contains("integers in grid units"));
}
#[test]
fn rejects_a_semicolon_after_the_exports() {
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b(); }").contains("without a semicolon"));
}
}
@@ -0,0 +1,324 @@
use super::*;
use crate::resolve::blank_field;
use core_types::registry::{FieldMetadata, GraphInputSource, GraphNodeImplementation, GraphValue, NodeFlags, RegistryValueSource};
use core_types::{Type, concrete};
fn parameter(identifier: &'static str, default_type: Type) -> FieldMetadata {
FieldMetadata {
name: identifier,
identifier,
description: "From the node.",
default_type: Some(default_type),
..blank_field()
}
}
fn proto_node(fields: Vec<FieldMetadata>) -> NodeMetadata {
NodeMetadata {
display_name: "",
category: "",
icon: None,
fields,
description: "",
inspector: None,
context_features: Vec::new(),
flags: NodeFlags::default(),
version: 1,
output_fields: None,
}
}
/// `test_nodes::Group(content)`, `test_nodes::Extend(base, new)`, and `test_nodes::Scale(value, factor, label)`.
fn proto_nodes() -> HashMap<ProtoNodeIdentifier, NodeMetadata> {
let list = || Type::List(Box::new(concrete!(f64)));
let number = || Type::Item(Box::new(concrete!(f64)));
let mut factor = parameter("factor", number());
factor.unit = Some(" px");
factor.value_source = RegistryValueSource::Default("2.");
HashMap::from([
(ProtoNodeIdentifier::new("test_nodes::GroupNode"), proto_node(vec![parameter("content", list())])),
(
ProtoNodeIdentifier::new("test_nodes::ExtendNode"),
proto_node(vec![parameter("base", list()), parameter("new", list())]),
),
(
ProtoNodeIdentifier::new("test_nodes::ScaleNode"),
proto_node(vec![parameter("value", number()), factor, parameter("label", Type::Item(Box::new(concrete!(String))))]),
),
])
}
fn source(text: &'static str) -> GraphSource {
GraphSource {
module_path: "test_graphs",
file: "test_graphs.rs",
line: 1,
column: 1,
text,
}
}
fn resolve_texts(texts: &[&'static str]) -> (Vec<GraphMetadata>, Vec<GraphTextError>) {
let sources: Vec<GraphSource> = texts.iter().map(|text| source(text)).collect();
resolve_sources(&sources, &proto_nodes())
}
fn resolve_one(text: &'static str) -> GraphMetadata {
let (mut graphs, errors) = resolve_texts(&[text]);
assert!(errors.is_empty(), "the graph should resolve: {}", errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("\n"));
graphs.remove(0)
}
fn error_message(text: &'static str) -> String {
let (graphs, errors) = resolve_texts(&[text]);
assert!(graphs.is_empty(), "the graph should be rejected");
errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("\n")
}
const MERGE: &str = r#"
#![syntax(1)]
use test_nodes::{extend@1, group@1};
/// Merges content.
#[category("Test"), layer]
fn merge@1(
/// The stack below.
base,
#[expose]
content,
) -> (out) {
base >> extend(new = content >> group())
}
"#;
#[test]
fn resolves_nodes_wires_and_layout() {
let graph = resolve_one(MERGE);
assert_eq!(graph.identifier, "Merge");
assert_eq!(graph.path, "test_graphs::merge");
assert_eq!(graph.description, "Merges content.");
assert!(graph.layer);
let implementations: Vec<_> = graph.nodes.iter().map(|node| node.implementation.clone()).collect();
assert_eq!(
implementations,
[
GraphNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test_nodes::GroupNode")),
GraphNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test_nodes::ExtendNode")),
]
);
assert!(matches!(
graph.nodes[1].inputs.as_slice(),
[(1, GraphInputSource::Node { node: 0, output: 0 }), (0, GraphInputSource::Import { index: 0, .. })]
));
assert!(matches!(graph.exports[0].source, GraphInputSource::Node { node: 1, output: 0 }));
let positions: Vec<_> = graph.nodes.iter().map(|node| node.position).collect();
assert_eq!(positions, [(-7, 1), (0, 0)]);
}
#[test]
fn imports_inherit_from_the_input_they_feed_unless_overridden() {
let graph = resolve_one(
r#"
#![syntax(1)]
use test_nodes::scale@1;
#[category("Test")]
fn scaled@1(value, factor, #[unit("%")] #[default(10)] other) -> (out) {
let first = value >> scale(factor);
first >> scale(factor = other)
}
"#,
);
let [value, factor, other] = graph.imports.as_slice() else {
panic!("the graph should have three imports")
};
assert_eq!(value.name, "Value");
assert_eq!(factor.unit, Some(" px"));
assert_eq!(factor.description, "From the node.");
assert!(matches!(factor.value_source, RegistryValueSource::Default("2.")));
assert_eq!(other.unit, Some("%"));
assert!(matches!(other.value_source, RegistryValueSource::Default("10")));
assert_eq!(other.default_type, Some(concrete!(i64)));
assert!(matches!(&graph.nodes[1].inputs[0].1, GraphInputSource::Import { index: 2, ty } if *ty == Type::Item(Box::new(concrete!(i64)))));
}
#[test]
fn an_import_inherits_from_the_parameter_of_its_own_name_first() {
let graph = resolve_one(
r#"
#![syntax(1)]
use test_nodes::scale@1;
#[category("Test")]
fn scaled@1(value, label) -> (out) {
let first = value >> scale(factor = 1., label = value);
first >> scale(label)
}
"#,
);
assert_eq!(graph.imports[0].default_type, Some(Type::Item(Box::new(concrete!(f64)))));
assert_eq!(graph.imports[1].default_type, Some(Type::Item(Box::new(concrete!(String)))));
}
#[test]
fn values_keep_the_type_they_are_written_with() {
let graph = resolve_one(
r#"
#![syntax(1)]
use test_nodes::scale@1;
#[category("Test")]
fn values@1(value) -> (out) {
value >> scale(factor = 2, #[exposed] label = "text")
}
"#,
);
let inputs = &graph.nodes[0].inputs;
assert!(matches!(
&inputs[0].1,
GraphInputSource::Value {
value: GraphValue::Integer(2),
exposed: None
}
));
assert!(matches!(&inputs[1].1, GraphInputSource::Value { value: GraphValue::String(text), exposed: Some(true) } if text == "text"));
}
#[test]
fn a_graph_resolves_after_a_graph_it_uses_and_chooses_its_outputs_by_name() {
let outer = r#"
#![syntax(1)]
use test_graphs::pair@1;
use test_nodes::group@1;
#[category("Test")]
fn outer@1(content) -> (out) {
content >> pair().second >> group()
}
"#;
let pair = r#"
#![syntax(1)]
use test_nodes::group@1;
#[category("Test")]
fn pair@1(content) -> (first, second) {
let grouped = content >> group();
(grouped, grouped >> group())
}
"#;
let (graphs, errors) = resolve_texts(&[outer, pair]);
assert!(errors.is_empty(), "both graphs should resolve");
let outer = graphs.iter().find(|graph| graph.identifier == "Outer").expect("the outer graph should resolve");
assert_eq!(outer.nodes[0].implementation, GraphNodeImplementation::Graph("Pair"));
assert!(matches!(outer.nodes[1].inputs[0].1, GraphInputSource::Node { node: 0, output: 1 }));
}
#[test]
fn rejects_names_that_dont_resolve() {
let unknown_parameter = error_message(
r#"
#![syntax(1)]
use test_nodes::group@1;
#[category("Test")]
fn bad@1(content) -> (out) { content >> group(weight = 2) }
"#,
);
assert!(unknown_parameter.contains("`group` has no parameter named `weight`"), "{unknown_parameter}");
let unknown_node = error_message(
r#"
#![syntax(1)]
use test_nodes::missing@1;
#[category("Test")]
fn bad@1(content) -> (out) { content >> missing() }
"#,
);
assert!(unknown_node.contains("No node or graph is named `test_nodes::missing`"), "{unknown_node}");
let not_used = error_message(
r#"
#![syntax(1)]
#[category("Test")]
fn bad@1(content) -> (out) { content >> group() }
"#,
);
assert!(not_used.contains("`group` isn't used"), "{not_used}");
}
#[test]
fn rejects_wrong_versions_and_unused_entries() {
let wrong_version = error_message(
r#"
#![syntax(1)]
use test_nodes::group@2;
#[category("Test")]
fn bad@1(content) -> (out) { content >> group() }
"#,
);
assert!(wrong_version.contains("is at version 1, not 2"), "{wrong_version}");
let unused = error_message(
r#"
#![syntax(1)]
use test_nodes::{extend@1, group@1};
#[category("Test")]
fn bad@1(content) -> (out) { content >> group() }
"#,
);
assert!(unused.contains("`extend` is used but never called"), "{unused}");
}
#[test]
fn rejects_wiring_mistakes() {
let primary_twice = error_message(
r#"
#![syntax(1)]
use test_nodes::group@1;
#[category("Test")]
fn bad@1(content) -> (out) { content >> group(content) }
"#,
);
assert!(primary_twice.contains("is already fed"), "{primary_twice}");
let looped = error_message(
r#"
#![syntax(1)]
use test_nodes::group@1;
#[category("Test")]
fn bad@1(content) -> (out) {
let node = group();
node >> node
}
"#,
);
assert!(looped.contains("makes a loop"), "{looped}");
let export_from_import = error_message(
r#"
#![syntax(1)]
#[category("Test")]
fn bad@1(content) -> (out) { content }
"#,
);
assert!(export_from_import.contains("straight from an import"), "{export_from_import}");
}
#[test]
fn errors_name_where_the_graph_is_written() {
let (_, errors) = resolve_texts(&["#![syntax(1)] #[category(\"Test\")] fn bad@1(content) -> (out) { content >> missing() }"]);
let error = errors.first().expect("the graph should be rejected");
assert_eq!((error.file, error.line, error.column), ("test_graphs.rs", 1, 1));
assert!(error.excerpt.starts_with("missing()"), "{}", error.excerpt);
}
+10 -13
View File
@@ -957,13 +957,13 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
} }
/// The display name an identifier derives, in Title Case. /// The display name an identifier derives, in Title Case.
pub(crate) fn derived_display_name(ident: &Ident) -> String { fn derived_display_name(ident: &Ident) -> String {
// A lone `_` comes out of the case conversion as a space // A lone `_` comes out of the case conversion as a space
ident.unraw().to_string().to_case(Case::Title).trim().to_string() 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. /// 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 { fn parameter_display_name(field: &ParsedField) -> String {
match &field.name { match &field.name {
Some(name) => name.value(), Some(name) => name.value(),
None => derived_display_name(&field.pat_ident.ident), None => derived_display_name(&field.pat_ident.ident),
@@ -971,24 +971,24 @@ pub(crate) fn parameter_display_name(field: &ParsedField) -> String {
} }
/// The symbol naming a parameter or output in a node's module, like `CountInput` for the `count` parameter. /// 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 { fn symbol_name(ident: &Ident, suffix: &str) -> Ident {
format_ident!("{}{suffix}", ident.unraw().to_string().to_case(Case::Pascal), span = ident.span()) 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. /// 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>) -> TokenStream2 { fn option_tokens(value: Option<TokenStream2>) -> TokenStream2 {
match value { match value {
Some(value) => quote!(::core::option::Option::Some(#value)), Some(value) => quote!(::core::option::Option::Some(#value)),
None => quote!(::core::option::Option::None), 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 /// The registry's `FieldMetadata` for a parameter.
/// how they work out whether it's internal state and which type its default is built from. fn field_metadata_tokens(field: &ParsedField, internal: bool, default_type: &TokenStream2, core_types: &TokenStream2) -> TokenStream2 {
pub(crate) fn field_metadata_tokens(field: &ParsedField, internal: bool, default_type: &TokenStream2, core_types: &TokenStream2) -> TokenStream2 {
let registry = quote!(#core_types::registry); let registry = quote!(#core_types::registry);
let name = parameter_display_name(field); let name = parameter_display_name(field);
let identifier = field.pat_ident.ident.unraw().to_string();
let description = &field.description; let description = &field.description;
let exposed = match field.ty.regular() { let exposed = match field.ty.regular() {
Some(regular) => regular.exposed, Some(regular) => regular.exposed,
@@ -1056,6 +1056,7 @@ pub(crate) fn field_metadata_tokens(field: &ParsedField, internal: bool, default
quote! { quote! {
#registry::FieldMetadata { #registry::FieldMetadata {
name: #name, name: #name,
identifier: #identifier,
description: #description, description: #description,
internal: #internal, internal: #internal,
exposed: #exposed, exposed: #exposed,
@@ -1101,8 +1102,8 @@ fn color_constant_paths(tokens: &TokenStream2) -> Option<Vec<ExprPath>> {
.collect() .collect()
} }
/// Generates the module named after the node's function, holding its identifier, its parameter count, and a symbol for each parameter. /// Generates the module named after the node's function, holding its identifier 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. /// The inputs the compiler fills in come after the parameters and get no symbol.
fn generate_node_input_references(parsed: &ParsedNodeFn, parameter_idents: &[&PatIdent], core_types: &TokenStream2, identifier: &Ident, cfg: &TokenStream2) -> TokenStream2 { 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 inputs_module_name = &parsed.fn_name;
@@ -1119,8 +1120,6 @@ fn generate_node_input_references(parsed: &ParsedNodeFn, parameter_idents: &[&Pa
} }
}); });
let parameter_count = parameter_idents.len();
quote! { quote! {
#cfg #cfg
pub mod #inputs_module_name { pub mod #inputs_module_name {
@@ -1128,8 +1127,6 @@ fn generate_node_input_references(parsed: &ParsedNodeFn, parameter_idents: &[&Pa
/// The `ProtoNodeIdentifier` of this node without any generics attached to it /// The `ProtoNodeIdentifier` of this node without any generics attached to it
pub const IDENTIFIER: #core_types::ProtoNodeIdentifier = #identifier(); 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)* #(#generated_input_accessor)*
} }
} }
File diff suppressed because it is too large. Load diff
-33
View File
@@ -5,7 +5,6 @@ mod codegen;
mod crate_ident; mod crate_ident;
mod derive_choice_type; mod derive_choice_type;
mod destructure; mod destructure;
mod graph;
mod parsing; mod parsing;
mod validation; mod validation;
@@ -17,38 +16,6 @@ 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() 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::<Footprint>()`. 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<Graphic>,
/// /// Outline thickness.
/// #[unit(" px")]
/// width: Item<f64>,
/// ) -> 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<T>` or `List<T>` fields an output connector. /// Derives `Destructure` for a struct returned by a multi-output node, making each of its `Item<T>` or `List<T>` fields an output connector.
/// ///
/// A node function returning such a struct (rather than an `Item` or `List`) becomes a multi-output node. The preprocessor /// A node function returning such a struct (rather than an `Item` or `List`) becomes a multi-output node. The preprocessor
+3 -4
View File
@@ -326,8 +326,8 @@ impl ToTokens for NumberBound {
/// Unlike a Rust range there is no `..=` form, `..` is purely this attribute DSL's bounds operator. /// Unlike a Rust range there is no `..=` form, `..` is purely this attribute DSL's bounds operator.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct NumberRange { pub struct NumberRange {
pub(crate) start: Option<NumberBound>, start: Option<NumberBound>,
pub(crate) end: Option<NumberBound>, end: Option<NumberBound>,
} }
impl Parse for NumberRange { impl Parse for NumberRange {
@@ -826,8 +826,7 @@ fn parse_node_implementations<T: Parse>(attr: &Attribute, name: &Ident) -> syn::
}) })
} }
/// Parses a parameter and its attributes, for a proto node's field or a graph's import. fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Result<ParsedField> {
pub(crate) fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Result<ParsedField> {
let ident = &pat_ident.ident; 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. // Checks for the #[data] attribute, indicating that this is a data field rather than an input parameter to the node.
+7 -5
View File
@@ -1,4 +1,3 @@
use crate::graph::VALUE_HELPERS;
use crate::parsing::{Implementation, NodeOutputTier, NodeParsedField, ParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, output_payload, output_tier}; use crate::parsing::{Implementation, NodeOutputTier, NodeParsedField, ParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, output_payload, output_tier};
use proc_macro_error3::{abort_if_dirty, emit_error}; use proc_macro_error3::{abort_if_dirty, emit_error};
use quote::quote; use quote::quote;
@@ -28,8 +27,11 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
Ok(()) 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. /// The calls graph text reads as values or input sources rather than as nodes, so no node can share one's name.
pub(crate) fn validate_name_isnt_a_value_helper(name: &Ident) { const VALUE_HELPERS: &[&str] = &["rgb", "rgba", "scope", "reflect"];
/// Graph text reads a call to a value helper like `rgb(...)` as a value, so a node of that name couldn't be called there.
fn validate_name_isnt_a_value_helper(name: &Ident) {
if let Some(message) = value_helper_name_violation(name) { if let Some(message) = value_helper_name_violation(name) {
emit_error!(name.span(), "{}", message); emit_error!(name.span(), "{}", message);
} }
@@ -305,8 +307,8 @@ fn is_unit_type(ty: &Type) -> bool {
matches!(ty, Type::Tuple(tuple) if tuple.elems.is_empty()) matches!(ty, Type::Tuple(tuple) if tuple.elems.is_empty())
} }
/// The checks on a node's parameters, shared by proto node fields and graph imports, where the first is the primary input. /// The checks on a node's parameters, where the first is the primary input.
pub(crate) fn validate_parameters(fields: &[ParsedField]) { fn validate_parameters(fields: &[ParsedField]) {
validate_primary_input_expose(fields); validate_primary_input_expose(fields);
validate_min_max(fields); validate_min_max(fields);
validate_range_slider_bounds(fields); validate_range_slider_bounds(fields);
+1
View File
@@ -43,6 +43,7 @@ dyn-any = { workspace = true }
graph-craft = { workspace = true } graph-craft = { workspace = true }
wgpu-executor = { workspace = true } wgpu-executor = { workspace = true }
core-types = { workspace = true } core-types = { workspace = true }
graph-text = { workspace = true }
vector-types = { workspace = true } vector-types = { workspace = true }
graphic-types = { workspace = true } graphic-types = { workspace = true }
raster-kernels = { workspace = true } raster-kernels = { workspace = true }
+2 -1
View File
@@ -5,11 +5,12 @@ pub mod render_background;
pub mod render_cache; pub mod render_cache;
pub mod render_node; pub mod render_node;
pub mod render_pixel_preview; pub mod render_pixel_preview;
pub mod subgraphs; mod subgraphs;
pub mod text; pub mod text;
pub use blending_nodes; pub use blending_nodes;
pub use brush_nodes as brush; pub use brush_nodes as brush;
pub use core_types::*; pub use core_types::*;
pub use graph_text;
pub use graphene_application_io as application_io; pub use graphene_application_io as application_io;
pub use graphene_core; pub use graphene_core;
pub use graphene_core::debug; pub use graphene_core::debug;
+143 -192
View File
@@ -1,218 +1,169 @@
use crate::artboard::create_artboard; use core_types::graph;
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. graph! {
#[node_macro::graph(category("Graphic"), icon("NodeMerge"), layer)] #![syntax(1)]
pub fn merge( use graphic_nodes::graphic::{as_graphic@1, extend@1, into_group@1};
/// The stack of layers below this one, which the content is placed above.
base: List<Graphic>, /// Merges the provided content as a new item in the layer's compositing stack.
/// The artwork this layer adds to the stack as a single item. #[category("Graphic"), icon("NodeMerge"), layer]
#[expose] fn merge@1(
content: List<Graphic>, /// The stack of layers below this one, which the content is placed above.
) -> out!( base,
/// The stack of layers with this layer's content placed on top. /// The artwork this layer adds to the stack as a single item.
out, #[expose]
) { content,
let grouped = content >> into_group().at(-7, -1); ) -> (
base >> as_graphic().at(-7, -2) >> extend(new = grouped).at(0, -2) /// The stack of layers with this layer's content placed on top.
out,
) {
base >> as_graphic() >> extend(new = content >> into_group())
}
} }
/// Creates a new Artboard which can be used as a working surface. graph! {
#[node_macro::graph(category("Graphic"), icon("NodeArtboard"), layer)] #![syntax(1)]
pub fn artboard( use graphic_nodes::artboard::create_artboard@1;
/// The stack of artboards below this one, which this artboard is placed above. use graphic_nodes::graphic::extend@1;
base: List<Artboard>,
/// Graphics to include within the artboard. /// Creates a new Artboard which can be used as a working surface.
#[expose] #[category("Graphic"), icon("NodeArtboard"), layer]
content: List<Graphic>, fn artboard@1(
/// Coordinate of the top-left corner of the artboard within the document. /// The stack of artboards below this one, which this artboard is placed above.
#[labels("X", "Y")] base,
#[unit(" px")] #[expose]
#[integer] content,
location: Item<DVec2>, #[labels("X", "Y")]
/// Width and height of the artboard within the document. #[integer]
#[labels("W", "H")] location,
#[unit(" px")] #[labels("W", "H")]
#[integer] #[integer]
#[default(1920., 1080.)] #[default(1920., 1080.)]
dimensions: Item<DVec2>, dimensions,
/// Color of the artboard background. #[widget(Custom = "artboard_background")]
#[widget(ParsedWidgetOverride::Custom = "artboard_background")] #[default(Color::WHITE)]
#[default(Color::WHITE)] background,
background: Item<Color>, clip,
/// Whether to cut off the contained content that extends outside the artboard, or keep it visible. ) -> (
#[default(true)] /// The stack of artboards with this artboard placed on top.
clip: Item<bool>, out,
) -> out!( ) {
/// The stack of artboards with this artboard placed on top. base >> extend(new = create_artboard(content, location, dimensions, background, clip))
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. graph! {
#[node_macro::graph(category("Vector: Deform"), icon("NodeBlend"))] #![syntax(1)]
pub fn blend( use core_types::vector::{morph@1, path_is_closed@1, separate_paths@1, read_index@1};
/// The vector objects to create intermediate shapes between. use graphene_core::vector::count@1;
content: List<Vector>, use math_nodes::{add@1, as_number@1, divide@1, floor@1, max@1, modulo@1, multiply@1, subtract@1, switch@1};
/// The number of shapes spanning from the first object to the last, repeated for each subpath of the control path. use repeat_nodes::repeat_nodes::repeat@1;
#[default(10)]
count: Item<i64>,
/// Flip the stacking order of the shapes, so the ones nearest the first object are on top.
reverse: Item<bool>,
/// What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.
distribution: Item<InterpolationDistribution>,
/// An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.
path: Item<Vector>,
) -> 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 /// Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path.
let index = read_index().at(2, 7); #[category("Vector: Deform"), icon("NodeBlend")]
let path_index = index >> divide(denominator = shapes_per_path).at(16, 10) >> floor().at(23, 4); fn blend@1(
let local_index = index >> modulo(modulus = shapes_per_path).at(16, 7); /// The vector objects to create intermediate shapes between.
content,
/// The number of shapes spanning from the first object to the last, repeated for each subpath of the control path.
#[default(10)]
count,
/// Flip the stacking order of the shapes, so the ones nearest the first object are on top.
reverse,
/// What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.
distribution,
/// An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.
path,
) -> (
/// The blended shapes, from the first object to the last.
out,
) {
let shapes_per_path = count >> as_number() >> max(other_value = 1.);
let path_count = path >> separate_paths() >> count() >> max(other_value = 1.);
// 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 index = read_index();
let open_spacing = shapes_per_path >> subtract(subtrahend = 1).at(16, 14) >> max(other_value = 1).at(23, 14); let path_index = index >> divide(denominator = shapes_per_path) >> floor();
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); let local_index = index >> modulo(modulus = shapes_per_path);
// Scaling just below 1 keeps the last shape from overflowing into the next subpath let open_spacing = shapes_per_path >> subtract(subtrahend = 1.) >> max(other_value = 1.);
let fraction = local_index >> divide(denominator = spacing).at(23, 7) >> multiply(multiplicand = 0.9999999999).at(30, 7); let spacing = path >> path_is_closed(index = path_index) >> switch(if_true = shapes_per_path, if_false = open_spacing);
let progression = path_index >> add(addend = fraction).at(37, 4);
let total = shapes_per_path >> multiply(multiplicand = path_count).at(16, 1); let fraction = local_index >> divide(denominator = spacing) >> multiply(multiplicand = 0.9999999999);
content >> morph(progression, distribution, path).at(44, 3) >> repeat(count = total, reverse).at(51, 0) let progression = path_index >> add(addend = fraction);
let total = shapes_per_path >> multiply(multiplicand = path_count);
content >> morph(progression, distribution, path) >> repeat(count = total, reverse)
}
} }
/// 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. graph! {
#[node_macro::graph(category("Vector: Path"), icon("NodeOriginsToPolyline"), name("Origins to Polyline"))] #![syntax(1)]
pub fn origins_to_polyline( use core_types::vector::{as_vector@1, extract_transform@1, points_to_polyline@1};
/// The vector objects to connect in order by their origins. use graphene_core::vector::{combine_paths@1, read_vector@1};
vector: List<Vector>, use graphic_nodes::graphic::{flatten_vector@1, map@1};
) -> out!( use transform_nodes::transform_nodes::decompose_translation@1;
/// 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) /// 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.
#[category("Vector: Path"), icon("NodeOriginsToPolyline"), name("Origins to Polyline")]
fn origins_to_polyline@1(
/// The vector objects to connect in order by their origins.
vector,
) -> (
/// An open polyline with an anchor point at the origin of each object.
vector,
) {
let origin = read_vector() >> extract_transform() >> decompose_translation() >> as_vector();
vector >> flatten_vector() >> map(mapped = origin) >> combine_paths() >> points_to_polyline(closed = false)
}
} }
/// Loads an image from a given URL. graph! {
#[node_macro::graph(category("Data: I/O"), icon("NodeLoadImage"))] #![syntax(1)]
pub fn load_image( use graphene_std::platform_application_io::{bytes_to_image@1, load_resource@1};
_: (),
/// The web address or local asset path of the image to load. /// Loads an image from a given URL.
#[name("URL")] #[category("Data: I/O"), icon("NodeLoadImage")]
url: Item<String>, fn load_image@1(
) -> out!( _,
/// The loaded image. /// The web address or local asset path of the image to load.
image, #[name("URL")]
) { url,
load_resource(url).at(0, 0) >> bytes_to_image().at(7, 0) ) -> (
/// The loaded image.
image,
) {
load_resource(url) >> bytes_to_image()
}
} }
/// 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. graph! {
#[node_macro::graph(category("String: Regex"), icon("NodeRegexFind"))] #![syntax(1)]
pub fn regex_find( use graphic_nodes::graphic::{item_at_index@1, remove_at_index@1};
/// The string to search within. use text_nodes::regex::regex_find@1 as find;
string: Item<String>,
/// The regular expression pattern to search for.
pattern: Item<String>,
/// 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<i64>,
/// Match letters regardless of case.
case_insensitive: Item<bool>,
/// Make `^` and `$` match the start and end of each line, not just the whole string.
multiline: Item<bool>,
) -> 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); /// 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.
let capture_groups = found >> remove_at_index(index = 0).at(8, 2); #[category("String: Regex"), icon("NodeRegexFind")]
fn regex_find@1(string, pattern, match_index, case_insensitive, multiline) -> (
(whole_match, capture_groups) /// The whole portion of the string matching the pattern, or empty if there is no match.
match,
/// The text matched by each capture group in the pattern, in order.
captures,
) {
let found = string >> find(pattern, match_index, case_insensitive, multiline);
(found >> item_at_index(index = 0), found >> remove_at_index(index = 0))
}
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use core_types::registry::{GRAPH_SOURCES, NODE_METADATA};
use core_types::registry::GraphInputSource;
/// Finds the capture groups of a pattern.
#[node_macro::graph(category("Test"))]
fn regex_captures(string: Item<String>, pattern: Item<String>) -> out!(captures) {
return string >> regex_find(pattern).captures;
}
#[test] #[test]
fn an_output_chosen_by_name_wires_from_that_output() { fn every_graph_resolves() {
let graph = _regex_captures_graph_metadata(); let sources = GRAPH_SOURCES.lock().unwrap().clone();
assert!(matches!(graph.exports[0].source, GraphInputSource::Node { node: 0, output: 1 })); let (graphs, errors) = graph_text::resolve_sources(&sources, &NODE_METADATA.lock().unwrap());
}
/// Puts its content on a board, setting every piece of node state. let messages: Vec<String> = errors.iter().map(ToString::to_string).collect();
#[node_macro::graph(category("Test"))] assert!(messages.is_empty(), "every graph should resolve:\n{}", messages.join("\n"));
fn boarded(content: List<Graphic>) -> out!(out) { assert_eq!(graphs.len(), sources.len());
return create_artboard(content, background = rgb(0x102030), clip = exposed(false)) assert!(graphs.iter().any(|graph| graph.identifier == "Merge"), "the graphs should be registered at startup");
.named("Board")
.hidden()
.locked()
.pinned()
.layer()
.call_argument::<impl Any>()
.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)
}
));
} }
} }
@@ -219,7 +219,7 @@ Writing to any other node fails, since another anchor's run may be editing it.
### Network definitions ### Network definitions
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: Some built-in nodes, like Merge and Artboard, are subgraphs. Each is defined in graph text 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 after the graph's name, like `fn artboard@2`, when instances saved before your change would load wrongly, and register a migration from the old version with the `network` prefix:
```rust ```rust
rename!(network "Artboard"@1 => @2); rename!(network "Artboard"@1 => @2);