mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b11b065c6b | ||
|
|
5862823504 | ||
|
|
5ca0ed032f | ||
|
|
efdf51023b | ||
|
|
3381e0b24e | ||
|
|
bf0e35197b |
No files matched your search
@@ -6,3 +6,5 @@ use migration_core::rename;
|
||||
rename!("graphene_core::ops::PassthroughNode"@1 => @2);
|
||||
// The removed Monitor node passes its one input on, as a Passthrough does
|
||||
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);
|
||||
@@ -4,6 +4,9 @@
|
||||
mod blending_nodes;
|
||||
mod graphene_core;
|
||||
mod graphene_std;
|
||||
mod graphic_nodes;
|
||||
mod math_nodes;
|
||||
mod raster_nodes;
|
||||
mod repeat_nodes;
|
||||
mod text_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;
|
||||
|
||||
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,
|
||||
compile_metadata: self.compile_metadata.unwrap_or_default(),
|
||||
upstream_context_features: Default::default(),
|
||||
upstream_index_levels: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,8 @@ impl Compiler {
|
||||
if !errors.is_empty() {
|
||||
return Err(CompileError::Graph(errors));
|
||||
}
|
||||
let warnings = proto_network.footprint_invariance_violations();
|
||||
let mut warnings = proto_network.footprint_invariance_violations();
|
||||
warnings.extend(proto_network.footprint_dependent_index_violations());
|
||||
|
||||
proto_network.generate_stable_node_ids();
|
||||
Ok(CompiledNetwork { network: proto_network, warnings })
|
||||
|
||||
@@ -127,6 +127,8 @@ pub struct ProtoNode {
|
||||
pub(crate) compile_metadata: NodeCompileMetadata,
|
||||
/// The context features read by this node and everything upstream of it.
|
||||
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 {
|
||||
@@ -138,6 +140,7 @@ impl Default for ProtoNode {
|
||||
original_location: OriginalLocation::default(),
|
||||
compile_metadata: Default::default(),
|
||||
upstream_context_features: ContextFeatures::empty(),
|
||||
upstream_index_levels: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -169,6 +172,7 @@ impl ProtoNode {
|
||||
},
|
||||
compile_metadata: Default::default(),
|
||||
upstream_context_features: ContextFeatures::empty(),
|
||||
upstream_index_levels: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,6 +290,24 @@ impl ProtoNetwork {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Loops whose body reads the pushed index while the rows it enumerates depend on the footprint.
|
||||
pub(crate) fn footprint_dependent_index_violations(&self) -> GraphErrors {
|
||||
self.nodes
|
||||
.iter()
|
||||
.filter(|(_, node)| {
|
||||
let ConstructionArgs::Nodes(inputs) = &node.construction_args else { return false };
|
||||
let metadata = node.compile_metadata;
|
||||
let input = |index: usize| &self.nodes[inputs[index].0 as usize].1;
|
||||
|
||||
let body_reads_pushed_index = (0..inputs.len()).any(|index| metadata.is_loop_body_input(index) && input(index).upstream_index_levels & 1 != 0);
|
||||
let index_follows_footprint = (0..inputs.len()).any(|index| metadata.is_used_as_index_input(index) && input(index).upstream_context_features.contains(ContextFeatures::FOOTPRINT));
|
||||
|
||||
body_reads_pushed_index && index_follows_footprint
|
||||
})
|
||||
.map(|(_, node)| GraphError::new(node, GraphErrorType::FootprintDependentIndex))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn non_constant_inputs(&self) -> GraphErrors {
|
||||
self.nodes
|
||||
.iter()
|
||||
@@ -304,22 +326,42 @@ impl ProtoNetwork {
|
||||
.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 {
|
||||
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");
|
||||
|
||||
match &node.construction_args {
|
||||
ConstructionArgs::Value(_) => return true,
|
||||
ConstructionArgs::Nodes(inputs) if node.compile_metadata.forwards_input => match inputs.first() {
|
||||
Some(&input) => id = input,
|
||||
None => return false,
|
||||
},
|
||||
_ => return false,
|
||||
ConstructionArgs::Value(value) => return Some(&**value),
|
||||
ConstructionArgs::Nodes(inputs) if node.compile_metadata.forwards_input => id = *inputs.first()?,
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
let (_, node) = &self.nodes[node_id.0 as usize];
|
||||
let mut path = node.original_location.path.clone();
|
||||
@@ -330,6 +372,7 @@ impl ProtoNetwork {
|
||||
}
|
||||
|
||||
let features = context_deps.features;
|
||||
let index_levels = node.upstream_index_levels;
|
||||
let forwarding = NodeCompileMetadata {
|
||||
forwards_input: true,
|
||||
..Default::default()
|
||||
@@ -348,6 +391,7 @@ impl ProtoNetwork {
|
||||
},
|
||||
compile_metadata: forwarding,
|
||||
upstream_context_features: features,
|
||||
upstream_index_levels: index_levels,
|
||||
},
|
||||
));
|
||||
|
||||
@@ -379,6 +423,7 @@ impl ProtoNetwork {
|
||||
},
|
||||
compile_metadata: forwarding,
|
||||
upstream_context_features: features,
|
||||
upstream_index_levels: index_levels,
|
||||
},
|
||||
));
|
||||
nullification_node_id
|
||||
@@ -427,16 +472,34 @@ impl ProtoNetwork {
|
||||
};
|
||||
|
||||
// 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);
|
||||
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.sources.extend(&branch.0.sources);
|
||||
branch_dependencies.push(branch);
|
||||
}
|
||||
// Remove requirements which this node provides and add requirements we have
|
||||
let features = (combined_deps.features & !dependencies.inject) | dependencies.extract;
|
||||
self.nodes[node_index].1.upstream_index_levels = index_levels;
|
||||
|
||||
// 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
|
||||
let we_introduces_new_deps = !combined_deps.features.contains(features);
|
||||
@@ -451,14 +514,8 @@ impl ProtoNetwork {
|
||||
}
|
||||
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
|
||||
|
||||
// Which dependencies do we supply (and don't need ourselves)?
|
||||
let net_injections = dependencies.inject.difference(dependencies.extract);
|
||||
|
||||
// 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();
|
||||
// Do we satisfy any existing dependencies, so they are no longer needed after this node?
|
||||
let we_supply_existing_deps = !combined_deps.features.difference(features).is_empty();
|
||||
|
||||
let new_deps = ContextModification {
|
||||
features,
|
||||
@@ -609,6 +666,7 @@ pub enum GraphErrorType {
|
||||
valid: Vec<NodeIOTypes>,
|
||||
},
|
||||
FootprintDependentInput,
|
||||
FootprintDependentIndex,
|
||||
NonConstantInput {
|
||||
index: usize,
|
||||
},
|
||||
@@ -663,6 +721,10 @@ 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::FootprintDependentIndex => write!(
|
||||
f,
|
||||
"Warning: the items this node loops over adapt to the visible canvas area, so the index read inside the loop changes when the view is panned or zoomed"
|
||||
),
|
||||
GraphErrorType::NonConstantInput { index } => write!(f, "Input {} must be a fixed value rather than computed by other nodes", index + 1),
|
||||
GraphErrorType::MissingResource { index } => write!(
|
||||
f,
|
||||
@@ -1330,6 +1392,102 @@ mod test {
|
||||
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,
|
||||
used_as_index_inputs: 0,
|
||||
index_level_input: Some(0),
|
||||
};
|
||||
|
||||
/// A loop over its first input's rows, evaluating its second input per row.
|
||||
const MAP: NodeCompileMetadata = NodeCompileMetadata {
|
||||
extract: ContextFeatures::empty(),
|
||||
inject: ContextFeatures::INDEX,
|
||||
footprint_invariant: false,
|
||||
forwards_input: false,
|
||||
constant_inputs: 0,
|
||||
loop_body_inputs: 0b10,
|
||||
used_as_index_inputs: 0b01,
|
||||
index_level_input: None,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn loops_warn_when_their_body_reads_an_index_over_footprint_dependent_rows() {
|
||||
let footprint_reader = NodeCompileMetadata {
|
||||
extract: ContextFeatures::FOOTPRINT,
|
||||
..Default::default()
|
||||
};
|
||||
let warnings = |loop_level: i64, rows_read_footprint: bool| {
|
||||
let rows_metadata = if rows_read_footprint { footprint_reader } else { NodeCompileMetadata::default() };
|
||||
let nodes = vec![
|
||||
(NodeId(0), integer_value(loop_level)),
|
||||
(NodeId(1), loop_test_node("index_reader", vec![NodeId(0)], INDEX_READER)),
|
||||
(NodeId(2), integer_value(2)),
|
||||
(NodeId(3), loop_test_node("rows", vec![NodeId(2)], rows_metadata)),
|
||||
(NodeId(4), loop_test_node("map", vec![NodeId(3), NodeId(1)], MAP)),
|
||||
];
|
||||
|
||||
let mut network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(4),
|
||||
nodes,
|
||||
};
|
||||
network.insert_context_nullification_nodes().unwrap();
|
||||
network.footprint_dependent_index_violations()
|
||||
};
|
||||
|
||||
let violations = warnings(0, true);
|
||||
assert_eq!(violations.len(), 1);
|
||||
assert_eq!(violations[0].identifier, "map");
|
||||
assert!(violations[0].error == GraphErrorType::FootprintDependentIndex);
|
||||
|
||||
assert!(warnings(1, true).is_empty(), "Reading an outer loop's index doesn't depend on the map's rows");
|
||||
assert!(warnings(0, false).is_empty());
|
||||
}
|
||||
|
||||
#[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]
|
||||
fn constant_inputs_must_resolve_to_values_through_forwarding_nodes() {
|
||||
let value = || ProtoNode::value(ConstructionArgs::Value(TaggedValue::String("name".into()).into()), vec![]);
|
||||
|
||||
@@ -233,11 +233,32 @@ pub struct NodeCompileMetadata {
|
||||
pub forwards_input: bool,
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
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,
|
||||
/// Inputs whose rows the pushed loop index enumerates.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub used_as_index_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 {
|
||||
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)
|
||||
}
|
||||
|
||||
pub fn is_used_as_index_input(&self, index: usize) -> bool {
|
||||
Self::contains_input(self.used_as_index_inputs, index)
|
||||
}
|
||||
|
||||
fn contains_input(mask: u64, index: usize) -> bool {
|
||||
index < u64::BITS as usize && mask & (1 << index) != 0
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -60,6 +60,20 @@ pub struct FieldMetadata {
|
||||
pub progression: bool,
|
||||
/// Whether the input must be fed by a value known at compile time, from `#[constant]`.
|
||||
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,
|
||||
/// The loop index enumerates this input's rows, from `#[used_as_index]`.
|
||||
UsedAsIndex,
|
||||
/// This input's constant value selects which loop level's index is read, from `#[index_level]`.
|
||||
Level,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
||||
@@ -318,6 +318,21 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
quote!(#constant)
|
||||
})
|
||||
.collect();
|
||||
let index_role: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| match field.index_role {
|
||||
ParsedIndexRole::None => quote!(gcore::registry::FieldIndexRole::None),
|
||||
ParsedIndexRole::UsedAsIndex => quote!(gcore::registry::FieldIndexRole::UsedAsIndex),
|
||||
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
|
||||
.iter()
|
||||
@@ -1078,6 +1093,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
multiline: #multiline,
|
||||
progression: #progression,
|
||||
constant: #constant,
|
||||
index_role: #index_role,
|
||||
lazy: #lazy,
|
||||
},
|
||||
)*
|
||||
],
|
||||
|
||||
@@ -123,6 +123,17 @@ impl Parse for ParsedWidgetOverride {
|
||||
}
|
||||
}
|
||||
|
||||
/// How a field takes part in loop index tracking, from `#[used_as_index]` or `#[index_level]`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum ParsedIndexRole {
|
||||
#[default]
|
||||
None,
|
||||
/// The loop index enumerates this field's rows.
|
||||
UsedAsIndex,
|
||||
/// This field's constant value selects which loop level's index the node reads.
|
||||
Level,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ParsedField {
|
||||
pub pat_ident: PatIdent,
|
||||
@@ -136,6 +147,7 @@ pub struct ParsedField {
|
||||
pub multiline: bool,
|
||||
pub progression: bool,
|
||||
pub constant: bool,
|
||||
pub index_role: ParsedIndexRole,
|
||||
pub is_data_field: bool,
|
||||
}
|
||||
|
||||
@@ -169,6 +181,7 @@ impl ParsedField {
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
index_role: ParsedIndexRole::None,
|
||||
is_data_field: false,
|
||||
}
|
||||
}
|
||||
@@ -856,8 +869,16 @@ 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();
|
||||
let index_role = match (extract_attribute(attrs, "used_as_index"), extract_attribute(attrs, "index_level")) {
|
||||
(None, None) => ParsedIndexRole::None,
|
||||
(Some(_), None) => ParsedIndexRole::UsedAsIndex,
|
||||
(None, Some(_)) => ParsedIndexRole::Level,
|
||||
(Some(_), Some(_)) => return Err(Error::new_spanned(&pat_ident, "A field cannot be both #[used_as_index] and #[index_level]")),
|
||||
};
|
||||
|
||||
// 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
|
||||
let source_id = extract_attribute(attrs, "source_id").is_some();
|
||||
@@ -888,6 +909,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",
|
||||
));
|
||||
}
|
||||
if index_role != ParsedIndexRole::None {
|
||||
return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot be #[used_as_index] or #[index_level]"));
|
||||
}
|
||||
if source_id {
|
||||
return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot have #[source_id] attribute"));
|
||||
}
|
||||
@@ -1035,6 +1059,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
multiline,
|
||||
progression,
|
||||
constant,
|
||||
index_role,
|
||||
is_data_field,
|
||||
})
|
||||
} else {
|
||||
@@ -1087,6 +1112,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
multiline,
|
||||
progression,
|
||||
constant,
|
||||
index_role,
|
||||
is_data_field,
|
||||
})
|
||||
}
|
||||
@@ -1386,6 +1412,7 @@ mod tests {
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
index_role: ParsedIndexRole::None,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1448,6 +1475,7 @@ mod tests {
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
index_role: ParsedIndexRole::None,
|
||||
is_data_field: false,
|
||||
},
|
||||
ParsedField {
|
||||
@@ -1472,6 +1500,7 @@ mod tests {
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
index_role: ParsedIndexRole::None,
|
||||
is_data_field: false,
|
||||
},
|
||||
],
|
||||
@@ -1535,6 +1564,7 @@ mod tests {
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
index_role: ParsedIndexRole::None,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1601,6 +1631,7 @@ mod tests {
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
index_role: ParsedIndexRole::None,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1670,6 +1701,7 @@ mod tests {
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
index_role: ParsedIndexRole::None,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1764,6 +1796,7 @@ mod tests {
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
index_role: ParsedIndexRole::None,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
|
||||
@@ -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`.
|
||||
#[hard(0..)]
|
||||
#[index_level]
|
||||
loop_level: Item<i64>,
|
||||
) -> Result<Item<f64>, ReadContextError> {
|
||||
// The graph outside any loop runs once, as index 0
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use brush_types::Stroke;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
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 graphic_types::graphic::{Graphic, IntoGraphicList, is_lone_anonymous_leaf};
|
||||
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.
|
||||
/// 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>(
|
||||
_: impl Ctx,
|
||||
/// 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.
|
||||
/// 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>(
|
||||
_: impl Ctx,
|
||||
/// 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.
|
||||
#[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>(
|
||||
_: impl Ctx,
|
||||
/// 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.
|
||||
#[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>(
|
||||
_: impl Ctx,
|
||||
/// 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.
|
||||
#[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>(
|
||||
_: impl Ctx,
|
||||
/// 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: (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.
|
||||
#[node_macro::node(category("Data: List"), icon("NodeIndices"))]
|
||||
#[node_macro::node(category("Data: List"), icon("NodeIndices"), footprint_invariant)]
|
||||
fn indices(
|
||||
_: impl Ctx,
|
||||
/// 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".
|
||||
///
|
||||
/// 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>(
|
||||
_: impl Ctx,
|
||||
/// 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.
|
||||
#[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>(
|
||||
_: impl Ctx,
|
||||
/// The list of data to reorder.
|
||||
@@ -396,9 +398,9 @@ fn sort<T: ElementOrder + Clone + Send + Sync + 'static, U: ElementOrder + Send
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Data: List"), icon("NodeMap"))]
|
||||
#[node_macro::node(category("Data: List"), icon("NodeMap"), version(2))]
|
||||
fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll,
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
|
||||
#[implementations(
|
||||
List<String>,
|
||||
List<bool>,
|
||||
@@ -414,6 +416,7 @@ fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
|
||||
List<Gradient>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
#[used_as_index]
|
||||
content: List<Item>,
|
||||
#[implementations(
|
||||
Context -> List<String>,
|
||||
@@ -446,9 +449,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.
|
||||
#[node_macro::node(category("Routing"), icon("NodeIterate"))]
|
||||
#[node_macro::node(category("Routing"), icon("NodeIterate"), version(2))]
|
||||
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.
|
||||
#[implementations(String, f64, Vector, Graphic, Raster<CPU>, Color, Gradient)]
|
||||
content: Item<T>,
|
||||
@@ -514,7 +517,7 @@ impl HasText for Raster<GPU> {}
|
||||
impl HasText for Color {}
|
||||
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>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
@@ -617,9 +620,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.
|
||||
/// 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)`.
|
||||
#[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>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx + InjectIndex,
|
||||
/// The list to set the named attribute on (one value per item).
|
||||
#[implementations(
|
||||
List<String>,
|
||||
@@ -639,6 +642,7 @@ fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
List<GradientForm>,
|
||||
List<GradientSpread>,
|
||||
)]
|
||||
#[used_as_index]
|
||||
content: List<T>,
|
||||
/// The attribute name (key) to write or replace.
|
||||
#[constant]
|
||||
|
||||
@@ -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`.
|
||||
///
|
||||
/// 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>(
|
||||
_: impl Ctx,
|
||||
/// 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.
|
||||
///
|
||||
/// 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>(
|
||||
_: impl Ctx,
|
||||
/// 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.
|
||||
#[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> {
|
||||
Item::new_from_element(values.iter_element_values().sum())
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
let count = values.len();
|
||||
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.
|
||||
#[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> {
|
||||
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.
|
||||
#[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> {
|
||||
Item::new_from_element(values.iter_element_values().copied().reduce(f64::max).unwrap_or_default())
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ pub enum BooleanOperationError {
|
||||
// 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.
|
||||
#[node_macro::node(category("Vector: Path"), icon("NodeBooleanOperation"), memoize)]
|
||||
#[node_macro::node(category("Vector: Path"), icon("NodeBooleanOperation"), memoize, footprint_invariant)]
|
||||
fn boolean_operation(
|
||||
_: impl Ctx,
|
||||
/// The `List` of vector paths to perform the boolean operation on. Nested `List`s are automatically flattened.
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
use crate::gcore::Context;
|
||||
use core::f64::consts::TAU;
|
||||
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 graphic_types::{Artboard, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::Gradient;
|
||||
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>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx + InjectIndex,
|
||||
#[implementations(
|
||||
Context -> List<String>,
|
||||
Context -> List<bool>,
|
||||
@@ -53,9 +53,9 @@ fn repeat<T: Send + Clone + 'static>(
|
||||
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>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx + InjectIndex,
|
||||
#[implementations(
|
||||
Context -> List<String>,
|
||||
Context -> List<bool>,
|
||||
@@ -114,9 +114,9 @@ fn repeat_array<T: Send + Clone + 'static>(
|
||||
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>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx + InjectIndex,
|
||||
#[implementations(
|
||||
Context -> List<String>,
|
||||
Context -> List<bool>,
|
||||
@@ -171,10 +171,10 @@ fn repeat_radial<T: Send + Clone + 'static>(
|
||||
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>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Sync + Ctx + InjectVarArgs,
|
||||
points: List<Vector>,
|
||||
ctx: impl ExtractAll + CloneVarArgs + Sync + Ctx + InjectVarArgs + InjectIndex,
|
||||
#[used_as_index] points: List<Vector>,
|
||||
#[implementations(
|
||||
Context -> List<String>,
|
||||
Context -> List<bool>,
|
||||
|
||||
@@ -13,7 +13,7 @@ use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::math::float_noise::round_away_float_noise;
|
||||
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 glam::DVec2;
|
||||
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.
|
||||
///
|
||||
/// 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(
|
||||
_: impl Ctx,
|
||||
/// The list of strings to join together.
|
||||
@@ -963,10 +963,10 @@ 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.
|
||||
#[node_macro::node(category("String"), icon("NodeStringMap"))]
|
||||
#[node_macro::node(category("String"), icon("NodeStringMap"), version(2))]
|
||||
fn string_map(
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll,
|
||||
strings: List<String>,
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
|
||||
#[used_as_index] strings: List<String>,
|
||||
#[expose]
|
||||
#[implementations(Context -> Item<String>)]
|
||||
mapped: impl Node<Context<'static>, Output = 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.
|
||||
#[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>(
|
||||
_: impl Ctx,
|
||||
/// 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.
|
||||
#[node_macro::node(category("Transform"), icon("NodeVaryScales"))]
|
||||
#[node_macro::node(category("Transform"), icon("NodeVaryScales"), footprint_invariant)]
|
||||
fn vary_scales<T: Send>(
|
||||
_: impl Ctx,
|
||||
/// The content with items to scale individually.
|
||||
|
||||
@@ -11,7 +11,7 @@ use core_types::transform::{Footprint, Transform};
|
||||
use core_types::uuid::NodeId;
|
||||
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,
|
||||
ExtractAll, OwnedContextImpl,
|
||||
ExtractAll, InjectFootprint, InjectIndex, OwnedContextImpl,
|
||||
};
|
||||
use core_types::{Interrupt, NodeError};
|
||||
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.
|
||||
#[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>(
|
||||
_: impl Ctx,
|
||||
/// 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.
|
||||
#[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>(
|
||||
_: impl Ctx,
|
||||
/// 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.
|
||||
#[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>(
|
||||
_: impl Ctx,
|
||||
/// The vector content to envelop in the hull, which may be points, paths, or both.
|
||||
@@ -1102,7 +1102,7 @@ pub enum BoxWarpError {
|
||||
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> {
|
||||
let target_transform: DAffine2 = rectangle.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
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
|
||||
}
|
||||
|
||||
#[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>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
@@ -1473,7 +1473,7 @@ fn push_contour(vector: &mut Vector, paths: &mut List<Path>, anchors: &[u32], ma
|
||||
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> {
|
||||
V::map_vector_items(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> {
|
||||
let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths());
|
||||
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.
|
||||
#[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(
|
||||
_: impl Ctx,
|
||||
/// 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.
|
||||
///
|
||||
/// 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> {
|
||||
V::try_map_vector_items(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.
|
||||
///
|
||||
/// 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> {
|
||||
V::try_map_vector_items(source, |source| {
|
||||
let mut source = source;
|
||||
@@ -2043,10 +2043,12 @@ fn path_is_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>(
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll,
|
||||
#[implementations(Graphic, Vector)] content: Item<V>,
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
|
||||
#[implementations(Graphic, Vector)]
|
||||
#[used_as_index]
|
||||
content: Item<V>,
|
||||
mapped: impl Node<Context<'static>, Output = Item<DVec2>>,
|
||||
) -> Result<Item<V>, Interrupt> {
|
||||
let mut content = content;
|
||||
@@ -2836,7 +2838,7 @@ fn offset_points<V: MapVectorItems + Send>(
|
||||
/// 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.
|
||||
#[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(
|
||||
_: impl Ctx,
|
||||
/// The vector objects to interpolate between. Mixed graphic content is deeply flattened to keep only vector elements.
|
||||
@@ -3871,12 +3873,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: (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> {
|
||||
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> {
|
||||
let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths());
|
||||
let count = content.element().anchor_indices(paths).len() as f64;
|
||||
@@ -3886,7 +3888,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.
|
||||
/// 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(
|
||||
_: impl Ctx,
|
||||
/// The vector element containing the anchor points to be retrieved.
|
||||
@@ -3912,7 +3914,7 @@ fn index_points(
|
||||
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> {
|
||||
let paths = paths_from_item_attributes(&source).unwrap_or_else(|| no_paths());
|
||||
let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
@@ -3928,8 +3930,8 @@ fn path_length(_: impl Ctx, source: Item<Vector>) -> Item<f64> {
|
||||
Item::new_from_element(length)
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Measure"), icon("NodeArea"), path(core_types::vector))]
|
||||
fn area(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node<Context<'static>, Output = Item<Vector>>) -> Result<Item<f64>, Interrupt> {
|
||||
#[node_macro::node(category("Vector: Measure"), icon("NodeArea"), path(core_types::vector), version(2))]
|
||||
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 vector = content.eval(new_ctx)?;
|
||||
|
||||
@@ -3947,8 +3949,12 @@ pub enum CentroidError {
|
||||
NoPoints,
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Measure"), icon("NodeCentroid"), path(core_types::vector))]
|
||||
fn centroid(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node<Context<'static>, Output = Item<Vector>>, centroid_type: Item<CentroidType>) -> Result<Item<DVec2>, Interrupt> {
|
||||
#[node_macro::node(category("Vector: Measure"), icon("NodeCentroid"), path(core_types::vector), version(2))]
|
||||
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 new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context();
|
||||
let vector = content.eval(new_ctx)?;
|
||||
|
||||
@@ -205,12 +205,18 @@ impl Preprocessor {
|
||||
context_features,
|
||||
..
|
||||
} = 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 {
|
||||
footprint_invariant: *footprint_invariant,
|
||||
forwards_input: *forwards_input,
|
||||
constant_inputs,
|
||||
..NodeCompileMetadata::from(context_features.as_slice())
|
||||
constant_inputs: input_mask(&|field| field.constant),
|
||||
loop_body_inputs: if pushes_index { input_mask(&|field| field.lazy) } else { 0 },
|
||||
used_as_index_inputs: input_mask(&|field| field.index_role == FieldIndexRole::UsedAsIndex),
|
||||
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);
|
||||
|
||||
@@ -864,4 +870,23 @@ mod tests {
|
||||
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_used_as_index_input(<map::ContentInput as NodeParameter>::INDEX));
|
||||
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");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user