Compare commits

...
Author SHA1 Message Date
Dennis Kobert a0ea7961f0 Store node and layer positions relative to their readers in the editor, with Ctrl keeping the upstream in place while dragging 2026-11-17 12:33:35 +01:00
Dennis Kobert dfa55a5791 Add relative node positions and use them for the nodes document migrations add 2026-11-16 17:19:04 +01:00
Dennis Kobert 9857f5ea29 Place the nodes document migrations add beside the node they replace by default 2026-11-16 17:19:03 +01:00
Keavon Chambers 5c78164939 Fix the Data panel showing internal attributes in single-item tables 2026-11-16 17:19:02 +01:00
Keavon Chambers 7109e31817 Fix mismatched timestamps when document migrations restart history 2026-11-16 17:19:01 +01:00
Dennis Kobert c1a77c4309 Let document migrations write attributes of the anchor and the nodes they add 2026-11-16 17:19:00 +01:00
Keavon Chambers 7b2715146c Remove the obsolete 'Monitor' node and its supporting infrastructure (#4962)
* Remove the obsolete 'Monitor' node and its supporting infrastructure

* Make the 'Merge' and 'Artboard' migration test check the rebuilt network
2026-11-15 23:59:57 +00:00
Keavon ChambersandDennis Kobert cf1f7dec80 Make 'Path' a single node instead of a subgraph holding a 'Monitor' node (#4958)
* Let migrations add reflection inputs

* Make 'Path' a single node instead of a subgraph holding a 'Monitor'

* Restore regression coverage for subgraph input narrowing through 'Memoize'

* Observe the content input of 'Path' nodes instead of special-casing them in the runtime

---------

Co-authored-by: Dennis Kobert <[email protected]>
2026-11-15 22:04:48 +00:00
92 changed files with 1621 additions and 696 deletions

No files matched your search

+55 -12
View File
@@ -104,7 +104,7 @@ impl<L: Layout> Gdd<L> {
Ok(rewritten) => rewritten,
Err(error) => {
log::warn!("Migrating this document's history failed, so undo can't reach before this point: {error}");
(self.session_with_truncated_history(migrated)?, remap_metadata(&self.metadata, |_| None))
(session_with_truncated_history(&self.session, migrated)?, remap_metadata(&self.metadata, |_| None))
}
};
self.keep_blobs_durably(blobs.into_added()).await?;
@@ -189,19 +189,24 @@ impl<L: Layout> Gdd<L> {
session.absorb_retired_marks(previous.retired_marks());
Ok((session, remap_metadata(&self.metadata, remap)))
}
}
/// A session whose history restarts from `migrated`.
fn session_with_truncated_history(&self, migrated: Registry) -> Result<Session, Error> {
let previous = &self.session;
let restarted = Session::bootstrap_from_registry(previous.peer(), previous.user(), migrated.clone())?;
/// A session continuing `previous` whose history restarts from `migrated`.
fn session_with_truncated_history(previous: &Session, migrated: Registry) -> Result<Session, Error> {
let peer_users = migrated.peer_users.clone();
let restarted = Session::bootstrap_from_registry(previous.peer(), previous.user(), migrated)?;
let history: Vec<Delta> = restarted.history().cloned().collect();
let mut session = Session::load(previous.peer(), previous.user(), migrated, history, restarted.head_rev(), Vec::new(), previous.next_node_counter());
session.restore_hot_sequence(previous.last_hot_sequence());
session.restore_clock_counter(previous.clock_counter().max(restarted.clock_counter()));
session.absorb_retired_marks(previous.retired_marks());
Ok(session)
}
// The bootstrap re-stamps every value, so its registry is the one matching its history. Its deltas leave out
// which user each device belongs to, so those registrations carry over directly.
let mut registry = restarted.retired_registry().clone();
registry.peer_users = peer_users;
let history: Vec<Delta> = restarted.history().cloned().collect();
let mut session = Session::load(previous.peer(), previous.user(), registry, history, restarted.head_rev(), Vec::new(), previous.next_node_counter());
session.restore_hot_sequence(previous.last_hot_sequence());
session.restore_clock_counter(previous.clock_counter().max(restarted.clock_counter()));
session.absorb_retired_marks(previous.retired_marks());
Ok(session)
}
/// Resolves declaration resources to the declarations migrations name. A declaration's resource derives from its identifier and version
@@ -269,3 +274,41 @@ impl DeclarationResolver for DocumentDeclarations {
Some(self.encoded.get(self.known.get(&resource)?)?.proto.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::{AttributeDelta, RegistryDelta, Value};
#[test]
fn a_truncated_history_matches_its_registry_and_keeps_device_registrations() {
let other_device = PeerId(2);
let mut previous = Session::with_peer(PeerId(1));
previous
.stage_computed_ops(vec![RegistryDelta::RegisterPeer {
peer: other_device,
user: previous.user(),
}])
.unwrap();
previous.retire_all().unwrap();
// Each edit stamps the value later than a fresh bootstrap would
for edit in 0..10 {
let delta = AttributeDelta {
key: "edit".to_string(),
value: Some(Value::Str(edit.to_string())),
};
previous.stage_computed_ops(vec![RegistryDelta::ChangeDocumentAttribute { delta }]).unwrap();
previous.retire_all().unwrap();
}
let session = session_with_truncated_history(&previous, previous.retired_registry().clone()).unwrap();
assert_eq!(session.user_of(other_device), Some(previous.user()));
// Device registrations carry over apart from the history, so everything else must match its replay
let replayed = Session::replay_from_history(session.peer(), session.user(), session.history().cloned(), session.next_node_counter()).unwrap();
let mut registry = session.retired_registry().clone();
registry.peer_users = replayed.retired_registry().peer_users.clone();
assert_eq!(&registry, replayed.retired_registry());
}
}
+11
View File
@@ -7,6 +7,17 @@ use std::collections::{BTreeMap, btree_map};
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
pub mod attr;
/// Unified storage-side position. The valid variants depend on `attr::node::ui::IS_LAYER`:
/// layers use `Absolute` or `Stack`; non-layer nodes use `Absolute`, `Chain`, or `Relative`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Position {
Absolute([i32; 2]),
Chain,
Stack(u32),
/// An offset from the top left corner of the bounding box of the positions of the nodes reading this one.
Relative([i32; 2]),
}
impl AttributeValue {
pub fn new(value: Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp, deleted: false }
@@ -1,7 +1,6 @@
pub mod node {
pub const CALL_ARGUMENT: &str = "call_argument";
pub const VISIBLE: &str = "visible";
pub const SKIP_DEDUPLICATION: &str = "skip_deduplication";
pub const REFLECTION_METADATA: &str = "reflection_metadata";
pub mod input {
@@ -382,9 +382,6 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
attributes
.set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp)
.map_err(map_serialization_error(node::VISIBLE))?;
attributes
.set_if_not_default(node::SKIP_DEDUPLICATION, &doc_node.skip_deduplication, &false, timestamp)
.map_err(map_serialization_error(node::SKIP_DEDUPLICATION))?;
write_ui_attributes(&mut attributes, ctx.metadata, network, runtime_node_id, timestamp)?;
+1 -1
View File
@@ -44,7 +44,7 @@ pub use from_runtime::{
encode_node_ui_attributes, node_value_resource_refs, storage_location_id, storage_node_id, value_resource_ref,
};
#[cfg(any(feature = "conversion", test))]
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource};
#[cfg(any(feature = "conversion", test))]
pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProjection};
+1 -10
View File
@@ -8,7 +8,7 @@ use std::collections::{BTreeMap, HashMap};
use core_types::uuid::NodeId as RuntimeNodeId;
use graph_craft::document::NetworkLocation;
use crate::{NetworkReference, Value};
use crate::{NetworkReference, Position, Value};
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. One entry per
/// node, since every node carries an identity to restore even when it carries no `ui::*` attribute.
@@ -124,12 +124,3 @@ pub trait NodeMetadataSource {
pub struct NoMetadata;
impl NodeMetadataSource for NoMetadata {}
/// Unified storage-side position. The valid variants depend on `attr::node::ui::IS_LAYER`:
/// layers use `Absolute` or `Stack`; non-layer nodes use `Absolute` or `Chain`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Position {
Absolute([i32; 2]),
Chain,
Stack(u32),
}
+3
View File
@@ -22,6 +22,9 @@ impl Node {
pub fn inputs_mut(&mut self) -> &mut Vec<InputSlot> {
&mut self.inputs
}
pub fn attributes_mut(&mut self) -> &mut Attributes {
&mut self.attributes
}
/// True if both nodes agree on every value-bearing field, ignoring slot/attribute timestamps.
pub fn value_equal(&self, other: &Self) -> bool {
+1 -10
View File
@@ -260,8 +260,7 @@ fn test_metadata_preservation() {
inputs: vec![NodeInput::import(concrete!(f64), 0), NodeInput::import(Type::Generic(Cow::Borrowed("T")), 1)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::NodeWithMetadata")),
call_argument: concrete!(String),
visible: false, // Non-default value
skip_deduplication: true, // Non-default value
visible: false, // Non-default value
..Default::default()
},
),
@@ -296,9 +295,6 @@ fn test_metadata_preservation() {
// Verify visible is preserved
assert_eq!(orig_node_0.visible, conv_node_0.visible, "visible should be preserved");
// Verify skip_deduplication is preserved
assert_eq!(orig_node_0.skip_deduplication, conv_node_0.skip_deduplication, "skip_deduplication should be preserved");
// Verify import_type is preserved for Import inputs
match (&orig_node_0.inputs[0], &conv_node_0.inputs[0]) {
(NodeInput::Import { import_type: orig_type, .. }, NodeInput::Import { import_type: conv_type, .. }) => {
@@ -354,11 +350,6 @@ fn test_demo_artwork_round_trip() {
artwork_name, node_id
);
assert_eq!(orig_node.visible, conv_node.visible, "{}: visible should be preserved for node {:?}", artwork_name, node_id);
assert_eq!(
orig_node.skip_deduplication, conv_node.skip_deduplication,
"{}: skip_deduplication should be preserved for node {:?}",
artwork_name, node_id
);
// Check input count
assert_eq!(
-1
View File
@@ -457,7 +457,6 @@ fn convert_node(context: &ConversionContext, node: &crate::Node) -> Result<Docum
call_argument: node.attributes.get_or(node::CALL_ARGUMENT, concrete!(core_types::Context)),
implementation: convert_implementation(context, &node.implementation)?,
visible: node.attributes.get_or(node::VISIBLE, true),
skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false),
// Regenerated during compilation; not stored.
compile_metadata: None,
original_location: Default::default(),
@@ -1,9 +1,10 @@
use document_graph_storage::attr::node::VISIBLE;
use document_graph_storage::attr::node::ui::DISPLAY_NAME;
use graphene_std::Color;
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::vector::Vector;
use graphene_std::vector::style::Gradient;
use migration_core::{Compiler, Inputs, MigrationError, NewNode, Node, NodeInput, Target, Upstream, decl, literal, literal_of, migration};
use migration_core::{Attributes, Compiler, Inputs, MigrationError, NewNode, Node, NodeInput, Target, Upstream, decl, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const CONTENT: usize = 1;
@@ -29,11 +30,23 @@ fn number(input: &NodeInput) -> Option<f64> {
/// Repeat on Points overwrites. Content that doesn't compile takes Flatten Graphic, which can't make that state any worse. A hidden node only passes
/// its points through, so it needs nothing past the repeat, and its unused scale and rotation are dropped.
#[migration("core_types::vector::CopyToPointsNode"@1 => "transform_nodes::transform_nodes::VaryRotationsNode"@2)]
pub fn vary_nodes_from_copy_to_points(node: &Node, compiler: Option<&dyn Compiler>, inputs: &mut Inputs, upstream: &mut Upstream, target: &mut Target) -> Result<(), MigrationError> {
pub fn vary_nodes_from_copy_to_points(
node: &Node,
compiler: Option<&dyn Compiler>,
inputs: &mut Inputs,
upstream: &mut Upstream,
target: &mut Target,
attributes: &mut Attributes,
) -> Result<(), MigrationError> {
let slots: Vec<NodeInput> = node.inputs().iter().map(|slot| slot.input.clone()).collect();
let [points, content, scale_min, scale_max, scale_bias, scale_seed, rotation, rotation_seed] =
<[NodeInput; 8]>::try_from(slots).map_err(|_| MigrationError::invariant("Copy to Points has eight inputs"))?;
// A stored default name would misname the new node
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Copy to Points") {
attributes.remove(node.id(), DISPLAY_NAME);
}
let repeat = decl!("repeat_nodes::repeat_nodes::RepeatOnPointsNode"@1);
let unset = || literal(Tagged::Bool(false));
@@ -170,7 +183,9 @@ fn bias_keeping_average_scale(bias: f64) -> f64 {
mod tests {
use super::*;
use crate::CompilerHost;
use migration_core::Declaration;
use document_graph_storage::attr::node::ui::POSITION;
use document_graph_storage::{NodeId, Position, TimeStamp, Value, to_value};
use migration_core::{CHAIN_WIDTH, Declaration, FEEDER_ROW_HEIGHT};
use migration_runner::testing::{Fixture, Random, SourceContract, check_commutation_with, check_undo_with};
const COPY_TO_POINTS: Declaration = decl!("core_types::vector::CopyToPointsNode"@1);
@@ -184,10 +199,13 @@ mod tests {
}
fn contract() -> SourceContract {
SourceContract::new(8, |random: &mut Random, slot| match slot {
2 | 3 | 4 | 6 => literal(Tagged::Number(random.below(3) as f64)),
_ => literal(Tagged::Integer(random.below(3) as i64)),
})
SourceContract {
display_names: &["Copy to Points"],
..SourceContract::new(8, |random: &mut Random, slot| match slot {
2 | 3 | 4 | 6 => literal(Tagged::Number(random.below(3) as f64)),
_ => literal(Tagged::Integer(random.below(3) as i64)),
})
}
}
fn star_inputs() -> Vec<NodeInput> {
@@ -262,6 +280,48 @@ mod tests {
assert_eq!(number(&fixture.inputs(&migrated, rotations)[2]), Some(45.));
}
#[test]
fn the_default_name_is_cleared() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let star = fixture.add(STAR, star_inputs());
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: star, index: 0 }, 2., 90.));
let name = Value::Str("Copy to Points".to_string());
fixture.registry.node_instances.get_mut(&copies).unwrap().attributes_mut().set(DISPLAY_NAME, name, TimeStamp::ORIGIN);
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
assert!(migrated.node_instances[&copies].attributes().get_typed::<String>(DISPLAY_NAME).is_none());
}
/// Matches the layout the legacy migration gives a star copied at a scale of 2 with random rotations spanning 90°.
#[test]
fn stages_lead_up_to_a_placed_node_in_a_row() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let star = fixture.add(STAR, star_inputs());
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: star, index: 0 }, 2., 90.));
let position = to_value(&Position::Absolute([20, 10])).unwrap();
fixture.registry.node_instances.get_mut(&copies).unwrap().attributes_mut().set(POSITION, position, TimeStamp::ORIGIN);
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
let position_of = |node: NodeId| migrated.node_instances[&node].attributes().get_typed::<Position>(POSITION);
// Walk back from the anchor through each stage's points
let mut stages = Vec::new();
let mut stage = copies;
while let NodeInput::Node { id, .. } = fixture.inputs(&migrated, stage)[0]
&& id != star
{
stages.insert(0, position_of(id));
stage = id;
}
let NodeInput::Node { id: group, .. } = fixture.inputs(&migrated, stage)[1] else {
panic!("the repeat reads the group")
};
assert_eq!(stages, [-1, 6, 13].map(|x| Some(Position::Absolute([x, 10]))));
assert_eq!(position_of(group), Some(Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT])));
}
#[test]
fn bias_keeps_its_average() {
assert_eq!(bias_keeping_average_scale(0.), 0.5);
+2 -2
View File
@@ -29,7 +29,7 @@ pub use connector::{InputConnector, NewNode, OutputConnector};
#[cfg(feature = "typed")]
pub use declaration::{Declaration, DeclarationKind, DeclarationResolver};
#[cfg(feature = "typed")]
pub use document_graph_storage::NodeInput;
pub use document_graph_storage::{NodeInput, Position, attr};
pub use error::MigrationError;
pub use format::{DocumentPayloads, FormatMigration, HistoryPolicy, Upgrade};
#[cfg(feature = "typed")]
@@ -44,7 +44,7 @@ pub use registry::{register_migration, registered_migrations};
#[cfg(feature = "typed")]
pub use value::{encode, literal, literal_of};
#[cfg(feature = "typed")]
pub use view::{AddedNode, AnchorContext, Downstream, Edits, Graph, Inputs, InputsEdit, Node, Region, Target, Upstream, View, implements};
pub use view::{AddedNode, AnchorContext, AttributeWrite, Attributes, CHAIN_WIDTH, Downstream, Edits, FEEDER_ROW_HEIGHT, Graph, Inputs, InputsEdit, Node, Region, Target, Upstream, View, implements};
// For the registration `#[migration]`, `rename!`, and `format_migration!` generate
#[doc(hidden)]
+74 -2
View File
@@ -1,7 +1,14 @@
use crate::{Compiler, Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector};
use document_graph_storage::{Implementation, InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp};
use crate::{Compiler, Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector, encode};
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
use document_graph_storage::{Implementation, InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp, Value};
use serde::Serialize;
use std::ops::Deref;
/// How many grid cells the editor's layout steps left for each node of a layer's chain.
pub const CHAIN_WIDTH: i32 = 7;
/// How many grid cells apart the rows of nodes feeding a node from below are.
pub const FEEDER_ROW_HEIGHT: i32 = 3;
/// Which part of the registry around an anchor a view reads or edits. A migration's footprint is the union of its views' regions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Region(u8);
@@ -14,6 +21,8 @@ impl Region {
pub const DOWNSTREAM: Self = Self(1 << 3);
/// The anchor's whole network, as read through [`Graph`].
pub const NETWORK: Self = Self(1 << 4);
/// Attributes of the anchor and of the nodes the run adds, such as their positions and display names.
pub const ATTRIBUTES: Self = Self(1 << 5);
pub const fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
@@ -223,6 +232,8 @@ pub struct Edits {
pub connections: Vec<(OutputConnector, InputConnector)>,
/// The declaration this anchor switches to, when not the migration's target.
pub target: Option<Declaration>,
/// Attribute writes to the anchor and the nodes this run adds.
pub attributes: Vec<AttributeWrite>,
}
impl Edits {
@@ -234,6 +245,57 @@ impl Edits {
self.removed_nodes.extend(other.removed_nodes);
self.connections.extend(other.connections);
self.target = other.target.or(self.target);
self.attributes.extend(other.attributes);
}
}
/// One attribute of the anchor or of a node the run adds. A run's writes apply in the order it recorded them.
#[derive(Debug)]
pub struct AttributeWrite {
pub node: NodeId,
pub key: String,
/// `None` deletes the key.
pub value: Option<Value>,
}
/// Attributes of the anchor and of the nodes this run adds, such as where they sit and what they're named.
#[derive(Default)]
pub struct Attributes {
writes: Vec<AttributeWrite>,
}
impl Attributes {
/// Write `value` under `key` on the anchor or on a node this run adds.
pub fn set<T: Serialize>(&mut self, node: NodeId, key: &str, value: &T) {
self.writes.push(AttributeWrite {
node,
key: key.to_string(),
value: Some(encode(value)),
});
}
/// Delete `key` from the anchor or from a node this run adds.
pub fn remove(&mut self, node: NodeId, key: &str) {
self.writes.push(AttributeWrite {
node,
key: key.to_string(),
value: None,
});
}
}
impl<'a> View<'a> for Attributes {
const REGION: Region = Region::ATTRIBUTES;
fn extract(_context: &AnchorContext<'a>) -> Self {
Self::default()
}
fn into_edits(self) -> Result<Edits, MigrationError> {
Ok(Edits {
attributes: self.writes,
..Default::default()
})
}
}
@@ -329,6 +391,16 @@ impl Inputs {
self.origins.push(None);
}
/// Add a slot the compiler fills in with what `metadata` names, a frozen mirror value such as the node's path.
pub fn push_reflection<T: Serialize>(&mut self, metadata: T) {
let mut slot = new_slot(NodeInput::Reflection);
slot.attributes.set(REFLECTION_METADATA, encode(&metadata), TimeStamp::ORIGIN);
self.edited = true;
self.slots.push(slot);
self.origins.push(None);
}
pub fn remove(&mut self, index: u32) {
if !self.check(index, self.slots.len()) {
return;
+1 -1
View File
@@ -16,7 +16,7 @@ use syn::{Error, FnArg, Ident, ItemFn, ReturnType, Type, parse_macro_input};
/// A `network` prefix names a built-in network definition, as in `#[migration(network "Merge"@1 => "module::merge"@2)]`.
///
/// Parameters state what the migration reads and writes: `&Node` and `&Graph` read the source state, `Option<&dyn Compiler>` asks what only the
/// compiler can tell about it, and each `&mut` parameter is a view (`Inputs`, `Upstream`, `Downstream`, `Target`) recording edits to its region. The function may return `()` or `Result<(), MigrationError>`.
/// compiler can tell about it, and each `&mut` parameter is a view (`Inputs`, `Upstream`, `Downstream`, `Target`, `Attributes`) recording edits to its region. The function may return `()` or `Result<(), MigrationError>`.
///
/// Generates a unit struct named after the function in Pascal case implementing `NodeMigration`, and registers it.
#[proc_macro_attribute]
@@ -4,3 +4,5 @@ use migration_core::rename;
// Version 2 is where old Upload Texture nodes join the lineage, and stored Passthrough nodes already have its layout
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);
+1
View File
@@ -4,3 +4,4 @@
mod graphene_core;
mod math_nodes;
mod raster_nodes;
mod vector_nodes;
@@ -0,0 +1,4 @@
//! Migrations of the nodes in `vector_nodes`.
mod path_from_path_network;
mod renames;
@@ -0,0 +1,49 @@
use migration_core::{Inputs, migration};
use serde::Serialize;
/// Frozen mirror of the `DocumentNodeMetadata` variant this migration uses.
#[derive(Serialize)]
enum Reflected {
DocumentNodePath,
}
/// The Path subgraph became the node it held, which takes the instance's inputs and is given its own path as that node was.
#[migration(network "Path"@1 => "vector_nodes::vector_modification_nodes::PathNode"@2)]
pub fn path_from_path_network(inputs: &mut Inputs) {
inputs.push_reflection(Reflected::DocumentNodePath);
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::NodeInput;
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PathFromPathNetwork, &contract());
check_undo(&PathFromPathNetwork, &contract());
}
#[test]
fn collapses_into_the_node_and_gives_it_its_path() {
let (content, modification) = (literal(1.), literal(2.));
let mut fixture = Fixture::new(&PathFromPathNetwork);
let (path, network) = fixture.add_network(decl!(network "Path"@1), vec![content.clone(), modification.clone()]);
let migrated = fixture.migrate(&PathFromPathNetwork).unwrap();
assert_eq!(fixture.declaration_of(&migrated, path), Some(decl!("vector_nodes::vector_modification_nodes::PathNode"@2)));
assert!(!migrated.networks.contains_key(&network));
assert_eq!(fixture.inputs(&migrated, path), [content, modification, NodeInput::Reflection]);
let own_path = &migrated.node_instances[&path].inputs()[2];
assert_eq!(own_path.attributes.get_typed::<String>(REFLECTION_METADATA).as_deref(), Some("DocumentNodePath"));
}
}
@@ -0,0 +1,5 @@
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
use migration_core::rename;
rename!("vector_nodes::vector_modification_nodes::PathModifyNode"@1 => "vector_nodes::vector_modification_nodes::PathNode"@2);
+2
View File
@@ -40,6 +40,8 @@ pub enum RunnerError {
DuplicateAddedNode { anchor: NodeId, declaration: Declaration, key: String },
#[error("added node {0:?} already exists")]
AddedNodeExists(NodeId),
#[error("node {anchor:?} writes attributes of {node:?}, which is neither it nor a node it adds")]
AttributesOutsideRegion { anchor: NodeId, node: NodeId },
#[error("{0:?} is rewired by one anchor while its own migration replaces or removes it")]
ConflictingSlot(InputConnector),
#[error("{0:?} does not exist in the migrated state")]
+97 -3
View File
@@ -2,10 +2,12 @@
use crate::{MigrationBlobs, RunnerError};
use document_graph_storage::TimeStamp;
use document_graph_storage::attributes::attr::node::ui::REFERENCE;
use document_graph_storage::attributes::attr::node::ui::{IS_LAYER, POSITION, REFERENCE};
use document_graph_storage::delta::compute_deltas;
use document_graph_storage::{Delta, Implementation, NetworkId, Node, NodeId, NodeInput, ProtoNode, Registry, RegistryDelta, ResourceHash, ResourceId, Rev, apply_retired_op};
use migration_core::{AnchorContext, Compiler, Declaration, DeclarationResolver, Edits, InputConnector, InputsEdit, MigrationHost, NodeMigration, OutputConnector, implements};
use document_graph_storage::{Delta, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, Registry, RegistryDelta, ResourceHash, ResourceId, Rev, apply_retired_op};
use migration_core::{
AnchorContext, CHAIN_WIDTH, Compiler, Declaration, DeclarationResolver, Edits, FEEDER_ROW_HEIGHT, InputConnector, InputsEdit, MigrationHost, NodeMigration, OutputConnector, encode, implements,
};
use std::collections::{HashMap, HashSet};
/// A [`DeclarationResolver`] over a fixed set of declarations for tests, whose resource IDs derive from `identifier@version` rather than the encoded declarations documents store.
@@ -173,6 +175,10 @@ fn apply_runs(migration: &dyn NodeMigration, source: &Registry, anchors: &[NodeI
}
add_nodes(&mut target, &runs, resolver)?;
for (anchor, edits) in &runs {
place_added_nodes(&mut target, *anchor, edits);
write_attributes(&mut target, *anchor, edits)?;
}
let input_edits: HashMap<NodeId, &InputsEdit> = runs.iter().filter_map(|(anchor, edits)| Some((*anchor, edits.inputs.as_ref()?))).collect();
for (anchor, inputs) in &input_edits {
@@ -328,6 +334,94 @@ fn add_nodes(target: &mut Registry, runs: &[(NodeId, Edits)], resolver: &dyn Dec
Ok(())
}
/// Default positions for the nodes one run adds, read from the anchor's own position only. The nodes leading up to the anchor's
/// chain input form a row, or join the chain of a chained or layer anchor. Each other node sits relative to the nodes reading it,
/// below the first one of this run that does, or on the anchor when nothing reads it.
fn place_added_nodes(target: &mut Registry, anchor: NodeId, edits: &Edits) {
let Some(anchor_node) = target.node_instances.get(&anchor) else { return };
let stored = anchor_node.attributes().get_typed::<Position>(POSITION);
let is_layer = anchor_node.attributes().get_or(IS_LAYER, false);
let anchor_inputs: Vec<NodeInput> = match &edits.inputs {
Some(inputs) => inputs.slots.iter().map(|slot| slot.input.clone()).collect(),
None => anchor_node.inputs().iter().map(|slot| slot.input.clone()).collect(),
};
let added_inputs: HashMap<NodeId, &[NodeInput]> = edits.added_nodes.iter().map(|added| (added.id, added.node.inputs.as_slice())).collect();
let reads = |inputs: &[NodeInput], node: NodeId| inputs.iter().any(|input| matches!(input, NodeInput::Node { id, .. } if *id == node));
let chain_input = if is_layer { 1 } else { 0 };
let mut chain = Vec::new();
let mut next = anchor_inputs.get(chain_input);
while let Some(NodeInput::Node { id, .. }) = next
&& let Some(inputs) = added_inputs.get(id)
&& !chain.contains(id)
{
chain.push(*id);
next = inputs.first();
}
let joins_chain = is_layer || stored == Some(Position::Chain);
let coordinates = match stored {
Some(Position::Absolute(coordinates)) => Some(coordinates),
_ => None,
};
let mut positions = Vec::new();
for (step, id) in chain.iter().enumerate() {
match coordinates {
_ if joins_chain => positions.push((*id, Position::Chain)),
Some([x, y]) => positions.push((*id, Position::Absolute([x - CHAIN_WIDTH * (step as i32 + 1), y]))),
None => {}
}
}
let readers: Vec<(NodeId, &[NodeInput])> = std::iter::once((anchor, anchor_inputs.as_slice()))
.chain(edits.added_nodes.iter().map(|added| (added.id, added.node.inputs.as_slice())))
.collect();
let mut feeders_below: HashMap<NodeId, i32> = HashMap::new();
for added in edits.added_nodes.iter().filter(|added| !chain.contains(&added.id)) {
let reader = readers.iter().find(|(_, inputs)| reads(inputs, added.id)).map(|(reader, _)| *reader);
let connected_downstream = edits.connections.iter().any(|(output, _)| output.node == added.id);
let position = match (reader, coordinates) {
(Some(reader), _) => {
let row = feeders_below.entry(reader).or_default();
*row += 1;
Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT * *row])
}
_ if connected_downstream => Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT]),
(None, Some(coordinates)) => Position::Absolute(coordinates),
(None, None) => continue,
};
positions.push((added.id, position));
}
for (id, position) in positions {
if let Some(node) = target.node_instances.get_mut(&id) {
node.attributes_mut().set(POSITION, encode(&position), TimeStamp::ORIGIN);
}
}
}
/// Apply one run's attribute writes, which may only name its anchor and the nodes it adds.
fn write_attributes(target: &mut Registry, anchor: NodeId, edits: &Edits) -> Result<(), RunnerError> {
for write in &edits.attributes {
let in_region = write.node == anchor || edits.added_nodes.iter().any(|added| added.id == write.node);
let node = target.node_instances.get_mut(&write.node).filter(|_| in_region);
let node = node.ok_or(RunnerError::AttributesOutsideRegion { anchor, node: write.node })?;
match &write.value {
Some(value) => node.attributes_mut().set(&write.key, value.clone(), TimeStamp::ORIGIN),
None => {
node.attributes_mut().remove(&write.key);
}
}
}
Ok(())
}
/// Make `consumer`, named in the source layout, read `output` in the target layout. Fails when the consumer's own migration replaced or
/// removed that slot, since two runs then disagree on what it should read.
fn connect(target: &mut Registry, output: OutputConnector, consumer: InputConnector, input_edits: &HashMap<NodeId, &InputsEdit>) -> Result<(), RunnerError> {
+39 -3
View File
@@ -3,9 +3,10 @@
use crate::node::{apply_migration, needs_whole_states, rewrite_history};
use crate::{DeclarationTable, MigrationBlobs, RunnerError, references, registry_at};
use document_graph_storage::attributes::attr::node::ui::REFERENCE;
use document_graph_storage::attributes::attr::node::ui::{DISPLAY_NAME, IS_LAYER, POSITION, REFERENCE};
use document_graph_storage::{
Delta, ExportSlot, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Session, TimeStamp, UserId, apply_retired_op,
AttributeDelta, Delta, ExportSlot, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Position, ROOT_NETWORK, Registry, RegistryDelta, Session, TimeStamp, UserId, Value,
apply_retired_op, to_value,
};
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration, decl, implements, literal, registered_migrations};
use std::collections::HashSet;
@@ -138,6 +139,8 @@ pub struct SourceContract {
pub literal: fn(&mut Random, usize) -> NodeInput,
/// Whether a slot may read an output of another node of the source declaration.
pub reads_own_output: fn(usize) -> bool,
/// Display names, besides a custom one, that generated histories give nodes, such as a default the migration clears.
pub display_names: &'static [&'static str],
}
impl SourceContract {
@@ -146,6 +149,7 @@ impl SourceContract {
input_count,
literal,
reads_own_output: |_| true,
display_names: &[],
}
}
}
@@ -276,11 +280,38 @@ impl Generator<'_> {
self.commit_interaction(ops);
}
/// A name, position, or layer flag, written or deleted.
fn attribute(&mut self) -> AttributeDelta {
let (key, value) = match self.random.below(3) {
0 => {
let names = self.contract.display_names;
let name = match self.random.below(names.len() + 2) {
index if index < names.len() => Some(names[index]),
index if index == names.len() => Some("Renamed"),
_ => None,
};
(DISPLAY_NAME, name.map(|name| Value::Str(name.to_string())))
}
1 => {
let coordinates = [self.random.below(20) as i32, self.random.below(20) as i32];
let position = match self.random.below(4) {
0 => Position::Chain,
1 => Position::Relative(coordinates),
_ => Position::Absolute(coordinates),
};
(POSITION, Some(to_value(&position).expect("positions serialize")))
}
_ => (IS_LAYER, (self.random.below(2) == 0).then_some(Value::Bool(true))),
};
AttributeDelta { key: key.to_string(), value }
}
fn step(&mut self) {
let nodes = self.live_nodes();
let root_nodes = self.live_nodes_in(ROOT_NETWORK);
match self.random.below(11) {
match self.random.below(13) {
0..=3 => {
let (declaration, input_count) = if self.random.below(3) == 0 {
(self.source, self.contract.input_count)
@@ -335,6 +366,11 @@ impl Generator<'_> {
self.session.undo().expect("an interaction is left to undo");
self.undoable -= 1;
}
11 | 12 if !nodes.is_empty() => {
let id = self.random.pick(&nodes);
let delta = self.attribute();
self.commit(RegistryDelta::ChangeNodeAttribute { id, delta });
}
_ => {}
}
}
@@ -0,0 +1,137 @@
//! Attribute writes on the anchor and the nodes it adds, and the positions added nodes get by default.
use document_graph_storage::attr::node::ui::{DISPLAY_NAME, POSITION};
use document_graph_storage::{NodeId, NodeInput, Position, Value, to_value};
use migration_core::{Attributes, CHAIN_WIDTH, Downstream, FEEDER_ROW_HEIGHT, Inputs, NewNode, Node, Upstream, decl, migration};
use migration_runner::RunnerError;
use migration_runner::testing::Fixture;
/// Clears the anchor's old default name and places a node it adds.
#[migration("attributes::renamed"@1 => @2)]
pub fn renamed(node: &Node, downstream: &mut Downstream, attributes: &mut Attributes) {
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Old name") {
attributes.remove(node.id(), DISPLAY_NAME);
}
let added = downstream.add_node(NewNode {
declaration: decl!("math_nodes::add"@1),
inputs: vec![],
});
attributes.set(added, POSITION, &Position::Absolute([3, 4]));
}
/// Renames the node its first input reads, which it neither is nor adds.
#[migration("attributes::outside"@1 => @2)]
pub fn outside(node: &Node, attributes: &mut Attributes) {
if let Some(NodeInput::Node { id, .. }) = node.inputs().first().map(|slot| &slot.input) {
attributes.set(*id, DISPLAY_NAME, &"Renamed");
}
}
/// Adds two nodes leading up to the anchor's first input, and one feeding the nearer of them from below.
#[migration("attributes::placed"@1 => @2)]
pub fn placed(node: &Node, inputs: &mut Inputs, upstream: &mut Upstream) {
let add = decl!("math_nodes::add"@1);
let source = node.inputs().first().map_or(NodeInput::Import { index: 0 }, |slot| slot.input.clone());
let far = upstream.add_node_keyed(
NewNode {
declaration: add,
inputs: vec![source],
},
"far",
);
let below = upstream.add_node_keyed(NewNode { declaration: add, inputs: vec![] }, "below");
let near = upstream.add_node_keyed(
NewNode {
declaration: add,
inputs: vec![wire(far), wire(below)],
},
"near",
);
inputs.set(0, wire(near));
}
fn set_name(fixture: &mut Fixture, node: NodeId, name: &str) {
let name = Value::Str(name.to_string());
fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut().set(DISPLAY_NAME, name, Default::default());
}
/// The positions of the far, near, and below nodes `Placed` adds for an anchor stored at `position`.
fn placed_around(position: Position) -> [Option<Position>; 3] {
let migration = &Placed;
let mut fixture = Fixture::new(migration);
let anchor = fixture.add(decl!("attributes::placed"@1), vec![NodeInput::Import { index: 0 }]);
let position = to_value(&position).unwrap();
fixture.registry.node_instances.get_mut(&anchor).unwrap().attributes_mut().set(POSITION, position, Default::default());
let migrated = fixture.migrate(migration).unwrap();
let position_of = |id: NodeId| migrated.node_instances[&id].attributes().get_typed::<Position>(POSITION);
let NodeInput::Node { id: near, .. } = fixture.inputs(&migrated, anchor)[0] else {
panic!("the anchor reads the near node")
};
let [NodeInput::Node { id: far, .. }, NodeInput::Node { id: below, .. }] = fixture.inputs(&migrated, near)[..] else {
panic!("the near node reads the far and below nodes")
};
[position_of(far), position_of(near), position_of(below)]
}
fn wire(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
#[test]
fn a_run_writes_its_anchor_and_the_nodes_it_adds() {
let migration = &Renamed;
let mut fixture = Fixture::new(migration);
let anchor = fixture.add(decl!("attributes::renamed"@1), vec![]);
set_name(&mut fixture, anchor, "Old name");
fixture.export(wire(anchor));
let migrated = fixture.migrate(migration).unwrap();
assert!(migrated.node_instances[&anchor].attributes().get(DISPLAY_NAME).is_none());
let added = migrated.node_instances.iter().find(|(id, _)| **id != anchor).map(|(_, node)| node).expect("the run adds a node");
assert_eq!(added.attributes().get_typed::<Position>(POSITION), Some(Position::Absolute([3, 4])));
}
#[test]
fn a_name_given_by_the_user_is_kept() {
let migration = &Renamed;
let mut fixture = Fixture::new(migration);
let anchor = fixture.add(decl!("attributes::renamed"@1), vec![]);
set_name(&mut fixture, anchor, "Mine");
let migrated = fixture.migrate(migration).unwrap();
assert_eq!(migrated.node_instances[&anchor].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), Some("Mine"));
}
#[test]
fn added_nodes_lead_up_to_a_placed_anchor() {
let [far, near, below] = placed_around(Position::Absolute([20, 10]));
assert_eq!(far, Some(Position::Absolute([20 - 2 * CHAIN_WIDTH, 10])));
assert_eq!(near, Some(Position::Absolute([20 - CHAIN_WIDTH, 10])));
assert_eq!(below, Some(Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT])));
}
#[test]
fn added_nodes_join_a_chained_anchors_chain() {
let [far, near, below] = placed_around(Position::Chain);
assert_eq!([far, near], [Some(Position::Chain); 2]);
assert_eq!(below, Some(Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT])));
}
#[test]
fn writing_another_nodes_attributes_fails() {
let migration = &Outside;
let mut fixture = Fixture::new(migration);
let other = fixture.add(decl!("math_nodes::add"@1), vec![]);
fixture.add(decl!("attributes::outside"@1), vec![wire(other)]);
let error = fixture.migrate(migration).unwrap_err();
assert!(matches!(error, RunnerError::AttributesOutsideRegion { node, .. } if node == other), "{error}");
}
@@ -33,6 +33,18 @@ pub fn opacity_toggles(inputs: &mut Inputs) {
inputs.push(literal(Tagged::Number(100.)));
}
/// Frozen mirror of the `DocumentNodeMetadata` variant the migration below uses.
#[derive(Serialize)]
pub enum Reflected {
DocumentNodePath,
}
/// Gives the node its own path.
#[migration("vector_nodes::bounding_box"@1 => @2)]
pub fn bounding_box_own_path(inputs: &mut Inputs) {
inputs.push_reflection(Reflected::DocumentNodePath);
}
pub const ROTATION: u32 = 2;
/// Rotation is now stored in degrees.
@@ -1,3 +1,4 @@
mod attributes;
mod blobs;
mod compiler;
mod examples;
@@ -5,8 +6,9 @@ mod networks;
mod registration;
mod rewrite;
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
use document_graph_storage::{NodeId, NodeInput, ROOT_NETWORK, Registry};
use examples::{AngleBetweenDegrees, Axis, ExtractXyToSplit, OpacityToggles, ROTATION, Tagged, TransformDegrees};
use examples::{AngleBetweenDegrees, Axis, BoundingBoxOwnPath, ExtractXyToSplit, OpacityToggles, ROTATION, Tagged, TransformDegrees};
use migration_core::{decl, literal, literal_of};
use migration_runner::RunnerError;
use migration_runner::testing::{Fixture, registered};
@@ -57,6 +59,19 @@ fn opacity_toggles_build_the_target_layout() {
assert_eq!(fixture.declaration_of(&migrated, opacity), Some(decl!("blending_nodes::opacity"@2)));
}
#[test]
fn reflection_input_stores_what_it_reflects() {
let mut fixture = Fixture::new(&BoundingBoxOwnPath);
let bounding_box = fixture.add(decl!("vector_nodes::bounding_box"@1), vec![literal(Tagged::Number(1.))]);
let migrated = fixture.migrate(&BoundingBoxOwnPath).unwrap();
let slots = migrated.node_instances[&bounding_box].inputs();
assert_eq!(slots.len(), 2);
assert_eq!(slots[1].input, NodeInput::Reflection);
assert_eq!(slots[1].attributes.get_typed::<String>(REFLECTION_METADATA).as_deref(), Some("DocumentNodePath"));
}
#[test]
fn transform_converts_a_literal_rotation() {
let mut fixture = Fixture::new(&TransformDegrees);
@@ -13,6 +13,9 @@ fn every_migration_registers_once() {
sources.sort();
let mut expected = vec![
decl!("attributes::outside"@1),
decl!("attributes::placed"@1),
decl!("attributes::renamed"@1),
decl!("blending_nodes::opacity"@1),
decl!("blob_nodes::text"@1),
decl!("compiler::anchor"@1),
@@ -30,6 +33,7 @@ fn every_migration_registers_once() {
decl!("order::static_late"@1),
decl!("transform_nodes::transform"@1),
decl!("vector_nodes::angle_between"@1),
decl!("vector_nodes::bounding_box"@1),
decl!("vector_nodes::extract_xy"@1),
decl!("vector_nodes::split_vec2"@2),
];
@@ -1,6 +1,6 @@
//! The history properties of `migration_runner::testing` on the examples.
use crate::examples::{AngleBetweenDegrees, Axis, ExtractXyToSplit, OpacityToggles, Tagged, TransformDegrees};
use crate::examples::{AngleBetweenDegrees, Axis, BoundingBoxOwnPath, ExtractXyToSplit, OpacityToggles, Tagged, TransformDegrees};
use migration_core::{decl, literal};
use migration_runner::testing::{Random, SourceContract, check_commutation, check_undo, registered};
@@ -18,6 +18,11 @@ fn opacity_toggles_commute() {
check_commutation(&OpacityToggles, &numbers(2));
}
#[test]
fn bounding_box_own_path_commutes() {
check_commutation(&BoundingBoxOwnPath, &numbers(1));
}
#[test]
fn transform_degrees_commutes() {
check_commutation(&TransformDegrees, &numbers(3));
+1 -1
View File
@@ -168,7 +168,7 @@ fn write_step(migrations: &Path, node: &NodeSource, name: &str, step: &str, from
/// Describe what changed from version {from}.\n\
#[migration({step})]\n\
pub fn {name}(inputs: &mut Inputs) {{\n\
\tcompile_error!(\"Migrate from version {from} here. Read the source state with `&Node` or `&Graph`, and edit it through `&mut Inputs`, `&mut Upstream`, or `&mut Downstream`\");\n\
\tcompile_error!(\"Migrate from version {from} here. Read the source state with `&Node` or `&Graph`, and edit it through `&mut Inputs`, `&mut Upstream`, `&mut Downstream`, or `&mut Attributes`\");\n\
}}\n\n\
#[cfg(test)]\n\
mod tests {{\n\
@@ -1,7 +1,7 @@
use crate::consts::DEFAULT_STROKE_WIDTH;
use crate::messages::portfolio::document::SelectionParts;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface;
use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes;
@@ -429,7 +429,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
let mut layers = Vec::new();
for (_, new_vector, transform) in paths {
let Some(node_type) = resolve_network_node_type("Path") else {
let Some(node_type) = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER) else {
error!("Path node does not exist");
continue;
};
@@ -618,7 +618,7 @@ impl<T: TableItemLayout> TableItemLayout for Item<T> {
}
}
let attribute_keys: Vec<String> = self.attributes().keys().map(str::to_string).collect();
let attribute_keys: Vec<String> = self.attributes().keys().filter(|key| !key.starts_with(INTERNAL_ATTRIBUTE_PREFIX)).map(str::to_string).collect();
// A single element, so no leading ID column, unlike the `List` table
let saved_gradient_settings = data.gradient_settings;
@@ -262,9 +262,6 @@ fn diff_document_node(out: &mut String, expected: &graph_craft::document::Docume
if expected.visible != actual.visible {
let _ = writeln!(out, " visible: expected={} actual={}", expected.visible, actual.visible);
}
if expected.skip_deduplication != actual.skip_deduplication {
let _ = writeln!(out, " skip_deduplication: expected={} actual={}", expected.skip_deduplication, actual.skip_deduplication);
}
if expected.compile_metadata != actual.compile_metadata {
let _ = writeln!(out, " compile_metadata: expected={:?} actual={:?}", expected.compile_metadata, actual.compile_metadata);
}
@@ -2232,6 +2232,7 @@ impl DocumentMessageHandler {
self.network_interface.validate_input_metadata(node_id, node, &path);
self.network_interface.validate_output_names(node_id, node, &path);
}
self.network_interface.convert_positions_to_relative();
// Restoring the parallel-array invariant is how the document arrives, not an edit to it, so what the
// fix-ups recorded must not ride along in the first real commit. They still have to reach storage,
@@ -4894,7 +4895,7 @@ mod document_message_handler_tests {
}
// Merging nodes whose output isn't wired downstream produces an encapsulating subnetwork with no exports.
// Inspecting it via the Data panel (which splices in a monitor node) must not leave a dangling reference that crashes compilation.
// Inspecting it via the Data panel must not leave a dangling reference that crashes compilation.
#[tokio::test]
async fn merge_selected_nodes_while_inspecting_does_not_crash() {
let mut editor = EditorTestUtils::create();
@@ -4909,7 +4910,7 @@ mod document_message_handler_tests {
let merged = editor.active_document().network_interface.selected_nodes_in_nested_network(&[]).unwrap().0.clone();
assert_eq!(merged.len(), 1, "merge should leave one encapsulating node selected");
// Simulate the Data panel inspecting the merged node, which compiles the graph with a monitor node spliced in
// Simulate the Data panel inspecting the merged node
let portfolio = &mut editor.editor.dispatcher.message_handlers.portfolio_message_handler;
let document_id = portfolio.active_document_id.unwrap();
let document = portfolio.documents.get_mut(&document_id).unwrap();
@@ -957,10 +957,10 @@ fn set_import_child_positions(
// Top of stack: set to `Absolute` position
network_interface.set_layer_position_for_import(&child_layer.to_node(), LayerPosition::Absolute(child_pos), &[]);
} else {
// Below top: set `Stack` with `y_offset` based on previous sibling's subtree extent
// Below top: stack it `y_offset` below its previous sibling, based on that sibling's subtree extent
let prev_sibling_svg_index = n - i;
let y_offset = child_extents_svg_order[prev_sibling_svg_index] + STACK_VERTICAL_GAP as u32;
network_interface.set_layer_position_for_import(&child_layer.to_node(), LayerPosition::Stack(y_offset), &[]);
network_interface.set_layer_position_for_import(&child_layer.to_node(), LayerPosition::stacked(y_offset), &[]);
}
// Recurse into group children to set their descendants' positions
@@ -137,7 +137,9 @@ impl<'a> ModifyInputsContext<'a> {
self.network_interface.move_node_to_chain_start(&smooth_anchors_id, layer, &[], self.import);
// Add Path node to chain start (closest to the Merge node)
let path = resolve_network_node_type("Path").expect("Path node does not exist").default_node_template();
let path = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER)
.expect("Path node does not exist")
.default_node_template();
let path_id = NodeId::new();
self.network_interface.insert_node(path_id, path, &[]);
self.network_interface.move_node_to_chain_start(&path_id, layer, &[], self.import);
@@ -150,7 +152,7 @@ impl<'a> ModifyInputsContext<'a> {
let (vector, paths) = Vector::from_bezpath(&bezpath);
let modification = Box::new(VectorModification::create_from_vector(&vector, &paths));
let shape = resolve_network_node_type("Path")
let shape = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER)
.expect("Path node does not exist")
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::VectorModification(modification), false))]);
let shape_id = NodeId::new();
@@ -410,7 +412,7 @@ impl<'a> ModifyInputsContext<'a> {
// If inserting a 'Path' node, insert a 'Combine Paths' node if the type is `Graphic`.
// TODO: Allow the 'Path' node to operate on `List` data by utilizing the reference (index or ID?) for each item.
if node_definition.identifier == "Path" {
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER) {
let layer_input_type = self.network_interface.input_type(&InputConnector::layer_secondary_input(output_layer.to_node()), &[]);
if layer_input_type.compiled_element_name().as_deref() == Some("Graphic") {
let Some(combine_paths_definition) = resolve_proto_node_type(graphene_std::vector_nodes::combine_paths::IDENTIFIER) else {
@@ -994,7 +996,7 @@ impl<'a> ModifyInputsContext<'a> {
}
pub fn vector_modify(&mut self, modification_type: VectorModificationType) {
let Some(path_node_id) = self.existing_network_node_id("Path", true) else {
let Some(path_node_id) = self.existing_proto_node_id(graphene_std::vector::path::IDENTIFIER, true) else {
return;
};
self.network_interface.vector_modify(&path_node_id, modification_type);
@@ -1108,7 +1110,7 @@ pub fn set_stroke_paint_order(network_interface: &mut NodeNetworkInterface, netw
if *was_chain {
network_interface.set_chain_position(&node_id, network_path);
} else if let Some(position) = position {
network_interface.set_absolute_position(&node_id, *position, network_path);
network_interface.place_at(&node_id, *position, network_path);
}
}
@@ -769,56 +769,6 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Path",
version: 1,
category: "Vector: Geometry",
icon: Some("NodePath"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 0)],
implementation: NodeTemplateImplementation::ProtoNode(memo::monitor::IDENTIFIER),
call_argument: generic!(T),
skip_deduplication: true,
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
NodeTemplate {
inputs: vec![
NodeInput::node(NodeId(0), 0),
NodeInput::import(concrete!(graphene_std::vector::VectorModification), 1),
NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath),
],
call_argument: generic!(T),
implementation: NodeTemplateImplementation::ProtoNode(vector::path_modify::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![
NodeInput::type_default(item!(Vector), true),
NodeInput::value(TaggedValue::VectorModification(Default::default()), false),
],
input_metadata: vec![
("Content", "The original shape that edits made with the Pen and Path tools are applied to.").into(),
("Modification", "The edits made with the Pen and Path tools, stored as changes to points and segments.").into(),
],
output_names: vec!["Modified".to_string()],
output_descriptions: vec!["The shape with the Pen and Path tool edits applied.".to_string()],
..Default::default()
},
description: Cow::Borrowed("Holds the edits made with the Pen and Path tools, applying them to the incoming shape."),
inspector: None,
},
];
document_node_derive::post_process_nodes(custom)
@@ -852,10 +802,6 @@ fn static_node_inspector() -> NodeInspector {
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
map.insert("sample_polyline_inspector".to_string(), Box::new(node_inspector::sample_polyline_inspector));
map.insert(
"monitor_inspector".to_string(),
Box::new(|_node_id, _context| node_inspector::string_inspector("Used internally by the editor to read the data passing through it.")),
);
map
}
@@ -23,7 +23,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
// Add the rest of the protonodes from the macro.
// Typed nodes are registered in `core_types::NODE_REGISTRY` via the macro's auto-generated `register_node` codegen.
// `skip_impl` nodes (e.g. Cache, Monitor) bypass that registration but are wired up manually in
// `skip_impl` nodes (e.g. Cache) bypass that registration but are wired up manually in
// `interpreted_executor::node_registry::NODE_REGISTRY` via `async_node!`. We consult that extended registry as a
// fallback when deriving `call_argument` so it reflects the impls actually registered, which will usually be `Context`.
let extended_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
@@ -89,6 +89,8 @@ pub struct NodeGraphMessageHandler {
pub selection_before_pointer_down: Vec<NodeId>,
/// If the grip icon is held during a drag, then shift without pushing other nodes
shift_without_push: bool,
/// Whether dragging leaves the relative nodes upstream of the dragged ones where they are drawn.
keep_upstream_in_place: bool,
disconnecting: Option<InputConnector>,
initial_disconnecting: bool,
/// Node to select on pointer up if multiple nodes are selected and they were not dragged.
@@ -183,7 +185,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
NodeGraphMessage::AddPathNode => {
if let Some(layer) = make_path_editable_is_allowed(network_interface) {
responses.add(NodeGraphMessage::CreateNodeInLayerWithTransaction {
node_type: DefinitionIdentifier::Network("Path".into()),
node_type: DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER),
layer,
});
responses.add(EventMessage::SelectionChanged);
@@ -1437,6 +1439,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
}
self.keep_upstream_in_place = ipp.keyboard.get(Key::Control as usize);
let mut graph_delta = IVec2::new(((point.x - drag_start.start_x) / 24.).round() as i32, ((point.y - drag_start.start_y) / 24.).round() as i32);
let previous_round_x = drag_start.round_x;
let previous_round_y = drag_start.round_y;
@@ -1622,6 +1626,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// End of dragging a node
else if let Some((drag_start, _)) = &self.drag_start {
self.shift_without_push = false;
self.keep_upstream_in_place = false;
// Reset all offsets to end the rubber banding while dragging
network_interface.clear_drag_offsets(selection_network_path);
@@ -2165,7 +2170,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// The shift can also push other nodes and the imports and exports, so everything it moves glides to where it lands
let positions_before = (glide && graph_view_overlay_open).then(|| Self::glide_positions(network_interface, selection_network_path));
network_interface.shift_selected_nodes(direction, self.shift_without_push, selection_network_path);
network_interface.shift_selected_nodes(direction, self.shift_without_push, self.keep_upstream_in_place, selection_network_path);
if !rubber_band {
network_interface.clear_drag_offsets(selection_network_path);
@@ -4076,6 +4081,7 @@ impl Default for NodeGraphMessageHandler {
double_click_used_by_press: false,
dot_drag_out: None,
shift_without_push: false,
keep_upstream_in_place: false,
box_selection_start: None,
drag_start_chain_nodes: Vec::new(),
wire_insertion_preview: None,
@@ -3143,8 +3143,8 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
} else {
let number_of_inputs = context.network_interface.number_of_inputs(&node_id, context.selection_network_path);
for input_index in 1..number_of_inputs {
// Hide inputs that are connected to a scope
if let Some(NodeInput::Scope(_)) = context
// Hide inputs that are connected to a scope or filled in by the compiler
if let Some(NodeInput::Scope(_) | NodeInput::Reflection(_)) = context
.network_interface
.input_from_connector(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
{
@@ -6,5 +6,6 @@
mod lifecycle_tests;
mod metadata_tests;
mod relative_positions_tests;
mod round_trip_tests;
pub(crate) mod test_support;
@@ -0,0 +1,87 @@
//! Opening a document converts its absolute and stacked positions to positions relative to the nodes reading them, without moving any node.
use super::test_support::{node_paths, open_demo};
use crate::messages::portfolio::document::utility_types::network_interface::{LayerPersistentMetadata, LayerPosition, NodeLocator, NodeNetworkInterface, NodeTypePersistentMetadata};
use glam::IVec2;
use graphene_std::uuid::NodeId;
const DEMOS: [&str; 8] = [
"changing-seasons.graphite",
"isometric-fountain.graphite",
"marbled-mandelbrot.graphite",
"painted-dreams.graphite",
"parametric-dunescape.graphite",
"procedural-string-lights.graphite",
"red-dress.graphite",
"valley-of-spires.graphite",
];
/// Each node in an editable network, by its network path and ID, with where it is drawn.
type DrawnPositions = Vec<((Vec<NodeId>, NodeId), Option<IVec2>)>;
fn editable_positions(interface: &NodeNetworkInterface) -> DrawnPositions {
node_paths(interface)
.into_iter()
.filter(|(network_path, _)| !interface.is_read_only(network_path))
.map(|(network_path, node_id)| {
let position = interface.position(&node_id, &network_path);
((network_path, node_id), position)
})
.collect()
}
/// Rewrites the converted positions the way older documents stored them, stacked layers as `Stack` and the rest as `Absolute`.
fn revert_to_stored_positions(interface: &mut NodeNetworkInterface, positions: &DrawnPositions) {
for ((network_path, node_id), position) in positions {
if !interface.is_relative(node_id, network_path) {
continue;
}
let stack_offset = interface.stack_offset(node_id, network_path);
let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) else { continue };
match (stack_offset, position) {
(Some(stack_offset), _) => {
node.set_node_type(NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Stack(stack_offset as u32),
}));
}
(None, Some(position)) => {
node.set_absolute_position(*position);
}
(None, None) => {}
}
interface.invalidate_position(node_id, network_path);
}
}
#[test]
fn opening_a_demo_makes_every_read_node_relative_where_it_was_drawn() {
for demo in DEMOS {
let mut document = open_demo(demo);
let interface = &mut document.network_interface;
let converted = editable_positions(interface);
assert!(converted.iter().all(|(_, position)| position.is_some()), "{demo}: every node should resolve a position");
for ((network_path, node_id), _) in &converted {
let read_by_a_node = interface
.with_outward_wires(network_path, |outward_wires| {
outward_wires
.iter()
.any(|(output, readers)| output.node_id() == Some(*node_id) && readers.iter().any(|reader| reader.node_id().is_some()))
})
.unwrap_or_default();
assert!(
!read_by_a_node || !interface.is_absolute(node_id, network_path),
"{demo}: node {node_id} is read by another node, so it should be relative"
);
}
revert_to_stored_positions(interface, &converted);
interface.convert_positions_to_relative();
let reconverted = editable_positions(interface);
let moved: Vec<_> = converted.iter().zip(&reconverted).filter(|(before, after)| before != after).collect();
assert!(moved.is_empty(), "{demo}: converting should leave every node where it was drawn, but moved {moved:?}");
}
}
@@ -872,7 +872,7 @@ async fn demo_artwork_vector_modifications_still_apply() {
let document = editor.active_document();
let network = &document.network_interface;
let path_definition = DefinitionIdentifier::Network("Path".into());
let path_definition = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER);
let mut path_layers = 0;
let mut any_curve = false;
@@ -131,7 +131,7 @@ impl DocumentMetadata {
let mut use_local = true;
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, network_interface);
let identifier = DefinitionIdentifier::Network("Path".into());
let identifier = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER);
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&identifier)
&& let Some(&source) = self.first_element_source_ids.get(&layer.to_node())
&& !network_interface
@@ -141,7 +141,7 @@ impl NodeNetworkInterface {
for layer in &selected_layers {
let mut current_node = *layer;
loop {
if self.is_layer(&current_node, network_path) && self.is_absolute(&current_node, network_path) {
if self.is_layer(&current_node, network_path) && !self.is_stack(&current_node, network_path) {
stack_tops.insert(current_node);
break;
};
@@ -1,6 +1,6 @@
use super::{
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata,
OutputConnector, Previewing, RootNode, TransactionStatus,
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition, NodeTemplate,
NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
};
use crate::consts::{GRID_SIZE, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
@@ -278,7 +278,7 @@ async fn a_dot_on_a_stack_wire_leaves_the_layer_beneath_it_where_it_was() {
let network_interface = &editor.active_document().network_interface;
assert_eq!(feeding(&editor, upper), Some(OutputConnector::node(dot, 0)), "the dot should feed the upper layer");
assert_eq!(feeding(&editor, dot), Some(OutputConnector::node(lower, 0)), "the lower layer should feed the dot");
assert!(network_interface.is_absolute(&lower, &[]), "a layer feeding a dot rather than a layer is no longer stacked");
assert!(!network_interface.is_stack(&lower, &[]), "a layer feeding a dot rather than a layer is no longer stacked");
assert_eq!(network_interface.position(&lower, &[]), lower_position, "the lower layer shouldn't move");
assert_invariants(&editor, "after putting a dot on a stack wire");
}
@@ -315,6 +315,163 @@ fn fill_definition() -> DefinitionIdentifier {
DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER)
}
#[tokio::test]
async fn a_relative_node_follows_its_readers_until_it_loses_the_last_one() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let lower_reader = editor.create_node_by_name_at(fill_definition(), 20, 10).await;
let upper_reader = editor.create_node_by_name_at(fill_definition(), 30, 4).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
let network_interface = &mut editor.active_document_mut().network_interface;
for reader in [lower_reader, upper_reader] {
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::primary_input(reader), &[]);
}
let relative = NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(-7, 3))));
network_interface.node_mut(NodeLocator::new(node, &[])).expect("the node exists").set_node_type(relative);
network_interface.invalidate_position(&node, &[]);
// The offset applies to the top left corner of the box around both readers
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 7)));
network_interface.disconnect_input(&InputConnector::primary_input(upper_reader), &[]);
assert!(network_interface.is_relative(&node, &[]), "A node still read by another node should stay relative");
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 13)));
network_interface.disconnect_input(&InputConnector::primary_input(lower_reader), &[]);
assert!(network_interface.is_absolute(&node, &[]), "A node losing its last reader should be pinned where it was drawn");
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 13)));
assert_invariants(&editor, "after a relative node loses its readers");
}
#[tokio::test]
async fn a_connected_node_stays_where_it_is_drawn_and_follows_a_rewire() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let reader = editor.create_node_by_name_at(fill_definition(), 20, 10).await;
let other_reader = editor.create_node_by_name_at(fill_definition(), 40, 30).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::primary_input(reader), &[]);
assert!(network_interface.is_relative(&node, &[]), "A node gaining its first reader should become relative to it");
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(0, 0)));
// Rewiring keeps the offset, so the node moves beside its new reader
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::primary_input(other_reader), &[]);
network_interface.disconnect_input(&InputConnector::primary_input(reader), &[]);
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(20, 20)));
assert_invariants(&editor, "after connecting and rewiring a relative node");
}
#[tokio::test]
async fn deleting_the_only_reader_of_a_relative_node_pins_it() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let reader = editor.create_node_by_name_at(fill_definition(), 20, 10).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 10, 10).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::primary_input(reader), &[]);
network_interface.delete_nodes(vec![reader], false, &[]);
assert!(network_interface.is_absolute(&node, &[]), "A node losing its last reader to a delete should be pinned");
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(10, 10)));
}
#[tokio::test]
async fn dragging_a_node_carries_its_upstream_unless_it_is_kept_in_place() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let reader = editor.create_node_by_name_at(fill_definition(), 20, 10).await;
let node = editor.create_node_by_name_at(fill_definition(), 10, 10).await;
let source = editor.create_node_by_name_at(rectangle_definition(), 0, 10).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::primary_input(reader), &[]);
network_interface.create_wire(&OutputConnector::primary_output(source), &InputConnector::primary_input(node), &[]);
network_interface.selected_nodes_mut(&[]).expect("the root network has a selection").set_selected_nodes(vec![reader]);
network_interface.shift_selected_nodes(Direction::Down, true, false, &[]);
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(10, 11)), "The node read by the dragged one should follow it");
assert_eq!(network_interface.position(&source, &[]), Some(IVec2::new(0, 11)), "Everything upstream should follow too");
network_interface.shift_selected_nodes(Direction::Down, true, true, &[]);
assert_eq!(network_interface.position(&reader, &[]), Some(IVec2::new(20, 12)));
assert_eq!(
network_interface.position(&node, &[]),
Some(IVec2::new(10, 11)),
"Keeping the upstream in place should leave the node where it was drawn"
);
assert_eq!(
network_interface.position(&source, &[]),
Some(IVec2::new(0, 11)),
"Keeping the upstream in place should leave its upstream too"
);
assert_invariants(&editor, "after dragging a node with and without its upstream");
}
#[tokio::test]
async fn moving_a_chain_node_out_of_its_chain_carries_its_upstream() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (_, near, far, source, outside) = layer_with_chain(&mut editor).await;
let network_interface = &mut editor.active_document_mut().network_interface;
assert!(network_interface.is_chain(&near, &[]) && network_interface.is_chain(&far, &[]), "fixture is wrong");
let [far_before, source_before, outside_before] = [far, source, outside].map(|node_id| network_interface.position(&node_id, &[]).expect("every node has a position"));
network_interface.selected_nodes_mut(&[]).expect("the root network has a selection").set_selected_nodes(vec![near]);
network_interface.shift_selected_nodes(Direction::Down, true, false, &[]);
assert!(!network_interface.is_chain(&far, &[]), "The chain upstream of a node moved out of it should leave the chain too");
for (node_id, before) in [(far, far_before), (source, source_before), (outside, outside_before)] {
assert_eq!(
network_interface.position(&node_id, &[]),
Some(before + IVec2::Y),
"Node {node_id} upstream of the moved node should follow it"
);
}
assert_invariants(&editor, "after moving a chain node out of its chain");
}
#[tokio::test]
async fn moving_a_chain_node_out_while_keeping_its_upstream_leaves_the_upstream_in_place() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (_, near, far, source, _) = layer_with_chain(&mut editor).await;
let network_interface = &mut editor.active_document_mut().network_interface;
let [far_before, source_before] = [far, source].map(|node_id| network_interface.position(&node_id, &[]).expect("every node has a position"));
network_interface.selected_nodes_mut(&[]).expect("the root network has a selection").set_selected_nodes(vec![near]);
network_interface.shift_selected_nodes(Direction::Down, true, true, &[]);
network_interface.shift_selected_nodes(Direction::Down, true, true, &[]);
assert_eq!(
network_interface.position(&far, &[]),
Some(far_before),
"The chain upstream of the moved node should stay where it was drawn"
);
assert_eq!(network_interface.position(&source, &[]), Some(source_before));
network_interface.shift_selected_nodes(Direction::Up, true, true, &[]);
network_interface.shift_selected_nodes(Direction::Up, true, true, &[]);
assert!(
network_interface.is_chain(&near, &[]) && network_interface.is_chain(&far, &[]),
"Moving the node back should restore the whole chain"
);
assert_invariants(&editor, "after moving a chain node out of its chain while keeping its upstream");
}
/// Builds a layer fed by the chain `near <- far <- source` (a generator fixed at the upstream end), with an outside node also wired into the near node's second input.
async fn layer_with_chain(editor: &mut EditorTestUtils) -> (NodeId, NodeId, NodeId, NodeId, NodeId) {
let layer = editor.create_node_by_name_at(merge_definition(), 30, 10).await;
@@ -889,10 +889,12 @@ impl document_graph_storage::NodeMetadataSource for MetadataCopySource<'_> {
NodeTypePersistentMetadata::Layer(layer) => Some(match layer.position {
LayerPosition::Absolute(offset) => Position::Absolute([offset.x, offset.y]),
LayerPosition::Stack(offset) => Position::Stack(offset),
LayerPosition::Relative(offset) => Position::Relative([offset.x, offset.y]),
}),
NodeTypePersistentMetadata::Node(node) => Some(match *node.position() {
NodePosition::Absolute(offset) => Position::Absolute([offset.x, offset.y]),
NodePosition::Chain => Position::Chain,
NodePosition::Relative(offset) => Position::Relative([offset.x, offset.y]),
}),
}
}
@@ -101,6 +101,12 @@ async fn wiring_and_export_edits_construct_the_exact_diff_ops() {
let a = editor.create_node_by_name(rectangle_definition()).await;
let b = editor.create_node_by_name(rectangle_definition()).await;
// Already read by `a`, so `b` is relative and the wiring edit below doesn't also reposition it
editor
.active_document_mut()
.network_interface
.set_input(&InputConnector::node_at_index(a, 2), NodeInput::node(b, 0), &[]);
let working = convert(&editor);
let wire = NodeInput::node(b, 0);
editor.active_document_mut().network_interface.set_input(&InputConnector::node_at_index(a, 1), wire.clone(), &[]);
@@ -8,8 +8,8 @@ use graphene_std::{Color, Graphic};
impl NodeNetworkInterface {
/// The top left corner of a node in node graph grid coordinates.
///
/// Only absolute positions are stored. A stack layer sits below its downstream sibling and a chain node to the
/// left of the layer it feeds, so both are resolved by walking downstream to the first stored position.
/// A relative node sits at an offset from the nodes reading it and a chain node to the left of the layer it feeds,
/// so both are resolved by walking downstream to the first absolute position.
pub fn position(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<IVec2> {
self.position_from_downstream(node_id, network_path, &mut HashSet::new(), &mut HashMap::new())
}
@@ -42,7 +42,7 @@ impl NodeNetworkInterface {
}
/// Walks downstream to the first stored position, accumulating the relative offsets along the way. `visited`
/// stops the walk on a cyclic graph, which concurrent edits can produce, rather than recursing forever.
/// holds the nodes on the current walk, which stops it on a cyclic graph that concurrent edits can produce.
fn position_from_downstream(&self, node_id: &NodeId, network_path: &[NodeId], visited: &mut HashSet<NodeId>, resolved: &mut HashMap<NodeId, IVec2>) -> Option<IVec2> {
if let Some(position) = resolved.get(node_id) {
return Some(*position);
@@ -53,6 +53,7 @@ impl NodeNetworkInterface {
}
let position = self.resolve_position(node_id, network_path, visited, resolved);
visited.remove(node_id);
if let Some(position) = position {
resolved.insert(*node_id, position);
}
@@ -69,6 +70,7 @@ impl NodeNetworkInterface {
match &node_metadata.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer_metadata) => match layer_metadata.position {
LayerPosition::Absolute(position) => Some(position),
LayerPosition::Relative(offset) => self.relative_position(node_id, offset, network_path, visited, resolved),
LayerPosition::Stack(y_offset) => {
let downstream_node_id = self
.with_outward_wires(network_path, |outward_wires| {
@@ -91,10 +93,12 @@ impl NodeNetworkInterface {
},
NodeTypePersistentMetadata::Node(node_metadata) => match node_metadata.position {
NodePosition::Absolute(position) => Some(position),
NodePosition::Relative(offset) => self.relative_position(node_id, offset, network_path, visited, resolved),
NodePosition::Chain => {
// A chain node is placed by its distance from the layer it feeds, so walk downstream to that layer
let mut current_node_id = *node_id;
let mut node_distance_from_layer = 1;
let mut chain_visited = HashSet::new();
loop {
// TODO: Use root node to restore if previewing
let downstream_node_id = self
@@ -122,7 +126,7 @@ impl NodeNetworkInterface {
.map(|layer_position| layer_position + IVec2::new(-node_distance_from_layer * NODE_CHAIN_WIDTH, 0));
}
if !visited.insert(downstream_node_id) {
if !chain_visited.insert(downstream_node_id) {
log::error!("Cycle reached while resolving the chain position of node {node_id}");
return None;
}
@@ -134,6 +138,127 @@ impl NodeNetworkInterface {
}
}
fn relative_position(&self, node_id: &NodeId, offset: IVec2, network_path: &[NodeId], visited: &mut HashSet<NodeId>, resolved: &mut HashMap<NodeId, IVec2>) -> Option<IVec2> {
let readers = self.reading_nodes(node_id, network_path);
let Some(top_left) = readers
.iter()
.filter_map(|reader| self.position_from_downstream(reader, network_path, visited, resolved))
.reduce(IVec2::min)
else {
log::error!("Could not get the position of any node reading relative node {node_id}");
return None;
};
Some(top_left + offset)
}
/// The top left corner of the bounding box of the positions of the nodes reading `node_id`.
fn readers_top_left(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<IVec2> {
let readers = self.reading_nodes(node_id, network_path);
self.positions(readers, network_path).into_iter().map(|(_, position)| position).reduce(IVec2::min)
}
/// Stores `position` as an offset from the nodes reading the node, or as an absolute position if no node reads it.
pub(crate) fn place_at(&mut self, node_id: &NodeId, position: IVec2, network_path: &[NodeId]) {
match self.readers_top_left(node_id, network_path) {
Some(top_left) => self.set_relative_position(node_id, position - top_left, network_path),
None => self.set_absolute_position(node_id, position, network_path),
}
}
pub(crate) fn set_relative_position(&mut self, node_id: &NodeId, offset: IVec2, network_path: &[NodeId]) {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
log::error!("Could not get node_metadata for node {node_id}");
return;
};
if !node.set_relative_position(offset) {
return;
}
self.transaction_modified();
self.invalidate_position(node_id, network_path);
}
/// Converts every absolute node that another node reads, and every stacked layer, in all networks to a position relative to its readers.
pub fn convert_positions_to_relative(&mut self) {
let mut network_paths = Vec::new();
self.for_each_network(&mut |network_path, _| network_paths.push(network_path.to_vec()));
network_paths.retain(|network_path| !self.is_read_only(network_path));
for network_path in network_paths {
let Some(network) = self.nested_network(&network_path) else { continue };
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
let positions: HashMap<NodeId, IVec2> = self.positions(node_ids.iter().copied(), &network_path).into_iter().collect();
let offsets: Vec<(NodeId, IVec2)> = node_ids
.iter()
.filter(|node_id| self.is_absolute(node_id, &network_path) || matches!(self.stored_layer_position(node_id, &network_path), Some(LayerPosition::Stack(_))))
.filter_map(|node_id| {
let top_left = self
.reading_nodes(node_id, &network_path)
.iter()
.filter_map(|reader| positions.get(reader).copied())
.reduce(IVec2::min)?;
Some((*node_id, positions.get(node_id)? - top_left))
})
.collect();
for (node_id, offset) in offsets {
self.set_relative_position(&node_id, offset, &network_path);
}
}
}
fn stored_layer_position(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<LayerPosition> {
match &self.node_metadata(node_id, network_path)?.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer_metadata) => Some(layer_metadata.position.clone()),
NodeTypePersistentMetadata::Node(_) => None,
}
}
/// The nodes reading any output of `node_id`.
fn reading_nodes(&self, node_id: &NodeId, network_path: &[NodeId]) -> Vec<NodeId> {
let output_count = self.number_of_outputs(node_id, network_path);
self.with_outward_wires(network_path, |outward_wires| {
(0..output_count)
.filter_map(|output_index| outward_wires.get(&OutputConnector::node(*node_id, output_index)))
.flatten()
.filter_map(InputConnector::node_id)
.collect()
})
.unwrap_or_default()
}
/// Pins a relative node at its drawn position before `leaving_reader` stops reading it, if no other node reads it.
pub(crate) fn pin_relative_node_losing_its_readers(&mut self, node_id: &NodeId, leaving_reader: &InputConnector, network_path: &[NodeId]) {
if !self.is_relative(node_id, network_path) {
return;
}
let output_count = self.number_of_outputs(node_id, network_path);
let still_read = self.with_outward_wires(network_path, |outward_wires| {
(0..output_count)
.filter_map(|output_index| outward_wires.get(&OutputConnector::node(*node_id, output_index)))
.flatten()
.any(|reader| reader != leaving_reader && reader.node_id().is_some())
});
if still_read != Some(false) {
return;
}
let Some(position) = self.position(node_id, network_path) else {
log::error!("Could not get the position of relative node {node_id} before it loses its readers");
return;
};
self.set_absolute_position(node_id, position, network_path);
}
/// Pins a relative node at `position`, where it was drawn, once no node reads it anymore.
pub(crate) fn pin_relative_node_without_readers(&mut self, node_id: &NodeId, position: IVec2, network_path: &[NodeId]) {
if self.is_relative(node_id, network_path) && self.reading_nodes(node_id, network_path).is_empty() {
self.set_absolute_position(node_id, position, network_path);
}
}
/// Sets the position of a node to an absolute position
pub(crate) fn set_absolute_position(&mut self, node_id: &NodeId, position: IVec2, network_path: &[NodeId]) {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
@@ -307,19 +432,19 @@ impl NodeNetworkInterface {
}
}
/// node_id is the first chain node, not the layer
pub(crate) fn set_upstream_chain_to_absolute(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
/// Takes `node_id`, the first chain node rather than the layer, and the chain nodes upstream of it out of the chain where they are drawn.
pub(crate) fn unchain_upstream(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
let Some(downstream_layer) = self.downstream_layer_for_chain_node(node_id, network_path) else {
log::error!("Could not get downstream layer in set_upstream_chain_to_absolute");
log::error!("Could not get downstream layer in unchain_upstream");
return;
};
for upstream_id in &self.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow).collect::<Vec<_>>() {
let Some(previous_position) = self.position(upstream_id, network_path) else {
log::error!("Could not get position in set_upstream_chain_to_absolute");
log::error!("Could not get position in unchain_upstream");
return;
};
if self.is_chain(upstream_id, network_path) {
self.set_absolute_position(upstream_id, previous_position, network_path);
self.place_at(upstream_id, previous_position, network_path);
// Reload click target of the layer which used to encapsulate the chain
self.unload_node_click_targets(&downstream_layer, network_path);
}
@@ -330,52 +455,44 @@ impl NodeNetworkInterface {
}
}
/// Places `upstream_node_id` for a connection just made to `input_connector`. Only layers move: one
/// that is the sole feed into the bottom of another layer stacks under it, and any other layer is
/// pinned where it already sits.
/// Places `upstream_node_id` for a connection just made to `input_connector`. A layer that is the sole
/// feed into the bottom of another layer stacks under it, a relative node keeps its offset from its
/// readers, and an absolute node becomes relative to them where it sits.
///
/// Returns whether the node could be placed, which is false only when it has no resolvable position.
pub(crate) fn reposition_connected_upstream(&mut self, upstream_node_id: &NodeId, input_connector: &InputConnector, network_path: &[NodeId]) -> bool {
let Some(current_position) = self.position(upstream_node_id, network_path) else {
if self.position(upstream_node_id, network_path).is_none() {
log::error!("Could not get position of node {upstream_node_id} in reposition_connected_upstream");
return false;
};
if !self.is_layer(upstream_node_id, network_path) {
return true;
}
// Only the bottom input of a layer stacks what feeds it; everything else leaves the layer where it is
let InputConnector::Node {
node_id: downstream_node_id,
input_index,
} = input_connector
else {
self.set_absolute_position(upstream_node_id, current_position, network_path);
return true;
let feeds_bottom_of_layer = match input_connector {
InputConnector::Node { node_id, input_index: 0 } => self.is_layer(node_id, network_path),
_ => false,
};
if *input_index != 0 || !self.is_layer(downstream_node_id, network_path) {
self.set_absolute_position(upstream_node_id, current_position, network_path);
return true;
}
let multiple_outward_wires = self
let single_outward_wire = self
.outward_wires(network_path)
.and_then(|all_outward_wires| all_outward_wires.get(&OutputConnector::primary_output(*upstream_node_id)))
.is_some_and(|outward_wires| outward_wires.len() > 1);
.is_some_and(|outward_wires| outward_wires.len() == 1);
if multiple_outward_wires {
self.set_absolute_position(upstream_node_id, current_position, network_path);
} else {
if let InputConnector::Node { node_id: downstream_node_id, .. } = input_connector
&& feeds_bottom_of_layer
&& single_outward_wire
&& self.is_layer(upstream_node_id, network_path)
{
self.set_stack_position_calculated_offset(upstream_node_id, downstream_node_id, network_path);
} else if self.is_absolute(upstream_node_id, network_path)
&& let Some(position) = self.position(upstream_node_id, network_path)
{
self.place_at(upstream_node_id, position, network_path);
}
true
}
/// Places `node_id` after the connection feeding it was removed. A layer that still feeds the bottom
/// of a single layer stacks under it, a node joins a chain where it is eligible, and any other layer
/// is pinned at `previous_position`.
/// of a single layer stacks under it, a node joins a chain where it is eligible, and any other absolute
/// layer is placed at `previous_position`.
///
/// Returns whether the node could be placed, which is false only when its outward wires are missing.
pub(crate) fn reposition_disconnected_upstream(&mut self, node_id: &NodeId, previous_position: IVec2, network_path: &[NodeId]) -> bool {
@@ -398,8 +515,8 @@ impl NodeNetworkInterface {
}
} else if !is_layer {
self.try_set_node_to_chain(node_id, network_path);
} else {
self.set_absolute_position(node_id, previous_position, network_path);
} else if !self.is_relative(node_id, network_path) {
self.place_at(node_id, previous_position, network_path);
}
true
@@ -436,7 +553,8 @@ impl NodeNetworkInterface {
self.invalidate_position(layer, network_path);
}
pub fn shift_selected_nodes(&mut self, direction: Direction, shift_without_push: bool, network_path: &[NodeId]) {
/// Shifts the selected nodes one grid step. The relative nodes upstream of them follow, unless `keep_upstream` leaves them where they are drawn.
pub fn shift_selected_nodes(&mut self, direction: Direction, shift_without_push: bool, keep_upstream: bool, network_path: &[NodeId]) {
let Some(node_ids) = self
.selected_nodes_in_nested_network(network_path)
.map(|selected_nodes| selected_nodes.selected_nodes().copied().collect::<HashSet<_>>())
@@ -444,7 +562,90 @@ impl NodeNetworkInterface {
log::error!("Could not get selected nodes in shift_selected_nodes");
return;
};
self.shift_nodes(node_ids, direction, shift_without_push, network_path);
let placements_before = keep_upstream.then(|| self.placements(network_path));
self.shift_nodes(node_ids.clone(), direction, shift_without_push, network_path);
if let Some(placements_before) = placements_before {
self.restore_followers(&placements_before, &node_ids, network_path);
}
}
/// The stored position of each node in the network and where it is drawn.
fn placements(&self, network_path: &[NodeId]) -> HashMap<NodeId, (NodeTypePersistentMetadata, IVec2)> {
let Some(network) = self.nested_network(network_path) else { return HashMap::new() };
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
self.positions(node_ids, network_path)
.into_iter()
.filter_map(|(node_id, position)| Some((node_id, (self.node_metadata(&node_id, network_path)?.persistent_metadata.node_type_metadata.clone(), position))))
.collect()
}
/// Moves each relative node that was only carried along by the nodes reading it back to where it was drawn, which keeps its upstream in place too.
/// A node the shift made relative, such as a chain leaving its layer, counts as carried along, while a relative node the shift pushed does not.
fn restore_followers(&mut self, placements_before: &HashMap<NodeId, (NodeTypePersistentMetadata, IVec2)>, moved_nodes: &HashSet<NodeId>, network_path: &[NodeId]) {
let followers: HashSet<NodeId> = placements_before
.iter()
.filter(|(node_id, (stored_position, position))| {
let was_relative = matches!(
stored_position,
NodeTypePersistentMetadata::Node(NodePersistentMetadata { position: NodePosition::Relative(_) })
| NodeTypePersistentMetadata::Layer(LayerPersistentMetadata { position: LayerPosition::Relative(_) })
);
let stored_position_unchanged = self
.node_metadata(node_id, network_path)
.is_some_and(|metadata| metadata.persistent_metadata.node_type_metadata == *stored_position);
!moved_nodes.contains(node_id) && self.is_relative(node_id, network_path) && (stored_position_unchanged || !was_relative) && self.position(node_id, network_path) != Some(*position)
})
.map(|(node_id, _)| *node_id)
.collect();
let mut restored = HashSet::new();
for follower in &followers {
self.restore_follower(follower, &followers, placements_before, &mut restored, network_path);
}
// Joining a chain needs a node to line up with its reader, which a follower only does again once restored
for follower in &followers {
if !self.is_layer(follower, network_path) {
self.try_set_node_to_chain(follower, network_path);
}
}
}
/// Restores the followers reading `node_id` first, since each one moves everything it reads.
fn restore_follower(
&mut self,
node_id: &NodeId,
followers: &HashSet<NodeId>,
placements_before: &HashMap<NodeId, (NodeTypePersistentMetadata, IVec2)>,
restored: &mut HashSet<NodeId>,
network_path: &[NodeId],
) {
if !restored.insert(*node_id) {
return;
}
for reader in self.reading_nodes(node_id, network_path) {
if followers.contains(&reader) {
self.restore_follower(&reader, followers, placements_before, restored, network_path);
}
}
if let Some((_, previous_position)) = placements_before.get(node_id) {
self.keep_drawn_at(node_id, *previous_position, network_path);
}
}
/// Moves an absolute or relative node back to `position` after an edit carried it away, along with everything relative to it.
pub(crate) fn keep_drawn_at(&mut self, node_id: &NodeId, position: IVec2, network_path: &[NodeId]) {
let Some(current_position) = self.position(node_id, network_path) else { return };
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
if node.shift_absolute_position(position - current_position) {
self.transaction_modified();
self.invalidate_position(node_id, network_path);
}
}
pub(crate) fn shift_nodes(&mut self, node_ids: HashSet<NodeId>, direction: Direction, shift_without_push: bool, network_path: &[NodeId]) {
@@ -510,6 +711,15 @@ impl NodeNetworkInterface {
}
}
// A relative node already follows its readers, so shifting it with all of them would move it twice
let shifting_nodes = node_ids.clone();
for selected_node in &shifting_nodes {
let readers = self.reading_nodes(selected_node, network_path);
if self.is_relative(selected_node, network_path) && !readers.is_empty() && readers.iter().all(|reader| shifting_nodes.contains(reader)) {
node_ids.remove(selected_node);
}
}
node_ids
}
@@ -518,14 +728,7 @@ impl NodeNetworkInterface {
/// A node that cannot be read blocks the shift rather than letting part of it through.
fn stack_shift_up_is_blocked(&mut self, node_ids: &HashSet<NodeId>, network_path: &[NodeId]) -> bool {
for node_id in node_ids {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get node metadata for node {node_id} in stack_shift_up_is_blocked");
return true;
};
let NodeTypePersistentMetadata::Layer(layer_metadata) = &node_metadata.persistent_metadata.node_type_metadata else {
continue;
};
let LayerPosition::Stack(offset) = layer_metadata.position else { continue };
let Some(offset) = self.stack_offset(node_id, network_path) else { continue };
let Some(outward_wires) = self.outward_wires(network_path).and_then(|outward_wires| outward_wires.get(&OutputConnector::primary_output(*node_id))) else {
log::error!("Could not get outward wires in stack_shift_up_is_blocked");
@@ -537,7 +740,7 @@ impl NodeNetworkInterface {
continue;
}
if offset == 0 {
if offset <= 0 {
return true;
}
}
@@ -562,9 +765,9 @@ impl NodeNetworkInterface {
return;
}
// Walk down the stack to the layer holding an absolute position, which anchors the rest
// Walk down the stack to its top layer, which anchors the rest
let mut downstream_absolute_layer = *node_id;
while !self.is_absolute(&downstream_absolute_layer, network_path) {
while self.is_stack(&downstream_absolute_layer, network_path) {
let Some(downstream_node) = self
.outward_wires(network_path)
.and_then(|outward_wires| outward_wires.get(&OutputConnector::primary_output(downstream_absolute_layer)))
@@ -602,8 +805,7 @@ impl NodeNetworkInterface {
}
}
/// Shifts one node vertically, pushing whatever it collides with unless the caller asked for a bare
/// shift. A layer that moves drags its stacked sibling the other way, so the sibling stays put.
/// Shifts one node vertically, pushing whatever it collides with unless the caller asked for a bare shift.
fn shift_vertically(&mut self, node_id: &NodeId, shift_sign: i32, shift_without_push: bool, shifted_nodes: &mut HashSet<NodeId>, network_path: &[NodeId]) {
if !shift_without_push && self.is_layer(node_id, network_path) {
self.shift_node_or_parent(node_id, shift_sign, shifted_nodes, network_path);
@@ -618,18 +820,6 @@ impl NodeNetworkInterface {
if self.with_stack_dependents_if_loaded(network_path, |stack_dependents| matches!(stack_dependents.get(node_id), Some(LayerOwner::None))) == Some(true) {
self.add_drag_offset(node_id, shift_sign, network_path);
}
if !self.is_layer(node_id, network_path) {
return;
}
let upstream_layer = self
.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::PrimaryFlow)
.nth(1)
.filter(|upstream_node| self.is_stack(upstream_node, network_path));
if let Some(upstream_layer) = upstream_layer {
self.shift_node(&upstream_layer, IVec2::new(0, -shift_sign), network_path);
}
}
/// Moves every node the shift pushed out of place back to where it started, as far as nothing has since
@@ -712,18 +902,6 @@ impl NodeNetworkInterface {
None => log::error!("Stack dependents should be loaded in vertical_shift_with_push"),
}
// Shift the upstream layer so that it stays in the same place
if self.is_layer(node_id, network_path) {
let upstream_layer = {
self.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::PrimaryFlow)
.nth(1)
.filter(|upstream_node| self.is_stack(upstream_node, network_path))
};
if let Some(upstream_layer) = upstream_layer {
self.shift_node(&upstream_layer, IVec2::new(0, -shift_sign), network_path);
}
}
if let Some(owned_nodes) = self.with_owned_nodes_if_loaded(node_id, network_path, |owned_nodes| owned_nodes.clone()) {
for owned_node in owned_nodes {
if self.is_absolute(&owned_node, network_path) {
@@ -845,7 +1023,7 @@ impl NodeNetworkInterface {
// A chain node has no position of its own to shift, so it leaves the chain first
NodeTypePersistentMetadata::Node(node_position) if matches!(node_position.position(), NodePosition::Chain) => {
self.set_upstream_chain_to_absolute(node_id, network_path);
self.unchain_upstream(node_id, network_path);
self.shift_node(node_id, shift, network_path);
}
@@ -1277,6 +1455,7 @@ impl NodeNetworkInterface {
/// upstream node's spot and that whole branch is shifted left (in absolute graph space) to make room.
pub fn insert_node_before_input(&mut self, node_id: &NodeId, input_connector: &InputConnector, network_path: &[NodeId]) {
let feeder = self.upstream_output_connector(input_connector, network_path).and_then(|output| output.node_id());
let feeder_position = feeder.and_then(|feeder| self.position(&feeder, network_path));
let Some(current_input) = self.input_from_connector(input_connector, network_path).cloned() else {
log::error!("Could not get input in insert_node_before_input");
@@ -1291,20 +1470,26 @@ impl NodeNetworkInterface {
self.set_input(input_connector, NodeInput::node(*node_id, 0), network_path);
// If `set_input` chain-positioned the node (it joined a layer chain), there's nothing more to do
if !self.is_absolute(node_id, network_path) {
if self.is_chain(node_id, network_path) {
return;
}
// Otherwise place the node where the displaced feeder was, then shift the feeder's branch left to make room
let Some(feeder) = feeder else { return };
// Otherwise place the node where the displaced feeder was, then move the feeder's branch left to make room
let (Some(feeder), Some(feeder_position)) = (feeder, feeder_position) else { return };
let Some(node_position) = self.position(node_id, network_path) else { return };
let Some(feeder_position) = self.position(&feeder, network_path) else { return };
self.shift_node(node_id, feeder_position - node_position, network_path);
// A chain feeder derives its position from its distance to the layer, which this insertion already grew,
// so shifting it would move it twice and cost it its place in the chain
if !self.is_absolute(&feeder, network_path) {
if self.is_chain(&feeder, network_path) {
return;
}
// A relative feeder carries its upstream along
if self.is_relative(&feeder, network_path) {
let Some(current_feeder_position) = self.position(&feeder, network_path) else { return };
self.shift_node(&feeder, feeder_position + IVec2::new(-NODE_CHAIN_WIDTH, 0) - current_feeder_position, network_path);
return;
}
@@ -437,7 +437,7 @@ impl NodeNetworkInterface {
let new_inputs = std::mem::take(&mut new_template.inputs);
let new_input_metadata = std::mem::take(&mut new_template.input_metadata);
// A chain whose link into this node is dropped loses the layer it's positioned against, so it becomes absolute while that layer is still reachable
// A chain whose link into this node is dropped loses the layer it's positioned against, so it leaves the chain while that layer is still reachable
let chain_input_index = if self.is_layer(node_id, network_path) { LAYER_SECONDARY_INPUT_INDEX } else { PRIMARY_INPUT_INDEX };
let disconnected_chain_node = self
.document_node(node_id, network_path)
@@ -453,9 +453,24 @@ impl NodeNetworkInterface {
})
.filter(|upstream_node_id| self.is_chain(upstream_node_id, network_path));
if let Some(upstream_node_id) = disconnected_chain_node {
self.set_upstream_chain_to_absolute(&upstream_node_id, network_path);
self.unchain_upstream(&upstream_node_id, network_path);
}
let disconnected_upstream_positions: Vec<(NodeId, IVec2)> = self
.document_node(node_id, network_path)
.map(|node| {
node.inputs
.iter()
.enumerate()
.filter(|(index, old_input)| new_inputs.get(*index) != Some(*old_input))
.filter_map(|(_, old_input)| old_input.as_node())
.collect::<Vec<_>>()
})
.unwrap_or_default()
.into_iter()
.filter_map(|upstream_node_id| Some((upstream_node_id, self.position(&upstream_node_id, network_path)?)))
.collect();
let Some(mut node) = self.node_interface_mut(NodeLocator::new(*node_id, network_path)) else {
log::error!("Could not get node {node_id} in replace_inputs");
return None;
@@ -463,6 +478,10 @@ impl NodeNetworkInterface {
let old_inputs = node.replace_inputs(new_inputs.clone(), new_input_metadata);
self.update_outward_wires_for_inputs(network_path, node_id, &old_inputs, &new_inputs);
for (upstream_node_id, position) in disconnected_upstream_positions {
self.pin_relative_node_without_readers(&upstream_node_id, position, network_path);
}
Some(old_inputs)
}
@@ -600,13 +619,17 @@ impl NodeNetworkInterface {
return;
}
if let NodeInput::Node { node_id: upstream_node_id, .. } = &previous_input {
self.pin_relative_node_losing_its_readers(upstream_node_id, input_connector, network_path);
}
// A chain positions its nodes relative to the layer they feed, so either end of the rewire
// leaving that layer breaks the chain it belonged to
for chain_input in [&previous_input, &new_input] {
if let NodeInput::Node { node_id: chain_node_id, .. } = chain_input
&& self.is_chain(chain_node_id, network_path)
{
self.set_upstream_chain_to_absolute(chain_node_id, network_path);
self.unchain_upstream(chain_node_id, network_path);
}
}
@@ -775,7 +798,7 @@ impl NodeNetworkInterface {
{
// If the node upstream from the disconnected input is a chain, then break the chain by setting it to absolute positioning
if self.is_chain(upstream_node_id, network_path) {
self.set_upstream_chain_to_absolute(upstream_node_id, network_path);
self.unchain_upstream(upstream_node_id, network_path);
}
// If the node upstream from the disconnected input has an outward wire to the bottom of a layer, set it back to stack positioning
if self.is_layer(upstream_node_id, network_path) {
@@ -887,10 +910,17 @@ impl NodeNetworkInterface {
dot_template.node_type_metadata = NodeTypePersistentMetadata::node(center - IVec2::Y);
self.insert_node(dot, dot_template, network_path);
let upstream_node = output_connector.node_id();
let upstream_position = upstream_node.and_then(|upstream_node| self.position(&upstream_node, network_path));
self.create_wire(output_connector, &InputConnector::primary_input(dot), network_path);
for fed_input in fed_inputs {
self.create_wire(&OutputConnector::primary_output(dot), fed_input, network_path);
}
if let (Some(upstream_node), Some(upstream_position)) = (upstream_node, upstream_position) {
self.keep_drawn_at(&upstream_node, upstream_position, network_path);
}
}
/// Used to insert a group of nodes into the network
@@ -1321,20 +1351,20 @@ impl NodeNetworkInterface {
}
pub fn set_to_node_or_layer(&mut self, node_id: &NodeId, network_path: &[NodeId], is_layer: bool) {
// If a layer is set to a node, set upstream nodes to absolute position, and upstream siblings to absolute position
// If a layer is set to a node, take its chain out of the chain and its upstream sibling out of the stack where they are drawn
let child_id = { self.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow).nth(1) };
let upstream_sibling_id = { self.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::PrimaryFlow).nth(1) };
match (self.is_layer(node_id, network_path), is_layer) {
(true, false) => {
if let Some(child_id) = child_id {
self.set_upstream_chain_to_absolute(&child_id, network_path);
self.unchain_upstream(&child_id, network_path);
}
if let Some(upstream_sibling_id) = upstream_sibling_id {
let Some(upstream_sibling_position) = self.position(&upstream_sibling_id, network_path) else {
log::error!("Could not get upstream sibling position in set_to_node_or_layer");
return;
};
self.set_absolute_position(&upstream_sibling_id, upstream_sibling_position, network_path);
self.place_at(&upstream_sibling_id, upstream_sibling_position, network_path);
}
}
(false, true) => {
@@ -1349,7 +1379,7 @@ impl NodeNetworkInterface {
{
self.set_stack_position_calculated_offset(&upstream_sibling_id, node_id, network_path);
} else {
self.set_upstream_chain_to_absolute(&upstream_sibling_id, network_path);
self.unchain_upstream(&upstream_sibling_id, network_path);
}
}
}
@@ -1372,7 +1402,7 @@ impl NodeNetworkInterface {
.filter(|downstream_node_id| self.is_layer(downstream_node_id, network_path))
.and_then(|downstream_layer| self.position(&downstream_layer, network_path));
// First set the position to absolute
// First switch between layer and node where it is drawn
let absolute = match is_layer {
true => NodeTypePersistentMetadata::layer(position),
false => NodeTypePersistentMetadata::node(position),
@@ -1382,6 +1412,7 @@ impl NodeNetworkInterface {
return;
};
node.set_node_type(absolute);
self.place_at(node_id, position, network_path);
// Try build the chain
if is_layer {
@@ -62,6 +62,19 @@ impl NodeNetworkInterface {
layer_paths
}
/// The path of every node in the document's networks made from the definition.
pub fn node_paths_with_reference(&self, reference: &DefinitionIdentifier) -> Vec<Vec<NodeId>> {
let mut node_paths = Vec::new();
self.for_each_network(&mut |network_path, network_metadata| {
for node_id in network_metadata.persistent_metadata.node_metadata.keys() {
if self.reference(node_id, network_path).as_ref() == Some(reference) {
node_paths.push([network_path, &[*node_id]].concat());
}
}
});
node_paths
}
fn for_each_layer(&self, visit: &mut impl FnMut(&[NodeId], NodeId)) {
self.for_each_network(&mut |network_path, network_metadata| {
for (node_id, node_metadata) in &network_metadata.persistent_metadata.node_metadata {
@@ -941,8 +954,27 @@ impl NodeNetworkInterface {
self.query(network_path, "is_chain", |view| view.is_chain(node_id)).unwrap_or_default()
}
pub fn is_relative(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
self.query(network_path, "is_relative", |view| view.is_relative(node_id)).unwrap_or_default()
}
/// Whether the layer sits straight below the one layer reading it through its stack input.
pub fn is_stack(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
self.query(network_path, "is_stack", |view| view.is_stack(node_id)).unwrap_or_default()
self.stack_offset(node_id, network_path).is_some()
}
/// The rows a stacked layer sits below the gap under the layer reading it.
pub fn stack_offset(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<i32> {
let stack_offset = self.query(network_path, "stack_offset", |view| view.stack_offset(node_id)).flatten()?;
let read_by_one_stack_input = self
.with_outward_wires(network_path, |outward_wires| match outward_wires.get(&OutputConnector::primary_output(*node_id)).map(Vec::as_slice) {
Some([InputConnector::Node { node_id: reader, input_index: 0 }]) => self.is_layer(reader, network_path),
_ => false,
})
.unwrap_or_default();
read_by_one_stack_input.then_some(stack_offset)
}
/// Whether the node is an Artboard node by identity, regardless of whether it currently participates in the scene.
@@ -1209,7 +1241,6 @@ impl NodeNetworkInterface {
node.inputs = old_node.inputs;
node.call_argument = old_node.manual_composition.unwrap_or_default();
node.visible = old_node.visible;
node.skip_deduplication = old_node.skip_deduplication;
node.original_location = old_node.original_location;
node_metadata.persistent_metadata.display_name = old_node.alias;
node_metadata.persistent_metadata.locked = old_node.locked;
@@ -221,7 +221,7 @@ impl NodeNetworkInterface {
return;
};
let deltas = if current.implementation == target.implementation && current.skip_deduplication == target.skip_deduplication {
let deltas = if current.implementation == target.implementation {
field_deltas(location, local_id, (current, current_metadata), (&target, &target_metadata))
} else {
vec![
@@ -61,7 +61,7 @@ static INPUT_CONVERSIONS: Lazy<HashMap<ProtoNodeIdentifier, Vec<Option<&'static
.collect()
});
/// Proto nodes whose every implementation returns its one input's type unchanged (like Monitor and Memoize), so a wire through one is constrained by what it feeds.
/// Proto nodes whose every implementation returns its one input's type unchanged (like Memoize), so a wire through one is constrained by what it feeds.
static TYPE_PRESERVING_NODES: Lazy<HashSet<ProtoNodeIdentifier>> = Lazy::new(|| {
NODE_REGISTRY
.iter()
@@ -420,7 +420,7 @@ impl NodeNetworkInterface {
}
/// A check of which wire types an input accepts, built once so testing many types searches the node's matching implementations only once.
/// Unlike [`Self::input_accepts_type`], a node passing its input's type through unchanged (like Monitor) also needs the inputs it feeds to accept the type.
/// Unlike [`Self::input_accepts_type`], a node passing its input's type through unchanged (like Memoize) also needs the inputs it feeds to accept the type.
fn type_acceptor(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Box<dyn Fn(&Type) -> bool> {
let accepts_here: Box<dyn Fn(&Type) -> bool> = match input_connector {
InputConnector::Export(export_index) => match network_path.split_last() {
@@ -768,25 +768,48 @@ mod tests {
#[tokio::test]
async fn subgraph_inputs_look_through_type_preserving_nodes() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use crate::test_utils::test_prelude::*;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let path_node_id = editor.create_node_by_name(DefinitionIdentifier::Network("Path".into())).await;
let merge = editor.create_node_by_name_at(DefinitionIdentifier::Network("Merge".into()), 0, 0).await;
// The Path subgraph's content goes through a Monitor node, which accepts most types, before the node that needs a vector
let content_types = editor
.active_document()
.network_interface
.potential_valid_input_types(&InputConnector::node_at_index(path_node_id, 0), &[])
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>();
assert!(content_types.iter().any(|ty| ty == "Vector"), "Path's content should accept a vector, found {content_types:?}");
// A new import feeding a Memoize, which accepts most types, before a Path that needs a vector
editor.enter_editable_network(merge).await;
let memoize = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::memo::memoize::IDENTIFIER), -20, 10).await;
let path = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER), -10, 10).await;
editor
.handle_message(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::node(memoize, 0),
input_connector: InputConnector::node_at_index(path, 0),
})
.await;
let import_index = editor.active_document().network_interface.number_of_imports(&[merge]);
editor
.handle_message(NodeGraphMessage::AddImportAndConnect {
import_index,
input_connector: InputConnector::node_at_index(memoize, 0),
})
.await;
let network_interface = &editor.active_document().network_interface;
let type_names = |input_connector: &InputConnector, network_path: &[super::NodeId]| {
network_interface
.potential_valid_input_types(input_connector, network_path)
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
};
let memoize_types = type_names(&InputConnector::node_at_index(memoize, 0), &[merge]);
assert!(memoize_types.iter().any(|ty| ty == "Color"), "Memoize itself should accept a color, found {memoize_types:?}");
let content_types = type_names(&InputConnector::node_at_index(merge, import_index), &[]);
assert!(content_types.iter().any(|ty| ty == "Vector"), "the input should accept a vector, found {content_types:?}");
assert!(
!content_types.iter().any(|ty| ty == "Color"),
"Path's content should not accept a color just because its Monitor does, found {content_types:?}"
"the input should not accept a color just because its Memoize does, found {content_types:?}"
);
}
@@ -14,8 +14,8 @@ use graph_craft::document::{DocumentNodeImplementation, NetworkLocation, NodeId,
use graphene_std::vector::style::RenderMode;
use super::{
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface, NodeNetworkMetadata,
NodeNetworkPersistentMetadata, NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing,
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface,
NodeNetworkMetadata, NodeNetworkPersistentMetadata, NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing,
};
use crate::messages::portfolio::document::node_graph::document_node_definitions::network_definition_version;
use crate::messages::portfolio::document::overlays::utility_types::OverlaysVisibilitySettings;
@@ -180,10 +180,12 @@ pub fn position_from_runtime(node_type: &NodeTypePersistentMetadata) -> Position
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
LayerPosition::Absolute(v) => Position::Absolute([v.x, v.y]),
LayerPosition::Stack(offset) => Position::Stack(offset),
LayerPosition::Relative(offset) => Position::Relative([offset.x, offset.y]),
},
NodeTypePersistentMetadata::Node(node) => match *node.position() {
NodePosition::Absolute(v) => Position::Absolute([v.x, v.y]),
NodePosition::Chain => Position::Chain,
NodePosition::Relative(offset) => Position::Relative([offset.x, offset.y]),
},
}
}
@@ -202,6 +204,10 @@ pub fn position_to_runtime(position: Position, is_layer: bool) -> NodeTypePersis
metadata
}
(Position::Chain, _) => NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Chain)),
(Position::Relative([x, y]), true) => NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Relative(IVec2::new(x, y)),
}),
(Position::Relative([x, y]), false) => NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(x, y)))),
}
}
@@ -144,14 +144,31 @@ impl NodeMut<'_> {
self.set_node_type(node_type)
}
/// Offsets a node that is absolutely positioned, leaving a stack or chain node where it is.
/// Places the node at an offset from the top left corner of the bounding box of the nodes reading it.
pub(crate) fn set_relative_position(&mut self, offset: IVec2) -> bool {
let node_type = match self.metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(_) => NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Relative(offset),
}),
NodeTypePersistentMetadata::Node(_) => NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(offset))),
};
self.set_node_type(node_type)
}
/// Offsets a node that is absolutely or relatively positioned, leaving a stack or chain node where it is.
pub(crate) fn shift_absolute_position(&mut self, shift: IVec2) -> bool {
let shifted = match self.metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Absolute(position),
}) => NodeTypePersistentMetadata::layer(position + shift),
NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Relative(offset),
}) => NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Relative(offset + shift),
}),
NodeTypePersistentMetadata::Node(ref node) => match node.position {
NodePosition::Absolute(position) => NodeTypePersistentMetadata::node(position + shift),
NodePosition::Relative(offset) => NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(offset + shift))),
NodePosition::Chain => return false,
},
NodeTypePersistentMetadata::Layer(_) => return false,
@@ -165,7 +182,7 @@ impl NodeMut<'_> {
return false;
}
self.set_node_type(NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Stack(y_offset),
position: LayerPosition::stacked(y_offset),
}))
}
@@ -6,7 +6,7 @@ impl NodeNetworkInterface {
pub fn compute_modified_vector(&self, layer: LayerNodeIdentifier) -> Option<VectorGeometry> {
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self);
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER))
&& let Some(geometry) = self.document_metadata.vector_modify.get(&path_node)
{
let mut modified = geometry.clone();
@@ -28,7 +28,7 @@ impl NodeNetworkInterface {
/// (e.g. the pre-solidified centerline for a Solidify Stroke layer) and otherwise do nothing.
pub fn upstream_path_node_vector(&self, layer: LayerNodeIdentifier) -> Option<VectorGeometry> {
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self);
graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))?;
graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER))?;
self.compute_modified_vector(layer)
}
@@ -21,8 +21,6 @@ pub struct NodeTemplate {
pub implementation: NodeTemplateImplementation,
/// Represents the eye icon for hiding/showing the node in the graph UI.
pub visible: bool,
/// Prevents identical proto nodes from being deduplicated during compilation, e.g. for monitor nodes.
pub skip_deduplication: bool,
/// A name chosen by the user for this instance of the node. Empty indicates no given name, in which case the implementation name is displayed in italics.
pub display_name: String,
/// Metadata to override the Inspector widgets for each input. Kept the same length as `inputs`.
@@ -57,7 +55,6 @@ impl Default for NodeTemplate {
call_argument: concrete!(Context),
implementation: NodeTemplateImplementation::default(),
visible: true,
skip_deduplication: false,
display_name: String::new(),
input_metadata: Vec::new(),
output_names: Vec::new(),
@@ -110,7 +107,6 @@ impl NodeTemplate {
call_argument,
implementation,
visible,
skip_deduplication,
compile_metadata: _,
original_location: _,
} = document_node;
@@ -161,7 +157,6 @@ impl NodeTemplate {
call_argument,
implementation,
visible,
skip_deduplication,
display_name,
input_metadata,
output_names,
@@ -179,7 +174,6 @@ impl NodeTemplate {
call_argument,
implementation,
visible,
skip_deduplication,
display_name,
mut input_metadata,
mut output_names,
@@ -211,7 +205,6 @@ impl NodeTemplate {
call_argument,
implementation,
visible,
skip_deduplication,
compile_metadata: None,
original_location: Default::default(),
};
@@ -1111,7 +1111,7 @@ impl NodeTypePersistentMetadata {
/// All fields in LayerMetadata should automatically be updated by using the network interface API
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct LayerPersistentMetadata {
/// Stores the position of a layer node, which can either be Absolute or Stack
/// Stores the position of a layer node, which can be Absolute or Relative, or Stack in older documents
pub position: LayerPosition,
}
@@ -1123,7 +1123,7 @@ impl PartialEq for LayerPersistentMetadata {
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct NodePersistentMetadata {
/// Stores the position of a non layer node, which can either be Absolute or Chain
/// Stores the position of a non layer node, which can be Absolute, Chain, or Relative
pub(crate) position: NodePosition,
}
@@ -1136,22 +1136,33 @@ impl NodePersistentMetadata {
}
}
/// A layer can either be position as Absolute or in a Stack
/// A layer is positioned as Absolute or Relative to the nodes reading it. Stack is only read from older documents, which opening converts to Relative.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum LayerPosition {
// Position of the node in grid spaces
Absolute(IVec2),
// A layer is in a Stack when it feeds into the bottom input of a layer. The Y position stores the vertical distance between the layer and its upstream sibling/parent.
Stack(u32),
// Offset from the top left corner of the bounding box of the positions of the nodes reading this one
Relative(IVec2),
}
/// A node can either be position as Absolute or in a Chain
impl LayerPosition {
/// Stacked `y_offset` rows below the gap under the layer reading it.
pub fn stacked(y_offset: u32) -> Self {
Self::Relative(IVec2::new(0, STACK_VERTICAL_GAP + y_offset as i32))
}
}
/// A node can be positioned as Absolute, in a Chain, or Relative to the nodes reading it
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum NodePosition {
// Position of the node in grid spaces
Absolute(IVec2),
// In a chain the position is based on the number of nodes to the first layer node
Chain,
// Offset from the top left corner of the bounding box of the positions of the nodes reading this one
Relative(IVec2),
}
/// Cached metadata that should be calculated when creating a node, and should be recalculated when modifying a node property that affects one of the cached fields.
@@ -237,10 +237,22 @@ impl<'a, 'p> NetworkView<'a, 'p> {
})
}
pub fn is_stack(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
pub fn is_relative(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
Ok(match &self.node_metadata(node_id)?.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer_metadata) => matches!(layer_metadata.position, LayerPosition::Stack(_)),
_ => false,
NodeTypePersistentMetadata::Layer(layer_metadata) => matches!(layer_metadata.position, LayerPosition::Relative(_)),
NodeTypePersistentMetadata::Node(node_metadata) => matches!(node_metadata.position, NodePosition::Relative(_)),
})
}
/// The rows a layer sits below the gap under the node reading it, if its position places it straight below that node.
pub fn stack_offset(&self, node_id: &NodeId) -> Result<Option<i32>, NetworkError> {
Ok(match &self.node_metadata(node_id)?.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer_metadata) => match layer_metadata.position {
LayerPosition::Stack(y_offset) => Some(y_offset as i32),
LayerPosition::Relative(offset) if offset.x == 0 => Some(offset.y - STACK_VERTICAL_GAP),
_ => None,
},
NodeTypePersistentMetadata::Node(_) => None,
})
}
@@ -117,10 +117,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"raster_nodes::std_nodes::SampleImageNode",
],
},
NodeReplacement {
node: graphene_std::memo::monitor::IDENTIFIER,
aliases: &["graphene_core::memo::MonitorNode"],
},
NodeReplacement {
node: graphene_std::memo::memoize::IDENTIFIER,
aliases: &["graphene_core::memo::MemoNode", "graphene_core::memo::ImpureMemoNode"],
@@ -944,8 +940,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
aliases: &["graphene_core::vector::PathLengthNode"],
},
NodeReplacement {
node: graphene_std::vector::path_modify::IDENTIFIER,
node: graphene_std::vector::path::IDENTIFIER,
aliases: &[
"vector_nodes::vector_modification_nodes::PathModifyNode",
"graphene_core::vector::vector_modification_nodes::PathModifyNode",
"graphene_core::vector::vector_data::modification::PathModifyNode",
"graphene_core::vector::vector_modification::PathModifyNode",
@@ -1162,6 +1159,14 @@ pub fn document_migration_replace_resources_referenced_by_hash(document_serializ
(out, hash_to_id)
}
/// The removed Monitor node, which old documents still hold.
const MONITOR_IDENTIFIER: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graphene_core::memo::MonitorNode");
/// Whether the implementation is the removed Monitor node, with or without the type arguments it was once stored with.
fn is_monitor(implementation: &DocumentNodeImplementation) -> bool {
matches!(implementation, DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().split('<').next() == Some(MONITOR_IDENTIFIER.as_str()))
}
/// Whether the node is a subgraph that feeds its first input through a Monitor into a Transform proto node and forwards the other four inputs unchanged, making it equivalent to a bare Transform node.
fn is_monitored_transform_subgraph(node: &DocumentNode, document_network: &graph_craft::document::NodeNetwork) -> bool {
let Some(network) = document_network.implementation_network(&node.implementation) else {
@@ -1177,7 +1182,7 @@ fn is_monitored_transform_subgraph(node: &DocumentNode, document_network: &graph
_ => false,
})
};
let Some((monitor_id, monitor)) = find_proto_node(&graphene_std::memo::monitor::IDENTIFIER) else {
let Some((monitor_id, monitor)) = find_proto_node(&MONITOR_IDENTIFIER) else {
return false;
};
let Some((transform_id, transform)) = find_proto_node(&graphene_std::transform_nodes::transform::IDENTIFIER) else {
@@ -1370,6 +1375,28 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
}
// The "Path" wrapper network was replaced with the `path` proto node directly. Convert old `Network("Path")` instances to the proto node, forwarding the Content and Modification inputs.
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer Path's network impl orphans its child paths.
let path_wrappers: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, _, path)| (document.network_interface.reference(node_id, &path) == Some(DefinitionIdentifier::Network("Path".into()))).then_some((*node_id, path)))
.collect();
for (node_id, network_path) in &path_wrappers {
let new_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER);
let Some(definition) = resolve_document_node_type(&new_reference) else { continue };
let mut node_template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
continue;
};
for (index, input) in old_inputs.into_iter().take(2).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
}
// The Merge and Artboard networks no longer pass their content through a Monitor node, since thumbnails are found from the layers themselves.
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: rebuilding the network orphans its child paths.
let monitored_layers: Vec<(NodeId, Vec<NodeId>, DefinitionIdentifier)> = document
@@ -1381,8 +1408,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
let reference = document.network_interface.reference(node_id, &path)?;
let is_merge_or_artboard = [DefinitionIdentifier::Network("Merge".into()), DefinitionIdentifier::Network("Artboard".into())].contains(&reference);
let monitor = DocumentNodeImplementation::ProtoNode(graphene_std::memo::monitor::IDENTIFIER);
let has_monitor = network.nodes.values().any(|inner_node| inner_node.implementation == monitor);
let has_monitor = network.nodes.values().any(|inner_node| is_monitor(&inner_node.implementation));
(is_merge_or_artboard && has_monitor).then_some((*node_id, path, reference))
})
@@ -1392,6 +1418,23 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
document.network_interface.replace_implementation(node_id, network_path, &mut definition.default_node_template());
}
// Any Monitor still left becomes a Passthrough of its content, once the passes above have used it to recognize old networks
let monitors: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter(|(_, node, _)| is_monitor(&node.implementation))
.map(|(node_id, _, path)| (*node_id, path))
.collect();
for (node_id, network_path) in &monitors {
let mut passthrough = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER),
..Default::default()
};
document.network_interface.replace_implementation(node_id, network_path, &mut passthrough);
document.network_interface.set_call_argument(node_id, network_path, passthrough.call_argument);
}
// The old "Math" node evaluated an expression over "A" and "B". A lexable static expression not reading a wired `B` becomes "Math Function"
// with `A` as `x` and a constant `B` inlined. Anything else becomes "Extend" feeding "Math Formula", which reads the pair as `a` and `b`.
let math_nodes: Vec<(NodeId, Vec<NodeId>, Vec<NodeInput>)> = document
@@ -1867,6 +1910,9 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
// Last, so the rest of the graph is upgraded enough to compile when each Copy to Points node's content type is resolved
migrate_copy_to_points_nodes(document);
// After the upgrades that add or rewire nodes, so the nodes they place are converted too
document.network_interface.convert_positions_to_relative();
// Bringing an old document up to date is not a set of edits on it, it is how the document arrives.
// The upgrades run through the ordinary mutators, so the store records them; dropping what they
// recorded leaves the opened document as the baseline rather than as a pile of changes to itself.
@@ -3463,7 +3509,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
// SVG-import legacy Path nodes baked their geometry at non-exposed input 0; move it to input 1 (the modern slot for VectorModification).
// For exposed input 0, any baked value is unused at runtime, so just reset it.
if reference == DefinitionIdentifier::Network("Path".into()) {
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER) {
let input_0 = node.inputs.first()?;
if let NodeInput::Value { tagged_value, exposed } = input_0
&& let TaggedValue::VectorModification(modification) = &**tagged_value
@@ -4918,7 +4964,7 @@ mod tests {
let content = std::mem::replace(&mut extend.inputs[1], NodeInput::node(monitor_id, 0));
let monitor_template = NodeTemplate {
inputs: vec![content],
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::memo::monitor::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(MONITOR_IDENTIFIER),
..Default::default()
};
network_template.nodes.insert(monitor_id, monitor_template);
@@ -4933,14 +4979,34 @@ mod tests {
else {
panic!("{name} should stay a network node")
};
let monitor = DocumentNodeImplementation::ProtoNode(graphene_std::memo::monitor::IDENTIFIER);
assert!(
network.nodes.values().all(|inner_node| inner_node.implementation != monitor),
"{name} should no longer have a Monitor node"
);
// A Monitor left in place would become a Passthrough, so only the rebuilt network has the definition's node count
let NodeTemplateImplementation::Network(shipped) = resolve_network_node_type(name).expect("The definition should exist").default_node_template().implementation else {
panic!("{name} should be a network node")
};
assert_eq!(network.nodes.len(), shipped.nodes.len(), "{name} should be rebuilt from its definition, without the Monitor node");
}
}
// The removed Monitor node keeps passing on its content wherever it's left
#[test]
fn a_monitor_node_becomes_a_passthrough() {
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
let content = NodeInput::value(TaggedValue::Number(42.), false);
let monitor_template = NodeTemplate {
inputs: vec![content.clone()],
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::memo::MonitorNode<_, _, _>")),
..Default::default()
};
document.network_interface.insert_node(node_id, monitor_template, &[]);
migrate(&mut document);
let node = &document.network_interface.document_network().nodes[&node_id];
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
assert_eq!(node.inputs, [content]);
}
// Regex Find's Match Index is now an integer, so an old instance rounds its stored F64 index and rebuilds the subgraph
// that fed the decimal index to its two item-at-index nodes
#[test]
@@ -78,7 +78,7 @@ impl EditTarget {
/// The Path node, which vector edits insert beside a layer with vector content when it's missing.
pub fn path() -> Self {
Self::network_node("Path", Insertion::BesideVectorLayer)
Self::proto_node(graphene_std::vector::path::IDENTIFIER, Insertion::BesideVectorLayer)
}
/// The Fill node, which paint edits insert under any Stroke node beside a layer with vector content when it's missing.
@@ -23,7 +23,11 @@ pub fn find_spline(document: &DocumentMessageHandler, layer: LayerNodeIdentifier
.network_interface
.upstream_flow_back_from_nodes([layer.to_node()].to_vec(), &[], FlowType::HorizontalFlow)
.map(|node_id| (document.network_interface.reference(&node_id, &[]), node_id))
.take_while(|(reference, _)| reference.as_ref().is_some_and(|node_ref| node_ref != &DefinitionIdentifier::Network("Path".into())))
.take_while(|(reference, _)| {
reference
.as_ref()
.is_some_and(|node_ref| node_ref != &DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER))
})
.find(|(reference, _)| {
reference
.as_ref()
@@ -115,7 +119,7 @@ pub fn merge_layers(document: &DocumentMessageHandler, first_layer: LayerNodeIde
// Add a path node after the combine paths node
let path_node_id = NodeId::new();
let path_node = document_node_definitions::resolve_network_node_type("Path")
let path_node = document_node_definitions::resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER)
.expect("Failed to create path node")
.default_node_template();
responses.add(NodeGraphMessage::InsertNode {
@@ -76,8 +76,8 @@ mod test_ellipse {
let node_graph_layer = NodeGraphLayer::new(layer, &document.network_interface);
let ellipse_node = node_graph_layer.upstream_node_id_from_protonode(ellipse::IDENTIFIER)?;
Some(ResolvedEllipse {
radius_x: instrumented.grab_ranked_input::<ellipse::RadiusXInput, f64>(&vec![ellipse_node], &editor.runtime).unwrap(),
radius_y: instrumented.grab_ranked_input::<ellipse::RadiusYInput, f64>(&vec![ellipse_node], &editor.runtime).unwrap(),
radius_x: instrumented.grab_ranked_input::<ellipse::RadiusXInput, f64>(&[ellipse_node], &editor.runtime).unwrap(),
radius_y: instrumented.grab_ranked_input::<ellipse::RadiusYInput, f64>(&[ellipse_node], &editor.runtime).unwrap(),
transform: document.metadata().transform_to_document(layer),
})
})
@@ -635,7 +635,8 @@ pub fn make_path_editable_is_allowed(network_interface: &mut NodeNetworkInterfac
// Must not already have an existing Path node, in the right-most part of the layer chain, which has an empty set of modifications
// (otherwise users could repeatedly keep running this command and stacking up empty Path nodes)
if let Some(TaggedValue::VectorModification(modifications)) = NodeGraphLayer::new(first_layer, network_interface).find_input(&DefinitionIdentifier::Network("Path".into()), 1)
if let Some(TaggedValue::VectorModification(modifications)) =
NodeGraphLayer::new(first_layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER), 1)
&& modifications.is_empty()
{
return None;
@@ -280,18 +280,25 @@ fn whole_expanse_rect(layer: LayerNodeIdentifier, document: &DocumentMessageHand
#[cfg(test)]
mod test_fill {
pub use crate::test_utils::test_prelude::*;
use graphene_std::Graphic;
use graphene_std::color::SRGBA8;
use graphene_std::list::Item;
use graphene_std::vector::fill;
// The Fill tool writes solid colors, whose stored values the input monitor records as `Item<Color>` wires
// The Fill tool writes solid colors, which reach the paint input embedded as `Graphic` items
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Item<Color>> {
let instrumented = match editor.eval_graph_until_finished().await {
Ok(instrumented) => instrumented,
Err(e) => panic!("Failed to evaluate graph: {e}"),
};
instrumented.grab_all_input::<fill::PaintInput, Item<Color>>(&editor.runtime).collect()
instrumented
.grab_all_input::<fill::PaintInput, Item<Graphic>>(&editor.runtime)
.filter_map(|paint| match paint.into_element() {
Graphic::Color(color) => Some(color),
_ => None,
})
.collect()
}
#[tokio::test]
@@ -1,6 +1,6 @@
use super::tool_prelude::*;
use crate::consts::SNAP_POINT_TOLERANCE;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::overlays::utility_functions::open_path_endpoint_overlays;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -312,7 +312,7 @@ impl Fsm for FreehandToolFsmState {
let parent = document.new_layer_bounding_artboard(input, viewport);
let node_type = resolve_network_node_type("Path").expect("Path node does not exist");
let node_type = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER).expect("Path node does not exist");
let node = node_type.default_node_template();
let nodes = vec![(NodeId(0), node)];
@@ -454,7 +454,7 @@ mod test_freehand {
.filter_map(|layer| {
let graph_layer = NodeGraphLayer::new(layer, &document.network_interface);
// Only get layers with path nodes
let _ = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))?;
let _ = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER))?;
let vector = document.network_interface.compute_modified_vector(layer)?;
let transform = document.metadata().transform_to_viewport(layer);
@@ -6,7 +6,7 @@ use crate::consts::{
};
use crate::messages::input_mapper::utility_types::macros::action_shortcut_manual;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::overlays::utility_functions::{path_overlays, selected_segments};
use crate::messages::portfolio::document::overlays::utility_types::{DrawHandles, OverlayContext};
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
@@ -2859,7 +2859,7 @@ impl Fsm for PathToolFsmState {
let layer = if shape_editor.selected_shape_state.contains_key(&layer) {
layer
} else {
let Some(node_type) = resolve_network_node_type("Path") else {
let Some(node_type) = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER) else {
error!("Could not resolve node type for Path");
continue;
};
@@ -1,7 +1,7 @@
use super::tool_prelude::*;
use crate::consts::{COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_05, HIDE_HANDLE_DISTANCE, SEGMENT_OVERLAY_SIZE};
use crate::messages::input_mapper::utility_types::pointer::MouseKeys;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::overlays::utility_functions::path_overlays;
use crate::messages::portfolio::document::overlays::utility_types::{DrawHandles, OverlayContext};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -1434,7 +1434,7 @@ impl PenToolData {
}
// New path layer
let node_type = resolve_network_node_type("Path").expect("Path node does not exist");
let node_type = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER).expect("Path node does not exist");
let nodes = vec![(NodeId(0), node_type.default_node_template())];
let parent = document.new_layer_bounding_artboard(input, viewport);
@@ -2526,7 +2526,7 @@ mod test_pen_tool {
/// The single Pen-drawn path layer and its vector, or `None` once the layer has been undone away.
fn drawn_path(editor: &EditorTestUtils) -> Option<(LayerNodeIdentifier, VectorGeometry)> {
let document = editor.active_document();
let path_identifier = DefinitionIdentifier::Network("Path".into());
let path_identifier = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER);
let mut path_layers = document
.metadata()
.all_layers()
@@ -1,7 +1,7 @@
use super::tool_prelude::*;
use crate::consts::{DRAG_THRESHOLD, PATH_JOIN_THRESHOLD, SNAP_POINT_TOLERANCE};
use crate::messages::input_mapper::utility_types::pointer::MouseKeys;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{resolve_network_node_type, resolve_proto_node_type};
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::overlays::utility_functions::open_path_endpoint_overlays;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -442,7 +442,7 @@ impl Fsm for SplineToolFsmState {
let parent = document.new_layer_bounding_artboard(input, viewport);
let path_node_type = resolve_network_node_type("Path").expect("Path node does not exist");
let path_node_type = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER).expect("Path node does not exist");
let path_node = path_node_type.default_node_template();
let spline_node_type = resolve_proto_node_type(graphene_std::vector::spline::IDENTIFIER).expect("Spline node does not exist");
let spline_node = spline_node_type.node_template_input_override([Some(NodeInput::node(NodeId(1), 0))]);
+82 -95
View File
@@ -1,7 +1,8 @@
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus};
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError;
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
@@ -10,12 +11,12 @@ use graph_craft::proto::GraphErrors;
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::color::SRGBA8;
use graphene_std::list::List;
use graphene_std::list::{Item, List};
use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint;
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic};
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use std::any::Any;
use std::sync::Arc;
@@ -38,7 +39,6 @@ pub struct ExecutionResponse {
responses: VecDeque<FrontendMessage>,
/// The layers whose thumbnails the runtime let go of, which it renders anew if they have content to show again.
dropped_thumbnails: Vec<NodeId>,
vector_modify: HashMap<NodeId, VectorGeometry>,
/// The latest result of each observation.
observations: HashMap<ObservationKey, InspectResult>,
}
@@ -48,6 +48,8 @@ pub struct ExecutionResponse {
pub enum ObservationKey {
/// The node the Data panel inspects.
DataPanel,
/// The content of a 'Path' node, which is the geometry the Pen and Path tools edit.
PathContent(NodeId),
// TODO: Eventually remove this document upgrade code
/// The "Fill" node whose geometry a gradient migration measures.
FillMeasurement,
@@ -241,14 +243,14 @@ impl NodeGraphExecutor {
.expect("Failed to send the thumbnails in view");
}
/// Updates the network to monitor all inputs. Useful for the testing.
/// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received.
#[cfg(test)]
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
// We should always invalidate the cache.
self.node_graph_hash = crate::application::generate_uuid();
let mut network = document.network_interface.document_network().clone();
network.inline_definitions().map_err(|error| error.to_string())?;
let instrumented = Instrumented::new(&mut network);
let instrumented = Instrumented::new(&network);
let resources = document.resources.registry.clone();
@@ -258,7 +260,7 @@ impl NodeGraphExecutor {
resources,
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
observations: HashMap::new(),
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
Ok(instrumented)
@@ -288,7 +290,7 @@ impl NodeGraphExecutor {
resources,
previewed,
layers,
observations: self.observations(),
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
} else if inspected_node_changed {
@@ -314,8 +316,9 @@ impl NodeGraphExecutor {
}
/// Every observation a graph update of the document starts with.
fn observations(&self) -> HashMap<ObservationKey, Observation> {
self.data_panel_observation().map(|observation| (ObservationKey::DataPanel, observation)).into_iter().collect()
fn observations(&self, network_interface: &NodeNetworkInterface) -> HashMap<ObservationKey, Observation> {
let data_panel = self.data_panel_observation().map(|observation| (ObservationKey::DataPanel, observation));
data_panel.into_iter().chain(path_content_observations(network_interface)).collect()
}
/// Adds an evaluate request for whatever current network is cached.
@@ -483,7 +486,7 @@ impl NodeGraphExecutor {
resources,
previewed,
layers: document.network_interface.layer_paths(),
observations: self.observations(),
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
let execution_id = self.queue_execution(render_config);
@@ -518,7 +521,6 @@ impl NodeGraphExecutor {
result,
responses: existing_responses,
dropped_thumbnails,
vector_modify,
mut observations,
} = *execution_response;
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
@@ -645,7 +647,7 @@ impl NodeGraphExecutor {
None => responses.add(response),
}
}
document.network_interface.update_vector_modify(vector_modify);
document.network_interface.update_vector_modify(path_contents(&observations));
match (node_graph_output, execution_context.export_config) {
(Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses),
@@ -1179,125 +1181,110 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
None
}
fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
path_nodes.into_iter().filter_map(|node_path| {
let key = ObservationKey::PathContent(*node_path.last()?);
let observation = Observation {
node_path,
connector: ObservedConnector::Input(path::ContentInput::INDEX),
overrides: ContextOverrides::default(),
};
Some((key, observation))
})
}
/// The incoming geometry of each 'Path' node, read from its observed content.
fn path_contents(observations: &HashMap<ObservationKey, InspectResult>) -> HashMap<NodeId, VectorGeometry> {
observations
.iter()
.filter_map(|(key, result)| {
let ObservationKey::PathContent(path_node) = *key else { return None };
let value = result.data.as_ref()?;
let geometry = match value.downcast_ref::<List<Vector>>() {
Some(list) => VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()),
None => VectorGeometry::from_item(value.downcast_ref::<Item<Vector>>()?),
};
Some((path_node, geometry))
})
.collect()
}
// Re-export for usage by tests in other modules
#[cfg(test)]
pub use test::Instrumented;
#[cfg(test)]
mod test {
use std::sync::Arc;
use super::*;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::test_utils::test_prelude::{self, NodeGraphLayer};
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::{DocumentNode, NodeNetwork};
use graphene_std::Context;
use graph_craft::document::NodeNetwork;
use graphene_std::NodeParameter;
use graphene_std::list::Item;
use graphene_std::memo::IORecord;
use test_prelude::LayerNodeIdentifier;
/// Stores all of the monitor nodes that have been attached to a graph
/// The path of each proto node in an evaluated graph, by which tests read the values its inputs received.
#[derive(Default)]
pub struct Instrumented {
protonodes_by_name: HashMap<ProtoNodeIdentifier, Vec<Vec<Vec<NodeId>>>>,
protonodes_by_path: HashMap<Vec<NodeId>, Vec<Vec<NodeId>>>,
protonodes_by_name: HashMap<ProtoNodeIdentifier, Vec<Vec<NodeId>>>,
}
impl Instrumented {
/// Adds montior nodes to the network
fn add(&mut self, network: &mut NodeNetwork, path: &mut Vec<NodeId>) {
// Required to do seperately to satiate the borrow checker.
let mut monitor_nodes = Vec::new();
for (id, node) in network.nodes.iter_mut() {
// Recursively instrument
if let DocumentNodeImplementation::Network(nested) = &mut node.implementation {
path.push(*id);
self.add(nested, path);
path.pop();
/// Records the path of each proto node in the network and the networks nested in it.
fn add(&mut self, network: &NodeNetwork, path: &mut Vec<NodeId>) {
for (id, node) in &network.nodes {
path.push(*id);
match &node.implementation {
DocumentNodeImplementation::Network(nested) => self.add(nested, path),
DocumentNodeImplementation::ProtoNode(identifier) => self.protonodes_by_name.entry(identifier.clone()).or_default().push(path.clone()),
_ => {}
}
let mut monitor_node_ids = Vec::with_capacity(node.inputs.len());
for input in &mut node.inputs {
let node_id = NodeId::new();
path.push(node_id);
monitor_node_ids.push(path.clone());
path.pop();
// A None value is a unit wire with nothing to record and no Monitor row, so its slot stays a dead path that introspects as absent
if matches!(input, NodeInput::Value { tagged_value, .. } if matches!(&**tagged_value, graph_craft::document::value::TaggedValue::None)) {
continue;
}
let old_input = std::mem::replace(input, NodeInput::node(node_id, 0));
monitor_nodes.push((old_input, node_id));
}
if let DocumentNodeImplementation::ProtoNode(identifier) = &mut node.implementation {
path.push(*id);
self.protonodes_by_name.entry(identifier.clone()).or_default().push(monitor_node_ids.clone());
self.protonodes_by_path.insert(path.clone(), monitor_node_ids);
path.pop();
}
}
for (input, monitor_id) in monitor_nodes {
let monitor_node = DocumentNode {
inputs: vec![input],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::memo::monitor::IDENTIFIER),
call_argument: graph_craft::generic!(T),
skip_deduplication: true,
..Default::default()
};
network.nodes.insert(monitor_id, monitor_node);
path.pop();
}
}
/// Instrument a graph and return a new [Instrumented] state.
pub fn new(network: &mut NodeNetwork) -> Self {
pub fn new(network: &NodeNetwork) -> Self {
let mut instrumented = Self::default();
instrumented.add(network, &mut Vec::new());
instrumented
}
/// Pulls a concrete output type out of a monitor record, tolerating the three context shapes the executor records against.
fn downcast_record<Output: Send + Sync + Clone + 'static>(dynamic: Arc<dyn std::any::Any + Send + Sync>) -> Option<Output> {
if let Some(x) = dynamic.downcast_ref::<IORecord<(), Output>>() {
Some(x.output.clone())
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Output>>() {
Some(x.output.clone())
} else {
dynamic.downcast_ref::<IORecord<Context, Output>>().map(|x| x.output.clone())
}
/// Reads the value an input of the proto node at this path received, if it has the `Output` type.
/// Only the value types the Data panel can show come through.
fn grab_input<Output: Clone + 'static>(path: &[NodeId], input_index: usize, runtime: &NodeRuntime) -> Option<Output> {
let observation = Observation {
node_path: path.to_vec(),
connector: ObservedConnector::Input(input_index),
overrides: ContextOverrides::default(),
};
runtime.observe(observation)?.downcast_ref::<Output>().cloned()
}
/// Grab all of the values of the input every time it occurs in the graph, downcast to the recorded `Output` type.
/// A record whose type does not match `Output` is skipped, so a wrong `Output` yields an empty iterator rather than an error.
pub fn grab_all_input<'a, Input: NodeParameter + 'a, Output: Send + Sync + Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = Output> + 'a {
/// Grab all of the values of the input every time it occurs in the graph, downcast to the received `Output` type.
/// A value whose type does not match `Output` is skipped, so a wrong `Output` yields an empty iterator rather than an error.
pub fn grab_all_input<'a, Input: NodeParameter + 'a, Output: Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = Output> + 'a {
self.protonodes_by_name
.get(&Input::NODE_IDENTIFIER)
.map_or([].as_slice(), |x| x.as_slice())
.map_or([].as_slice(), |paths| paths.as_slice())
.iter()
.filter_map(|inputs| inputs.get(Input::INDEX))
.filter_map(|input_monitor_node| runtime.executor.introspect(input_monitor_node).ok())
.filter_map(Instrumented::downcast_record::<Output>)
.filter_map(|path| Self::grab_input::<Output>(path, Input::INDEX, runtime))
}
pub fn grab_protonode_input<Input: NodeParameter, Output: Send + Sync + Clone + 'static>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Output> {
let input_monitor_node = self.protonodes_by_path.get(path)?.get(Input::INDEX)?;
let dynamic = runtime.executor.introspect(input_monitor_node).ok()?;
Self::downcast_record::<Output>(dynamic)
pub fn grab_protonode_input<Input: NodeParameter, Output: Clone + 'static>(&self, path: &[NodeId], runtime: &NodeRuntime) -> Option<Output> {
Self::grab_input::<Output>(path, Input::INDEX, runtime)
}
/// Grabs a ranked input's recorded value as its bare element `Element`.
/// A stored value materializes as an `Item<Element>` wire, so the monitor records the whole cell and this unwraps its element.
pub fn grab_ranked_input<Input: NodeParameter, Element: Send + Sync + Clone + 'static>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Element> {
let input_monitor_node = self.protonodes_by_path.get(path)?.get(Input::INDEX)?;
let dynamic = runtime.executor.introspect(input_monitor_node).ok()?;
Self::downcast_record::<Item<Element>>(dynamic).map(|item| item.into_element())
/// Grabs a ranked input's received value as its bare element `Element`.
/// A stored value materializes as an `Item<Element>` wire, so the input receives the whole cell and this unwraps its element.
pub fn grab_ranked_input<Input: NodeParameter, Element: Clone + 'static>(&self, path: &[NodeId], runtime: &NodeRuntime) -> Option<Element> {
Self::grab_input::<Item<Element>>(path, Input::INDEX, runtime).map(Item::into_element)
}
pub fn grab_input_from_layer<Input: NodeParameter, Output: Send + Sync + Clone + 'static>(
pub fn grab_input_from_layer<Input: NodeParameter, Output: Clone + 'static>(
&self,
layer: LayerNodeIdentifier,
network_interface: &NodeNetworkInterface,
@@ -1305,7 +1292,7 @@ mod test {
) -> Option<Output> {
let node_graph_layer = NodeGraphLayer::new(layer, network_interface);
let node = node_graph_layer.upstream_node_id_from_protonode(Input::NODE_IDENTIFIER)?;
self.grab_protonode_input::<Input, Output>(&vec![node], runtime)
self.grab_protonode_input::<Input, Output>(&[node], runtime)
}
}
}
@@ -19,7 +19,7 @@ async fn compile_and_run(editor: &mut EditorTestUtils) {
}
/// The proto node IDs compiled for the document node paths that pass `keep`. The executor keeps the nodes an update drops
/// for one more update, so a first update clears those of the test harness's instrumented graph.
/// for one more update, so a first update clears those of the graph before it.
async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> {
compile_and_run(editor).await;
compile_and_run(editor).await;
+11 -65
View File
@@ -11,15 +11,12 @@ use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler};
use graph_craft::proto::GraphErrors;
use graphene_hash::CacheHash;
use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture};
use graphene_std::list::{Item, List};
use graphene_std::memo::IORecord;
use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
use graphene_std::raster_types::Raster;
use graphene_std::runtime::AsyncRuntime;
use graphene_std::vector::style::RenderMode;
use graphene_std::vector::{Vector, VectorGeometry, paths_from_list_row_attributes};
use graphene_std::{Context, NodeError, Poll};
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::util::wrap_network_in_scope;
@@ -57,7 +54,6 @@ pub struct NodeRuntime {
resources: ResourceRegistry,
node_graph_errors: GraphErrors,
node_graph_warnings: GraphErrors,
monitor_nodes: Vec<(Vec<NodeId>, NodeId)>,
thumbnails: Thumbnails,
observer: Observer<ObservationKey>,
/// Whether an observation changed since its results were last sent.
@@ -65,9 +61,6 @@ pub struct NodeRuntime {
preprocessor: preprocessor::Preprocessor,
vector_modify: HashMap<NodeId, VectorGeometry>,
vector_evaluations: HashMap<NodeId, (NodeId, u64)>,
/// Cached surface for Wasm viewport rendering (reused across frames)
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
wasm_canvas_cache: CanvasSurfaceHandle,
@@ -155,15 +148,12 @@ impl NodeRuntime {
node_graph_errors: Vec::new(),
node_graph_warnings: Vec::new(),
monitor_nodes: Vec::new(),
thumbnails: Thumbnails::new(),
observer: Observer::default(),
observations_changed: false,
preprocessor: preprocessor::Preprocessor::new(),
vector_modify: Default::default(),
vector_evaluations: Default::default(),
#[cfg(all(target_family = "wasm", feature = "gpu"))]
wasm_canvas_cache: CanvasSurfaceHandle::new(),
#[cfg(all(target_family = "wasm", feature = "gpu"))]
@@ -376,7 +366,6 @@ impl NodeRuntime {
result: ExecutionResult::Panic(payload),
responses: VecDeque::new(),
dropped_thumbnails: Vec::new(),
vector_modify: HashMap::new(),
observations: HashMap::new(),
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
@@ -388,7 +377,7 @@ impl NodeRuntime {
async fn respond(&mut self, execution_id: u64, result: ExecutionResult) {
let mut responses = VecDeque::new();
let dropped_thumbnails = self.process_monitor_nodes(&mut responses).await;
let dropped_thumbnails = self.update_thumbnails(&mut responses).await;
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
let response = ExecutionResponse {
@@ -396,12 +385,19 @@ impl NodeRuntime {
result,
responses,
dropped_thumbnails,
vector_modify: self.vector_modify.clone(),
observations,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
}
/// Reads one observation from the last evaluation, apart from the observations the runtime keeps.
#[cfg(test)]
pub(crate) fn observe(&self, observation: Observation) -> Option<ObservedValue> {
let mut observer = Observer::default();
observer.set((), Some(observation));
observer.evaluate(&self.executor, self.old_graph.as_ref()).remove(&())?.data
}
async fn read_back(&self, texture: Texture) -> Raster<CPU> {
let application_io = self.editor_api.application_io.as_ref().unwrap();
let executor = application_io.gpu_executor().expect("GPU executor should be available when we receive a texture");
@@ -429,12 +425,6 @@ impl NodeRuntime {
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
};
self.node_graph_warnings = warnings;
self.monitor_nodes = proto_network
.nodes
.iter()
.filter(|(_, node)| node.identifier == graphene_std::memo::monitor::IDENTIFIER)
.map(|(id, node)| (node.original_location.path.clone().unwrap_or_default(), *id))
.collect();
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
let result = self.executor.update(proto_network).map_err(|(types, e)| {
@@ -465,41 +455,9 @@ impl NodeRuntime {
EvaluationErrors(errors.into())
}
/// Updates state data, giving back the layers whose thumbnails were dropped because they no longer have content to show.
async fn process_monitor_nodes(&mut self, responses: &mut VecDeque<FrontendMessage>) -> Vec<NodeId> {
/// Renders the stale thumbnails, giving back the layers whose thumbnails were dropped because they no longer have content to show.
async fn update_thumbnails(&mut self, responses: &mut VecDeque<FrontendMessage>) -> Vec<NodeId> {
let dropped_thumbnails = self.thumbnails.drop_sourceless();
for (monitor_node_path, _) in &self.monitor_nodes {
let Some(parent_network_node_id) = monitor_parent_node(monitor_node_path) else {
warn!("Monitor node has invalid node id");
continue;
};
if !records_vector(&self.executor, monitor_node_path) {
continue;
}
let tree = self.executor.tree();
let Ok(content_node) = tree.input_node(monitor_node_path, 0) else { continue };
let Ok(Some(context)) = tree.last_context(content_node) else { continue };
let context_hash = context_hash(&context);
if self.vector_evaluations.get(&parent_network_node_id) == Some(&(content_node, context_hash)) {
continue;
}
let Some(output) = tree.evaluate(content_node, &context).ok().and_then(evaluated_output) else {
continue;
};
let geometry = if let Some(list) = output.downcast_ref::<List<Vector>>() {
VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default())
} else if let Some(item) = output.downcast_ref::<Item<Vector>>() {
VectorGeometry::from_item(item)
} else {
continue;
};
self.vector_modify.insert(parent_network_node_id, geometry);
self.vector_evaluations.insert(parent_network_node_id, (content_node, context_hash));
}
self.thumbnails.render_stale(&self.executor, &self.editor_api, responses).await;
dropped_thumbnails
@@ -514,18 +472,6 @@ impl ExecutionResult {
}
}
/// The layer a monitor node belongs to, since monitor nodes sit within the network of the document node they monitor.
fn monitor_parent_node(monitor_node_path: &[NodeId]) -> Option<NodeId> {
monitor_node_path.len().checked_sub(2).and_then(|index| monitor_node_path.get(index)).copied()
}
fn records_vector(executor: &DynamicExecutor, monitor_node_path: &[NodeId]) -> bool {
// TODO: Tell this from the monitor node's type once the types the borrow tree records can be compared with concrete ones
executor
.introspect(monitor_node_path)
.is_ok_and(|data| data.is::<IORecord<Context, List<Vector>>>() || data.is::<IORecord<Context, Item<Vector>>>())
}
fn evaluated_output(poll: Poll<graphene_std::registry::Any>) -> Option<graphene_std::registry::Any> {
match poll {
Poll::Final(output) | Poll::Partial(output) => Some(output),
+1 -2
View File
@@ -14,7 +14,6 @@ pub struct DocumentNode {
pub call_argument: Type,
pub implementation: DocumentNodeImplementation,
pub visible: bool,
pub skip_deduplication: bool,
pub compile_metadata: Option<NodeCompileMetadata>,
pub original_location: OriginalLocation,
}
@@ -139,7 +138,7 @@ When the document graph is executed, the following steps occur:
- The constructor functions are run with the `ConstructionArgs` enum. Constructors generally evaluate the result of these inputs, e.g. if you have a `Pi` node that is used as the second input to an `Add` node, the `Add` node's constructor will evaluate the `Pi` node. This is visible if you place a log statement in the `Pi` node's implementation.
- The resolved functions are stored in a `BorrowTree`, which allows previous proto-nodes to be referenced as inputs by later nodes. The `BorrowTree` ensures nodes can't be removed while being referenced by other nodes.
The registry rows for a node declared with the `node` macro are generated by it, one per `#[implementations(...)]` pairing. The rows written by hand in `node_registry.rs` are for the adapters that convert between wire types and for executor-internal nodes such as the memoize and monitor nodes.
The registry rows for a node declared with the `node` macro are generated by it, one per `#[implementations(...)]` pairing. The rows written by hand in `node_registry.rs` are for the adapters that convert between wire types and for executor-internal nodes such as the memoize nodes.
## Debugging
@@ -29,7 +29,7 @@ impl DocumentNode {
}
impl NodeNetwork {
/// Populate the [`DocumentNode::path`], which stores the location of the document node to allow for matching the resulting proto nodes to the document node for the purposes of typing and finding monitor nodes.
/// Populate the [`DocumentNode::path`], which stores the location of the document node to allow for matching the resulting proto nodes to the document node for the purposes of typing and observing node values.
///
/// Table entries are not visited, since each instance gets its paths when [`Self::flatten`] copies the entry.
pub fn generate_node_paths(&mut self, prefix: &[NodeId]) {
@@ -28,7 +28,6 @@ impl DocumentNode {
call_argument: self.call_argument,
construction_args,
original_location: self.original_location,
skip_deduplication: self.skip_deduplication,
compile_metadata: self.compile_metadata.unwrap_or_default(),
upstream_context_features: Default::default(),
}
-7
View File
@@ -44,11 +44,6 @@ pub struct DocumentNode {
/// Represents the eye icon for hiding/showing the node in the graph UI. When hidden, a node gets replaced with a passthrough node during the graph flattening step.
#[serde(default = "return_true")]
pub visible: bool,
/// When two different proto nodes hash to the same value (e.g. two value nodes each containing `2_u32` or two multiply nodes that have the same node IDs as input), the duplicates are removed.
/// See [`ProtoNetwork::generate_stable_node_ids`] for details.
/// However sometimes this is not desirable, for example in the case of a [`graphene_core::memo::MonitorNode`] that needs to be accessed outside of the graph.
#[serde(default)]
pub skip_deduplication: bool,
#[serde(skip)]
pub compile_metadata: Option<NodeCompileMetadata>,
/// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called.
@@ -82,7 +77,6 @@ impl Default for DocumentNode {
call_argument: concrete!(Context),
implementation: Default::default(),
visible: true,
skip_deduplication: Default::default(),
original_location: OriginalLocation::default(),
compile_metadata: Default::default(),
}
@@ -817,7 +811,6 @@ impl core_types::graphene_hash::CacheHash for DocumentNode {
self.call_argument.cache_hash(state);
self.implementation.cache_hash(state);
self.visible.cache_hash(state);
self.skip_deduplication.cache_hash(state);
self.compile_metadata.cache_hash(state);
}
}
@@ -88,11 +88,6 @@ pub struct OldDocumentNode {
pub locked: bool,
/// Metadata about the node including its position in the graph UI. Ensure the click target in the encapsulating network is updated when the node moves by using network.update_click_target(node_id).
pub metadata: OldDocumentNodeMetadata,
/// When two different proto nodes hash to the same value (e.g. two value nodes each containing `2_u32` or two multiply nodes that have the same node IDs as input), the duplicates are removed.
/// See [`ProtoNetwork::generate_stable_node_ids`] for details.
/// However sometimes this is not desirable, for example in the case of a [`graphene_core::memo::MonitorNode`] that needs to be accessed outside of the graph.
#[serde(default)]
pub skip_deduplication: bool,
/// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called.
#[serde(skip)]
pub original_location: OriginalLocation,
-9
View File
@@ -124,7 +124,6 @@ pub struct ProtoNode {
pub call_argument: Type,
pub identifier: ProtoNodeIdentifier,
pub original_location: OriginalLocation,
pub skip_deduplication: bool,
pub(crate) compile_metadata: NodeCompileMetadata,
/// The context features read by this node and everything upstream of it.
pub upstream_context_features: ContextFeatures,
@@ -137,7 +136,6 @@ impl Default for ProtoNode {
construction_args: ConstructionArgs::Value(value::TaggedValue::Integer(0).into()),
call_argument: concrete!(()),
original_location: OriginalLocation::default(),
skip_deduplication: false,
compile_metadata: Default::default(),
upstream_context_features: ContextFeatures::empty(),
}
@@ -146,16 +144,12 @@ impl Default for ProtoNode {
impl ProtoNode {
/// A stable node ID is a hash of a node that should stay constant. This is used in order to remove duplicates from the graph.
/// In the case of `skip_deduplication`, the `document_node_path` is also hashed in order to avoid duplicate monitor nodes from being removed (which would make it impossible to load thumbnails).
pub fn stable_node_id(&self) -> Option<NodeId> {
use std::hash::Hasher;
let mut hasher = rustc_hash::FxHasher::default();
self.identifier.as_str().hash(&mut hasher);
self.construction_args.cache_hash(&mut hasher);
if self.skip_deduplication {
self.original_location.path.hash(&mut hasher);
}
std::mem::discriminant(&self.call_argument).hash(&mut hasher);
self.call_argument.hash(&mut hasher);
@@ -173,7 +167,6 @@ impl ProtoNode {
path: Some(path),
..Default::default()
},
skip_deduplication: false,
compile_metadata: Default::default(),
upstream_context_features: ContextFeatures::empty(),
}
@@ -355,7 +348,6 @@ impl ProtoNetwork {
},
compile_metadata: forwarding,
upstream_context_features: features,
..Default::default()
},
));
@@ -387,7 +379,6 @@ impl ProtoNetwork {
},
compile_metadata: forwarding,
upstream_context_features: features,
..Default::default()
},
));
nullification_node_id
@@ -113,11 +113,6 @@ impl DynamicExecutor {
Ok(ResolvedDocumentNodeTypesDelta { add, remove })
}
/// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path.
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
self.tree.introspect(node_path)
}
pub fn input_type(&self) -> Option<Type> {
self.typing_context.type_of(self.output).map(|node_io| node_io.call_argument.clone())
}
@@ -311,13 +306,6 @@ impl BorrowTree {
self.nodes.insert(id, (node, path, inputs));
}
/// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path.
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
let (node, _path, _) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?;
node.node().serialize().ok_or(IntrospectError::NoData)
}
pub fn get(&self, id: NodeId) -> Option<SharedNodeContainer> {
self.nodes.get(&id).map(|(node, _, _)| node.clone() as SharedNodeContainer)
}
@@ -34,50 +34,6 @@ use std::sync::Arc;
// TODO: turn into hashmap
fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> {
let mut node_types: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
// =============
// MONITOR NODES
// =============
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Artboard>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Graphic>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Vector>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Gradient>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Artboard>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Graphic>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Vector>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Raster<CPU>>]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Gradient>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<TransferCurve>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<String>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<f64>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DAffine2>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Footprint>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DVec2>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<bool>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<BlendMode>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<String>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<NodeIdPath>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<f64>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<DVec2>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<bool>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<DAffine2>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<BlendMode>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientForm>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientSpread>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientSpace>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientHueDirection>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientInterpolation>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<AttributeValueDyn>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => ListDyn]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<graphene_std::brush::Stroke>]),
// Context nullification
#[cfg(feature = "gpu")]
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<Arc<PlatformEditorApi>>, Context => Item<graphene_std::ContextModification>]),
@@ -298,8 +254,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
}};
}
// The single list of value/enum element types that ride ranked wires as framable node parameters.
// Each needs both a rank promotion adapter and a cache chain (memoize/monitor/context),
// so both registrations below are driven from here by callback, which is what keeps a value type from ending up monitorable but not promotable, or vice versa.
// Each needs both a rank promotion adapter and a cache chain (memoize/context),
// so both registrations below are driven from here by callback, which is what keeps a value type from ending up cacheable but not promotable, or vice versa.
macro_rules! ranked_value_types {
($register:ident) => {
$register!(
@@ -354,7 +310,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
)
};
}
// Primary element types (graphical data and scalars) get promotion adapters here; their monitor/memoize rows are the
// Primary element types (graphical data and scalars) get promotion adapters here; their memoize rows are the
// explicit ones near the top of the registry, so they are deliberately absent from the shared value-type list above
node_types.extend(rank_adapter_nodes!(
Vector,
@@ -438,14 +394,12 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
));
#[cfg(feature = "gpu")]
node_types.extend(bundle_adapter_nodes!(Raster<GPU>));
// The memoize + monitor + context-nullification triple for each value type in the shared list above: the compiler wraps
// a ranked connector's broadcast sibling in a Memoize + context-nullification pair, and test instrumentation monitors any wire.
// The memoize + context-nullification pair the compiler wraps a ranked connector's broadcast sibling in, for each value type in the shared list above.
// Node identifiers are passed explicitly since `stringify!` would mangle the path's whitespace through this nested macro.
macro_rules! cache_chain_nodes {
(each: $value:ty) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
async_node!(identifier: graphene_core::memo::memoize::IDENTIFIER, graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => $value]),
async_node!(identifier: graphene_core::memo::monitor::IDENTIFIER, graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => $value]),
async_node!(identifier: graphene_core::context_modification::context_modification::IDENTIFIER, graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => $value, Context => Item<graphene_std::ContextModification>]),
];
entries
@@ -55,11 +55,6 @@ pub trait Node<Input: ?Sized> {
fn node_name(&self) -> &'static str {
std::any::type_name::<Self>()
}
/// Serialize the node which is used for the `introspect` function which can retrieve values from monitor nodes.
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
log::warn!("Node::serialize not implemented for {}", std::any::type_name::<Self>());
None
}
}
mod types;
@@ -107,9 +102,6 @@ impl<I: ?Sized, N: Node<I> + ?Sized> Node<I> for &N {
fn node_name(&self) -> &'static str {
(**self).node_name()
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
}
impl<I: ?Sized, N: Node<I> + ?Sized> Node<I> for Box<N> {
type Output = N::Output;
@@ -120,9 +112,6 @@ impl<I: ?Sized, N: Node<I> + ?Sized> Node<I> for Box<N> {
fn node_name(&self) -> &'static str {
(**self).node_name()
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
}
impl<I: ?Sized, N: Node<I> + ?Sized> Node<I> for std::sync::Arc<N> {
type Output = N::Output;
@@ -133,9 +122,6 @@ impl<I: ?Sized, N: Node<I> + ?Sized> Node<I> for std::sync::Arc<N> {
fn node_name(&self) -> &'static str {
(**self).node_name()
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
}
/// A compile-time symbol naming one parameter of one proto node.
@@ -4,13 +4,6 @@ use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::sync::Arc;
/// Stores both what a node was called with and what it returned.
#[derive(Clone, Debug)]
pub struct IORecord<I, O> {
pub input: I,
pub output: O,
}
#[derive(Clone, Debug)]
pub struct MemoHash<T: CacheHash> {
hash: u64,
@@ -17,10 +17,6 @@ where
fn eval(&self, input: &I) -> Poll<O> {
self.0.eval(input)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
self.0.serialize()
}
}
impl<N: Node<I>, I> TypeNode<N, I, <N as Node<I>>::Output> {
pub fn new(node: N) -> Self {
@@ -76,6 +76,7 @@ pub enum RegistryValueSource {
Default(&'static str),
Scope(&'static str),
SourceId,
NodePath,
}
#[derive(Clone, Debug)]
@@ -350,10 +351,6 @@ where
.unwrap_or_else(|_| panic!("DowncastBothNode wrong output type: expected {} in: \n{}", std::any::type_name::<O>(), self.node.node().node_name()))
})
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
self.node.node().serialize()
}
}
impl<I, O> DowncastBothNode<I, O> {
pub const fn new(node: SharedNodeContainer) -> Self {
@@ -385,10 +382,6 @@ where
.unwrap_or_else(|| panic!("DynAnyNode Input: expected {} in:\n{}", std::any::type_name::<I>(), std::any::type_name::<N>()));
self.node.eval(input).map(|output| Box::new(output) as Any)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
self.node.serialize()
}
}
impl<I, O, N> DynAnyNode<I, O, N> {
pub const fn new(node: N) -> Self {
@@ -683,7 +683,7 @@ fn create_peniko_gradient_brush(gradient_item: ItemRef<'_, Gradient>, multiplied
Some((brush, gradient_to_device))
}
// TODO: Click targets can be removed from the render output, since the vector data is available in the vector modify data from Monitor nodes.
// TODO: Click targets can be removed from the render output, since the vector data is available in the vector modify data the editor observes on 'Path' nodes.
// This will require that the transform for child layers into that layer space be calculated, or it could be returned from the RenderOutput instead of click targets.
#[derive(Debug, Default, Clone, PartialEq, DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
+1 -20
View File
@@ -205,6 +205,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
}
}
ParsedValueSource::SourceId => quote!(RegistryValueSource::SourceId),
ParsedValueSource::NodePath => quote!(RegistryValueSource::NodePath),
_ => quote!(RegistryValueSource::None),
})
.collect();
@@ -523,18 +524,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
quote!(#[derive(Debug, Clone)])
};
// Generate serialize method if serialize attribute is specified
let serialize_impl = if let Some(serialize_fn) = &parsed.attributes.serialize {
let data_field_refs = data_field_names.iter().map(|name| quote!(&self.#name));
quote! {
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
#serialize_fn(#(#data_field_refs),*)
}
}
} else {
quote!()
};
let eval_prelude = quote! {
use #core_types::misc::Clampable;
@@ -646,8 +635,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
let __state = self.slots.resolve(__key, &__runtime, __source, __placeholder, move || async move { #landed_call });
__cell.merge(__state)
}
#serialize_impl
}
} else {
quote! {
@@ -661,8 +648,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
};
#fold
}
#serialize_impl
}
};
@@ -756,8 +741,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
};
__cell.run(__kernel)
}
#serialize_impl
}
});
@@ -831,8 +814,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
};
__cell.run(__kernel)
}
#serialize_impl
}
});
+5 -5
View File
@@ -236,7 +236,7 @@ pub fn derive_destructure_impl(item: TokenStream2) -> syn::Result<TokenStream2>
}
};
// Memoize lets the node's outputs share one evaluation, and Monitor lets the editor inspect the struct
// Memoize lets the node's outputs share one evaluation
let registration_module = format_ident!("_{struct_snake_name}_registration");
let wasm_registration = format_ident!("__node_registry_{}_{}", NODE_ID.fetch_add(1, Ordering::SeqCst), struct_ident);
let registration = quote! {
@@ -246,15 +246,15 @@ pub fn derive_destructure_impl(item: TokenStream2) -> syn::Result<TokenStream2>
use #gcore::ctor::ctor;
#[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = core_types::ctor))]
fn register_memoize_and_monitor() {
#graphene_core::memo::register_memoize_and_monitor::<#struct_ident>();
#graphene_core::memo::register_memoize_and_monitor::<#mapped_ident>();
fn register_memoize() {
#graphene_core::memo::register_memoize::<#struct_ident>();
#graphene_core::memo::register_memoize::<#mapped_ident>();
}
#[cfg(target_family = "wasm")]
#[unsafe(no_mangle)]
extern "C" fn #wasm_registration() {
register_memoize_and_monitor();
register_memoize();
}
}
};
+39 -21
View File
@@ -65,8 +65,6 @@ pub(crate) struct NodeFnAttributes {
pub(crate) inspector_string: Option<LitStr>,
/// whether to `#[cfg]` gate the node implementation, defaults to None
pub(crate) cfg: Option<TokenStream2>,
/// Custom serialization function path (e.g., "my_module::custom_serialize")
pub(crate) serialize: Option<Path>,
pub(crate) flags: NodeFlags,
/// Fn producing an placeholder value used while node evaluation is pending
pub(crate) placeholder: Option<Path>,
@@ -81,6 +79,7 @@ pub enum ParsedValueSource {
Default(TokenStream2),
Scope(Box<Expr>),
SourceId,
NodePath,
}
// #[widget(ParsedWidgetOverride::Hidden)]
@@ -174,10 +173,10 @@ impl ParsedField {
}
}
/// Whether the field is environment rather than an argument: `#[data]` state or a `#[scope]`-injected wire.
/// Whether the field is environment rather than an argument: `#[data]` state, a `#[scope]`-injected wire, or a `#[source_id]` or `#[node_path]` value the compiler fills in.
/// Environment fields never classify the node, never supply the element-wise frame, and broadcast by clone.
pub(crate) fn is_environment(&self) -> bool {
self.is_data_field || matches!(self.ty.value_source(), ParsedValueSource::Scope(_) | ParsedValueSource::SourceId)
self.is_data_field || matches!(self.ty.value_source(), ParsedValueSource::Scope(_) | ParsedValueSource::SourceId | ParsedValueSource::NodePath)
}
}
@@ -440,7 +439,6 @@ impl Parse for NodeFnAttributes {
let mut path = None;
let mut inspector_string = None;
let mut cfg = None;
let mut serialize = None;
let mut flags = NodeFlags::default();
let mut placeholder = None;
let mut version = None;
@@ -543,20 +541,6 @@ impl Parse for NodeFnAttributes {
let meta = meta.require_list()?;
cfg = Some(meta.tokens.clone());
}
// Function name for custom serialization of this node's data. This is only used by the Monitor node.
//
// Example usage:
// #[node_macro::node(..., serialize(my_module::custom_serialize), ...)]
"serialize" => {
let meta = meta.require_list()?;
if serialize.is_some() {
return Err(Error::new_spanned(meta, "Multiple 'serialize' attributes are not allowed"));
}
let parsed_path: Path = meta
.parse_args()
.map_err(|_| Error::new_spanned(meta, "Expected a valid path for 'serialize', e.g., serialize(my_module::custom_serialize)"))?;
serialize = Some(parsed_path);
}
// Instructs the preprocessor to insert a Memoize node after this node in the generated subnetwork,
// caching its output across evaluations with identical inputs.
//
@@ -620,7 +604,7 @@ impl Parse for NodeFnAttributes {
indoc!(
r#"
Unsupported attribute in `node`.
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'serialize', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', 'no_partial', and 'version'.
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', 'no_partial', and 'version'.
Example usage:
#[node_macro::node(..., name("Test Node"), ...)]
"#
@@ -650,7 +634,6 @@ impl Parse for NodeFnAttributes {
path,
inspector_string,
cfg,
serialize,
flags,
placeholder,
version,
@@ -879,6 +862,9 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
// 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();
// Gives a node the path of the document node it was placed as
let node_path = extract_attribute(attrs, "node_path").is_some();
// Validate data field attributes
if is_data_field {
if default_value.is_some() {
@@ -905,6 +891,18 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
if source_id {
return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot have #[source_id] attribute"));
}
if node_path {
return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot have #[node_path] attribute"));
}
}
if source_id && node_path {
return Err(Error::new_spanned(&pat_ident, "Cannot have both `source_id` and `node_path` attributes"));
}
if exposed && (source_id || node_path) {
return Err(Error::new_spanned(
&pat_ident,
"Inputs the compiler fills in (#[source_id] or #[node_path]) cannot be exposed (#[expose]). They aren't set in the graph",
));
}
if exposed && ident.to_string().starts_with('_') {
return Err(Error::new_spanned(
@@ -916,9 +914,11 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
let value_source = match (default_value, scope) {
(Some(_), Some(_)) => return Err(Error::new_spanned(&pat_ident, "Cannot have both `default` and `scope` attributes")),
(Some(_), _) | (_, Some(_)) if source_id => return Err(Error::new_spanned(&pat_ident, "`source_id` cannot have a `default` or `scope` attribute")),
(Some(_), _) | (_, Some(_)) if node_path => return Err(Error::new_spanned(&pat_ident, "`node_path` cannot have a `default` or `scope` attribute")),
(Some(default_value), _) => ParsedValueSource::Default(default_value),
(_, Some(scope)) => ParsedValueSource::Scope(Box::new(scope)),
_ if source_id => ParsedValueSource::SourceId,
_ if node_path => ParsedValueSource::NodePath,
_ => ParsedValueSource::None,
};
@@ -1880,6 +1880,24 @@ mod tests {
parse_node_fn(attr, input).unwrap();
}
#[test]
#[should_panic(expected = "Inputs the compiler fills in (#[source_id] or #[node_path]) cannot be exposed (#[expose])")]
fn test_exposed_node_path() {
let attr = quote!(category("Invalid"));
let input = quote!(
fn invalid_node(
_: impl Ctx,
content: Item<f64>,
#[expose]
#[node_path]
node_path: Item<NodeIdPath>,
) -> Item<f64> {
content
}
);
parse_node_fn(attr, input).unwrap();
}
#[test]
#[should_panic(expected = "Unsupported attribute in `node`")]
fn test_unsupported_attribute() {
+3 -37
View File
@@ -1,7 +1,6 @@
use core_types::graphene_hash::CacheHash;
use core_types::memo::*;
use core_types::registry::{DowncastBothNode, DynAnyNode, NODE_REGISTRY, NodeConstructor, PanicNode, TypeErasedBox};
use core_types::{Context, Interrupt, NodeIO, NodeIOTypes, Poll, WasmNotSend, concrete, fn_type};
use core_types::{Context, NodeIO, NodeIOTypes, Poll, WasmNotSend, concrete, fn_type};
use dyn_any::StaticType;
use std::hash::DefaultHasher;
use std::hash::Hasher;
@@ -36,39 +35,13 @@ fn memoize<I: CacheHash + Clone + Send, T: Clone + WasmNotSend>(input: I, conten
state
}
type MonitorValue<I, T> = Arc<Mutex<Option<Arc<IORecord<I, T>>>>>;
/// The Monitor node is used by the editor to access the data flowing through it.
#[node_macro::node(category(""), path(graphene_core::memo), serialize(serialize_monitor), inspector("monitor_inspector"), skip_impl, forwards_input)]
fn monitor<I: Clone + 'static + Send + Sync, T: Clone + 'static + Send + Sync>(
input: I,
content: impl Node<I, Output = T>,
#[allow(clippy::type_complexity)]
#[data]
io: MonitorValue<I, T>,
) -> Result<T, Interrupt> {
let output = content.eval(input.clone())?;
*io.lock().unwrap() = Some(Arc::new(IORecord { input, output: output.clone() }));
Ok(output)
}
fn serialize_monitor<I: Clone + 'static + Send + Sync, T: Clone + 'static + Send + Sync>(io: &MonitorValue<I, T>) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
let io = io.lock().unwrap();
io.as_ref().map(|output| output.clone() as Arc<dyn std::any::Any + Send + Sync>)
}
/// Registers the Memoize and Monitor implementations for `T`, as `#[derive(node_macro::Destructure)]` does for each multi-output node struct.
pub fn register_memoize_and_monitor<T: Clone + Send + Sync + StaticType<Static: Sized> + 'static>() {
/// Registers the Memoize implementation for `T`, as `#[derive(node_macro::Destructure)]` does for each multi-output node struct.
pub fn register_memoize<T: Clone + Send + Sync + StaticType<Static: Sized> + 'static>() {
let memoize_constructor: NodeConstructor = |mut arguments| {
let node = MemoizeNode::new(DowncastBothNode::<Context, T>::new(arguments.pop().expect("Not enough arguments provided to construct node")));
let any: DynAnyNode<Context, _, _> = DynAnyNode::new(node);
Box::new(any) as TypeErasedBox
};
let monitor_constructor: NodeConstructor = |mut arguments| {
let node = MonitorNode::new(DowncastBothNode::<Context, T>::new(arguments.pop().expect("Not enough arguments provided to construct node")));
let any: DynAnyNode<Context, _, _> = DynAnyNode::new(node);
Box::new(any) as TypeErasedBox
};
let memoize_types: NodeIOTypes = {
let node = MemoizeNode::new(PanicNode::<Context, T>::new());
@@ -76,16 +49,9 @@ pub fn register_memoize_and_monitor<T: Clone + Send + Sync + StaticType<Static:
node_io.call_argument = concrete!(<Context as StaticType>::Static);
node_io
};
let monitor_types: NodeIOTypes = {
let node = MonitorNode::new(PanicNode::<Context, T>::new());
let mut node_io = NodeIO::<Context>::to_node_io(&node, vec![fn_type!(Context, T)]);
node_io.call_argument = concrete!(<Context as StaticType>::Static);
node_io
};
let mut registry = NODE_REGISTRY.lock().unwrap();
registry.entry(memoize::IDENTIFIER).or_default().push((memoize_constructor, memoize_types));
registry.entry(monitor::IDENTIFIER).or_default().push((monitor_constructor, monitor_types));
}
#[cfg(test)]
+2 -2
View File
@@ -1058,12 +1058,12 @@ fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: Item<bool
pub fn flatten_vector(_: impl Ctx, content: List<Graphic>) -> List<Vector> {
let mut output: List<Vector> = content.clone().into_flattened_list();
// TODO: Replace this snapshot hack with per-layer metadata driven by each layer's Monitor node.
// TODO: Replace this snapshot hack with per-layer metadata driven by observing each layer's content.
// TODO: Flattening here erases the upstream `List<Graphic>` hierarchy that editor metadata collection walks
// TODO: to populate `upstream_footprints` / `local_transforms` / `click_targets` per child layer. As a workaround
// TODO: we stash the pre-flattened list on the output so `List<Vector>::collect_metadata` can recurse into it,
// TODO: which conflates render output with editor metadata and forces the pre-compensation dance below.
// TODO: The cleaner fix is to drive each layer's metadata from its own Monitor's captured `(Context, List<Graphic>)`,
// TODO: The cleaner fix is to drive each layer's metadata from an observation of its `List<Graphic>` content and context,
// TODO: at which point this attribute (and the equivalents in Boolean Operation, Solidify Stroke, Combine Paths,
// TODO: Morph, Rasterize) become unnecessary.
if !output.is_empty() && !is_lone_anonymous_leaf(&content) {
@@ -1,16 +1,22 @@
use core_types::list::{ATTR_GEOMETRY_CACHE, Item, List, NodeIdPath};
use core_types::list::{ATTR_GEOMETRY_CACHE, Item, NodeIdPath};
use core_types::transform::BakeTransform;
use core_types::uuid::NodeId;
use core_types::{ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_TRANSFORM, Ctx};
use glam::{DAffine2, DVec2};
use graphic_types::Vector;
use vector_types::kurbo::BezPath;
use vector_types::vector::{GeometryCache, VectorModification, edit_item_geometry, ensure_paths_attribute, shared_paths_from_item_attributes};
/// Applies a differential modification to a vector path, associating changes made by the Pen and Path tools to indices of edited points and segments.
#[node_macro::node(category(""), memoize)]
fn path_modify(_ctx: impl Ctx, vector: Item<Vector>, modification: Item<Box<VectorModification>>, node_path: Item<NodeIdPath>) -> Item<Vector> {
let mut vector = vector;
/// Holds the edits made with the Pen and Path tools, applying them to the incoming shape.
#[node_macro::node(category("Vector: Geometry"), icon("NodePath"), memoize, version(2))]
fn path(
_ctx: impl Ctx,
/// The original shape that edits made with the Pen and Path tools are applied to.
content: Item<Vector>,
/// The edits made with the Pen and Path tools, stored as changes to points and segments.
modification: Item<Box<VectorModification>>,
#[node_path] node_path: Item<NodeIdPath>,
) -> Item<Vector> {
let mut vector = content;
let modification = modification.into_element();
// Moving points leaves the paths as they are, so they stay shared with the incoming geometry instead of being copied
@@ -39,16 +45,10 @@ fn path_modify(_ctx: impl Ctx, vector: Item<Vector>, modification: Item<Box<Vect
// Drop the stale click-target override so hit testing uses the geometry the user is now editing
vector.remove_attribute::<BezPath>(ATTR_EDITOR_CLICK_TARGET);
// Set the path to the encapsulating subgraph (drop our own trailing entry from `node_path`),
// matching the `path_of_subgraph` proto so editor tools can route data back to the parent layer.
let node_path = node_path.into_element().0;
let subgraph_path: List<NodeId> = {
let len = node_path.len();
node_path.into_iter().take(len.saturating_sub(1)).collect()
};
let existing = vector.attribute_cloned_or_default::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH).0;
let layer_path = if existing.is_empty() { subgraph_path } else { existing };
vector.set_attribute(ATTR_EDITOR_LAYER_PATH, NodeIdPath(layer_path));
// Trace a vector no layer has claimed back to this node for the editor's tools
if vector.attribute_cloned_or_default::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH).0.is_empty() {
vector.set_attribute(ATTR_EDITOR_LAYER_PATH, node_path.into_element());
}
vector
}
@@ -67,7 +67,7 @@ fn bake_transform<T: BakeTransform + Send + 'static>(_ctx: impl Ctx, #[implement
#[cfg(test)]
mod tests {
use super::*;
use core_types::list::{ATTR_ID, ATTR_PATHS};
use core_types::list::{ATTR_ID, ATTR_PATHS, List};
use vector_types::vector::{CurveType, PointId, SegmentId, VectorModificationType, paths_from_item_attributes, push_path};
// A lone loop fills by its contour alone, so it keeps the direction it was drawn in even when that winds backwards
@@ -81,7 +81,7 @@ mod tests {
bezpath.close_path();
let drawn = Vector::item_from_bezpath(&bezpath);
let modified = path_modify((), drawn.clone(), Item::default(), Item::default());
let modified = path((), drawn.clone(), Item::default(), Item::default());
assert_eq!(paths_from_item_attributes(&modified), paths_from_item_attributes(&drawn));
}
@@ -106,7 +106,7 @@ mod tests {
let mut modification = VectorModification::default();
modification.modify(&VectorModificationType::ApplyPointDelta { point: hub, delta: DVec2::X });
let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default());
let modified = path((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default());
let first_path = |item: &Item<Vector>| paths_from_item_attributes(item).unwrap().element(0).unwrap().0.iter_element_values().copied().collect::<Vec<_>>();
assert_eq!(first_path(&drawn), [0, 1, 2, 3, 0]);
@@ -125,7 +125,7 @@ mod tests {
let mut modification = VectorModification::default();
modification.modify(&VectorModificationType::ApplyPointDelta { point: corner, delta: DVec2::X });
let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default());
let modified = path((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default());
assert_eq!(modified.element().0.element(1), Some(&DVec2::new(11., 0.)));
assert!(std::ptr::eq(paths_from_item_attributes(&drawn).unwrap(), paths_from_item_attributes(&modified).unwrap()));
@@ -149,7 +149,7 @@ mod tests {
});
for modification in [VectorModification::default(), adds_a_point] {
let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default());
let modified = path((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default());
assert_eq!(paths_from_item_attributes(&modified).map(List::len), Some(0));
assert_eq!(
+2 -3
View File
@@ -315,7 +315,6 @@ impl Preprocessor {
call_argument: input_type.clone(),
implementation: DocumentNodeImplementation::ProtoNode(id.clone()),
visible: true,
skip_deduplication: false,
..Default::default()
};
@@ -371,7 +370,6 @@ impl Preprocessor {
generated: true,
}),
visible: true,
skip_deduplication: false,
..Default::default()
};
@@ -426,6 +424,7 @@ pub fn node_inputs(fields: &[registry::FieldMetadata], first_node_io: &NodeIOTyp
}
RegistryValueSource::Scope(data) => return NodeInput::scope(*data),
RegistryValueSource::SourceId => return NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
RegistryValueSource::NodePath => return NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath),
};
// A ranked `Item<T>` type prefers a bare `T` value (promoted at resolution), since bare values drive the Inspector widgets
@@ -861,7 +860,7 @@ mod tests {
assert_eq!(info.constant_inputs.count_ones(), 1, "{identifier:?} should only require its name to be constant");
}
for identifier in [graphene_core::memo::memoize::IDENTIFIER, graphene_core::memo::monitor::IDENTIFIER, ops::passthrough::IDENTIFIER] {
for identifier in [graphene_core::memo::memoize::IDENTIFIER, ops::passthrough::IDENTIFIER] {
assert!(compile_metadata(&identifier).forwards_input, "{identifier:?} should forward its input");
}
}
@@ -74,10 +74,13 @@ The function runs once per **anchor**: a node of the source declaration. The run
| `&mut Inputs` | the anchor's input slots | `set`, `insert`, `push`, `remove`, `truncate` |
| `&mut Upstream` | new and existing nodes upstream of the anchor | `add_node`, `add_node_keyed`, `remove_node` |
| `&mut Downstream` | the slots and exports reading the anchor's outputs, plus new downstream nodes | `consumers`, `add_node`, `add_node_keyed`, `connect` |
| `&mut Attributes` | attributes of the anchor and of the nodes the run adds | `set`, `remove` |
| `&mut Resources` | document resources | `add_embedded` |
`Inputs` operations apply in order to the target layout being built. `node.inputs()` is always the source layout. Reads through a mutable view (such as `Downstream::consumers`) also see the source state, so nodes added by the migration never appear among the anchor's consumers.
The runner places added nodes from the anchor's own position. Nodes leading up to the anchor's chain input form a row, or join the chain when the anchor is chained or a layer. Each other node gets a `Position::Relative` offset, which places it below and left of the nodes reading it wherever they are drawn, so it needs no coordinates of the anchor. A migration overrides these positions, or clears a stored name that no longer fits the anchor, through `Attributes`.
A migration addresses declarations with `decl!`, values with a frozen mirror of the value variants it uses, and connections with plain connector types:
```rust
@@ -538,7 +541,7 @@ document/migrations/
- **Input attributes of inserted nodes.** `NewNode` takes bare `NodeInput`s, so inserted nodes start with empty per-input attributes. Taking `InputSlot`s would let a migration carry them over.
- **Removal safety.** `Upstream::remove_node` is only correct when nothing else reads the removed node, which the region system can't check.
- **`unrepresentable` in CI.** Whether reaching it in the commutation test fails CI outright.
- **Layout.** Whether migrations may write node positions and chain placement, or leave inserted nodes to a host-side layout pass.
- **Layout.** Migrations write positions of the nodes they add but can't move existing nodes, so an inserted node can overlap what sits upstream. Storing every node's position relative to its consumers, as `Position::Relative` does for the nodes migrations add, would move the upstream without writing it.
- **Multiple pending migrations.** Whether consecutive pending node migrations run as separate rewrite passes or are fused into one replay.
- **Migrations reading a subgraph.** A migration that inspects an instance's inner nodes depends on their versions, which change independently of the definition's. The planned answer is a cascading bump: the API dump lists a definition's inner `identifier@version`s, so bumping an inner node also requires bumping every definition containing it, and pins order that node's migrations around the definition's. Nothing reads a subgraph yet, so neither a read view for it nor the cascading bump exists.
- **Detaching.** Whether a migration may clear an edited instance's reference, keeping it as a custom subgraph, instead of collapsing it.
@@ -103,4 +103,3 @@ Since Graphene is fundamentally a programming language, throughout this document
<!-- Guide for implementing a node -->
<!-- The `Node` trait -->
<!-- Generics, type inference, type erasure, and the node registry -->
<!-- Monitor nodes -->
@@ -84,13 +84,16 @@ You ask for what you need through the function's parameters, in any order. The f
| `&Node` | The anchor before migration | `id()`, `inputs()`, and the stored node's other accessors |
| `&Graph` | The anchor's network before migration | `node(id)`, `declaration(id)`, `consumers(output)` |
| `Option<&dyn Compiler>` | What only the compiler can tell about the state before migration, see [Asking the compiler](#asking-the-compiler) | `input_type(node, slot)` |
| `&mut Inputs` | The anchor's input slots | `set`, `insert`, `push`, `remove`, `truncate`, `len` |
| `&mut Inputs` | The anchor's input slots | `set`, `insert`, `push`, `push_reflection`, `remove`, `truncate`, `len` |
| `&mut Upstream` | Nodes feeding the anchor | `add_node`, `add_node_keyed`, `remove_node` |
| `&mut Downstream` | Whatever reads the anchor's outputs | `consumers`, `add_node`, `add_node_keyed`, `connect` |
| `&mut Target` | Which declaration the anchor becomes, see [Choosing a target](#choosing-a-target) | `set` |
| `&mut Attributes` | Attributes of the anchor and of the nodes you add, see [Placing and naming nodes](#placing-and-naming-nodes) | `set`, `remove` |
Reads always see the old document. `node.inputs()` returns the old layout however many edits you've made, and nodes you add never show up in `consumers`. `Inputs` edits apply in order to the layout being built. After `inputs.insert(1, ...)`, later `Inputs` calls see the old slot 1 as slot 2. `node.inputs()[1]` is still the old slot 1.
An input the compiler fills in, like a node's own path, is added with `inputs.push_reflection(...)`, which takes a frozen mirror of the `DocumentNodeMetadata` variant it reflects.
### Values
A migration has to keep working after the code around it changes, so it can't use live types like `TaggedValue`. Declare an enum with only the variants you read or write, named the same as in `TaggedValue`:
@@ -202,6 +205,18 @@ pub fn vary_from_style(node: &Node, target: &mut Target) {
A wire written to a removed node brings that node back, so avoid switching a wire on and off depending on state. Keep the slot reading the same thing, and add nodes downstream of the anchor instead.
### Placing and naming nodes
Nodes you add are placed beside the anchor for you. Those leading up to the anchor's primary input form a row to its left, or join its layer's chain, and the others are stored relative to the node they feed, so they sit below it wherever it is drawn. `Attributes::set` writes an attribute of the anchor or of a node this run adds, named by the ID `add_node` returned, and `remove` deletes one. A display name stored as the old node's default would misname the new one, so clear it:
```rust
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Copy to Points") {
attributes.remove(node.id(), DISPLAY_NAME);
}
```
Writing to any other node fails, since another anchor's run may be editing it.
### Network definitions
Some built-in nodes, like Merge and Artboard, are subgraphs. Each instance holds its own copy of a network defined in `document_node_definitions.rs`, and stores the definition's identifier and `version` next to it. Bump `version` on the `DocumentNodeDefinition` when instances saved before your change would load wrongly, and register a migration from the old version with the `network` prefix: