mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 15:53:26 -10:00
Cleanup const checking in the compiler (#4825)
* Cleanup const checking in the compiler * Reject constant data fields and update README node snippet * Group all boolean node attributes into NodeFlags
This commit is contained in:
1 parent
b9e5fcfae4
commit
f73fbfb719
22 files changed
+309
-301
No files matched your search
Generated
-1
@@ -2073,7 +2073,6 @@ dependencies = [
|
||||
"graphene-canvas-utils",
|
||||
"graphene-core",
|
||||
"graphene-hash",
|
||||
"graphic-nodes",
|
||||
"graphic-types",
|
||||
"gungraun",
|
||||
"js-sys",
|
||||
|
||||
@@ -335,7 +335,7 @@ fn convert_node(
|
||||
visible: node.attributes.get_or(node::VISIBLE, true),
|
||||
skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false),
|
||||
// Regenerated during compilation; not stored.
|
||||
context_dependencies: None,
|
||||
compile_metadata: None,
|
||||
original_location: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -266,8 +266,8 @@ fn diff_document_node(out: &mut String, expected: &graph_craft::document::Docume
|
||||
if expected.skip_deduplication != actual.skip_deduplication {
|
||||
let _ = writeln!(out, " skip_deduplication: expected={} actual={}", expected.skip_deduplication, actual.skip_deduplication);
|
||||
}
|
||||
if expected.context_dependencies != actual.context_dependencies {
|
||||
let _ = writeln!(out, " context_dependencies: expected={:?} actual={:?}", expected.context_dependencies, actual.context_dependencies);
|
||||
if expected.compile_metadata != actual.compile_metadata {
|
||||
let _ = writeln!(out, " compile_metadata: expected={:?} actual={:?}", expected.compile_metadata, actual.compile_metadata);
|
||||
}
|
||||
if expected.original_location != actual.original_location {
|
||||
let _ = writeln!(out, " original_location differs (recomputed at load, not stored):");
|
||||
|
||||
@@ -114,7 +114,7 @@ impl NodeTemplate {
|
||||
implementation,
|
||||
visible,
|
||||
skip_deduplication,
|
||||
context_dependencies: _,
|
||||
compile_metadata: _,
|
||||
original_location: _,
|
||||
} = document_node;
|
||||
let DocumentNodePersistentMetadata {
|
||||
@@ -198,7 +198,7 @@ impl NodeTemplate {
|
||||
implementation,
|
||||
visible,
|
||||
skip_deduplication,
|
||||
context_dependencies: None,
|
||||
compile_metadata: None,
|
||||
original_location: Default::default(),
|
||||
};
|
||||
let persistent_node_metadata = DocumentNodePersistentMetadata {
|
||||
|
||||
@@ -15,7 +15,7 @@ pub struct DocumentNode {
|
||||
pub implementation: DocumentNodeImplementation,
|
||||
pub visible: bool,
|
||||
pub skip_deduplication: bool,
|
||||
pub context_features: ContextDependencies,
|
||||
pub compile_metadata: Option<NodeCompileMetadata>,
|
||||
pub original_location: OriginalLocation,
|
||||
}
|
||||
```
|
||||
|
||||
@@ -40,7 +40,6 @@ rendering = { workspace = true, features = ["serde"] }
|
||||
raster-nodes = { workspace = true, features = ["serde"] }
|
||||
vector-nodes = { workspace = true, features = ["serde"] }
|
||||
graphic-types = { workspace = true, features = ["serde"] }
|
||||
graphic-nodes = { workspace = true }
|
||||
text-nodes = { workspace = true, features = ["serde"] }
|
||||
|
||||
# Workspace dependencies
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::proto::{ConstructionArgs, ProtoNetwork, ProtoNode};
|
||||
use core_types::memo::MemoHashGuard;
|
||||
pub use core_types::uuid::NodeId;
|
||||
pub use core_types::uuid::generate_uuid;
|
||||
use core_types::{Context, ContextDependencies, Cow, MemoHash, NodeParameter, ProtoNodeIdentifier, Type};
|
||||
use core_types::{Context, Cow, MemoHash, NodeCompileMetadata, NodeParameter, ProtoNodeIdentifier, Type};
|
||||
use dyn_any::DynAny;
|
||||
use glam::IVec2;
|
||||
use log::Metadata;
|
||||
@@ -58,7 +58,7 @@ pub struct DocumentNode {
|
||||
#[serde(default)]
|
||||
pub skip_deduplication: bool,
|
||||
#[serde(skip)]
|
||||
pub context_dependencies: Option<ContextDependencies>,
|
||||
pub compile_metadata: Option<NodeCompileMetadata>,
|
||||
/// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called.
|
||||
#[serde(skip)]
|
||||
pub original_location: OriginalLocation,
|
||||
@@ -92,7 +92,7 @@ impl Default for DocumentNode {
|
||||
visible: true,
|
||||
skip_deduplication: Default::default(),
|
||||
original_location: OriginalLocation::default(),
|
||||
context_dependencies: Default::default(),
|
||||
compile_metadata: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -166,7 +166,7 @@ impl DocumentNode {
|
||||
construction_args,
|
||||
original_location: self.original_location,
|
||||
skip_deduplication: self.skip_deduplication,
|
||||
context_dependencies: self.context_dependencies.unwrap_or_default(),
|
||||
compile_metadata: self.compile_metadata.unwrap_or_default(),
|
||||
upstream_context_features: Default::default(),
|
||||
}
|
||||
}
|
||||
@@ -961,9 +961,9 @@ impl NodeNetwork {
|
||||
return;
|
||||
};
|
||||
debug_assert!(
|
||||
node.context_dependencies.is_none(),
|
||||
"Network {id} should not have context dependencies: {deps:#?}",
|
||||
deps = node.context_dependencies
|
||||
node.compile_metadata.is_none(),
|
||||
"Network {id} should not have compile metadata: {compile_metadata:#?}",
|
||||
compile_metadata = node.compile_metadata
|
||||
);
|
||||
|
||||
// Replace value and reflection imports with value nodes, added inside nested network
|
||||
@@ -1337,7 +1337,7 @@ impl core_types::graphene_hash::CacheHash for DocumentNode {
|
||||
self.implementation.cache_hash(state);
|
||||
self.visible.cache_hash(state);
|
||||
self.skip_deduplication.cache_hash(state);
|
||||
self.context_dependencies.cache_hash(state);
|
||||
self.compile_metadata.cache_hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ impl Compiler {
|
||||
proto_networks.map(move |mut proto_network| {
|
||||
proto_network.insert_context_nullification_nodes()?;
|
||||
|
||||
let errors = proto_network.non_constant_attribute_names();
|
||||
let errors = proto_network.non_constant_inputs();
|
||||
if !errors.is_empty() {
|
||||
return Err(CompileError::Graph(errors));
|
||||
}
|
||||
|
||||
@@ -133,7 +133,7 @@ pub struct ProtoNode {
|
||||
pub identifier: ProtoNodeIdentifier,
|
||||
pub original_location: OriginalLocation,
|
||||
pub skip_deduplication: bool,
|
||||
pub(crate) context_dependencies: ContextDependencies,
|
||||
pub(crate) compile_metadata: NodeCompileMetadata,
|
||||
/// The context features read by this node and everything upstream of it.
|
||||
pub upstream_context_features: ContextFeatures,
|
||||
}
|
||||
@@ -146,7 +146,7 @@ impl Default for ProtoNode {
|
||||
call_argument: concrete!(()),
|
||||
original_location: OriginalLocation::default(),
|
||||
skip_deduplication: false,
|
||||
context_dependencies: Default::default(),
|
||||
compile_metadata: Default::default(),
|
||||
upstream_context_features: ContextFeatures::empty(),
|
||||
}
|
||||
}
|
||||
@@ -182,7 +182,7 @@ impl ProtoNode {
|
||||
..Default::default()
|
||||
},
|
||||
skip_deduplication: false,
|
||||
context_dependencies: Default::default(),
|
||||
compile_metadata: Default::default(),
|
||||
upstream_context_features: ContextFeatures::empty(),
|
||||
}
|
||||
}
|
||||
@@ -203,42 +203,6 @@ impl ProtoNode {
|
||||
}
|
||||
}
|
||||
|
||||
const fn parameter<P: NodeParameter>() -> (ProtoNodeIdentifier, usize) {
|
||||
(P::NODE_IDENTIFIER, P::INDEX)
|
||||
}
|
||||
|
||||
static ATTRIBUTE_NAME_INPUTS: [(ProtoNodeIdentifier, usize); 16] = {
|
||||
use graphic_nodes::graphic::*;
|
||||
[
|
||||
parameter::<write_attribute::NameInput>(),
|
||||
parameter::<read_attribute_vector::NameInput>(),
|
||||
parameter::<read_attribute_number::NameInput>(),
|
||||
parameter::<read_attribute_bool::NameInput>(),
|
||||
parameter::<read_attribute_string::NameInput>(),
|
||||
parameter::<read_attribute_transform::NameInput>(),
|
||||
parameter::<read_attribute_color::NameInput>(),
|
||||
parameter::<read_attribute_blend_mode::NameInput>(),
|
||||
parameter::<read_attribute_gradient_form::NameInput>(),
|
||||
parameter::<read_attribute_gradient_spread::NameInput>(),
|
||||
parameter::<read_attribute_gradient_space::NameInput>(),
|
||||
parameter::<read_attribute_gradient_interpolation::NameInput>(),
|
||||
parameter::<read_attribute_gradient_hue_direction::NameInput>(),
|
||||
parameter::<read_attribute_gradient_stops::NameInput>(),
|
||||
parameter::<read_attribute_artboard::NameInput>(),
|
||||
parameter::<read_attribute_raster::NameInput>(),
|
||||
]
|
||||
};
|
||||
|
||||
fn is_transparent(identifier: &ProtoNodeIdentifier) -> bool {
|
||||
let pass_through_nodes = [
|
||||
graphene_core::ops::passthrough::IDENTIFIER,
|
||||
graphene_core::memo::memoize::IDENTIFIER,
|
||||
graphene_core::memo::monitor::IDENTIFIER,
|
||||
graphene_core::context_modification::context_modification::IDENTIFIER,
|
||||
];
|
||||
pass_through_nodes.contains(identifier) || identifier.as_str().starts_with("input_adapter<")
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum NodeState {
|
||||
Unvisited,
|
||||
@@ -332,20 +296,25 @@ impl ProtoNetwork {
|
||||
pub(crate) fn footprint_invariance_violations(&self) -> GraphErrors {
|
||||
self.nodes
|
||||
.iter()
|
||||
.filter(|(_, node)| node.context_dependencies.footprint_invariant && node.upstream_context_features.contains(ContextFeatures::FOOTPRINT))
|
||||
.filter(|(_, node)| node.compile_metadata.footprint_invariant && node.upstream_context_features.contains(ContextFeatures::FOOTPRINT))
|
||||
.map(|(_, node)| GraphError::new(node, GraphErrorType::FootprintDependentInput))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn non_constant_attribute_names(&self) -> GraphErrors {
|
||||
pub(crate) fn non_constant_inputs(&self) -> GraphErrors {
|
||||
self.nodes
|
||||
.iter()
|
||||
.filter_map(|(_, node)| {
|
||||
let (_, name_index) = ATTRIBUTE_NAME_INPUTS.iter().find(|(identifier, _)| *identifier == node.identifier)?;
|
||||
let ConstructionArgs::Nodes(inputs) = &node.construction_args else { return None };
|
||||
let name_input = *inputs.get(*name_index)?;
|
||||
|
||||
(!self.resolves_to_value(name_input)).then(|| GraphError::new(node, GraphErrorType::NonConstantAttributeName))
|
||||
.filter(|(_, node)| node.compile_metadata.constant_inputs != 0)
|
||||
.flat_map(|(_, node)| {
|
||||
let inputs = match &node.construction_args {
|
||||
ConstructionArgs::Nodes(inputs) => inputs.as_slice(),
|
||||
_ => &[],
|
||||
};
|
||||
inputs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|&(index, &input)| node.compile_metadata.requires_constant_input(index) && !self.resolves_to_value(input))
|
||||
.map(|(index, _)| GraphError::new(node, GraphErrorType::NonConstantInput { index }))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -357,7 +326,7 @@ impl ProtoNetwork {
|
||||
|
||||
match &node.construction_args {
|
||||
ConstructionArgs::Value(_) => return true,
|
||||
ConstructionArgs::Nodes(inputs) if is_transparent(&node.identifier) => match inputs.first() {
|
||||
ConstructionArgs::Nodes(inputs) if node.compile_metadata.forwards_input => match inputs.first() {
|
||||
Some(&input) => id = input,
|
||||
None => return false,
|
||||
},
|
||||
@@ -376,6 +345,10 @@ impl ProtoNetwork {
|
||||
}
|
||||
|
||||
let features = context_deps.features;
|
||||
let forwarding = NodeCompileMetadata {
|
||||
forwards_input: true,
|
||||
..Default::default()
|
||||
};
|
||||
let memoize_node_id = NodeId(self.nodes.len() as u64);
|
||||
|
||||
self.nodes.push((
|
||||
@@ -388,6 +361,7 @@ impl ProtoNetwork {
|
||||
path: path.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
compile_metadata: forwarding,
|
||||
upstream_context_features: features,
|
||||
..Default::default()
|
||||
},
|
||||
@@ -419,6 +393,7 @@ impl ProtoNetwork {
|
||||
path: path.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
compile_metadata: forwarding,
|
||||
upstream_context_features: features,
|
||||
..Default::default()
|
||||
},
|
||||
@@ -441,7 +416,7 @@ impl ProtoNetwork {
|
||||
let mut combined_deps = ContextModification::default();
|
||||
let node_index = id.0 as usize;
|
||||
|
||||
let dependencies = self.nodes[node_index].1.context_dependencies;
|
||||
let dependencies = self.nodes[node_index].1.compile_metadata;
|
||||
|
||||
let mut inputs = match &self.nodes[node_index].1.construction_args {
|
||||
ConstructionArgs::Nodes(items) => items.clone(),
|
||||
@@ -641,7 +616,9 @@ pub enum GraphErrorType {
|
||||
valid: Vec<NodeIOTypes>,
|
||||
},
|
||||
FootprintDependentInput,
|
||||
NonConstantAttributeName,
|
||||
NonConstantInput {
|
||||
index: usize,
|
||||
},
|
||||
}
|
||||
impl Debug for GraphErrorType {
|
||||
// TODO: format with the document graph context so the input index is the same as in the graph UI.
|
||||
@@ -689,7 +666,7 @@ impl Debug for GraphErrorType {
|
||||
f,
|
||||
"Warning: an upstream node adapts to the visible canvas area, so this node's output changes when the view is panned or zoomed"
|
||||
),
|
||||
GraphErrorType::NonConstantAttributeName => write!(f, "The attribute name must be a fixed value rather than computed by other nodes"),
|
||||
GraphErrorType::NonConstantInput { index } => write!(f, "Input {} must be a fixed value rather than computed by other nodes", index + 1),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1228,7 +1205,7 @@ mod test {
|
||||
identifier: ProtoNodeIdentifier::new(name),
|
||||
call_argument: concrete!(()),
|
||||
construction_args,
|
||||
context_dependencies: ContextDependencies {
|
||||
compile_metadata: NodeCompileMetadata {
|
||||
extract,
|
||||
inject,
|
||||
..Default::default()
|
||||
@@ -1266,22 +1243,22 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn footprint_invariant_nodes_warn_only_when_their_inputs_read_the_footprint() {
|
||||
let node = |name: &'static str, inputs: Vec<NodeId>, dependencies: ContextDependencies| ProtoNode {
|
||||
let node = |name: &'static str, inputs: Vec<NodeId>, compile_metadata: NodeCompileMetadata| ProtoNode {
|
||||
identifier: ProtoNodeIdentifier::new(name),
|
||||
call_argument: concrete!(()),
|
||||
construction_args: ConstructionArgs::Nodes(inputs),
|
||||
context_dependencies: dependencies,
|
||||
compile_metadata,
|
||||
..Default::default()
|
||||
};
|
||||
let reader = ContextDependencies {
|
||||
let reader = NodeCompileMetadata {
|
||||
extract: ContextFeatures::FOOTPRINT,
|
||||
..Default::default()
|
||||
};
|
||||
let footprint_injector = ContextDependencies {
|
||||
let footprint_injector = NodeCompileMetadata {
|
||||
inject: ContextFeatures::FOOTPRINT,
|
||||
..Default::default()
|
||||
};
|
||||
let invariant = ContextDependencies {
|
||||
let invariant = NodeCompileMetadata {
|
||||
footprint_invariant: true,
|
||||
..Default::default()
|
||||
};
|
||||
@@ -1310,34 +1287,42 @@ mod test {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attribute_names_must_resolve_to_values_through_transparent_nodes() {
|
||||
fn constant_inputs_must_resolve_to_values_through_forwarding_nodes() {
|
||||
let value = || ProtoNode::value(ConstructionArgs::Value(TaggedValue::String("name".into()).into()), vec![]);
|
||||
let node = |identifier: ProtoNodeIdentifier, inputs: Vec<NodeId>| ProtoNode {
|
||||
identifier,
|
||||
let node = |inputs: Vec<NodeId>, compile_metadata: NodeCompileMetadata| ProtoNode {
|
||||
construction_args: ConstructionArgs::Nodes(inputs),
|
||||
compile_metadata,
|
||||
..Default::default()
|
||||
};
|
||||
let errors = |name_wrapper: ProtoNodeIdentifier| {
|
||||
let forwarding = NodeCompileMetadata {
|
||||
forwards_input: true,
|
||||
..Default::default()
|
||||
};
|
||||
let consumer = NodeCompileMetadata {
|
||||
constant_inputs: 1 << 1,
|
||||
..Default::default()
|
||||
};
|
||||
let errors = |name_wrapper: NodeCompileMetadata| {
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(5),
|
||||
nodes: vec![
|
||||
(NodeId(0), value()),
|
||||
(NodeId(1), value()),
|
||||
(NodeId(2), node(name_wrapper, vec![NodeId(1)])),
|
||||
(NodeId(3), node(ProtoNodeIdentifier::new("input_adapter<String>"), vec![NodeId(2)])),
|
||||
(NodeId(2), node(vec![NodeId(1)], name_wrapper)),
|
||||
(NodeId(3), node(vec![NodeId(2)], forwarding)),
|
||||
(NodeId(4), value()),
|
||||
(NodeId(5), node(graphic_nodes::graphic::write_attribute::IDENTIFIER, vec![NodeId(0), NodeId(3), NodeId(4)])),
|
||||
(NodeId(5), node(vec![NodeId(0), NodeId(3), NodeId(4)], consumer)),
|
||||
],
|
||||
};
|
||||
network.non_constant_attribute_names()
|
||||
network.non_constant_inputs()
|
||||
};
|
||||
|
||||
assert!(errors(graphene_core::memo::memoize::IDENTIFIER).is_empty());
|
||||
assert!(errors(forwarding).is_empty());
|
||||
|
||||
let computed = errors(ProtoNodeIdentifier::new("string_concatenate"));
|
||||
let computed = errors(NodeCompileMetadata::default());
|
||||
assert_eq!(computed.len(), 1);
|
||||
assert!(computed[0].error == GraphErrorType::NonConstantAttributeName);
|
||||
assert!(computed[0].error == GraphErrorType::NonConstantInput { index: 1 });
|
||||
}
|
||||
|
||||
fn source_branch_network(branch_a_sources: &[SourceId], branch_b_sources: &[SourceId]) -> ProtoNetwork {
|
||||
|
||||
@@ -31,7 +31,7 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::import(core_types::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate::IDENTIFIER),
|
||||
context_dependencies: Some(graphene_std::ContextDependencies {
|
||||
compile_metadata: Some(graphene_std::NodeCompileMetadata {
|
||||
extract: ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::INDEX,
|
||||
..Default::default()
|
||||
@@ -42,7 +42,7 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
|
||||
context_dependencies: Some(graphene_std::ContextDependencies {
|
||||
compile_metadata: Some(graphene_std::NodeCompileMetadata {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::empty(),
|
||||
..Default::default()
|
||||
@@ -57,7 +57,7 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
|
||||
context_dependencies: Some(graphene_std::ContextDependencies {
|
||||
compile_metadata: Some(graphene_std::NodeCompileMetadata {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::VARARGS,
|
||||
..Default::default()
|
||||
@@ -68,7 +68,7 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER),
|
||||
context_dependencies: Some(graphene_std::ContextDependencies {
|
||||
compile_metadata: Some(graphene_std::NodeCompileMetadata {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
..Default::default()
|
||||
@@ -82,7 +82,7 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
NodeInput::node(NodeId(3), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER),
|
||||
context_dependencies: Some(graphene_std::ContextDependencies {
|
||||
compile_metadata: Some(graphene_std::NodeCompileMetadata {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::empty(),
|
||||
..Default::default()
|
||||
@@ -93,7 +93,7 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::node(NodeId(4), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
|
||||
context_dependencies: Some(graphene_std::ContextDependencies {
|
||||
compile_metadata: Some(graphene_std::NodeCompileMetadata {
|
||||
// INDEX is never read; it forces a nullification and cache pair onto the `data` parameter's wire so the render cache keys on a stable context
|
||||
extract: ContextFeatures::VARARGS | ContextFeatures::INDEX,
|
||||
inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
|
||||
@@ -210,20 +210,30 @@ impl ContextFeatures {
|
||||
}
|
||||
}
|
||||
|
||||
// ====================
|
||||
// CONTEXT DEPENDENCIES
|
||||
// ====================
|
||||
// =====================
|
||||
// NODE COMPILE METADATA
|
||||
// =====================
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, graphene_hash::CacheHash, dyn_any::DynAny, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct ContextDependencies {
|
||||
pub struct NodeCompileMetadata {
|
||||
pub extract: ContextFeatures,
|
||||
pub inject: ContextFeatures,
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub footprint_invariant: bool,
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub forwards_input: bool,
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub constant_inputs: u64,
|
||||
}
|
||||
|
||||
impl From<&[ContextFeature]> for ContextDependencies {
|
||||
impl NodeCompileMetadata {
|
||||
pub fn requires_constant_input(&self, index: usize) -> bool {
|
||||
index < u64::BITS as usize && self.constant_inputs & (1 << index) != 0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&[ContextFeature]> for NodeCompileMetadata {
|
||||
fn from(features: &[ContextFeature]) -> Self {
|
||||
let mut extract = ContextFeatures::empty();
|
||||
let mut inject = ContextFeatures::empty();
|
||||
@@ -252,7 +262,7 @@ impl From<&[ContextFeature]> for ContextDependencies {
|
||||
Self {
|
||||
extract,
|
||||
inject,
|
||||
footprint_invariant: false,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,11 +15,18 @@ pub struct NodeMetadata {
|
||||
pub description: &'static str,
|
||||
pub inspector: Option<&'static str>,
|
||||
pub context_features: Vec<ContextFeature>,
|
||||
pub flags: NodeFlags,
|
||||
pub output_fields: Option<DestructureMetadata>,
|
||||
}
|
||||
|
||||
/// Boolean node properties from `#[node_macro::node(...)]` and the node function's signature.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct NodeFlags {
|
||||
pub memoize: bool,
|
||||
pub footprint_invariant: bool,
|
||||
pub forwards_input: bool,
|
||||
pub inject_scope: bool,
|
||||
pub asynchronous: bool,
|
||||
pub output_fields: Option<DestructureMetadata>,
|
||||
}
|
||||
|
||||
// Translation struct between macro and definition
|
||||
@@ -49,6 +56,8 @@ pub struct FieldMetadata {
|
||||
pub multiline: bool,
|
||||
/// Whether a number parameter uses the progression widget, which splits the value into fractional-progress and whole-element-number fields, from `#[progression]`.
|
||||
pub progression: bool,
|
||||
/// Whether the input must be fed by a value known at compile time, from `#[constant]`.
|
||||
pub constant: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
||||
@@ -323,6 +323,13 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
quote!(#progression)
|
||||
})
|
||||
.collect();
|
||||
let constant: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let constant = field.constant;
|
||||
quote!(#constant)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let exposed: Vec<_> = regular_fields
|
||||
.iter()
|
||||
@@ -545,7 +552,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
#(#unwrap_args)*
|
||||
#(#min_max_args)*
|
||||
};
|
||||
let cell_ctor = match attributes.no_partial {
|
||||
let cell_ctor = match attributes.flags.no_partial {
|
||||
true => quote!(#core_types::Status::no_partial()),
|
||||
false => quote!(#core_types::Status::new()),
|
||||
};
|
||||
@@ -855,10 +862,14 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
|
||||
let inspector = &attributes.inspector_string.as_ref().map(|value| quote!(Some(#value))).unwrap_or(quote!(None));
|
||||
let icon = &attributes.icon.as_ref().map(|value| quote!(Some(#value))).unwrap_or(quote!(None));
|
||||
let memoize_flag = attributes.memoize;
|
||||
let footprint_invariant_flag = attributes.footprint_invariant;
|
||||
let asynchronous_flag = parsed.is_async;
|
||||
let inject_scope_flag = attributes.inject_scope;
|
||||
let NodeFlags {
|
||||
memoize,
|
||||
footprint_invariant,
|
||||
forwards_input,
|
||||
inject_scope,
|
||||
..
|
||||
} = attributes.flags;
|
||||
let asynchronous = parsed.is_async;
|
||||
// A node returning a `Destructure` struct records its fields as output connectors
|
||||
let output_fields = match may_return_destructure_struct(parsed) {
|
||||
true => {
|
||||
@@ -1083,10 +1094,13 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
description: #description,
|
||||
inspector: #inspector,
|
||||
context_features: vec![#(ContextFeature::#context_features,)*],
|
||||
memoize: #memoize_flag,
|
||||
footprint_invariant: #footprint_invariant_flag,
|
||||
inject_scope: #inject_scope_flag,
|
||||
asynchronous: #asynchronous_flag,
|
||||
flags: gcore::registry::NodeFlags {
|
||||
memoize: #memoize,
|
||||
footprint_invariant: #footprint_invariant,
|
||||
forwards_input: #forwards_input,
|
||||
inject_scope: #inject_scope,
|
||||
asynchronous: #asynchronous,
|
||||
},
|
||||
output_fields: #output_fields,
|
||||
fields: vec![
|
||||
#(
|
||||
@@ -1109,6 +1123,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
unit: #unit_suffix,
|
||||
multiline: #multiline,
|
||||
progression: #progression,
|
||||
constant: #constant,
|
||||
},
|
||||
)*
|
||||
],
|
||||
@@ -1148,7 +1163,7 @@ fn generate_node_input_references(parsed: &ParsedNodeFn, field_idents: &[&PatIde
|
||||
let inputs_module_name = format_ident!("{}", parsed.struct_name.to_string().to_case(Case::Snake));
|
||||
|
||||
let mut generated_input_accessor = Vec::new();
|
||||
if !parsed.attributes.skip_impl {
|
||||
if !parsed.attributes.flags.skip_impl {
|
||||
for (input_index, input_ident) in field_idents.iter().enumerate() {
|
||||
// TODO: figure out a better name that doesn't conflict with so many types
|
||||
let struct_name = format_ident!("{}Input", input_ident.ident.to_string().to_case(Case::Pascal));
|
||||
@@ -1217,7 +1232,7 @@ impl RegisterVariant {
|
||||
/// connector's `Output = Item<T>`), which marks the node as element-wise.
|
||||
fn primary_item_element(parsed: &ParsedNodeFn) -> Option<syn::Type> {
|
||||
// Manually registered nodes control their own variants
|
||||
if parsed.attributes.skip_impl {
|
||||
if parsed.attributes.flags.skip_impl {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -1258,7 +1273,7 @@ fn generates_mapped_variant(parsed: &ParsedNodeFn) -> bool {
|
||||
|
||||
/// Whether the node is a `()`-primary generator that frames over its ranked params: a unit primary with at least one ranked (`Item<T>`) param.
|
||||
fn is_generator_frame(parsed: &ParsedNodeFn) -> bool {
|
||||
if parsed.attributes.skip_impl {
|
||||
if parsed.attributes.flags.skip_impl {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1312,7 +1327,7 @@ fn generate_register_node_impl(
|
||||
// On Wasm, `ctor` isn't available, so this `extern "C"` fn is invoked from JS to register the same way.
|
||||
// `skip_impl` nodes don't generate a `register_node`, so the shim calls only `register_metadata` for them.
|
||||
let registry_name = format_ident!("__node_registry_{}_{}", NODE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst), struct_name);
|
||||
let register_node_call = if parsed.attributes.skip_impl { quote!() } else { quote!(register_node();) };
|
||||
let register_node_call = if parsed.attributes.flags.skip_impl { quote!() } else { quote!(register_node();) };
|
||||
let wasm_shim = quote! {
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[unsafe(no_mangle)]
|
||||
@@ -1322,7 +1337,7 @@ fn generate_register_node_impl(
|
||||
}
|
||||
};
|
||||
|
||||
if parsed.attributes.skip_impl {
|
||||
if parsed.attributes.flags.skip_impl {
|
||||
return Ok(wasm_shim);
|
||||
}
|
||||
|
||||
|
||||
@@ -41,13 +41,28 @@ pub(crate) struct ParsedNodeFn {
|
||||
pub(crate) description: String,
|
||||
}
|
||||
|
||||
/// Boolean node attributes. The registry-facing subset is emitted as `core_types::registry::NodeFlags`, which this proc-macro crate cannot depend on.
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub(crate) struct NodeFlags {
|
||||
/// Whether the preprocessor should add a Memoize node after this node in the generated subnetwork.
|
||||
pub(crate) memoize: bool,
|
||||
pub(crate) footprint_invariant: bool,
|
||||
pub(crate) forwards_input: bool,
|
||||
/// Whether this node provides a scope.
|
||||
pub(crate) inject_scope: bool,
|
||||
pub(crate) skip_impl: bool,
|
||||
/// Whether the node refuses placeholder data.
|
||||
pub(crate) no_partial: bool,
|
||||
/// Set on the `Destructure` derive's generated extractor nodes, which take the struct rather than an `Item` or `List`. Not parsed from source.
|
||||
pub(crate) destructure_extractor: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub(crate) struct NodeFnAttributes {
|
||||
pub(crate) category: Option<LitStr>,
|
||||
pub(crate) display_name: Option<LitStr>,
|
||||
pub(crate) icon: Option<LitStr>,
|
||||
pub(crate) path: Option<Path>,
|
||||
pub(crate) skip_impl: bool,
|
||||
pub(crate) inspector_string: Option<LitStr>,
|
||||
/// whether to `#[cfg]` gate the node implementation, defaults to None
|
||||
pub(crate) cfg: Option<TokenStream2>,
|
||||
@@ -55,17 +70,9 @@ pub(crate) struct NodeFnAttributes {
|
||||
pub(crate) shader_node: Option<ShaderNodeType>,
|
||||
/// Custom serialization function path (e.g., "my_module::custom_serialize")
|
||||
pub(crate) serialize: Option<Path>,
|
||||
/// Whether the preprocessor should add a Memoize node after this node in the generated subnetwork
|
||||
pub(crate) memoize: bool,
|
||||
pub(crate) footprint_invariant: bool,
|
||||
/// Whether this node provides a scope
|
||||
pub(crate) inject_scope: bool,
|
||||
pub(crate) flags: NodeFlags,
|
||||
/// Fn producing an placeholder value used while node evaluation is pending
|
||||
pub(crate) placeholder: Option<Path>,
|
||||
/// Whether the node refuses placeholder data
|
||||
pub(crate) no_partial: bool,
|
||||
/// Set on the `Destructure` derive's generated extractor nodes, which take the struct rather than an `Item` or `List`. Not parsed from source.
|
||||
pub(crate) destructure_extractor: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -130,6 +137,7 @@ pub struct ParsedField {
|
||||
pub unit: Option<LitStr>,
|
||||
pub multiline: bool,
|
||||
pub progression: bool,
|
||||
pub constant: bool,
|
||||
pub is_data_field: bool,
|
||||
}
|
||||
|
||||
@@ -164,6 +172,7 @@ impl ParsedField {
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
}
|
||||
}
|
||||
@@ -450,16 +459,12 @@ impl Parse for NodeFnAttributes {
|
||||
let mut display_name = None;
|
||||
let mut icon = None;
|
||||
let mut path = None;
|
||||
let mut skip_impl = false;
|
||||
let mut inspector_string = None;
|
||||
let mut cfg = None;
|
||||
let mut shader_node = None;
|
||||
let mut serialize = None;
|
||||
let mut memoize = false;
|
||||
let mut footprint_invariant = false;
|
||||
let mut inject_scope = false;
|
||||
let mut flags = NodeFlags::default();
|
||||
let mut placeholder = None;
|
||||
let mut no_partial = false;
|
||||
|
||||
let content = input;
|
||||
// let content;
|
||||
@@ -531,13 +536,7 @@ impl Parse for NodeFnAttributes {
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., skip_impl, ...)]
|
||||
"skip_impl" => {
|
||||
let path = meta.require_path_only()?;
|
||||
if skip_impl {
|
||||
return Err(Error::new_spanned(path, "Multiple 'skip_impl' attributes are not allowed"));
|
||||
}
|
||||
skip_impl = true;
|
||||
}
|
||||
"skip_impl" => set_flag(&mut flags.skip_impl, meta, "skip_impl")?,
|
||||
// Override UI layout generator function name defined in `node_inspector.rs` that returns a custom Inspector layout for this node.
|
||||
// This is used to create custom UI for the input parameters of the node in cases where the defaults generated from the type and attributes are insufficient.
|
||||
//
|
||||
@@ -595,36 +594,23 @@ impl Parse for NodeFnAttributes {
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., memoize, ...)]
|
||||
"memoize" => {
|
||||
let path = meta.require_path_only()?;
|
||||
if memoize {
|
||||
return Err(Error::new_spanned(path, "Multiple 'memoize' attributes are not allowed"));
|
||||
}
|
||||
memoize = true;
|
||||
}
|
||||
"memoize" => set_flag(&mut flags.memoize, meta, "memoize")?,
|
||||
// Warns at compile time when an upstream node of this node reads the footprint.
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., footprint_invariant, ...)]
|
||||
"footprint_invariant" => {
|
||||
let path = meta.require_path_only()?;
|
||||
if footprint_invariant {
|
||||
return Err(Error::new_spanned(path, "Multiple 'footprint_invariant' attributes are not allowed"));
|
||||
}
|
||||
footprint_invariant = true;
|
||||
}
|
||||
"footprint_invariant" => set_flag(&mut flags.footprint_invariant, meta, "footprint_invariant")?,
|
||||
// Marks the node's output as its first input's value, so a compile-time constant stays constant through it.
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., forwards_input, ...)]
|
||||
"forwards_input" => set_flag(&mut flags.forwards_input, meta, "forwards_input")?,
|
||||
// Instructs the preprocessor to make this node available as a scope.
|
||||
// Other nodes can then access it with `#[scope(node::IDENTIFIER)]`.
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., inject_scope, ...)]
|
||||
"inject_scope" => {
|
||||
let path = meta.require_path_only()?;
|
||||
if inject_scope {
|
||||
return Err(Error::new_spanned(path, "Multiple 'inject_scope' attributes are not allowed"));
|
||||
}
|
||||
inject_scope = true;
|
||||
}
|
||||
"inject_scope" => set_flag(&mut flags.inject_scope, meta, "inject_scope")?,
|
||||
// The placeholder value used while a node's evaluation is pending.
|
||||
//
|
||||
// Example usage:
|
||||
@@ -642,20 +628,14 @@ impl Parse for NodeFnAttributes {
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., no_partial, ...)]
|
||||
"no_partial" => {
|
||||
let path = meta.require_path_only()?;
|
||||
if no_partial {
|
||||
return Err(Error::new_spanned(path, "Multiple 'no_partial' attributes are not allowed"));
|
||||
}
|
||||
no_partial = true;
|
||||
}
|
||||
"no_partial" => set_flag(&mut flags.no_partial, meta, "no_partial")?,
|
||||
_ => {
|
||||
return Err(Error::new_spanned(
|
||||
meta,
|
||||
indoc!(
|
||||
r#"
|
||||
Unsupported attribute in `node`.
|
||||
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'shader_node', 'serialize', 'memoize', 'footprint_invariant', 'inject_scope', 'placeholder', and 'no_partial'.
|
||||
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'shader_node', 'serialize', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', and 'no_partial'.
|
||||
Example usage:
|
||||
#[node_macro::node(..., name("Test Node"), ...)]
|
||||
"#
|
||||
@@ -683,21 +663,25 @@ impl Parse for NodeFnAttributes {
|
||||
display_name,
|
||||
icon,
|
||||
path,
|
||||
skip_impl,
|
||||
inspector_string,
|
||||
cfg,
|
||||
shader_node,
|
||||
serialize,
|
||||
memoize,
|
||||
footprint_invariant,
|
||||
inject_scope,
|
||||
flags,
|
||||
placeholder,
|
||||
no_partial,
|
||||
destructure_extractor: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn set_flag(flag: &mut bool, meta: &Meta, name: &str) -> syn::Result<()> {
|
||||
let path = meta.require_path_only()?;
|
||||
if *flag {
|
||||
return Err(Error::new_spanned(path, format!("Multiple '{name}' attributes are not allowed")));
|
||||
}
|
||||
*flag = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn parse_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result<ParsedNodeFn> {
|
||||
let attributes = syn::parse2::<NodeFnAttributes>(attr.clone()).map_err(|e| Error::new(e.span(), format!("Failed to parse node_fn attributes:\n{e}")))?;
|
||||
let input_fn = syn::parse2::<ItemFn>(item.clone()).map_err(|e| Error::new(e.span(), format!("Failed to parse function: {e}. Make sure it's a valid Rust function.")))?;
|
||||
@@ -907,6 +891,9 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
|
||||
let exposed = extract_attribute(attrs, "expose").is_some();
|
||||
|
||||
// The `#[constant]` marker makes the compiler reject inputs not fed by a value known at compile time
|
||||
let constant = extract_attribute(attrs, "constant").is_some();
|
||||
|
||||
// Validate data field attributes
|
||||
if is_data_field {
|
||||
if default_value.is_some() {
|
||||
@@ -924,6 +911,12 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
"Data fields (#[data]) cannot be exposed (#[expose]). They are internal state, not node parameters",
|
||||
));
|
||||
}
|
||||
if constant {
|
||||
return Err(Error::new_spanned(
|
||||
&pat_ident,
|
||||
"Data fields (#[data]) cannot be #[constant]. They are internal state, not node parameters",
|
||||
));
|
||||
}
|
||||
}
|
||||
if exposed && ident.to_string().starts_with('_') {
|
||||
return Err(Error::new_spanned(
|
||||
@@ -1051,6 +1044,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
unit,
|
||||
multiline,
|
||||
progression,
|
||||
constant,
|
||||
is_data_field,
|
||||
})
|
||||
} else {
|
||||
@@ -1104,6 +1098,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
unit,
|
||||
multiline,
|
||||
progression,
|
||||
constant,
|
||||
is_data_field,
|
||||
})
|
||||
}
|
||||
@@ -1224,7 +1219,7 @@ pub fn new_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result<TokenS
|
||||
/// exempt from the ranked-input validation.
|
||||
pub(crate) fn new_destructure_extractor_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result<TokenStream2> {
|
||||
let mut parsed_node = parse_node_fn(attr, item).map_err(|e| Error::new(e.span(), format!("Failed to parse node function:\n{e}")))?;
|
||||
parsed_node.attributes.destructure_extractor = true;
|
||||
parsed_node.attributes.flags.destructure_extractor = true;
|
||||
generate_parsed_node_fn(parsed_node)
|
||||
}
|
||||
|
||||
@@ -1337,7 +1332,7 @@ mod tests {
|
||||
assert_eq!(parsed.attributes.category, expected.attributes.category);
|
||||
assert_eq!(parsed.attributes.display_name, expected.attributes.display_name);
|
||||
assert_eq!(parsed.attributes.path, expected.attributes.path);
|
||||
assert_eq!(parsed.attributes.skip_impl, expected.attributes.skip_impl);
|
||||
assert_eq!(parsed.attributes.flags.skip_impl, expected.attributes.flags.skip_impl);
|
||||
assert_eq!(parsed.fields.len(), expected.fields.len());
|
||||
assert_eq!(parsed.description, expected.description);
|
||||
|
||||
@@ -1424,20 +1419,12 @@ mod tests {
|
||||
vis: Visibility::Inherited,
|
||||
attributes: NodeFnAttributes {
|
||||
category: Some(parse_quote!("Math: Arithmetic")),
|
||||
display_name: None,
|
||||
icon: None,
|
||||
path: Some(parse_quote!(core_types::TestNode)),
|
||||
skip_impl: true,
|
||||
inspector_string: None,
|
||||
cfg: None,
|
||||
shader_node: None,
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
footprint_invariant: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
no_partial: false,
|
||||
destructure_extractor: false,
|
||||
flags: NodeFlags {
|
||||
skip_impl: true,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
fn_name: Ident::new("add", Span::call_site()),
|
||||
struct_name: Ident::new("Add", Span::call_site()),
|
||||
@@ -1476,6 +1463,7 @@ mod tests {
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1503,20 +1491,7 @@ mod tests {
|
||||
vis: Visibility::Inherited,
|
||||
attributes: NodeFnAttributes {
|
||||
category: Some(parse_quote!("General")),
|
||||
display_name: None,
|
||||
icon: None,
|
||||
path: None,
|
||||
skip_impl: false,
|
||||
inspector_string: None,
|
||||
cfg: None,
|
||||
shader_node: None,
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
footprint_invariant: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
no_partial: false,
|
||||
destructure_extractor: false,
|
||||
..Default::default()
|
||||
},
|
||||
fn_name: Ident::new("transform", Span::call_site()),
|
||||
struct_name: Ident::new("Transform", Span::call_site()),
|
||||
@@ -1549,6 +1524,7 @@ mod tests {
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
},
|
||||
ParsedField {
|
||||
@@ -1574,6 +1550,7 @@ mod tests {
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
},
|
||||
],
|
||||
@@ -1599,20 +1576,7 @@ mod tests {
|
||||
vis: Visibility::Inherited,
|
||||
attributes: NodeFnAttributes {
|
||||
category: Some(parse_quote!("Vector: Shape")),
|
||||
display_name: None,
|
||||
icon: None,
|
||||
path: None,
|
||||
skip_impl: false,
|
||||
inspector_string: None,
|
||||
cfg: None,
|
||||
shader_node: None,
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
footprint_invariant: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
no_partial: false,
|
||||
destructure_extractor: false,
|
||||
..Default::default()
|
||||
},
|
||||
fn_name: Ident::new("circle", Span::call_site()),
|
||||
struct_name: Ident::new("Circle", Span::call_site()),
|
||||
@@ -1651,6 +1615,7 @@ mod tests {
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1674,20 +1639,7 @@ mod tests {
|
||||
vis: Visibility::Inherited,
|
||||
attributes: NodeFnAttributes {
|
||||
category: Some(parse_quote!("Raster: Adjustment")),
|
||||
display_name: None,
|
||||
icon: None,
|
||||
path: None,
|
||||
skip_impl: false,
|
||||
inspector_string: None,
|
||||
cfg: None,
|
||||
shader_node: None,
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
footprint_invariant: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
no_partial: false,
|
||||
destructure_extractor: false,
|
||||
..Default::default()
|
||||
},
|
||||
fn_name: Ident::new("levels", Span::call_site()),
|
||||
struct_name: Ident::new("Levels", Span::call_site()),
|
||||
@@ -1731,6 +1683,7 @@ mod tests {
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1761,20 +1714,8 @@ mod tests {
|
||||
vis: Visibility::Inherited,
|
||||
attributes: NodeFnAttributes {
|
||||
category: Some(parse_quote!("Math: Arithmetic")),
|
||||
display_name: None,
|
||||
icon: None,
|
||||
path: Some(parse_quote!(core_types::TestNode)),
|
||||
skip_impl: false,
|
||||
inspector_string: None,
|
||||
cfg: None,
|
||||
shader_node: None,
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
footprint_invariant: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
no_partial: false,
|
||||
destructure_extractor: false,
|
||||
..Default::default()
|
||||
},
|
||||
fn_name: Ident::new("add", Span::call_site()),
|
||||
struct_name: Ident::new("Add", Span::call_site()),
|
||||
@@ -1813,6 +1754,7 @@ mod tests {
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1851,20 +1793,7 @@ mod tests {
|
||||
vis: Visibility::Inherited,
|
||||
attributes: NodeFnAttributes {
|
||||
category: Some(parse_quote!("IO")),
|
||||
display_name: None,
|
||||
icon: None,
|
||||
path: None,
|
||||
skip_impl: false,
|
||||
inspector_string: None,
|
||||
cfg: None,
|
||||
shader_node: None,
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
footprint_invariant: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
no_partial: false,
|
||||
destructure_extractor: false,
|
||||
..Default::default()
|
||||
},
|
||||
fn_name: Ident::new("load_image", Span::call_site()),
|
||||
struct_name: Ident::new("LoadImage", Span::call_site()),
|
||||
@@ -1903,6 +1832,7 @@ mod tests {
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1927,19 +1857,7 @@ mod tests {
|
||||
attributes: NodeFnAttributes {
|
||||
category: Some(parse_quote!("Custom")),
|
||||
display_name: Some(parse_quote!("CustomNode2")),
|
||||
icon: None,
|
||||
path: None,
|
||||
skip_impl: false,
|
||||
inspector_string: None,
|
||||
cfg: None,
|
||||
shader_node: None,
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
footprint_invariant: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
no_partial: false,
|
||||
destructure_extractor: false,
|
||||
..Default::default()
|
||||
},
|
||||
fn_name: Ident::new("custom_node", Span::call_site()),
|
||||
struct_name: Ident::new("CustomNode", Span::call_site()),
|
||||
@@ -1999,6 +1917,24 @@ mod tests {
|
||||
parse_node_fn(attr, input).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "Data fields (#[data]) cannot be #[constant]")]
|
||||
fn test_constant_data_field() {
|
||||
let attr = quote!(category("Invalid"));
|
||||
let input = quote!(
|
||||
fn invalid_node(
|
||||
_: impl Ctx,
|
||||
input: i32,
|
||||
#[data]
|
||||
#[constant]
|
||||
cache: i32,
|
||||
) -> i32 {
|
||||
input
|
||||
}
|
||||
);
|
||||
parse_node_fn(attr, input).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "Unsupported attribute in `node`")]
|
||||
fn test_unsupported_attribute() {
|
||||
|
||||
@@ -272,6 +272,7 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
});
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
|
||||
}
|
||||
|
||||
fn validate_no_item_parameters(parsed: &ParsedNodeFn) {
|
||||
if parsed.attributes.skip_impl {
|
||||
if parsed.attributes.flags.skip_impl {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ fn validate_no_item_parameters(parsed: &ParsedNodeFn) {
|
||||
}
|
||||
|
||||
fn validate_element_wise(parsed: &ParsedNodeFn) {
|
||||
if parsed.attributes.skip_impl {
|
||||
if parsed.attributes.flags.skip_impl {
|
||||
return;
|
||||
}
|
||||
let output = output_payload(&parsed.output_type);
|
||||
@@ -134,7 +134,7 @@ fn validate_ranked_inputs(parsed: &ParsedNodeFn) {
|
||||
fn ranked_input_violations(parsed: &ParsedNodeFn) -> Vec<(proc_macro2::Span, String)> {
|
||||
let mut violations = Vec::new();
|
||||
// A `Destructure` derive's extractor takes the struct itself rather than an `Item` or `List`
|
||||
if parsed.attributes.skip_impl || parsed.attributes.destructure_extractor {
|
||||
if parsed.attributes.flags.skip_impl || parsed.attributes.flags.destructure_extractor {
|
||||
return violations;
|
||||
}
|
||||
|
||||
@@ -239,7 +239,7 @@ fn validate_implementations_row_counts(parsed: &ParsedNodeFn) {
|
||||
}
|
||||
|
||||
fn implementations_row_count_violations(parsed: &ParsedNodeFn) -> Vec<(proc_macro2::Span, String)> {
|
||||
if parsed.attributes.skip_impl {
|
||||
if parsed.attributes.flags.skip_impl {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
@@ -399,7 +399,7 @@ fn validate_primary_input_expose(parsed: &ParsedNodeFn) {
|
||||
}
|
||||
|
||||
fn validate_implementations_for_generics(parsed: &ParsedNodeFn) {
|
||||
let has_skip_impl = parsed.attributes.skip_impl;
|
||||
let has_skip_impl = parsed.attributes.flags.skip_impl;
|
||||
|
||||
if !has_skip_impl && !parsed.fn_generics.is_empty() {
|
||||
for field in &parsed.fields {
|
||||
|
||||
@@ -11,7 +11,7 @@ use raster_types::{CPU, GPU, Raster};
|
||||
|
||||
/// Filters out what should be unused components of the context based on the specified requirements.
|
||||
/// This node is inserted by the compiler to "zero out" unused context components.
|
||||
#[node_macro::node(category("_Context Nullification"))]
|
||||
#[node_macro::node(category("_Context Nullification"), forwards_input)]
|
||||
fn context_modification<T>(
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll,
|
||||
/// The data to pass through, evaluated with the stripped down context.
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::sync::Mutex;
|
||||
/// Helps speed up repeated renders in a computationally-heavy part of the node graph.
|
||||
///
|
||||
/// Stores the last evaluated data that flowed through this node and immediately returns that data on subsequent renders if the context has not changed.
|
||||
#[node_macro::node(category("Routing"), icon("NodeMemoize"), path(graphene_core::memo), skip_impl)]
|
||||
#[node_macro::node(category("Routing"), icon("NodeMemoize"), path(graphene_core::memo), skip_impl, forwards_input)]
|
||||
fn memoize<I: CacheHash + Clone + Send, T: Clone + WasmNotSend>(input: I, content: impl Node<I, Output = T>, #[data] cache: Arc<Mutex<Option<(u64, Poll<T>)>>>) -> Poll<T> {
|
||||
// Caches the output of a given node called with a specific input.
|
||||
//
|
||||
@@ -39,7 +39,7 @@ fn memoize<I: CacheHash + Clone + Send, T: Clone + WasmNotSend>(input: I, conten
|
||||
type MonitorValue<I, T> = Arc<Mutex<Option<Arc<IORecord<I, T>>>>>;
|
||||
|
||||
/// The Monitor node is used by the editor to access the data flowing through it.
|
||||
#[node_macro::node(category(""), path(graphene_core::memo), serialize(serialize_monitor), inspector("monitor_inspector"), skip_impl)]
|
||||
#[node_macro::node(category(""), path(graphene_core::memo), serialize(serialize_monitor), inspector("monitor_inspector"), skip_impl, forwards_input)]
|
||||
fn monitor<I: Clone + 'static + Send + Sync, T: Clone + 'static + Send + Sync>(
|
||||
input: I,
|
||||
content: impl Node<I, Output = T>,
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::marker::PhantomData;
|
||||
pub use core_types::ops::TypeNode;
|
||||
|
||||
/// Passes-through the input value without changing it. This is useful for rerouting wires for organization purposes.
|
||||
#[node_macro::node(category("Routing"), icon("NodePassthrough"), skip_impl)]
|
||||
#[node_macro::node(category("Routing"), icon("NodePassthrough"), skip_impl, forwards_input)]
|
||||
fn passthrough<'i, T: 'i + Send>(_: impl Ctx, content: T) -> T {
|
||||
content
|
||||
}
|
||||
|
||||
@@ -539,6 +539,7 @@ fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
)]
|
||||
content: List<T>,
|
||||
/// The attribute name (key) to write or replace.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
/// The node that produces the attribute value for each item. Called once per item with the item's index in context.
|
||||
value: impl Node<Context<'static>, Output = Item<AttributeValueDyn>>,
|
||||
@@ -561,6 +562,7 @@ fn read_attribute_vector(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
) -> List<Vector> {
|
||||
let name = name.into_element();
|
||||
@@ -578,6 +580,7 @@ fn read_attribute_number(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
) -> List<f64> {
|
||||
let name = name.into_element();
|
||||
@@ -596,6 +599,7 @@ fn read_attribute_bool(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
) -> List<bool> {
|
||||
let name = name.into_element();
|
||||
@@ -613,6 +617,7 @@ fn read_attribute_string(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
) -> List<String> {
|
||||
let name = name.into_element();
|
||||
@@ -630,6 +635,7 @@ fn read_attribute_transform(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
) -> List<DAffine2> {
|
||||
let name = name.into_element();
|
||||
@@ -647,6 +653,7 @@ fn read_attribute_color(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
) -> List<Color> {
|
||||
let name = name.into_element();
|
||||
@@ -664,6 +671,7 @@ fn read_attribute_blend_mode(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
) -> List<BlendMode> {
|
||||
let name = name.into_element();
|
||||
@@ -681,6 +689,7 @@ fn read_attribute_gradient_form(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
) -> List<GradientForm> {
|
||||
let name = name.into_element();
|
||||
@@ -698,6 +707,7 @@ fn read_attribute_gradient_spread(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
) -> List<GradientSpread> {
|
||||
let name = name.into_element();
|
||||
@@ -715,6 +725,7 @@ fn read_attribute_gradient_space(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
) -> List<GradientSpace> {
|
||||
let name = name.into_element();
|
||||
@@ -732,6 +743,7 @@ fn read_attribute_gradient_interpolation(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
) -> List<GradientInterpolation> {
|
||||
let name = name.into_element();
|
||||
@@ -749,6 +761,7 @@ fn read_attribute_gradient_hue_direction(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
) -> List<GradientHueDirection> {
|
||||
let name = name.into_element();
|
||||
@@ -766,6 +779,7 @@ fn read_attribute_gradient_stops(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
) -> List<Gradient> {
|
||||
let name = name.into_element();
|
||||
@@ -783,6 +797,7 @@ fn read_attribute_artboard(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
) -> List<Artboard> {
|
||||
let name = name.into_element();
|
||||
@@ -800,6 +815,7 @@ fn read_attribute_raster(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
) -> List<Raster<CPU>> {
|
||||
let name = name.into_element();
|
||||
|
||||
@@ -33,7 +33,7 @@ struct Substitution {
|
||||
pub struct Preprocessor {
|
||||
substitutions: HashMap<ProtoNodeIdentifier, Substitution>,
|
||||
inject_scopes: HashMap<ProtoNodeIdentifier, (DocumentNode, Type)>,
|
||||
context_dependencies: HashMap<ProtoNodeIdentifier, ContextDependencies>,
|
||||
compile_metadata: HashMap<ProtoNodeIdentifier, NodeCompileMetadata>,
|
||||
}
|
||||
|
||||
impl Preprocessor {
|
||||
@@ -122,7 +122,7 @@ impl Preprocessor {
|
||||
match &mut node.implementation {
|
||||
DocumentNodeImplementation::Network(node_network) => self.expand_network(node_network),
|
||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => {
|
||||
let context_dependencies = node.context_dependencies.take().or_else(|| self.context_dependencies.get(proto_node_identifier).copied());
|
||||
let compile_metadata = node.compile_metadata.take().or_else(|| self.compile_metadata.get(proto_node_identifier).copied());
|
||||
|
||||
if let Some(Substitution { node: new_node, wrapped_node_id }) = self.substitutions.get(proto_node_identifier) {
|
||||
// Reconcile the document node's inputs with what the current node definition expects,
|
||||
@@ -134,14 +134,14 @@ impl Preprocessor {
|
||||
|
||||
node.implementation = new_node.implementation.clone();
|
||||
|
||||
// Move context dependencies to the wrapped node because networks are not allowed to have context dependencies so we need to
|
||||
// Move the compile metadata to the wrapped node because networks are not allowed to have compile metadata
|
||||
if let DocumentNodeImplementation::Network(network) = &mut node.implementation
|
||||
&& let Some(wrapped_node) = network.nodes.get_mut(wrapped_node_id)
|
||||
{
|
||||
wrapped_node.context_dependencies = context_dependencies;
|
||||
wrapped_node.compile_metadata = compile_metadata;
|
||||
}
|
||||
} else {
|
||||
node.context_dependencies = context_dependencies;
|
||||
node.compile_metadata = compile_metadata;
|
||||
}
|
||||
}
|
||||
DocumentNodeImplementation::Extract => (),
|
||||
@@ -151,7 +151,7 @@ impl Preprocessor {
|
||||
|
||||
pub fn new() -> Self {
|
||||
let mut substitutions = HashMap::new();
|
||||
let mut context_dependencies = HashMap::new();
|
||||
let mut compile_metadata = HashMap::new();
|
||||
let mut inject_scopes = HashMap::new();
|
||||
// We pre initialize the node registry here to avoid a deadlock
|
||||
let into_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
|
||||
@@ -161,19 +161,25 @@ impl Preprocessor {
|
||||
|
||||
let NodeMetadata {
|
||||
fields,
|
||||
memoize,
|
||||
footprint_invariant,
|
||||
inject_scope,
|
||||
asynchronous,
|
||||
flags: NodeFlags {
|
||||
memoize,
|
||||
footprint_invariant,
|
||||
forwards_input,
|
||||
inject_scope,
|
||||
asynchronous,
|
||||
},
|
||||
output_fields,
|
||||
context_features,
|
||||
..
|
||||
} = metadata;
|
||||
let dependencies = ContextDependencies {
|
||||
let constant_inputs = fields.iter().enumerate().filter(|(_, field)| field.constant).fold(0, |mask, (index, _)| mask | 1 << index);
|
||||
let node_compile_metadata = NodeCompileMetadata {
|
||||
footprint_invariant: *footprint_invariant,
|
||||
..ContextDependencies::from(context_features.as_slice())
|
||||
forwards_input: *forwards_input,
|
||||
constant_inputs,
|
||||
..NodeCompileMetadata::from(context_features.as_slice())
|
||||
};
|
||||
context_dependencies.insert(id.clone(), dependencies);
|
||||
compile_metadata.insert(id.clone(), node_compile_metadata);
|
||||
|
||||
let Some(implementations) = node_registry.get(&id) else { continue };
|
||||
let valid_call_args: HashSet<_> = implementations.iter().map(|(_, node_io)| node_io.call_argument.clone()).collect();
|
||||
@@ -194,6 +200,10 @@ impl Preprocessor {
|
||||
let network_inputs = (0..input_count).map(|i| NodeInput::node(NodeId(i as u64), 0)).collect();
|
||||
|
||||
let passthrough_node = ops::passthrough::IDENTIFIER;
|
||||
let forwarding = Some(NodeCompileMetadata {
|
||||
forwards_input: true,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let mut generated_nodes = 0;
|
||||
let mut nodes: HashMap<_, _, _> = node_io_types
|
||||
@@ -209,6 +219,7 @@ impl Preprocessor {
|
||||
inputs: vec![NodeInput::import(generic!(X), i)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(input_adapter_identifier),
|
||||
visible: true,
|
||||
compile_metadata: forwarding,
|
||||
original_location,
|
||||
..Default::default()
|
||||
};
|
||||
@@ -229,6 +240,7 @@ impl Preprocessor {
|
||||
inputs: vec![NodeInput::import(input.clone(), i)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(passthrough_node.clone()),
|
||||
visible: true,
|
||||
compile_metadata: forwarding,
|
||||
original_location,
|
||||
..Default::default()
|
||||
}
|
||||
@@ -237,6 +249,7 @@ impl Preprocessor {
|
||||
inputs: vec![NodeInput::import(generic!(X), i)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(passthrough_node.clone()),
|
||||
visible: false,
|
||||
compile_metadata: forwarding,
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
@@ -283,6 +296,7 @@ impl Preprocessor {
|
||||
inputs: vec![NodeInput::node(wrapped_node_id, 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_core::memo::memoize::IDENTIFIER.clone()),
|
||||
visible: true,
|
||||
compile_metadata: forwarding,
|
||||
..Default::default()
|
||||
};
|
||||
nodes.insert(memoize_node_id, memoize_node);
|
||||
@@ -347,7 +361,7 @@ impl Preprocessor {
|
||||
|
||||
Self {
|
||||
substitutions,
|
||||
context_dependencies,
|
||||
compile_metadata,
|
||||
inject_scopes,
|
||||
}
|
||||
}
|
||||
@@ -741,9 +755,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn substitution_moves_context_dependencies_onto_the_wrapped_node() {
|
||||
fn substitution_moves_compile_metadata_onto_the_wrapped_node() {
|
||||
let identifier = graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER;
|
||||
let context_dependencies = ContextDependencies {
|
||||
let compile_metadata = NodeCompileMetadata {
|
||||
extract: ContextFeatures::FOOTPRINT,
|
||||
inject: ContextFeatures::INDEX,
|
||||
..Default::default()
|
||||
@@ -753,7 +767,7 @@ mod tests {
|
||||
NodeId(0),
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(identifier.clone()),
|
||||
context_dependencies: Some(context_dependencies),
|
||||
compile_metadata: Some(compile_metadata),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
@@ -765,10 +779,7 @@ mod tests {
|
||||
Preprocessor::new().expand_network(&mut network);
|
||||
|
||||
let node = &network.nodes[&NodeId(0)];
|
||||
assert_eq!(
|
||||
node.context_dependencies, None,
|
||||
"The network node replacing the substituted node should not keep its context dependencies"
|
||||
);
|
||||
assert_eq!(node.compile_metadata, None, "The network node replacing the substituted node should not keep its compile metadata");
|
||||
let DocumentNodeImplementation::Network(substitution) = &node.implementation else {
|
||||
panic!("Boolean Operation is memoized, so it should be substituted with a network");
|
||||
};
|
||||
@@ -778,13 +789,40 @@ mod tests {
|
||||
.values()
|
||||
.find(|inner| inner.implementation == DocumentNodeImplementation::ProtoNode(identifier.clone()))
|
||||
.expect("The substitution network should contain the wrapped proto node");
|
||||
assert_eq!(wrapped_node.context_dependencies, Some(context_dependencies), "The wrapped proto node should carry the override");
|
||||
assert_eq!(wrapped_node.compile_metadata, Some(compile_metadata), "The wrapped proto node should carry the override");
|
||||
|
||||
let NodeInput::Node { node_id: export_id, .. } = substitution.exports[0] else {
|
||||
panic!("The substitution network should export a node");
|
||||
};
|
||||
let export = &substitution.nodes[&export_id];
|
||||
assert_eq!(export.implementation, DocumentNodeImplementation::ProtoNode(graphene_core::memo::memoize::IDENTIFIER));
|
||||
assert_eq!(export.context_dependencies, None, "The memoize node should not take over the wrapped node's context dependencies");
|
||||
let export_compile_metadata = export.compile_metadata.unwrap_or_default();
|
||||
assert!(export_compile_metadata.forwards_input, "The generated memoize node should forward its input");
|
||||
assert_eq!(
|
||||
export_compile_metadata.extract,
|
||||
ContextFeatures::empty(),
|
||||
"The memoize node should not take over the wrapped node's context features"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_attributes_reach_the_compile_metadata() {
|
||||
use graphene_std::graphic::{read_attribute_number, write_attribute};
|
||||
|
||||
let preprocessor = Preprocessor::new();
|
||||
let compile_metadata = |identifier: &ProtoNodeIdentifier| preprocessor.compile_metadata.get(identifier).copied().unwrap_or_default();
|
||||
|
||||
for (identifier, name_index) in [
|
||||
(write_attribute::IDENTIFIER, <write_attribute::NameInput as NodeParameter>::INDEX),
|
||||
(read_attribute_number::IDENTIFIER, <read_attribute_number::NameInput as NodeParameter>::INDEX),
|
||||
] {
|
||||
let info = compile_metadata(&identifier);
|
||||
assert!(info.requires_constant_input(name_index), "{identifier:?} should require a constant name");
|
||||
assert_eq!(info.constant_inputs.count_ones(), 1, "{identifier:?} should only require its name to be constant");
|
||||
}
|
||||
|
||||
for identifier in [graphene_core::memo::memoize::IDENTIFIER, graphene_core::memo::monitor::IDENTIFIER, ops::passthrough::IDENTIFIER] {
|
||||
assert!(compile_metadata(&identifier).forwards_input, "{identifier:?} should forward its input");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ use convert_case::{Case, Casing};
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value;
|
||||
use graph_craft::proto::{NodeMetadata, RegistryValueSource};
|
||||
use graphene_std::{ContextDependencies, core_types};
|
||||
use graphene_std::{NodeCompileMetadata, core_types};
|
||||
use indoc::formatdoc;
|
||||
use std::collections::HashSet;
|
||||
use std::io::Write;
|
||||
@@ -19,7 +19,7 @@ pub fn write_node_page(index: usize, id: &core_types::ProtoNodeIdentifier, metad
|
||||
|
||||
// Context features
|
||||
let context_features = &metadata.context_features;
|
||||
let context_dependencies: ContextDependencies = context_features.as_slice().into();
|
||||
let context_dependencies: NodeCompileMetadata = context_features.as_slice().into();
|
||||
|
||||
// Input types
|
||||
let mut valid_input_types = vec![Vec::new(); metadata.fields.len()];
|
||||
@@ -85,7 +85,7 @@ fn write_interface_header(page: &mut std::fs::File) {
|
||||
page.write_all(content.as_bytes()).expect("Failed to write to node page file");
|
||||
}
|
||||
|
||||
fn write_context(page: &mut std::fs::File, context_dependencies: ContextDependencies) {
|
||||
fn write_context(page: &mut std::fs::File, context_dependencies: NodeCompileMetadata) {
|
||||
let extract = context_dependencies.extract;
|
||||
let inject = context_dependencies.inject;
|
||||
if !extract.is_empty() || !inject.is_empty() {
|
||||
|
||||
Reference in new issue
Block a user