Compare commits

...
24 changed files with 326 additions and 85 deletions

No files matched your search

@@ -6,3 +6,5 @@ use migration_core::rename;
rename!("graphene_core::ops::PassthroughNode"@1 => @2); rename!("graphene_core::ops::PassthroughNode"@1 => @2);
// The removed Monitor node passes its one input on, as a Passthrough does // The removed Monitor node passes its one input on, as a Passthrough does
rename!("graphene_core::memo::MonitorNode"@1 => "graphene_core::ops::PassthroughNode"@2); rename!("graphene_core::memo::MonitorNode"@1 => "graphene_core::ops::PassthroughNode"@2);
// Version 2 only adds `InjectIndex` to the context bounds, so stored nodes keep their layout
rename!("graphene_core::vector::MapPointsNode"@1 => @2);
@@ -0,0 +1,3 @@
//! Migrations of the nodes in `graphic_nodes`.
mod renames;
@@ -0,0 +1,8 @@
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
use migration_core::rename;
// Version 2 only adds `InjectIndex` to the context bounds, so stored nodes keep their layout
rename!("graphic_nodes::graphic::MapNode"@1 => @2);
rename!("graphic_nodes::graphic::IterateNode"@1 => @2);
rename!("graphic_nodes::graphic::WriteAttributeNode"@1 => @2);
+3
View File
@@ -4,6 +4,9 @@
mod blending_nodes; mod blending_nodes;
mod graphene_core; mod graphene_core;
mod graphene_std; mod graphene_std;
mod graphic_nodes;
mod math_nodes; mod math_nodes;
mod raster_nodes; mod raster_nodes;
mod repeat_nodes;
mod text_nodes;
mod vector_nodes; mod vector_nodes;
@@ -0,0 +1,3 @@
//! Migrations of the nodes in `repeat_nodes`.
mod renames;
@@ -0,0 +1,9 @@
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
use migration_core::rename;
// Version 2 only adds `InjectIndex` to the context bounds, so stored nodes keep their layout
rename!("repeat_nodes::repeat_nodes::RepeatNode"@1 => @2);
rename!("repeat_nodes::repeat_nodes::RepeatArrayNode"@1 => @2);
rename!("repeat_nodes::repeat_nodes::RepeatRadialNode"@1 => @2);
rename!("repeat_nodes::repeat_nodes::RepeatOnPointsNode"@1 => @2);
@@ -0,0 +1,3 @@
//! Migrations of the nodes in `text_nodes`.
mod renames;
@@ -0,0 +1,6 @@
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
use migration_core::rename;
// Version 2 only adds `InjectIndex` to the context bounds, so stored nodes keep their layout
rename!("text_nodes::StringMapNode"@1 => @2);
@@ -3,3 +3,6 @@
use migration_core::rename; use migration_core::rename;
rename!("vector_nodes::vector_modification_nodes::PathModifyNode"@1 => "vector_nodes::vector_modification_nodes::PathNode"@2); rename!("vector_nodes::vector_modification_nodes::PathModifyNode"@1 => "vector_nodes::vector_modification_nodes::PathNode"@2);
// Version 2 only adds `InjectFootprint` to the context bounds, so stored nodes keep their layout
rename!("core_types::vector::AreaNode"@1 => @2);
rename!("core_types::vector::CentroidNode"@1 => @2);
@@ -28,6 +28,7 @@ impl DocumentNode {
original_location: self.original_location, original_location: self.original_location,
compile_metadata: self.compile_metadata.unwrap_or_default(), compile_metadata: self.compile_metadata.unwrap_or_default(),
upstream_context_features: Default::default(), upstream_context_features: Default::default(),
upstream_index_levels: 0,
} }
} }
} }
+118 -19
View File
@@ -127,6 +127,8 @@ pub struct ProtoNode {
pub(crate) compile_metadata: NodeCompileMetadata, pub(crate) compile_metadata: NodeCompileMetadata,
/// The context features read by this node and everything upstream of it. /// The context features read by this node and everything upstream of it.
pub upstream_context_features: ContextFeatures, pub upstream_context_features: ContextFeatures,
/// The loop levels whose index this node and everything upstream of it read, as a bitmask where bit `k` is the `k`-th innermost loop.
pub upstream_index_levels: u64,
} }
impl Default for ProtoNode { impl Default for ProtoNode {
@@ -138,6 +140,7 @@ impl Default for ProtoNode {
original_location: OriginalLocation::default(), original_location: OriginalLocation::default(),
compile_metadata: Default::default(), compile_metadata: Default::default(),
upstream_context_features: ContextFeatures::empty(), upstream_context_features: ContextFeatures::empty(),
upstream_index_levels: 0,
} }
} }
} }
@@ -169,6 +172,7 @@ impl ProtoNode {
}, },
compile_metadata: Default::default(), compile_metadata: Default::default(),
upstream_context_features: ContextFeatures::empty(), upstream_context_features: ContextFeatures::empty(),
upstream_index_levels: 0,
} }
} }
@@ -304,22 +308,42 @@ impl ProtoNetwork {
.collect() .collect()
} }
fn resolves_to_value(&self, mut id: NodeId) -> bool { fn resolves_to_value(&self, id: NodeId) -> bool {
self.constant_value(id).is_some()
}
/// The value feeding this node, following nodes which forward their first input.
fn constant_value(&self, mut id: NodeId) -> Option<&TaggedValue> {
loop { loop {
let Some((node_id, node)) = self.nodes.get(id.0 as usize) else { return false }; let (node_id, node) = self.nodes.get(id.0 as usize)?;
debug_assert_eq!(*node_id, id, "Node IDs must be dense indices"); debug_assert_eq!(*node_id, id, "Node IDs must be dense indices");
match &node.construction_args { match &node.construction_args {
ConstructionArgs::Value(_) => return true, ConstructionArgs::Value(value) => return Some(&**value),
ConstructionArgs::Nodes(inputs) if node.compile_metadata.forwards_input => match inputs.first() { ConstructionArgs::Nodes(inputs) if node.compile_metadata.forwards_input => id = *inputs.first()?,
Some(&input) => id = input, _ => return None,
None => return false,
},
_ => return false,
} }
} }
} }
/// The loop levels a node reads the index from itself, assuming all levels when the level isn't known at compile time.
fn own_index_levels(&self, node: &ProtoNode) -> u64 {
if !node.compile_metadata.extract.contains(ContextFeatures::INDEX) {
return 0;
}
let ConstructionArgs::Nodes(inputs) = &node.construction_args else { return u64::MAX };
let level_value = node
.compile_metadata
.index_level_input
.and_then(|index| inputs.get(index as usize))
.and_then(|&input| self.constant_value(input));
match level_value {
Some(TaggedValue::Integer(level)) => u32::try_from((*level).max(0)).ok().and_then(|level| 1_u64.checked_shl(level)).unwrap_or(u64::MAX),
_ => u64::MAX,
}
}
fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextModification) -> NodeId { fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextModification) -> NodeId {
let (_, node) = &self.nodes[node_id.0 as usize]; let (_, node) = &self.nodes[node_id.0 as usize];
let mut path = node.original_location.path.clone(); let mut path = node.original_location.path.clone();
@@ -330,6 +354,7 @@ impl ProtoNetwork {
} }
let features = context_deps.features; let features = context_deps.features;
let index_levels = node.upstream_index_levels;
let forwarding = NodeCompileMetadata { let forwarding = NodeCompileMetadata {
forwards_input: true, forwards_input: true,
..Default::default() ..Default::default()
@@ -348,6 +373,7 @@ impl ProtoNetwork {
}, },
compile_metadata: forwarding, compile_metadata: forwarding,
upstream_context_features: features, upstream_context_features: features,
upstream_index_levels: index_levels,
}, },
)); ));
@@ -379,6 +405,7 @@ impl ProtoNetwork {
}, },
compile_metadata: forwarding, compile_metadata: forwarding,
upstream_context_features: features, upstream_context_features: features,
upstream_index_levels: index_levels,
}, },
)); ));
nullification_node_id nullification_node_id
@@ -427,16 +454,34 @@ impl ProtoNetwork {
}; };
// Compute the dependencies for each branch and combine all of them // Compute the dependencies for each branch and combine all of them
for &node in &inputs { // An index injection without a loop body replaces the whole index stack for everything upstream
let replaces_index_stack = dependencies.inject.contains(ContextFeatures::INDEX) && dependencies.loop_body_inputs == 0;
let mut index_levels = self.own_index_levels(&self.nodes[node_index].1);
for (input_index, &node) in inputs.iter().enumerate() {
let branch = self.find_context_dependencies(node, analyzed); let branch = self.find_context_dependencies(node, analyzed);
self.nodes[node.0 as usize].1.upstream_context_features = branch.0.features; self.nodes[node.0 as usize].1.upstream_context_features = branch.0.features;
// A loop body's innermost index is the one this node pushes, so its outer levels are one closer to us
let branch_index_levels = self.nodes[node.0 as usize].1.upstream_index_levels;
index_levels |= if replaces_index_stack {
0
} else if dependencies.is_loop_body_input(input_index) {
branch_index_levels >> 1
} else {
branch_index_levels
};
combined_deps.features |= branch.0.features; combined_deps.features |= branch.0.features;
combined_deps.sources.extend(&branch.0.sources); combined_deps.sources.extend(&branch.0.sources);
branch_dependencies.push(branch); branch_dependencies.push(branch);
} }
// Remove requirements which this node provides and add requirements we have self.nodes[node_index].1.upstream_index_levels = index_levels;
let features = (combined_deps.features & !dependencies.inject) | dependencies.extract;
// Remove requirements which this node provides and add requirements we have, with the index tracked per loop level instead
let inject = dependencies.inject - ContextFeatures::INDEX;
let mut features = (combined_deps.features & !inject) | (dependencies.extract - ContextFeatures::INDEX);
features.set(ContextFeatures::INDEX, index_levels != 0);
// If we either introduce new dependencies, we can cache all children which don't yet need that dependency // If we either introduce new dependencies, we can cache all children which don't yet need that dependency
let we_introduces_new_deps = !combined_deps.features.contains(features); let we_introduces_new_deps = !combined_deps.features.contains(features);
@@ -451,14 +496,8 @@ impl ProtoNetwork {
} }
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs); self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
// Which dependencies do we supply (and don't need ourselves)? // Do we satisfy any existing dependencies, so they are no longer needed after this node?
let net_injections = dependencies.inject.difference(dependencies.extract); let we_supply_existing_deps = !combined_deps.features.difference(features).is_empty();
// Which dependencies still need to be met after this node?
let remaining_deps_from_children = combined_deps.features.difference(net_injections);
// Do we satisfy any existing dependencies?
let we_supply_existing_deps = !combined_deps.features.difference(remaining_deps_from_children).is_empty();
let new_deps = ContextModification { let new_deps = ContextModification {
features, features,
@@ -1330,6 +1369,66 @@ mod test {
assert!(warnings(true).is_empty()); assert!(warnings(true).is_empty());
} }
fn loop_test_node(name: &'static str, inputs: Vec<NodeId>, compile_metadata: NodeCompileMetadata) -> ProtoNode {
ProtoNode {
identifier: ProtoNodeIdentifier::new(name),
call_argument: concrete!(()),
construction_args: ConstructionArgs::Nodes(inputs),
compile_metadata,
..Default::default()
}
}
fn integer_value(value: i64) -> ProtoNode {
ProtoNode::value(ConstructionArgs::Value(TaggedValue::Integer(value).into()), vec![])
}
const INDEX_READER: NodeCompileMetadata = NodeCompileMetadata {
extract: ContextFeatures::INDEX,
inject: ContextFeatures::empty(),
footprint_invariant: false,
forwards_input: false,
constant_inputs: 0b1,
loop_body_inputs: 0,
index_level_input: Some(0),
};
/// A loop evaluating its second input once per row of its first input.
const MAP: NodeCompileMetadata = NodeCompileMetadata {
extract: ContextFeatures::empty(),
inject: ContextFeatures::INDEX,
footprint_invariant: false,
forwards_input: false,
constant_inputs: 0,
loop_body_inputs: 0b10,
index_level_input: None,
};
#[test]
fn nested_loops_keep_the_outer_index_for_the_inner_body() {
let nodes = vec![
(NodeId(0), integer_value(1)),
(NodeId(1), loop_test_node("index_reader", vec![NodeId(0)], INDEX_READER)),
(NodeId(2), integer_value(2)),
(NodeId(3), loop_test_node("inner_map", vec![NodeId(2), NodeId(1)], MAP)),
(NodeId(4), integer_value(3)),
(NodeId(5), loop_test_node("outer_map", vec![NodeId(4), NodeId(3)], MAP)),
];
let mut network = ProtoNetwork {
inputs: vec![],
output: NodeId(5),
nodes,
};
network.insert_context_nullification_nodes().unwrap();
let node_named = |name: &str| &network.nodes.iter().find(|(_, node)| node.identifier.as_str() == name).unwrap().1;
assert!(node_named("inner_map").upstream_context_features.contains(ContextFeatures::INDEX));
assert_eq!(node_named("inner_map").upstream_index_levels, 0b1);
assert_eq!(node_named("outer_map").upstream_index_levels, 0);
assert!(!node_named("outer_map").upstream_context_features.contains(ContextFeatures::INDEX));
}
#[test] #[test]
fn constant_inputs_must_resolve_to_values_through_forwarding_nodes() { fn constant_inputs_must_resolve_to_values_through_forwarding_nodes() {
let value = || ProtoNode::value(ConstructionArgs::Value(TaggedValue::String("name".into()).into()), vec![]); let value = || ProtoNode::value(ConstructionArgs::Value(TaggedValue::String("name".into()).into()), vec![]);
+15 -1
View File
@@ -233,11 +233,25 @@ pub struct NodeCompileMetadata {
pub forwards_input: bool, pub forwards_input: bool,
#[cfg_attr(feature = "serde", serde(default))] #[cfg_attr(feature = "serde", serde(default))]
pub constant_inputs: u64, pub constant_inputs: u64,
/// Inputs evaluated inside the loop scope this node pushes an index for.
#[cfg_attr(feature = "serde", serde(default))]
pub loop_body_inputs: u64,
/// The input whose constant value selects the loop level this node reads the index from.
#[cfg_attr(feature = "serde", serde(default))]
pub index_level_input: Option<u8>,
} }
impl NodeCompileMetadata { impl NodeCompileMetadata {
pub fn requires_constant_input(&self, index: usize) -> bool { pub fn requires_constant_input(&self, index: usize) -> bool {
index < u64::BITS as usize && self.constant_inputs & (1 << index) != 0 Self::contains_input(self.constant_inputs, index)
}
pub fn is_loop_body_input(&self, index: usize) -> bool {
Self::contains_input(self.loop_body_inputs, index)
}
fn contains_input(mask: u64, index: usize) -> bool {
index < u64::BITS as usize && mask & (1 << index) != 0
} }
} }
@@ -60,6 +60,18 @@ pub struct FieldMetadata {
pub progression: bool, pub progression: bool,
/// Whether the input must be fed by a value known at compile time, from `#[constant]`. /// Whether the input must be fed by a value known at compile time, from `#[constant]`.
pub constant: bool, pub constant: bool,
pub index_role: FieldIndexRole,
/// Whether the node evaluates the input itself (an `impl Node` parameter) rather than receiving its value.
pub lazy: bool,
}
/// How an input takes part in loop index tracking.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FieldIndexRole {
#[default]
None,
/// This input's constant value selects which loop level's index is read, from `#[index_level]`.
Level,
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
+16
View File
@@ -318,6 +318,20 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
quote!(#constant) quote!(#constant)
}) })
.collect(); .collect();
let index_role: Vec<_> = regular_fields
.iter()
.map(|field| match field.index_role {
ParsedIndexRole::None => quote!(gcore::registry::FieldIndexRole::None),
ParsedIndexRole::Level => quote!(gcore::registry::FieldIndexRole::Level),
})
.collect();
let lazy: Vec<_> = regular_fields
.iter()
.map(|field| {
let lazy = matches!(field.ty, ParsedFieldType::Node(_));
quote!(#lazy)
})
.collect();
let exposed: Vec<_> = regular_fields let exposed: Vec<_> = regular_fields
.iter() .iter()
@@ -1078,6 +1092,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
multiline: #multiline, multiline: #multiline,
progression: #progression, progression: #progression,
constant: #constant, constant: #constant,
index_role: #index_role,
lazy: #lazy,
}, },
)* )*
], ],
+31 -2
View File
@@ -123,6 +123,15 @@ impl Parse for ParsedWidgetOverride {
} }
} }
/// How a field takes part in loop index tracking, from `#[index_level]`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ParsedIndexRole {
#[default]
None,
/// This field's constant value selects which loop level's index the node reads.
Level,
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct ParsedField { pub struct ParsedField {
pub pat_ident: PatIdent, pub pat_ident: PatIdent,
@@ -136,6 +145,7 @@ pub struct ParsedField {
pub multiline: bool, pub multiline: bool,
pub progression: bool, pub progression: bool,
pub constant: bool, pub constant: bool,
pub index_role: ParsedIndexRole,
pub is_data_field: bool, pub is_data_field: bool,
} }
@@ -169,6 +179,7 @@ impl ParsedField {
multiline: false, multiline: false,
progression: false, progression: false,
constant: false, constant: false,
index_role: ParsedIndexRole::None,
is_data_field: false, is_data_field: false,
} }
} }
@@ -856,8 +867,14 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
let exposed = extract_attribute(attrs, "expose").is_some(); 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 index_role = match extract_attribute(attrs, "index_level") {
let constant = extract_attribute(attrs, "constant").is_some(); Some(_) => ParsedIndexRole::Level,
None => ParsedIndexRole::None,
};
// The `#[constant]` marker makes the compiler reject inputs not fed by a value known at compile time.
// An `#[index_level]` must be constant too, so the compiler knows which loop's index is read.
let constant = extract_attribute(attrs, "constant").is_some() || index_role == ParsedIndexRole::Level;
// Gives a synchronous node its `SourceId`, as async nodes get it, so it can bump its own generation // Gives a synchronous node its `SourceId`, as async nodes get it, so it can bump its own generation
let source_id = extract_attribute(attrs, "source_id").is_some(); let source_id = extract_attribute(attrs, "source_id").is_some();
@@ -888,6 +905,9 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
"Data fields (#[data]) cannot be #[constant]. They are internal state, not node parameters", "Data fields (#[data]) cannot be #[constant]. They are internal state, not node parameters",
)); ));
} }
if index_role != ParsedIndexRole::None {
return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot be #[index_level]"));
}
if source_id { if source_id {
return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot have #[source_id] attribute")); return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot have #[source_id] attribute"));
} }
@@ -1035,6 +1055,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
multiline, multiline,
progression, progression,
constant, constant,
index_role,
is_data_field, is_data_field,
}) })
} else { } else {
@@ -1087,6 +1108,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
multiline, multiline,
progression, progression,
constant, constant,
index_role,
is_data_field, is_data_field,
}) })
} }
@@ -1386,6 +1408,7 @@ mod tests {
multiline: false, multiline: false,
progression: false, progression: false,
constant: false, constant: false,
index_role: ParsedIndexRole::None,
is_data_field: false, is_data_field: false,
}], }],
body: TokenStream2::new(), body: TokenStream2::new(),
@@ -1448,6 +1471,7 @@ mod tests {
multiline: false, multiline: false,
progression: false, progression: false,
constant: false, constant: false,
index_role: ParsedIndexRole::None,
is_data_field: false, is_data_field: false,
}, },
ParsedField { ParsedField {
@@ -1472,6 +1496,7 @@ mod tests {
multiline: false, multiline: false,
progression: false, progression: false,
constant: false, constant: false,
index_role: ParsedIndexRole::None,
is_data_field: false, is_data_field: false,
}, },
], ],
@@ -1535,6 +1560,7 @@ mod tests {
multiline: false, multiline: false,
progression: false, progression: false,
constant: false, constant: false,
index_role: ParsedIndexRole::None,
is_data_field: false, is_data_field: false,
}], }],
body: TokenStream2::new(), body: TokenStream2::new(),
@@ -1601,6 +1627,7 @@ mod tests {
multiline: false, multiline: false,
progression: false, progression: false,
constant: false, constant: false,
index_role: ParsedIndexRole::None,
is_data_field: false, is_data_field: false,
}], }],
body: TokenStream2::new(), body: TokenStream2::new(),
@@ -1670,6 +1697,7 @@ mod tests {
multiline: false, multiline: false,
progression: false, progression: false,
constant: false, constant: false,
index_role: ParsedIndexRole::None,
is_data_field: false, is_data_field: false,
}], }],
body: TokenStream2::new(), body: TokenStream2::new(),
@@ -1764,6 +1792,7 @@ mod tests {
multiline: false, multiline: false,
progression: false, progression: false,
constant: false, constant: false,
index_role: ParsedIndexRole::None,
is_data_field: false, is_data_field: false,
}], }],
body: TokenStream2::new(), body: TokenStream2::new(),
+1
View File
@@ -88,6 +88,7 @@ fn read_index(
/// ///
/// In programming terms: inside the double loop `i { j { ... } }`, *Loop Level* 0 = `j` and 1 = `i`. After inserting a third loop `k { ... }`, inside it, levels would be 0 = `k`, 1 = `j`, and 2 = `i`. /// In programming terms: inside the double loop `i { j { ... } }`, *Loop Level* 0 = `j` and 1 = `i`. After inserting a third loop `k { ... }`, inside it, levels would be 0 = `k`, 1 = `j`, and 2 = `i`.
#[hard(0..)] #[hard(0..)]
#[index_level]
loop_level: Item<i64>, loop_level: Item<i64>,
) -> Result<Item<f64>, ReadContextError> { ) -> Result<Item<f64>, ReadContextError> {
// The graph outside any loop runs once, as index 0 // The graph outside any loop runs once, as index 0
+18 -16
View File
@@ -1,7 +1,9 @@
use brush_types::Stroke; use brush_types::Stroke;
use core_types::bounds::{BoundingBox, RenderBoundingBox}; use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath}; use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath};
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, Interrupt, OwnedContextImpl}; use core_types::{
ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, InjectIndex, Interrupt, OwnedContextImpl,
};
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2};
use graphic_types::graphic::{Graphic, IntoGraphicList, is_lone_anonymous_leaf}; use graphic_types::graphic::{Graphic, IntoGraphicList, is_lone_anonymous_leaf};
use graphic_types::{Artboard, Vector}; use graphic_types::{Artboard, Vector};
@@ -14,7 +16,7 @@ use vector_types::{Gradient, ReferencePoint};
/// Returns the list with the item at the specified index removed. /// Returns the list with the item at the specified index removed.
/// If no value exists at that index, the list is returned unchanged. /// If no value exists at that index, the list is returned unchanged.
#[node_macro::node(category("Data: List"), icon("NodeRemoveAtIndex"), name("Remove at Index"))] #[node_macro::node(category("Data: List"), icon("NodeRemoveAtIndex"), name("Remove at Index"), footprint_invariant)]
fn remove_at_index<T: graphic_types::graphic::OmitIndex + Clone + Default>( fn remove_at_index<T: graphic_types::graphic::OmitIndex + Clone + Default>(
_: impl Ctx, _: impl Ctx,
/// The list of data. /// The list of data.
@@ -48,7 +50,7 @@ fn remove_at_index<T: graphic_types::graphic::OmitIndex + Clone + Default>(
/// Returns the item at the specified index in a list, keeping its attributes. /// Returns the item at the specified index in a list, keeping its attributes.
/// If no value exists at that index, the element type's default is returned. /// If no value exists at that index, the element type's default is returned.
#[node_macro::node(category("Data: List"), icon("NodeItemAtIndex"), name("Item at Index"))] #[node_macro::node(category("Data: List"), icon("NodeItemAtIndex"), name("Item at Index"), footprint_invariant)]
fn item_at_index<T: Clone + Default + Send + Sync + 'static>( fn item_at_index<T: Clone + Default + Send + Sync + 'static>(
_: impl Ctx, _: impl Ctx,
/// The list of data to take the item from. /// The list of data to take the item from.
@@ -85,7 +87,7 @@ fn item_at_index<T: Clone + Default + Send + Sync + 'static>(
} }
/// Keeps chosen items from a list (those corresponding to `true` values) and discards the others (those corresponding to `false` values) based on the *Keep Pattern* `Bool` list. A short pattern is repeated over the remainder of the filtered list, allowing a pattern like `[true, false]` to keep every other item starting from the first. An empty pattern keeps all items. /// Keeps chosen items from a list (those corresponding to `true` values) and discards the others (those corresponding to `false` values) based on the *Keep Pattern* `Bool` list. A short pattern is repeated over the remainder of the filtered list, allowing a pattern like `[true, false]` to keep every other item starting from the first. An empty pattern keeps all items.
#[node_macro::node(category("Data: List"), icon("NodeFilter"))] #[node_macro::node(category("Data: List"), icon("NodeFilter"), footprint_invariant)]
fn filter<T: Send + Sync + Clone + 'static>( fn filter<T: Send + Sync + Clone + 'static>(
_: impl Ctx, _: impl Ctx,
/// The list of data to filter. /// The list of data to filter.
@@ -143,7 +145,7 @@ fn reverse<T: Send + Sync + Clone + 'static>(
} }
/// Shifts the items in a list by a number of positions. With wrapping, items pushed off one end reappear at the other. Otherwise they are dropped, shortening the list. /// Shifts the items in a list by a number of positions. With wrapping, items pushed off one end reappear at the other. Otherwise they are dropped, shortening the list.
#[node_macro::node(category("Data: List"), icon("NodeShift"))] #[node_macro::node(category("Data: List"), icon("NodeShift"), footprint_invariant)]
fn shift<T: Send + Sync + Clone + 'static>( fn shift<T: Send + Sync + Clone + 'static>(
_: impl Ctx, _: impl Ctx,
/// The list of data to shift. /// The list of data to shift.
@@ -188,7 +190,7 @@ fn shift<T: Send + Sync + Clone + 'static>(
} }
/// Randomly reorders the items in a list. The same seed always produces the same ordering. /// Randomly reorders the items in a list. The same seed always produces the same ordering.
#[node_macro::node(category("Data: List"), icon("NodeShuffle"))] #[node_macro::node(category("Data: List"), icon("NodeShuffle"), footprint_invariant)]
fn shuffle<T: Send + Sync + Clone + 'static>( fn shuffle<T: Send + Sync + Clone + 'static>(
_: impl Ctx, _: impl Ctx,
/// The list to have its items randomly reordered. /// The list to have its items randomly reordered.
@@ -244,7 +246,7 @@ fn number_sequence(
// TODO: Return i64 instead of f64 once automatic type conversion is implemented for nodes with generic type inputs, so an integer output doesn't wall these indices off from the generic math nodes. // TODO: Return i64 instead of f64 once automatic type conversion is implemented for nodes with generic type inputs, so an integer output doesn't wall these indices off from the generic math nodes.
// TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.) // TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.)
/// Counts out the index of each item in a list (0, 1, 2, and so on), producing a list of numbers with one for each item. /// Counts out the index of each item in a list (0, 1, 2, and so on), producing a list of numbers with one for each item.
#[node_macro::node(category("Data: List"), icon("NodeIndices"))] #[node_macro::node(category("Data: List"), icon("NodeIndices"), footprint_invariant)]
fn indices( fn indices(
_: impl Ctx, _: impl Ctx,
/// The list whose items are counted. /// The list whose items are counted.
@@ -260,7 +262,7 @@ fn indices(
/// Extracts a portion of a list, starting at "Start" and ending before "End". /// Extracts a portion of a list, starting at "Start" and ending before "End".
/// ///
/// Negative indices count from the end of the list. If the index of "Start" equals or exceeds "End", the result is an empty list. /// Negative indices count from the end of the list. If the index of "Start" equals or exceeds "End", the result is an empty list.
#[node_macro::node(category("Data: List"), icon("NodeSlice"))] #[node_macro::node(category("Data: List"), icon("NodeSlice"), footprint_invariant)]
fn slice<T: Send + Sync + Clone + 'static>( fn slice<T: Send + Sync + Clone + 'static>(
_: impl Ctx, _: impl Ctx,
/// The list of data to take a portion of. /// The list of data to take a portion of.
@@ -342,7 +344,7 @@ pub enum SortError {
} }
/// Reorders a list's items from smallest to largest, either by each item's own value or by a parallel list of sortable values in the *Sort Order* input. The sort is stable, so items with the same sort order retain their relative positions. /// Reorders a list's items from smallest to largest, either by each item's own value or by a parallel list of sortable values in the *Sort Order* input. The sort is stable, so items with the same sort order retain their relative positions.
#[node_macro::node(category("Data: List"), icon("NodeSort"))] #[node_macro::node(category("Data: List"), icon("NodeSort"), footprint_invariant)]
fn sort<T: ElementOrder + Clone + Send + Sync + 'static, U: ElementOrder + Send + Sync + 'static>( fn sort<T: ElementOrder + Clone + Send + Sync + 'static, U: ElementOrder + Send + Sync + 'static>(
_: impl Ctx, _: impl Ctx,
/// The list of data to reorder. /// The list of data to reorder.
@@ -396,9 +398,9 @@ fn sort<T: ElementOrder + Clone + Send + Sync + 'static, U: ElementOrder + Send
Ok(result) Ok(result)
} }
#[node_macro::node(category("Data: List"), icon("NodeMap"))] #[node_macro::node(category("Data: List"), icon("NodeMap"), version(2), footprint_invariant)]
fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>( fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
ctx: impl Ctx + CloneVarArgs + ExtractAll, ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
#[implementations( #[implementations(
List<String>, List<String>,
List<bool>, List<bool>,
@@ -446,9 +448,9 @@ fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
} }
/// Feeds the content through the same steps over and over, each time starting from the previous result. Inside the steps, a **Read** node like **Read String** or **Read Vector** reads the result so far, and **Read Index** reads how many times around it has been. /// Feeds the content through the same steps over and over, each time starting from the previous result. Inside the steps, a **Read** node like **Read String** or **Read Vector** reads the result so far, and **Read Index** reads how many times around it has been.
#[node_macro::node(category("Routing"), icon("NodeIterate"))] #[node_macro::node(category("Routing"), icon("NodeIterate"), version(2))]
fn iterate<T: AnyHash + Send + Sync + CacheHash + Clone>( fn iterate<T: AnyHash + Send + Sync + CacheHash + Clone>(
ctx: impl Ctx + CloneVarArgs + ExtractAll, ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
/// The starting value, which the steps rework each time around. /// The starting value, which the steps rework each time around.
#[implementations(String, f64, Vector, Graphic, Raster<CPU>, Color, Gradient)] #[implementations(String, f64, Vector, Graphic, Raster<CPU>, Color, Gradient)]
content: Item<T>, content: Item<T>,
@@ -514,7 +516,7 @@ impl HasText for Raster<GPU> {}
impl HasText for Color {} impl HasText for Color {}
impl HasText for Gradient {} impl HasText for Gradient {}
#[node_macro::node(category("Graphic"), icon("NodeMirror"))] #[node_macro::node(category("Graphic"), icon("NodeMirror"), footprint_invariant)]
fn mirror<T: BoundingBox + HasText + Send + Clone>( fn mirror<T: BoundingBox + HasText + Send + Clone>(
_: impl Ctx, _: impl Ctx,
#[implementations( #[implementations(
@@ -617,9 +619,9 @@ fn write_layer_path<T: 'static + Send>(
/// be derived from the item's own data. If the attribute already exists, its values are replaced; if not, it's added. /// be derived from the item's own data. If the attribute already exists, its values are replaced; if not, it's added.
/// The value is type-erased into an `Item<AttributeValueDyn>` by the auto-inserted input adapter, so this node only /// The value is type-erased into an `Item<AttributeValueDyn>` by the auto-inserted input adapter, so this node only
/// monomorphizes over `T` instead of the cartesian product `(T, U)`. /// monomorphizes over `T` instead of the cartesian product `(T, U)`.
#[node_macro::node(category("Data: Attribute"), icon("NodeWriteAttribute"))] #[node_macro::node(category("Data: Attribute"), icon("NodeWriteAttribute"), version(2))]
fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>( fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
ctx: impl ExtractAll + CloneVarArgs + Ctx, ctx: impl ExtractAll + CloneVarArgs + Ctx + InjectIndex,
/// The list to set the named attribute on (one value per item). /// The list to set the named attribute on (one value per item).
#[implementations( #[implementations(
List<String>, List<String>,
+6 -6
View File
@@ -366,7 +366,7 @@ fn operator_reducer(operator: &str) -> Result<Reducer, MathExpressionError> {
/// Reduces all the items to a single value by folding an operator like `+` or `*` across them, or by passing them all to a function like `max` or `mean`. /// Reduces all the items to a single value by folding an operator like `+` or `*` across them, or by passing them all to a function like `max` or `mean`.
/// ///
/// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. Boolean items read as 0 or 1 and Vec2 items as such vectors. Across Transforms, `*` and `/` compose in order, `mean` averages, and `count` counts. /// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. Boolean items read as 0 or 1 and Vec2 items as such vectors. Across Transforms, `*` and `/` compose in order, `mean` averages, and `count` counts.
#[node_macro::node(category("Math"), icon("NodeMathAggregate"))] #[node_macro::node(category("Math"), icon("NodeMathAggregate"), footprint_invariant)]
fn math_aggregate<T: ExpressionValue, U: ExpressionValue>( fn math_aggregate<T: ExpressionValue, U: ExpressionValue>(
_: impl Ctx, _: impl Ctx,
/// The items reduced to one value. /// The items reduced to one value.
@@ -416,7 +416,7 @@ fn math_aggregate<T: ExpressionValue, U: ExpressionValue>(
/// Scans along the items, giving each one the result of folding an operator like `+` over it and every item before it, such as a running total, or of a function like `max`, such as the highest value so far. /// Scans along the items, giving each one the result of folding an operator like `+` over it and every item before it, such as a running total, or of a function like `max`, such as the highest value so far.
/// ///
/// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. Boolean items read as 0 or 1 and Vec2 items as such vectors. Across Transforms, `*` composes in order, which turns a list of steps into where each step ends up. /// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. Boolean items read as 0 or 1 and Vec2 items as such vectors. Across Transforms, `*` composes in order, which turns a list of steps into where each step ends up.
#[node_macro::node(category("Math"), icon("NodeMathRunning"))] #[node_macro::node(category("Math"), icon("NodeMathRunning"), footprint_invariant)]
fn math_running<T: ExpressionValue, U: ExpressionValue>( fn math_running<T: ExpressionValue, U: ExpressionValue>(
_: impl Ctx, _: impl Ctx,
/// The items scanned along, each giving one result. /// The items scanned along, each giving one result.
@@ -1532,13 +1532,13 @@ fn least_common_multiple(
} }
/// Adds together all the numbers in the input list, producing their total. /// Adds together all the numbers in the input list, producing their total.
#[node_macro::node(category("Math: Arithmetic"), icon("NodeSum"))] #[node_macro::node(category("Math: Arithmetic"), icon("NodeSum"), footprint_invariant)]
fn sum(_: impl Ctx, values: List<f64>) -> Item<f64> { fn sum(_: impl Ctx, values: List<f64>) -> Item<f64> {
Item::new_from_element(values.iter_element_values().sum()) Item::new_from_element(values.iter_element_values().sum())
} }
/// Averages all the numbers in the input list. An empty list gives 0. /// Averages all the numbers in the input list. An empty list gives 0.
#[node_macro::node(category("Math: Numeric"), icon("NodeAverage"))] #[node_macro::node(category("Math: Numeric"), icon("NodeAverage"), footprint_invariant)]
fn average(_: impl Ctx, values: List<f64>) -> Item<f64> { fn average(_: impl Ctx, values: List<f64>) -> Item<f64> {
let count = values.len(); let count = values.len();
let average = if count == 0 { 0. } else { values.iter_element_values().sum::<f64>() / count as f64 }; let average = if count == 0 { 0. } else { values.iter_element_values().sum::<f64>() / count as f64 };
@@ -1547,13 +1547,13 @@ fn average(_: impl Ctx, values: List<f64>) -> Item<f64> {
} }
/// Gives the smallest number in the input list. An empty list gives 0. /// Gives the smallest number in the input list. An empty list gives 0.
#[node_macro::node(category("Math: Numeric"), icon("NodeMinimum"))] #[node_macro::node(category("Math: Numeric"), icon("NodeMinimum"), footprint_invariant)]
fn minimum(_: impl Ctx, values: List<f64>) -> Item<f64> { fn minimum(_: impl Ctx, values: List<f64>) -> Item<f64> {
Item::new_from_element(values.iter_element_values().copied().reduce(f64::min).unwrap_or_default()) Item::new_from_element(values.iter_element_values().copied().reduce(f64::min).unwrap_or_default())
} }
/// Gives the largest number in the input list. An empty list gives 0. /// Gives the largest number in the input list. An empty list gives 0.
#[node_macro::node(category("Math: Numeric"), icon("NodeMaximum"))] #[node_macro::node(category("Math: Numeric"), icon("NodeMaximum"), footprint_invariant)]
fn maximum(_: impl Ctx, values: List<f64>) -> Item<f64> { fn maximum(_: impl Ctx, values: List<f64>) -> Item<f64> {
Item::new_from_element(values.iter_element_values().copied().reduce(f64::max).unwrap_or_default()) Item::new_from_element(values.iter_element_values().copied().reduce(f64::max).unwrap_or_default())
} }
+1 -1
View File
@@ -29,7 +29,7 @@ pub enum BooleanOperationError {
// TODO: with multiple items while still assuming a single item for the boolean operations. // TODO: with multiple items while still assuming a single item for the boolean operations.
/// Combines the geometric forms of one or more closed paths into a new vector path that results from cutting or joining the paths by the chosen method. /// Combines the geometric forms of one or more closed paths into a new vector path that results from cutting or joining the paths by the chosen method.
#[node_macro::node(category("Vector: Path"), icon("NodeBooleanOperation"), memoize)] #[node_macro::node(category("Vector: Path"), icon("NodeBooleanOperation"), memoize, footprint_invariant)]
fn boolean_operation( fn boolean_operation(
_: impl Ctx, _: impl Ctx,
/// The `List` of vector paths to perform the boolean operation on. Nested `List`s are automatically flattened. /// The `List` of vector paths to perform the boolean operation on. Nested `List`s are automatically flattened.
+9 -9
View File
@@ -1,16 +1,16 @@
use crate::gcore::Context; use crate::gcore::Context;
use core::f64::consts::TAU; use core::f64::consts::TAU;
use core_types::list::{Item, List}; use core_types::list::{Item, List};
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectVarArgs, Interrupt, OwnedContextImpl}; use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectIndex, InjectVarArgs, Interrupt, OwnedContextImpl};
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2};
use graphic_types::{Artboard, Graphic, Vector}; use graphic_types::{Artboard, Graphic, Vector};
use raster_types::{CPU, GPU, Raster}; use raster_types::{CPU, GPU, Raster};
use vector_types::Gradient; use vector_types::Gradient;
use vector_types::vector::{no_paths, paths_from_list_row_attributes}; use vector_types::vector::{no_paths, paths_from_list_row_attributes};
#[node_macro::node(category("Graphic"), icon("NodeRepeat"))] #[node_macro::node(category("Graphic"), icon("NodeRepeat"), version(2))]
fn repeat<T: Send + Clone + 'static>( fn repeat<T: Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx, ctx: impl ExtractAll + CloneVarArgs + Ctx + InjectIndex,
#[implementations( #[implementations(
Context -> List<String>, Context -> List<String>,
Context -> List<bool>, Context -> List<bool>,
@@ -53,9 +53,9 @@ fn repeat<T: Send + Clone + 'static>(
Ok(result_list) Ok(result_list)
} }
#[node_macro::node(category("Graphic"), icon("NodeRepeatArray"))] #[node_macro::node(category("Graphic"), icon("NodeRepeatArray"), version(2))]
fn repeat_array<T: Send + Clone + 'static>( fn repeat_array<T: Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx, ctx: impl ExtractAll + CloneVarArgs + Ctx + InjectIndex,
#[implementations( #[implementations(
Context -> List<String>, Context -> List<String>,
Context -> List<bool>, Context -> List<bool>,
@@ -114,9 +114,9 @@ fn repeat_array<T: Send + Clone + 'static>(
Ok(result_list) Ok(result_list)
} }
#[node_macro::node(category("Graphic"), icon("NodeRepeatRadial"))] #[node_macro::node(category("Graphic"), icon("NodeRepeatRadial"), version(2))]
fn repeat_radial<T: Send + Clone + 'static>( fn repeat_radial<T: Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx, ctx: impl ExtractAll + CloneVarArgs + Ctx + InjectIndex,
#[implementations( #[implementations(
Context -> List<String>, Context -> List<String>,
Context -> List<bool>, Context -> List<bool>,
@@ -171,9 +171,9 @@ fn repeat_radial<T: Send + Clone + 'static>(
Ok(result_list) Ok(result_list)
} }
#[node_macro::node(category("Graphic"), icon("NodeRepeatOnPoints"), name("Repeat on Points"))] #[node_macro::node(category("Graphic"), icon("NodeRepeatOnPoints"), name("Repeat on Points"), version(2))]
fn repeat_on_points<T: Send + Clone + 'static>( fn repeat_on_points<T: Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Sync + Ctx + InjectVarArgs, ctx: impl ExtractAll + CloneVarArgs + Sync + Ctx + InjectVarArgs + InjectIndex,
points: List<Vector>, points: List<Vector>,
#[implementations( #[implementations(
Context -> List<String>, Context -> List<String>,
+4 -4
View File
@@ -13,7 +13,7 @@ use core_types::graphene_hash::CacheHash;
use core_types::list::{Item, List}; use core_types::list::{Item, List};
use core_types::math::float_noise::round_away_float_noise; use core_types::math::float_noise::round_away_float_noise;
use core_types::misc::{format_f64, parse_f64}; use core_types::misc::{format_f64, parse_f64};
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractVarArgs, OwnedContextImpl}; use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractVarArgs, InjectIndex, OwnedContextImpl};
use dyn_any::DynAny; use dyn_any::DynAny;
use glam::DVec2; use glam::DVec2;
use rand::{RngExt, SeedableRng}; use rand::{RngExt, SeedableRng};
@@ -941,7 +941,7 @@ fn string_split(
/// Joins a list of strings together with a separator between each pair. This is the inverse of the **String Split** node. /// Joins a list of strings together with a separator between each pair. This is the inverse of the **String Split** node.
/// ///
/// For example, joining `["a", "b", "c"]` with separator ", " produces "a, b, c". /// For example, joining `["a", "b", "c"]` with separator ", " produces "a, b, c".
#[node_macro::node(category("String"), icon("NodeStringJoin"))] #[node_macro::node(category("String"), icon("NodeStringJoin"), footprint_invariant)]
fn string_join( fn string_join(
_: impl Ctx, _: impl Ctx,
/// The list of strings to join together. /// The list of strings to join together.
@@ -963,9 +963,9 @@ fn string_join(
} }
/// Iterates over a list of strings, evaluating the mapped operation for each one. Use the **Read String** node to access the current string inside the loop. /// Iterates over a list of strings, evaluating the mapped operation for each one. Use the **Read String** node to access the current string inside the loop.
#[node_macro::node(category("String"), icon("NodeStringMap"))] #[node_macro::node(category("String"), icon("NodeStringMap"), version(2))]
fn string_map( fn string_map(
ctx: impl Ctx + CloneVarArgs + ExtractAll, ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
strings: List<String>, strings: List<String>,
#[expose] #[expose]
#[implementations(Context -> Item<String>)] #[implementations(Context -> Item<String>)]
@@ -220,7 +220,7 @@ fn decompose_skew(_: impl Ctx, transform: Item<DAffine2>) -> Item<f64> {
} }
/// Rotates every item of the content about its origin by its own angle, selected from along a chosen range. /// Rotates every item of the content about its origin by its own angle, selected from along a chosen range.
#[node_macro::node(category("Transform"), icon("NodeVaryRotations"), version(2))] #[node_macro::node(category("Transform"), icon("NodeVaryRotations"), version(2), footprint_invariant)]
fn vary_rotations<T: Send>( fn vary_rotations<T: Send>(
_: impl Ctx, _: impl Ctx,
/// The content with items to rotate individually. /// The content with items to rotate individually.
@@ -274,7 +274,7 @@ fn vary_rotations<T: Send>(
} }
/// Scales every item of the content about its origin by its own factor, selected from along a chosen range. /// Scales every item of the content about its origin by its own factor, selected from along a chosen range.
#[node_macro::node(category("Transform"), icon("NodeVaryScales"))] #[node_macro::node(category("Transform"), icon("NodeVaryScales"), footprint_invariant)]
fn vary_scales<T: Send>( fn vary_scales<T: Send>(
_: impl Ctx, _: impl Ctx,
/// The content with items to scale individually. /// The content with items to scale individually.
+26 -22
View File
@@ -11,7 +11,7 @@ use core_types::transform::{Footprint, Transform};
use core_types::uuid::NodeId; use core_types::uuid::NodeId;
use core_types::{ use core_types::{
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_FORM, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, CloneVarArgs, Color, Context, Ctx, ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_FORM, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, CloneVarArgs, Color, Context, Ctx,
ExtractAll, OwnedContextImpl, ExtractAll, InjectFootprint, InjectIndex, OwnedContextImpl,
}; };
use core_types::{Interrupt, NodeError}; use core_types::{Interrupt, NodeError};
use glam::{DAffine2, DMat2, DVec2}; use glam::{DAffine2, DMat2, DVec2};
@@ -282,7 +282,7 @@ pub enum VaryColorsError {
} }
/// Uniquely recolors the fill of every vector element to individual colors sampled along a chosen gradient. /// Uniquely recolors the fill of every vector element to individual colors sampled along a chosen gradient.
#[node_macro::node(category("Vector: Style"), icon("NodeVaryFillColors"), path(graphene_core::vector), version(2))] #[node_macro::node(category("Vector: Style"), icon("NodeVaryFillColors"), path(graphene_core::vector), version(2), footprint_invariant)]
fn vary_fill_colors<T>( fn vary_fill_colors<T>(
_: impl Ctx, _: impl Ctx,
/// The content with vector paths to apply the fill style to. /// The content with vector paths to apply the fill style to.
@@ -313,7 +313,7 @@ where
} }
/// Uniquely recolors the stroke of every vector element to individual colors sampled along a chosen gradient. /// Uniquely recolors the stroke of every vector element to individual colors sampled along a chosen gradient.
#[node_macro::node(category("Vector: Style"), icon("NodeVaryStrokeColors"), path(graphene_core::vector))] #[node_macro::node(category("Vector: Style"), icon("NodeVaryStrokeColors"), path(graphene_core::vector), footprint_invariant)]
fn vary_stroke_colors<T>( fn vary_stroke_colors<T>(
_: impl Ctx, _: impl Ctx,
/// The content with vector paths to apply the stroke style to. /// The content with vector paths to apply the stroke style to.
@@ -794,7 +794,7 @@ fn unweld<V: MapVectorItems + Send + Sync + 'static>(
} }
/// Wraps the points and paths of the vector content in a closed path in the shape of a rubber band stretched around everything. A curvature above zero may be given to obtain the concave hull, letting the (closed, open, or mesh-like) path or paths press into indents of the content where a ball with that curvature would be able to reach. /// Wraps the points and paths of the vector content in a closed path in the shape of a rubber band stretched around everything. A curvature above zero may be given to obtain the concave hull, letting the (closed, open, or mesh-like) path or paths press into indents of the content where a ball with that curvature would be able to reach.
#[node_macro::node(category("Vector: Point"), icon("NodeConvexHull"), path(core_types::vector))] #[node_macro::node(category("Vector: Point"), icon("NodeConvexHull"), path(core_types::vector), footprint_invariant)]
fn convex_hull<V: MapVectorItems + Send>( fn convex_hull<V: MapVectorItems + Send>(
_: impl Ctx, _: impl Ctx,
/// The vector content to envelop in the hull, which may be points, paths, or both. /// The vector content to envelop in the hull, which may be points, paths, or both.
@@ -1102,7 +1102,7 @@ pub enum BoxWarpError {
TooFewCorners, TooFewCorners,
} }
#[node_macro::node(category("Vector: Deform"), icon("NodeBoxWarp"), path(core_types::vector))] #[node_macro::node(category("Vector: Deform"), icon("NodeBoxWarp"), path(core_types::vector), footprint_invariant)]
fn box_warp<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item<V>, #[expose] rectangle: Item<Vector>) -> Result<Item<V>, BoxWarpError> { fn box_warp<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item<V>, #[expose] rectangle: Item<Vector>) -> Result<Item<V>, BoxWarpError> {
let target_transform: DAffine2 = rectangle.attribute_cloned_or_default(ATTR_TRANSFORM); let target_transform: DAffine2 = rectangle.attribute_cloned_or_default(ATTR_TRANSFORM);
let target_paths = shared_paths_from_item_attributes(&rectangle); let target_paths = shared_paths_from_item_attributes(&rectangle);
@@ -1171,7 +1171,7 @@ fn bilinear_interpolate(t: DVec2, quad: &[DVec2; 4]) -> DVec2 {
tl * (1. - t.x) * (1. - t.y) + tr * t.x * (1. - t.y) + br * t.x * t.y + bl * (1. - t.x) * t.y tl * (1. - t.x) * (1. - t.y) + tr * t.x * (1. - t.y) + br * t.x * t.y + bl * (1. - t.x) * t.y
} }
#[node_macro::node(category("Transform"), icon("NodePackStrips"), path(graphene_core::vector))] #[node_macro::node(category("Transform"), icon("NodePackStrips"), path(graphene_core::vector), footprint_invariant)]
fn pack_strips<T: Send + Clone>( fn pack_strips<T: Send + Clone>(
_: impl Ctx, _: impl Ctx,
#[implementations( #[implementations(
@@ -1473,7 +1473,7 @@ fn push_contour(vector: &mut Vector, paths: &mut List<Path>, anchors: &[u32], ma
push_paths(paths, runs); push_paths(paths, runs);
} }
#[node_macro::node(category("Vector: Geometry"), icon("NodeBoundingBox"), path(core_types::vector))] #[node_macro::node(category("Vector: Geometry"), icon("NodeBoundingBox"), path(core_types::vector), footprint_invariant)]
fn bounding_box<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item<V>) -> Item<V> { fn bounding_box<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item<V>) -> Item<V> {
V::map_vector_items(content, |content| { V::map_vector_items(content, |content| {
let mut content = content; let mut content = content;
@@ -1490,7 +1490,7 @@ fn bounding_box<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic
}) })
} }
#[node_macro::node(category("Vector: Measure"), icon("NodeDimensions"), path(core_types::vector))] #[node_macro::node(category("Vector: Measure"), icon("NodeDimensions"), path(core_types::vector), footprint_invariant)]
fn dimensions(_: impl Ctx, content: Item<Vector>) -> Item<DVec2> { fn dimensions(_: impl Ctx, content: Item<Vector>) -> Item<DVec2> {
let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths()); let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths());
let dimensions = content let dimensions = content
@@ -1509,7 +1509,7 @@ fn as_vector(_: impl Ctx, value: Item<Vector>) -> Item<Vector> {
} }
/// Creates vector points at the given positions, as a point cloud with nothing connecting them. **Points to Polyline** can join them into a path. /// Creates vector points at the given positions, as a point cloud with nothing connecting them. **Points to Polyline** can join them into a path.
#[node_macro::node(category("Vector: Point"), icon("NodePointsToVector"), name("Points to Vector"), path(core_types::vector))] #[node_macro::node(category("Vector: Point"), icon("NodePointsToVector"), name("Points to Vector"), path(core_types::vector), footprint_invariant)]
fn points_to_vector( fn points_to_vector(
_: impl Ctx, _: impl Ctx,
/// The positions to place the points at, in order. /// The positions to place the points at, in order.
@@ -1635,7 +1635,7 @@ fn relax_points<V: MapVectorItems + Send>(
/// Builds a Voronoi diagram from the anchor points. Each point claims the region of space closest to it, and those regions tessellate the plane. Cells around the outside are clipped to the convex hull of the points so the diagram stays finite. /// Builds a Voronoi diagram from the anchor points. Each point claims the region of space closest to it, and those regions tessellate the plane. Cells around the outside are clipped to the convex hull of the points so the diagram stays finite.
/// ///
/// When Connect Cells is off, every cell becomes its own closed, fillable subpath. When on, the cells share their common points and segments, forming a single connected mesh. /// When Connect Cells is off, every cell becomes its own closed, fillable subpath. When on, the cells share their common points and segments, forming a single connected mesh.
#[node_macro::node(category("Vector: Point"), icon("NodeVoronoiCells"), path(core_types::vector))] #[node_macro::node(category("Vector: Point"), icon("NodeVoronoiCells"), path(core_types::vector), footprint_invariant)]
fn voronoi_cells<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item<V>, connect_cells: Item<bool>) -> Result<Item<V>, PointDiagramError> { fn voronoi_cells<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item<V>, connect_cells: Item<bool>) -> Result<Item<V>, PointDiagramError> {
V::try_map_vector_items(source, |source| { V::try_map_vector_items(source, |source| {
let mut source = source; let mut source = source;
@@ -1658,7 +1658,7 @@ fn voronoi_cells<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphi
/// Builds a Delaunay triangulation connecting the anchor points. It is the geometric dual of the **Voronoi** node: a mesh of triangles in which no point lies inside any triangle's circumscribed circle. /// Builds a Delaunay triangulation connecting the anchor points. It is the geometric dual of the **Voronoi** node: a mesh of triangles in which no point lies inside any triangle's circumscribed circle.
/// ///
/// When Connect Cells is off, every triangle becomes its own closed, fillable subpath. When on, the triangles share their common points and segments, forming a single connected mesh. /// When Connect Cells is off, every triangle becomes its own closed, fillable subpath. When on, the triangles share their common points and segments, forming a single connected mesh.
#[node_macro::node(category("Vector: Point"), icon("NodeTriangulate"), path(core_types::vector))] #[node_macro::node(category("Vector: Point"), icon("NodeTriangulate"), path(core_types::vector), footprint_invariant)]
fn triangulate<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item<V>, connect_cells: Item<bool>) -> Result<Item<V>, PointDiagramError> { fn triangulate<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item<V>, connect_cells: Item<bool>) -> Result<Item<V>, PointDiagramError> {
V::try_map_vector_items(source, |source| { V::try_map_vector_items(source, |source| {
let mut source = source; let mut source = source;
@@ -2043,9 +2043,9 @@ fn path_is_closed(
Item::new_from_element(closed) Item::new_from_element(closed)
} }
#[node_macro::node(category("Vector: Point"), icon("NodeMapPoints"), path(graphene_core::vector))] #[node_macro::node(category("Vector: Point"), icon("NodeMapPoints"), path(graphene_core::vector), version(2))]
fn map_points<V: MapVectorItems + Send>( fn map_points<V: MapVectorItems + Send>(
ctx: impl Ctx + CloneVarArgs + ExtractAll, ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
#[implementations(Graphic, Vector)] content: Item<V>, #[implementations(Graphic, Vector)] content: Item<V>,
mapped: impl Node<Context<'static>, Output = Item<DVec2>>, mapped: impl Node<Context<'static>, Output = Item<DVec2>>,
) -> Result<Item<V>, Interrupt> { ) -> Result<Item<V>, Interrupt> {
@@ -2836,7 +2836,7 @@ fn offset_points<V: MapVectorItems + Send>(
/// Interpolates the geometry, appearance, and transform between multiple vector layers, producing a single morphed vector shape. /// Interpolates the geometry, appearance, and transform between multiple vector layers, producing a single morphed vector shape.
/// ///
/// *Progression* morphs through all objects. Interpolation is linear unless *Path* geometry is provided to control the trajectory between key objects. The **Origins to Polyline** node may be used to create a path with anchor points corresponding to each object. Other nodes can modify its path segments. /// *Progression* morphs through all objects. Interpolation is linear unless *Path* geometry is provided to control the trajectory between key objects. The **Origins to Polyline** node may be used to create a path with anchor points corresponding to each object. Other nodes can modify its path segments.
#[node_macro::node(category("Vector: Deform"), icon("NodeMorph"), path(core_types::vector))] #[node_macro::node(category("Vector: Deform"), icon("NodeMorph"), path(core_types::vector), footprint_invariant)]
fn morph( fn morph(
_: impl Ctx, _: impl Ctx,
/// The vector objects to interpolate between. Mixed graphic content is deeply flattened to keep only vector elements. /// The vector objects to interpolate between. Mixed graphic content is deeply flattened to keep only vector elements.
@@ -3871,12 +3871,12 @@ fn point_inside(_: impl Ctx, source: Item<Vector>, point: Item<DVec2>) -> Item<b
// TODO: Return i64 instead of f64 once automatic type conversion is implemented for nodes with generic type inputs, so an integer output doesn't wall this count off from the generic math nodes. // TODO: Return i64 instead of f64 once automatic type conversion is implemented for nodes with generic type inputs, so an integer output doesn't wall this count off from the generic math nodes.
// TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.) // TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.)
#[node_macro::node(category("Data: List"), icon("NodeCount"), path(graphene_core::vector))] #[node_macro::node(category("Data: List"), icon("NodeCount"), path(graphene_core::vector), footprint_invariant)]
fn count(_: impl Ctx, content: ListDyn) -> Item<f64> { fn count(_: impl Ctx, content: ListDyn) -> Item<f64> {
Item::new_from_element(content.len() as f64) Item::new_from_element(content.len() as f64)
} }
#[node_macro::node(category("Vector: Measure"), icon("NodeCountPoints"), path(graphene_core::vector))] #[node_macro::node(category("Vector: Measure"), icon("NodeCountPoints"), path(graphene_core::vector), footprint_invariant)]
fn count_points(_: impl Ctx, content: Item<Vector>) -> Item<f64> { fn count_points(_: impl Ctx, content: Item<Vector>) -> Item<f64> {
let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths()); let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths());
let count = content.element().anchor_indices(paths).len() as f64; let count = content.element().anchor_indices(paths).len() as f64;
@@ -3886,7 +3886,7 @@ fn count_points(_: impl Ctx, content: Item<Vector>) -> Item<f64> {
/// Retrieves the vec2 position (in local space) of the anchor point at the specified index within a vector element. /// Retrieves the vec2 position (in local space) of the anchor point at the specified index within a vector element.
/// If no value exists at that index, the position (0, 0) is returned. /// If no value exists at that index, the position (0, 0) is returned.
#[node_macro::node(category("Vector: Measure"), icon("NodeIndexPoints"), path(graphene_core::vector))] #[node_macro::node(category("Vector: Measure"), icon("NodeIndexPoints"), path(graphene_core::vector), footprint_invariant)]
fn index_points( fn index_points(
_: impl Ctx, _: impl Ctx,
/// The vector element containing the anchor points to be retrieved. /// The vector element containing the anchor points to be retrieved.
@@ -3912,7 +3912,7 @@ fn index_points(
Item::new_from_element(positions[index]) Item::new_from_element(positions[index])
} }
#[node_macro::node(category("Vector: Measure"), icon("NodePathLength"), path(core_types::vector))] #[node_macro::node(category("Vector: Measure"), icon("NodePathLength"), path(core_types::vector), footprint_invariant)]
fn path_length(_: impl Ctx, source: Item<Vector>) -> Item<f64> { fn path_length(_: impl Ctx, source: Item<Vector>) -> Item<f64> {
let paths = paths_from_item_attributes(&source).unwrap_or_else(|| no_paths()); let paths = paths_from_item_attributes(&source).unwrap_or_else(|| no_paths());
let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM); let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM);
@@ -3928,8 +3928,8 @@ fn path_length(_: impl Ctx, source: Item<Vector>) -> Item<f64> {
Item::new_from_element(length) Item::new_from_element(length)
} }
#[node_macro::node(category("Vector: Measure"), icon("NodeArea"), path(core_types::vector))] #[node_macro::node(category("Vector: Measure"), icon("NodeArea"), path(core_types::vector), version(2))]
fn area(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node<Context<'static>, Output = Item<Vector>>) -> Result<Item<f64>, Interrupt> { fn area(ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectFootprint, content: impl Node<Context<'static>, Output = Item<Vector>>) -> Result<Item<f64>, Interrupt> {
let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context(); let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context();
let vector = content.eval(new_ctx)?; let vector = content.eval(new_ctx)?;
@@ -3947,8 +3947,12 @@ pub enum CentroidError {
NoPoints, NoPoints,
} }
#[node_macro::node(category("Vector: Measure"), icon("NodeCentroid"), path(core_types::vector))] #[node_macro::node(category("Vector: Measure"), icon("NodeCentroid"), path(core_types::vector), version(2))]
fn centroid(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node<Context<'static>, Output = Item<Vector>>, centroid_type: Item<CentroidType>) -> Result<Item<DVec2>, Interrupt> { fn centroid(
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectFootprint,
content: impl Node<Context<'static>, Output = Item<Vector>>,
centroid_type: Item<CentroidType>,
) -> Result<Item<DVec2>, Interrupt> {
let centroid_type = centroid_type.into_element(); let centroid_type = centroid_type.into_element();
let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context(); let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context();
let vector = content.eval(new_ctx)?; let vector = content.eval(new_ctx)?;
+26 -3
View File
@@ -205,12 +205,17 @@ impl Preprocessor {
context_features, context_features,
.. ..
} = metadata; } = metadata;
let constant_inputs = fields.iter().enumerate().filter(|(_, field)| field.constant).fold(0, |mask, (index, _)| mask | 1 << index); let input_mask = |predicate: &dyn Fn(&FieldMetadata) -> bool| fields.iter().enumerate().filter(|(_, field)| predicate(field)).fold(0, |mask, (index, _)| mask | 1 << index);
let context_metadata = NodeCompileMetadata::from(context_features.as_slice());
let pushes_index = context_metadata.inject.contains(ContextFeatures::INDEX);
let node_compile_metadata = NodeCompileMetadata { let node_compile_metadata = NodeCompileMetadata {
footprint_invariant: *footprint_invariant, footprint_invariant: *footprint_invariant,
forwards_input: *forwards_input, forwards_input: *forwards_input,
constant_inputs, constant_inputs: input_mask(&|field| field.constant),
..NodeCompileMetadata::from(context_features.as_slice()) loop_body_inputs: if pushes_index { input_mask(&|field| field.lazy) } else { 0 },
index_level_input: fields.iter().position(|field| field.index_role == FieldIndexRole::Level).map(|index| index as u8),
..context_metadata
}; };
compile_metadata.insert(id.clone(), node_compile_metadata); compile_metadata.insert(id.clone(), node_compile_metadata);
@@ -864,4 +869,22 @@ mod tests {
assert!(compile_metadata(&identifier).forwards_input, "{identifier:?} should forward its input"); assert!(compile_metadata(&identifier).forwards_input, "{identifier:?} should forward its input");
} }
} }
#[test]
fn loop_index_roles_reach_the_compile_metadata() {
use graphene_std::context::read_index;
use graphene_std::graphic::map;
let preprocessor = Preprocessor::new();
let compile_metadata = |identifier: &ProtoNodeIdentifier| preprocessor.compile_metadata.get(identifier).copied().unwrap_or_default();
let map_metadata = compile_metadata(&map::IDENTIFIER);
assert!(map_metadata.is_loop_body_input(<map::MappedInput as NodeParameter>::INDEX));
assert_eq!(map_metadata.loop_body_inputs.count_ones(), 1, "Only the mapped lambda runs inside the loop");
let read_index_metadata = compile_metadata(&read_index::IDENTIFIER);
let loop_level_index = <read_index::LoopLevelInput as NodeParameter>::INDEX;
assert_eq!(read_index_metadata.index_level_input, Some(loop_level_index as u8));
assert!(read_index_metadata.requires_constant_input(loop_level_index), "The loop level must be a constant");
}
} }