Compare commits

..
106 changed files with 1331 additions and 2828 deletions

No files matched your search

@@ -26,8 +26,8 @@ env:
CARGO_TERM_COLOR: always
# The four benchmarks, built and run by one `cargo bench` call so their slow thin-LTO links happen in parallel
BENCHMARKS: --bench compile_demo_art_gungraun --bench update_executor_gungraun --bench run_once_gungraun --bench run_cached_gungraun
# The brush benchmark, which needs the GPU nodes and so gets its own call rather than changing what the others build
BRUSH_BENCHMARK: -p interpreted-executor --features gpu --bench brush_stroke_gungraun
# The benchmarks in `node-graph/interpreted-executor/benches` that render on the GPU, built with its `gpu` feature in a call of their own so the others build as before
GPU_BENCHMARKS: brush_stroke_gungraun artwork_gungraun
jobs:
profile:
@@ -57,7 +57,7 @@ jobs:
- name: Install lavapipe
run: |
# The runners have no GPU, so the brush benchmark renders on Mesa's software Vulkan device
# The runners have no GPU, so the GPU benchmarks render on Mesa's software Vulkan device
sudo apt-get update
sudo apt-get install -y mesa-vulkan-drivers
# Mesa releases name the ICD with or without the architecture (`lvp_icd.x86_64.json` or `lvp_icd.json`), so ask the package where it put it
@@ -87,10 +87,9 @@ jobs:
run: |
cargo bench $BENCHMARKS -- --save-baseline=master
# Until the brush benchmark reaches master, a baseline commit may predate it
if [ -f node-graph/interpreted-executor/benches/brush_stroke_gungraun.rs ]; then
cargo bench $BRUSH_BENCHMARK -- --save-baseline=master
fi
# A PR adding a GPU benchmark is measured against a baseline commit that predates it
gpu_benchmarks=$(for benchmark in $GPU_BENCHMARKS; do if [ -f "node-graph/interpreted-executor/benches/$benchmark.rs" ]; then echo "--bench $benchmark"; fi; done)
if [ -n "$gpu_benchmarks" ]; then cargo bench -p interpreted-executor --features gpu $gpu_benchmarks -- --save-baseline=master; fi
# Saved before the PR benchmarks run, since they write their own results into the same folder
- name: Save benchmark baseline
@@ -109,23 +108,31 @@ jobs:
# Unlike the default, this sets `pipefail`, so a failed benchmark fails the step rather than leaving its results empty
shell: bash
run: |
# The brush benchmark has nothing to compare against until the baseline commit has it
git cat-file -e HEAD^1:node-graph/interpreted-executor/benches/brush_stroke_gungraun.rs 2>/dev/null && brush=true || brush=false
# A GPU benchmark has nothing to compare against until the baseline commit has it
baselined=$(for benchmark in $GPU_BENCHMARKS; do if git cat-file -e "HEAD^1:node-graph/interpreted-executor/benches/$benchmark.rs" 2>/dev/null; then echo "$benchmark"; fi; done)
gpu_benchmarks=$(for benchmark in $baselined; do echo "--bench $benchmark"; done)
{
cargo bench $BENCHMARKS -- --baseline=master --output-format=json
if $brush; then cargo bench $BRUSH_BENCHMARK -- --baseline=master --output-format=json; fi
if [ -n "$gpu_benchmarks" ]; then cargo bench -p interpreted-executor --features gpu $gpu_benchmarks -- --baseline=master --output-format=json; fi
} | jq -sc | sed 's/\\"//g' > /tmp/all_output.json
# Split the results into one file per benchmark for the analysis below
split_results() { jq -c --arg prefix "$1::" '[.[] | select(.module_path | startswith($prefix))]' /tmp/all_output.json > "/tmp/$2_output.json"; }
# Split the results into one file per benchmark, or per function of one, for the analysis below
split_results() { jq -c --arg path "$1" '[.[] | select(.module_path == $path or (.module_path | startswith($path + "::")))]' /tmp/all_output.json > "/tmp/$2_output.json"; }
split_results compile_demo_art_gungraun compile
split_results update_executor_gungraun update
split_results run_once_gungraun run_once
split_results run_cached_gungraun run_cached
if $brush; then
split_results brush_stroke_gungraun brush_stroke
fi
for benchmark in $baselined; do
case $benchmark in
# Its edits and zooms take different render paths, so each gets a section of its own
artwork_gungraun)
split_results artwork_gungraun::artwork_group::add_rectangle artwork_edit
split_results artwork_gungraun::artwork_group::zoom artwork_zoom
;;
*) split_results "$benchmark" "$benchmark" ;;
esac
done
- name: Make old comments collapsed by default
# Only run if we have write permissions (not a fork)
@@ -178,18 +185,22 @@ jobs:
return benchmark.profiles?.find((profile) => profile.tool === 'Callgrind')?.data?.total?.metrics;
}
// The brush benchmark only has results once the baseline commit has it too
const brush = fs.existsSync('/tmp/brush_stroke_output.json');
// A GPU benchmark only has results once the baseline commit has it too
const gpuBenchmarks = [
['brush_stroke_gungraun', 'Brush Strokes'],
['artwork_edit', 'Artwork Edit'],
['artwork_zoom', 'Zoom'],
].filter(([name]) => fs.existsSync(`/tmp/${name}_output.json`));
const allOutputs = [
JSON.parse(fs.readFileSync('/tmp/compile_output.json', 'utf8')),
JSON.parse(fs.readFileSync('/tmp/update_output.json', 'utf8')),
JSON.parse(fs.readFileSync('/tmp/run_once_output.json', 'utf8')),
JSON.parse(fs.readFileSync('/tmp/run_cached_output.json', 'utf8')),
...(brush ? [JSON.parse(fs.readFileSync('/tmp/brush_stroke_output.json', 'utf8'))] : [])
...gpuBenchmarks.map(([name]) => JSON.parse(fs.readFileSync(`/tmp/${name}_output.json`, 'utf8')))
];
const outputNames = ['compile', 'update', 'run_once', 'run_cached', ...(brush ? ['brush_stroke'] : [])];
const sectionTitles = ['Compilation', 'Update', 'Run Once', 'Cached Execution', ...(brush ? ['Brush Stroke'] : [])];
const outputNames = ['compile', 'update', 'run_once', 'run_cached', ...gpuBenchmarks.map(([name]) => name)];
const sectionTitles = ['Compilation', 'Update', 'Run Once', 'Cached Execution', ...gpuBenchmarks.map(([, title]) => title)];
// Fail instead of reporting no changes when a benchmark has no baseline comparison, such as after gungraun changes its output format
const missingComparisons = [];
@@ -252,9 +263,11 @@ jobs:
const updateOutput = JSON.parse(fs.readFileSync('/tmp/update_output.json', 'utf8'));
const runOnceOutput = JSON.parse(fs.readFileSync('/tmp/run_once_output.json', 'utf8'));
const runCachedOutput = JSON.parse(fs.readFileSync('/tmp/run_cached_output.json', 'utf8'));
// The brush benchmark only has results once the baseline commit has it too, and a section without results is left out
// A GPU benchmark only has results once the baseline commit has it too, and a section without results is left out
const readOptional = (path) => (fs.existsSync(path) ? JSON.parse(fs.readFileSync(path, 'utf8')) : []);
const brushStrokeOutput = readOptional('/tmp/brush_stroke_output.json');
const brushStrokeOutput = readOptional('/tmp/brush_stroke_gungraun_output.json');
const artworkEditOutput = readOptional('/tmp/artwork_edit_output.json');
const artworkZoomOutput = readOptional('/tmp/artwork_zoom_output.json');
const hasSignificantChanges = '${{ steps.analyze.outputs.has-significant-changes }}' === 'true';
let commentBody = "";
@@ -344,7 +357,9 @@ jobs:
{ output: updateOutput, title: "🔄 Executor Update" },
{ output: runOnceOutput, title: "🚀 Render: Cold Execution" },
{ output: runCachedOutput, title: "⚡ Render: Cached Execution" },
{ output: brushStrokeOutput, title: "🖌️ Render: Brush Strokes" }
{ output: brushStrokeOutput, title: "🖌️ Render: Brush Strokes" },
{ output: artworkEditOutput, title: "✏️ Render: Artwork Edit" },
{ output: artworkZoomOutput, title: "🔍 Render: Zoom" }
];
// Generate sections and determine which ones have results
Generated
-1
View File
@@ -2866,7 +2866,6 @@ dependencies = [
"log",
"math-parser",
"migration-compiled",
"migration-core",
"migration-formats",
"migration-nodes",
"node-macro",
+12 -55
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}");
(session_with_truncated_history(&self.session, migrated)?, remap_metadata(&self.metadata, |_| None))
(self.session_with_truncated_history(migrated)?, remap_metadata(&self.metadata, |_| None))
}
};
self.keep_blobs_durably(blobs.into_added()).await?;
@@ -189,24 +189,19 @@ impl<L: Layout> Gdd<L> {
session.absorb_retired_marks(previous.retired_marks());
Ok((session, remap_metadata(&self.metadata, remap)))
}
}
/// 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)?;
/// 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())?;
// 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)
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)
}
}
/// Resolves declaration resources to the declarations migrations name. A declaration's resource derives from its identifier and version
@@ -274,41 +269,3 @@ 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,17 +7,6 @@ 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,6 +1,7 @@
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 {
@@ -23,8 +24,7 @@ pub mod node {
pub const PINNED: &str = "ui::pinned";
pub const OUTPUT_NAMES: &str = "ui::output_names";
pub const OUTPUT_DESCRIPTIONS: &str = "ui::output_descriptions";
/// The built-in network definition a network was created from, stored on the network's attributes. See [`NetworkReference`](crate::NetworkReference).
pub const REFERENCE: &str = "ui::reference";
pub const REFERENCE: &str = "ui::reference"; // TODO: Remove?
}
}
+4 -1
View File
@@ -382,6 +382,9 @@ 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)?;
@@ -488,7 +491,7 @@ fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
if let Some(reference) = metadata.reference(location) {
attributes.set(node::ui::REFERENCE, reference.to_value(), timestamp);
attributes.set(node::ui::REFERENCE, Value::Str(reference.to_string()), timestamp);
}
write_network_interface_attributes(attributes, metadata, location, timestamp)?;
+1 -3
View File
@@ -9,7 +9,6 @@ pub mod history;
mod history_metadata;
pub mod ids;
pub mod model;
mod network_reference;
mod prior;
pub mod registry;
pub mod resources;
@@ -31,7 +30,6 @@ pub use document::*;
pub use history::{History, rehash_deltas};
pub use history_metadata::{HistoryMetadata, MetadataFact, Subject, WallStamp, rev_attr, user_attr};
pub use ids::*;
pub use network_reference::NetworkReference;
pub use schema::*;
pub use session::*;
pub use sorted::Sorted;
@@ -44,7 +42,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};
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
#[cfg(any(feature = "conversion", test))]
pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProjection};
+11 -2
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, Position, Value};
use crate::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.
@@ -98,7 +98,7 @@ pub trait NodeMetadataSource {
}
/// The definition the network was instantiated from, if it still names one.
fn reference(&self, _network: NetworkLocation) -> Option<NetworkReference> {
fn reference(&self, _network: NetworkLocation) -> Option<&str> {
None
}
@@ -124,3 +124,12 @@ 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,9 +22,6 @@ 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,77 +0,0 @@
use crate::attr::node::ui::REFERENCE;
use crate::{Attributes, Value};
const IDENTIFIER: &str = "identifier";
const VERSION: &str = "version";
/// The built-in network definition a network was created from, stored under [`REFERENCE`] on the network's attributes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NetworkReference {
pub identifier: String,
/// The definition's position in its lineage, like [`ProtoNode::version`](crate::ProtoNode).
pub version: u32,
}
impl NetworkReference {
pub fn read(attributes: &Attributes) -> Option<Self> {
attributes.get(REFERENCE).filter(|value| !value.deleted).and_then(|value| Self::from_value(&value.value))
}
/// A bare identifier at version 1, so first versions keep the value they had before definitions were versioned.
pub fn to_value(&self) -> Value {
if self.version == 1 {
return Value::Str(self.identifier.clone());
}
Value::Object(vec![
(IDENTIFIER.to_string(), Value::Str(self.identifier.clone())),
(VERSION.to_string(), Value::Int(self.version.into())),
])
}
pub fn from_value(value: &Value) -> Option<Self> {
match value {
Value::Str(identifier) => Some(Self {
identifier: identifier.clone(),
version: 1,
}),
Value::Object(fields) => {
let field = |name: &str| fields.iter().find(|(key, _)| key == name).map(|(_, value)| value);
let (Some(Value::Str(identifier)), Some(Value::Int(version))) = (field(IDENTIFIER), field(VERSION)) else {
return None;
};
Some(Self {
identifier: identifier.clone(),
version: (*version).try_into().ok()?,
})
}
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_through_its_value() {
for version in [1, 2] {
let reference = NetworkReference {
identifier: "Merge".to_string(),
version,
};
assert_eq!(NetworkReference::from_value(&reference.to_value()), Some(reference));
}
}
#[test]
fn first_version_is_a_bare_identifier() {
let reference = NetworkReference {
identifier: "Merge".to_string(),
version: 1,
};
assert_eq!(reference.to_value(), Value::Str("Merge".to_string()));
}
}
+10 -33
View File
@@ -260,7 +260,8 @@ 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
visible: false, // Non-default value
skip_deduplication: true, // Non-default value
..Default::default()
},
),
@@ -295,6 +296,9 @@ 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, .. }) => {
@@ -350,6 +354,11 @@ 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!(
@@ -886,35 +895,3 @@ fn large_input_value_round_trips_through_a_blob() {
let error = registry.to_runtime_with_metadata(&declarations, &crate::blob::BlobBytes::new()).expect_err("a missing blob must error");
assert!(matches!(error, crate::to_runtime::ConversionError::BlobNotFound(hash) if hash == blob), "{error}");
}
/// Names the nested network a built-in definition at `version`.
struct ReferenceMetadata {
version: u32,
}
impl NodeMetadataSource for ReferenceMetadata {
fn reference(&self, network: NetworkLocation) -> Option<crate::NetworkReference> {
(network == Some(NESTED)).then(|| crate::NetworkReference {
identifier: "Merge".into(),
version: self.version,
})
}
}
#[test]
fn network_reference_round_trips_with_its_version() {
for version in [1, 2] {
let network = create_nested_network();
let conversion = Registry::convert_from_runtime(&network, &ReferenceMetadata { version }, &Default::default(), PeerId(0)).expect("the nested network converts");
let stored: Vec<_> = conversion.registry.networks.values().filter_map(|network| crate::NetworkReference::read(&network.attributes)).collect();
assert_eq!(stored, vec![crate::NetworkReference { identifier: "Merge".into(), version }]);
let (_, _, network_entries) = conversion
.registry
.to_runtime_with_full_metadata(&conversion.declarations, &conversion.blob_bytes)
.expect("the registry converts back");
let references: Vec<_> = network_entries.iter().filter_map(|entry| entry.reference.as_deref()).collect();
assert_eq!(references, vec!["Merge"]);
}
}
+3 -2
View File
@@ -11,7 +11,7 @@ use rustc_hash::{FxHashMap, FxHashSet};
use crate::attr::*;
use crate::blob::{BlobBytes, decode_blob};
use crate::metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry};
use crate::{BlobHash, Implementation, NetworkId, NetworkReference, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
use crate::{BlobHash, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
#[derive(Debug, thiserror::Error)]
pub enum ConversionError {
@@ -421,7 +421,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
NetworkMetadataEntry {
network,
network_id,
reference: NetworkReference::read(attributes).map(|reference| reference.identifier),
reference: attributes.get_typed(node::ui::REFERENCE),
pinned_order,
import_metadata: attributes.get_or_default(network::IMPORT_METADATA),
export_names: attributes.get_or_default(network::EXPORT_NAMES),
@@ -457,6 +457,7 @@ 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,10 +1,9 @@
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::{Attributes, Compiler, Inputs, MigrationError, NewNode, Node, NodeInput, Target, Upstream, decl, literal, literal_of, migration};
use migration_core::{Compiler, Inputs, MigrationError, NewNode, Node, NodeInput, Target, Upstream, decl, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const CONTENT: usize = 1;
@@ -30,23 +29,11 @@ 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,
attributes: &mut Attributes,
) -> 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) -> 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));
@@ -183,9 +170,7 @@ fn bias_keeping_average_scale(bias: f64) -> f64 {
mod tests {
use super::*;
use crate::CompilerHost;
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_core::Declaration;
use migration_runner::testing::{Fixture, Random, SourceContract, check_commutation_with, check_undo_with};
const COPY_TO_POINTS: Declaration = decl!("core_types::vector::CopyToPointsNode"@1);
@@ -199,13 +184,10 @@ mod tests {
}
fn contract() -> SourceContract {
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)),
})
}
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> {
@@ -280,48 +262,6 @@ 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);
+5 -62
View File
@@ -1,85 +1,28 @@
use document_graph_storage::{Attributes, NetworkReference, ProtoNode, ResourceEntry, ResourceId};
use document_graph_storage::{ProtoNode, ResourceEntry, ResourceId};
use serde::Serialize;
/// What a declaration describes: a proto node, or a built-in network definition that instances copy.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
pub enum DeclarationKind {
#[default]
Proto,
Network,
}
impl DeclarationKind {
fn is_proto(&self) -> bool {
*self == Self::Proto
}
}
/// A declaration at one version, written `identifier@version`, or `network identifier@version` for a network definition.
/// A proto-node declaration at one version, written `identifier@version`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
pub struct Declaration {
pub identifier: &'static str,
pub version: u32,
/// Skipped for proto nodes, so the IDs derived from declarations predating network definitions stay the same.
#[serde(skip_serializing_if = "DeclarationKind::is_proto")]
pub kind: DeclarationKind,
}
impl Declaration {
pub const fn new(identifier: &'static str, version: u32) -> Self {
Self {
identifier,
version,
kind: DeclarationKind::Proto,
}
}
pub const fn network(identifier: &'static str, version: u32) -> Self {
Self {
identifier,
version,
kind: DeclarationKind::Network,
}
}
pub fn is_network(&self) -> bool {
self.kind == DeclarationKind::Network
}
/// Whether a network's attributes name this network definition.
pub fn describes_network(&self, attributes: &Attributes) -> bool {
NetworkReference::read(attributes).is_some_and(|reference| self.is_reference(&reference))
}
/// Whether `reference` names this network definition.
pub fn is_reference(&self, reference: &NetworkReference) -> bool {
self.is_network() && reference.identifier == self.identifier && reference.version == self.version
}
/// The reference a network of this definition stores. Meaningless for a proto node.
pub fn network_reference(&self) -> NetworkReference {
NetworkReference {
identifier: self.identifier.to_string(),
version: self.version,
}
Self { identifier, version }
}
}
impl std::fmt::Display for Declaration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.kind {
DeclarationKind::Proto => write!(f, "{}@{}", self.identifier, self.version),
DeclarationKind::Network => write!(f, "network {}@{}", self.identifier, self.version),
}
write!(f, "{}@{}", self.identifier, self.version)
}
}
/// Names a declaration as `decl!("module::node"@2)`, or a network definition as `decl!(network "Merge"@2)`.
/// Names a declaration as `decl!("module::node"@2)`.
#[macro_export]
macro_rules! decl {
(network $identifier:literal @ $version:literal) => {
$crate::Declaration::network($identifier, $version)
};
($identifier:literal @ $version:literal) => {
$crate::Declaration::new($identifier, $version)
};
+3 -3
View File
@@ -27,9 +27,9 @@ pub use compiler::{Compiler, MigrationHost, ValueType};
#[cfg(feature = "typed")]
pub use connector::{InputConnector, NewNode, OutputConnector};
#[cfg(feature = "typed")]
pub use declaration::{Declaration, DeclarationKind, DeclarationResolver};
pub use declaration::{Declaration, DeclarationResolver};
#[cfg(feature = "typed")]
pub use document_graph_storage::{NodeInput, Position, attr};
pub use document_graph_storage::NodeInput;
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, AttributeWrite, Attributes, CHAIN_WIDTH, Downstream, Edits, FEEDER_ROW_HEIGHT, Graph, Inputs, InputsEdit, Node, Region, Target, Upstream, View, implements};
pub use view::{AddedNode, AnchorContext, Downstream, Edits, Graph, Inputs, InputsEdit, Node, Region, Target, Upstream, View};
// For the registration `#[migration]`, `rename!`, and `format_migration!` generate
#[doc(hidden)]
+4 -84
View File
@@ -1,14 +1,7 @@
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 crate::{Compiler, Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector};
use document_graph_storage::{InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp};
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);
@@ -21,8 +14,6 @@ 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)
@@ -157,9 +148,9 @@ impl<'a> Graph<'a> {
self.registry.node_instances.get(&id).filter(|node| node.network() == self.network)
}
/// The proto-node declaration a node of this network implements, if it is one a migration knows.
/// The declaration a node of this network implements, if it is one a migration knows.
pub fn declaration(&self, id: NodeId) -> Option<Declaration> {
let Implementation::ProtoNode(resource) = self.node(id)?.implementation() else {
let document_graph_storage::Implementation::ProtoNode(resource) = self.node(id)?.implementation() else {
return None;
};
self.resolver.declaration(*resource)
@@ -205,14 +196,6 @@ impl<'a> Graph<'a> {
}
}
/// Whether `node` implements `declaration`: a proto node through its declaration resource, a network instance through the definition its network names.
pub fn implements(registry: &Registry, node: &document_graph_storage::Node, declaration: Declaration, resolver: &dyn DeclarationResolver) -> bool {
match node.implementation() {
Implementation::ProtoNode(resource) => !declaration.is_network() && resolver.declaration(*resource) == Some(declaration),
Implementation::Network(network) => registry.networks.get(network).is_some_and(|network| declaration.describes_network(&network.attributes)),
}
}
/// A parameter type of a migration: a window onto one region around the anchor that records edits rather than applying them.
pub trait View<'a>: Sized {
/// The region this view reads or edits.
@@ -232,8 +215,6 @@ 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 {
@@ -245,57 +226,6 @@ 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()
})
}
}
@@ -391,16 +321,6 @@ 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;
+4 -17
View File
@@ -13,10 +13,9 @@ use syn::{Error, FnArg, Ident, ItemFn, ReturnType, Type, parse_macro_input};
/// Turns a function into a node migration, named by its source and target declarations:
/// `#[migration("module::node"@1 => @2)]` for a version step, `#[migration("module::old"@1 => "module::new"@2)]` for a replacement.
/// 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`, `Attributes`) 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`) 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]
@@ -234,16 +233,7 @@ fn expand_rename(step: Step) -> syn::Result<TokenStream2> {
}
fn step_name(step: &Step) -> String {
let prefix = |declaration: &Declaration| if declaration.network { "network " } else { "" };
format!(
"{}{}@{}=>{}{}@{}",
prefix(&step.source),
step.source.identifier,
step.source.version,
prefix(&step.target),
step.target.identifier,
step.target.version
)
format!("{}@{}=>{}@{}", step.source.identifier, step.source.version, step.target.identifier, step.target.version)
}
/// Passes `migration` to `register` at startup: through `ctor` on native targets, and through an exported function the host calls
@@ -269,11 +259,8 @@ fn registration(core: &TokenStream2, register: TokenStream2, migration: TokenStr
}
fn declaration(core: &TokenStream2, declaration: &Declaration) -> TokenStream2 {
let Declaration { identifier, version, network } = declaration;
match network {
true => quote!(#core::Declaration::network(#identifier, #version)),
false => quote!(#core::Declaration::new(#identifier, #version)),
}
let Declaration { identifier, version } = declaration;
quote!(#core::Declaration::new(#identifier, #version))
}
/// How the expansion names `migration-core`: `crate` inside it, its (possibly renamed) dependency name elsewhere.
+6 -27
View File
@@ -1,18 +1,16 @@
use proc_macro2::{TokenStream, TokenTree};
use syn::parse::{Parse, ParseStream};
use syn::{Error, Ident, LitInt, LitStr, Token};
use syn::{Error, LitInt, LitStr, Token};
/// A declaration as written in macro input: `"identifier"@version`, or `network "identifier"@version` for a network definition.
/// A declaration as written in macro input: `"identifier"@version`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Declaration {
pub identifier: String,
pub version: u32,
pub network: bool,
}
impl Parse for Declaration {
fn parse(input: ParseStream) -> syn::Result<Self> {
let network = parse_network_keyword(input)?;
let identifier: LitStr = input.parse()?;
input.parse::<Token![@]>()?;
let version: LitInt = input.parse()?;
@@ -20,26 +18,11 @@ impl Parse for Declaration {
Ok(Self {
identifier: identifier.value(),
version: version.base10_parse()?,
network,
})
}
}
/// Consumes a leading `network` keyword, returning whether it was there.
fn parse_network_keyword(input: ParseStream) -> syn::Result<bool> {
if !input.peek(Ident) {
return Ok(false);
}
let keyword: Ident = input.parse()?;
if keyword != "network" {
return Err(Error::new(keyword.span(), "expected `network` or a declaration identifier string"));
}
Ok(true)
}
/// `"identifier"@n => "identifier"@m`, or `"identifier"@n => @m` for a version step that keeps the identifier and kind. Either side may be a
/// `network` definition.
/// `"identifier"@n => "identifier"@m`, or `"identifier"@n => @m` for a version step that keeps the identifier.
pub(crate) struct Step {
pub source: Declaration,
pub target: Declaration,
@@ -50,12 +33,9 @@ impl Parse for Step {
let source: Declaration = input.parse()?;
input.parse::<Token![=>]>()?;
let (target_identifier, target_network) = match input.peek(LitStr) || input.peek(Ident) {
true => {
let network = parse_network_keyword(input)?;
(input.parse::<LitStr>()?.value(), network)
}
false => (source.identifier.clone(), source.network),
let target_identifier = match input.peek(LitStr) {
true => input.parse::<LitStr>()?.value(),
false => source.identifier.clone(),
};
input.parse::<Token![@]>()?;
let target_version_literal: LitInt = input.parse()?;
@@ -72,7 +52,6 @@ impl Parse for Step {
let target = Declaration {
identifier: target_identifier,
version: target_version,
network: target_network,
};
Ok(Self { source, target })
}
@@ -4,5 +4,3 @@ 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,4 +4,3 @@
mod graphene_core;
mod math_nodes;
mod raster_nodes;
mod vector_nodes;
@@ -1,4 +0,0 @@
//! Migrations of the nodes in `vector_nodes`.
mod path_from_path_network;
mod renames;
@@ -1,49 +0,0 @@
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"));
}
}
@@ -1,5 +0,0 @@
//! 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);
-6
View File
@@ -32,16 +32,10 @@ pub enum RunnerError {
Migration { migration: Declaration, anchor: NodeId, error: MigrationError },
#[error("node {anchor:?} chose {target}, which the migration from {migration} doesn't name")]
UnnamedTarget { migration: Declaration, anchor: NodeId, target: Declaration },
#[error("proto node {anchor:?} can't become {target}, which the migration from {migration} chose")]
ProtoToNetwork { migration: Declaration, anchor: NodeId, target: Declaration },
#[error("node {anchor:?} adds a node of {declaration}, but migrations only add proto nodes")]
AddedNetworkDefinition { anchor: NodeId, declaration: Declaration },
#[error("node {anchor:?} adds two nodes of {declaration} under the key {key:?}")]
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")]
+9 -174
View File
@@ -1,13 +1,9 @@
//! The node tier: `M` as a function on registry states, and the history rewrite derived from it.
use crate::{MigrationBlobs, RunnerError};
use document_graph_storage::TimeStamp;
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, 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 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};
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.
@@ -175,10 +171,6 @@ 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 {
@@ -209,11 +201,13 @@ fn apply_runs(migration: &dyn NodeMigration, source: &Registry, anchors: &[NodeI
});
}
switch_implementation(&mut target, *anchor, chosen, resolver).map_err(|error| error.for_anchor(migration.source(), *anchor))?;
if let Some(node) = target.node_instances.get_mut(anchor) {
*node.implementation_mut() = Implementation::ProtoNode(resolver.resource(chosen));
}
used_declarations.push(chosen);
used_declarations.extend(edits.added_nodes.iter().map(|added| added.node.declaration));
}
for declaration in used_declarations.into_iter().filter(|declaration| !declaration.is_network()) {
for declaration in used_declarations {
if let Some(entry) = resolver.resource_entry(declaration) {
target.resources.entry(resolver.resource(declaration)).or_insert(entry);
}
@@ -222,65 +216,6 @@ fn apply_runs(migration: &dyn NodeMigration, source: &Registry, anchors: &[NodeI
Ok(target)
}
/// Why an anchor can't switch to the declaration its run chose.
enum SwitchError {
/// Only a network anchor can become a network definition, since a proto node has no network to name it.
ProtoToNetwork(Declaration),
}
impl SwitchError {
fn for_anchor(self, migration: Declaration, anchor: NodeId) -> RunnerError {
match self {
Self::ProtoToNetwork(target) => RunnerError::ProtoToNetwork { migration, anchor, target },
}
}
}
/// Switch `anchor` to `declaration`. A network anchor becoming a proto node drops the network it implemented, with every network nested in it.
fn switch_implementation(registry: &mut Registry, anchor: NodeId, declaration: Declaration, resolver: &dyn DeclarationResolver) -> Result<(), SwitchError> {
let Some(implementation) = registry.node_instances.get(&anchor).map(|node| node.implementation().clone()) else {
return Ok(());
};
match (implementation, declaration.is_network()) {
(Implementation::ProtoNode(_), true) => Err(SwitchError::ProtoToNetwork(declaration)),
(Implementation::Network(network), true) => {
if let Some(network) = registry.networks.get_mut(&network) {
network.attributes.set(REFERENCE, declaration.network_reference().to_value(), TimeStamp::ORIGIN);
}
Ok(())
}
(implementation, false) => {
if let Implementation::Network(network) = implementation {
remove_network_tree(registry, network);
}
if let Some(node) = registry.node_instances.get_mut(&anchor) {
*node.implementation_mut() = Implementation::ProtoNode(resolver.resource(declaration));
}
Ok(())
}
}
}
/// Remove `network`, its nodes, and every network one of them implements.
fn remove_network_tree(registry: &mut Registry, network: NetworkId) {
let mut pending = vec![network];
while let Some(network) = pending.pop() {
registry.networks.remove(&network);
registry.node_instances.retain(|_, node| {
if node.network() != network {
return true;
}
if let Implementation::Network(nested) = node.implementation() {
pending.push(*nested);
}
false
});
}
}
/// Whether a live node of `registry` implements `declaration`.
pub fn holds(registry: &Registry, declaration: Declaration, resolver: &dyn DeclarationResolver) -> bool {
!anchors(declaration, registry, resolver).is_empty()
@@ -291,7 +226,7 @@ fn anchors(declaration: Declaration, registry: &Registry, resolver: &dyn Declara
let mut anchors: Vec<NodeId> = registry
.node_instances
.iter()
.filter(|(_, node)| implements(registry, node, declaration, resolver))
.filter(|(_, node)| matches!(node.implementation(), Implementation::ProtoNode(resource) if resolver.declaration(*resource) == Some(declaration)))
.map(|(id, _)| *id)
.collect();
anchors.sort_unstable();
@@ -305,12 +240,6 @@ fn add_nodes(target: &mut Registry, runs: &[(NodeId, Edits)], resolver: &dyn Dec
let Some(network) = target.node_instances.get(anchor).map(Node::network) else { continue };
for added in &edits.added_nodes {
if added.node.declaration.is_network() {
return Err(RunnerError::AddedNetworkDefinition {
anchor: *anchor,
declaration: added.node.declaration,
});
}
if !added_ids.insert(added.id) {
return Err(RunnerError::DuplicateAddedNode {
anchor: *anchor,
@@ -334,94 +263,6 @@ 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> {
@@ -464,7 +305,7 @@ struct Branch {
/// Undoing and then editing leaves an abandoned branch, which rewrites like any other since each delta only depends on its ancestors.
/// Fails on a delta that merges branches, or whose parent isn't in `history`.
///
/// A migration reading the graph, asking the compiler, or starting from a network definition needs whole states, so it only runs at the boundaries undo can land on, the end of an interaction,
/// A migration reading the graph or asking the compiler needs whole states, so it only runs at the boundaries undo can land on, the end of an interaction,
/// and rewrites everything since the last one as a single chain. Each delta inside maps to the boundary before it, and `kept` names further states to keep.
///
/// Each delta costs one full evaluation of `M` and one full diff, so this is O(history × registry), until the RFC's footprint-scoped
@@ -487,7 +328,7 @@ pub(crate) fn rewrite_history(
}
let child_counts = children.clone();
let whole_states_only = needs_whole_states(migration);
let whole_states_only = migration.footprint().reads_network();
let is_boundary = |delta: &Delta| {
let continues_alone = child_counts.get(&Some(delta.id)) == Some(&1) && child_authors.get(&delta.id).is_some_and(|authors| authors.contains(&delta.author));
delta.is_interaction_end() || !continues_alone || kept.contains(&delta.id)
@@ -584,12 +425,6 @@ pub fn registry_at(deltas: &[Delta], head: Option<Rev>) -> Result<Registry, Runn
Ok(registry)
}
/// A network definition's instance is a node and the network it implements, which a history adds in separate deltas. In between, the network
/// names the definition without an anchor to migrate it, so only states where both or neither exist are migrated.
pub(crate) fn needs_whole_states(migration: &dyn NodeMigration) -> bool {
migration.footprint().reads_network() || migration.source().is_network()
}
/// Ops `M` can't affect and `compute_deltas` doesn't diff, which therefore keep their original form.
fn passes_through(kind: &RegistryDelta) -> bool {
matches!(kind, RegistryDelta::RegisterPeer { .. } | RegistryDelta::Other(_))
+2 -19
View File
@@ -2,8 +2,7 @@
use crate::node::{apply_migration, rewrite_history};
use crate::{MigrationBlobs, RewrittenHistory, RunnerError};
use document_graph_storage::attributes::attr::node::ui::REFERENCE;
use document_graph_storage::{Delta, Implementation, NetworkReference, Node, Registry, RegistryDelta, Rev};
use document_graph_storage::{Delta, Implementation, Node, Registry, RegistryDelta, Rev};
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration};
use std::collections::{BTreeSet, HashMap, HashSet};
@@ -122,24 +121,8 @@ pub fn migrate_registry(
Ok(migrated)
}
/// Whether `kind` stores a node implementing `declaration`, or for a network definition, a network naming it.
/// Whether `kind` stores a node implementing `declaration`.
pub fn references(kind: &RegistryDelta, declaration: Declaration, resolver: &dyn DeclarationResolver) -> bool {
if declaration.is_network() {
return match kind {
RegistryDelta::AddNetwork { network, .. } => declaration.describes_network(&network.attributes),
RegistryDelta::RemoveNetwork { snapshot, .. } => declaration.describes_network(&snapshot.attributes),
RegistryDelta::ChangeNetworkAttribute { delta, .. } => {
delta.key == REFERENCE
&& delta
.value
.as_ref()
.and_then(NetworkReference::from_value)
.is_some_and(|reference| declaration.is_reference(&reference))
}
_ => false,
};
}
let is_declaration = |implementation: &Implementation| matches!(implementation, Implementation::ProtoNode(resource) if resolver.declaration(*resource) == Some(declaration));
let implements = |node: &Node| is_declaration(node.implementation());
+21 -163
View File
@@ -1,14 +1,10 @@
//! What every migration's tests need: fixtures for one anchor, and the property that rewriting a generated history gives `M` of it at every step.
//! Panics on failure, since it only runs in tests.
use crate::node::{apply_migration, needs_whole_states, rewrite_history};
use crate::node::{apply_migration, rewrite_history};
use crate::{DeclarationTable, MigrationBlobs, RunnerError, references, registry_at};
use document_graph_storage::attributes::attr::node::ui::{DISPLAY_NAME, IS_LAYER, POSITION, REFERENCE};
use document_graph_storage::{
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 document_graph_storage::{Delta, ExportSlot, Implementation, Network, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Session, UserId, apply_retired_op};
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration, decl, literal, registered_migrations};
use std::collections::HashSet;
/// A root network built node by node, for running one migration on.
@@ -30,35 +26,11 @@ impl Fixture {
}
pub fn add(&mut self, declaration: Declaration, inputs: Vec<NodeInput>) -> NodeId {
self.add_in(ROOT_NETWORK, declaration, inputs)
}
/// Add a proto node of `declaration` to `network`.
pub fn add_in(&mut self, network: NetworkId, declaration: Declaration, inputs: Vec<NodeInput>) -> NodeId {
let resource = self.table.register(declaration);
self.insert_node(network, Implementation::ProtoNode(resource), inputs)
}
/// Add a node to the root network implementing a new, empty network that names the network definition `declaration`.
pub fn add_network(&mut self, declaration: Declaration, inputs: Vec<NodeInput>) -> (NodeId, NetworkId) {
assert!(declaration.is_network(), "{declaration} is not a network definition");
self.next_id += 1;
let network_id = NetworkId(self.next_id);
let mut network = Network::default();
network.attributes.set(REFERENCE, declaration.network_reference().to_value(), TimeStamp::ORIGIN);
self.registry.networks.insert(network_id, network);
let node = self.insert_node(ROOT_NETWORK, Implementation::Network(network_id), inputs);
(node, network_id)
}
fn insert_node(&mut self, network: NetworkId, implementation: Implementation, inputs: Vec<NodeInput>) -> NodeId {
self.next_id += 1;
let id = NodeId(self.next_id);
let mut node = Node::new(network, implementation, inputs.len());
let resource = self.table.register(declaration);
let mut node = Node::new(ROOT_NETWORK, Implementation::ProtoNode(resource), inputs.len());
for (slot, input) in node.inputs_mut().iter_mut().zip(inputs) {
slot.input = input;
}
@@ -68,11 +40,7 @@ impl Fixture {
}
pub fn export(&mut self, input: NodeInput) {
self.export_from(ROOT_NETWORK, input);
}
pub fn export_from(&mut self, network: NetworkId, input: NodeInput) {
let network = self.registry.networks.get_mut(&network).expect("exports go to a network the fixture created");
let network = self.registry.networks.get_mut(&ROOT_NETWORK).expect("the fixture creates the root network");
network.exports.push(ExportSlot {
target: Some(input),
..Default::default()
@@ -139,8 +107,6 @@ 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 {
@@ -149,7 +115,6 @@ impl SourceContract {
input_count,
literal,
reads_own_output: |_| true,
display_names: &[],
}
}
}
@@ -170,11 +135,7 @@ struct Generator<'a> {
impl Generator<'_> {
fn commit(&mut self, op: RegistryDelta) {
self.commit_interaction(vec![op]);
}
fn commit_interaction(&mut self, ops: Vec<RegistryDelta>) {
self.session.stage_computed_ops(ops).expect("generated ops are valid");
self.session.stage_computed_ops(vec![op]).expect("generated ops are valid");
let revs = self.session.retire_all().expect("staged ops retire");
if let Some(last) = revs.last() {
self.session.mark_interaction_end(*last);
@@ -188,37 +149,24 @@ impl Generator<'_> {
nodes
}
fn live_nodes_in(&self, network: NetworkId) -> Vec<NodeId> {
let registry = self.session.registry();
self.live_nodes().into_iter().filter(|node| registry.node_instances[node].network() == network).collect()
}
fn declaration_of(&self, node: &Node) -> Option<Declaration> {
if implements(self.session.registry(), node, self.source, &*self.table) {
return Some(self.source);
}
let Implementation::ProtoNode(resource) = node.implementation() else { return None };
(DeclarationTable::resource_id(CONSUMER) == *resource).then_some(CONSUMER)
[self.source, CONSUMER].into_iter().find(|declaration| DeclarationTable::resource_id(*declaration) == *resource)
}
/// A literal, a wire to another live node of `network`, or inside a source network, one of its imports.
fn input_for(&mut self, declaration: Declaration, slot: usize, exclude: Option<NodeId>, network: NetworkId) -> NodeInput {
/// A literal or a wire to another live node.
fn input_for(&mut self, declaration: Declaration, slot: usize, exclude: Option<NodeId>) -> NodeInput {
let is_source = declaration == self.source;
let reads_own_output = !is_source || (self.contract.reads_own_output)(slot);
let registry = self.session.registry();
let allowed = |node: &NodeId| reads_own_output || self.declaration_of(&registry.node_instances[node]) != Some(self.source);
let candidates: Vec<NodeId> = self.live_nodes_in(network).into_iter().filter(|node| Some(*node) != exclude && allowed(node)).collect();
let candidates: Vec<NodeId> = self.live_nodes().into_iter().filter(|node| Some(*node) != exclude && allowed(node)).collect();
if !candidates.is_empty() && self.random.below(2) == 0 {
let node = self.random.pick(&candidates);
return NodeInput::Node { id: node, index: 0 };
}
if network != ROOT_NETWORK && self.contract.input_count > 0 && self.random.below(2) == 0 {
let index = self.random.below(self.contract.input_count) as u32;
return NodeInput::Import { index };
}
if is_source {
(self.contract.literal)(&mut self.random, slot)
@@ -227,106 +175,21 @@ impl Generator<'_> {
}
}
/// An instance of the source network definition with one inner node, adding the network before the node that implements it, as the editor does.
fn add_network_instance(&mut self) {
let network_id = NetworkId(self.session.next_node_id().0);
let mut network = Network::default();
network.attributes.set(REFERENCE, self.source.network_reference().to_value(), TimeStamp::ORIGIN);
let inner_id = self.session.next_node_id();
let mut inner = Node::new(network_id, Implementation::ProtoNode(self.table.register(CONSUMER)), CONSUMER_INPUTS);
for slot in 0..CONSUMER_INPUTS {
inner.inputs_mut()[slot].input = self.input_for(CONSUMER, slot, None, network_id);
}
let mut instance = Node::new(ROOT_NETWORK, Implementation::Network(network_id), self.contract.input_count);
for slot in 0..self.contract.input_count {
instance.inputs_mut()[slot].input = self.input_for(self.source, slot, None, ROOT_NETWORK);
}
let instance_id = self.session.next_node_id();
self.commit_interaction(vec![
RegistryDelta::AddNetwork { id: network_id, network },
RegistryDelta::AddNode { id: inner_id, node: inner },
RegistryDelta::SetNetworkExport {
id: network_id,
index: 0,
export: Some(NodeInput::Node { id: inner_id, index: 0 }),
},
RegistryDelta::AddNode { id: instance_id, node: instance },
]);
}
/// Remove a node, along with the network it implements and that network's nodes.
fn remove(&mut self, id: NodeId) {
let registry = self.session.registry();
let snapshot = registry.node_instances[&id].clone();
let mut ops = Vec::new();
if let Implementation::Network(network) = snapshot.implementation()
&& let Some(network_snapshot) = registry.networks.get(network)
{
for inner in self.live_nodes_in(*network) {
let snapshot = registry.node_instances[&inner].clone();
ops.push(RegistryDelta::RemoveNode { id: inner, snapshot });
}
ops.push(RegistryDelta::RemoveNetwork {
id: *network,
snapshot: network_snapshot.clone(),
});
}
ops.insert(0, RegistryDelta::RemoveNode { id, snapshot });
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(13) {
match self.random.below(11) {
0..=3 => {
let (declaration, input_count) = if self.random.below(3) == 0 {
(self.source, self.contract.input_count)
} else {
(CONSUMER, CONSUMER_INPUTS)
};
if declaration.is_network() {
self.add_network_instance();
return;
}
let resource = self.table.register(declaration);
let mut node = Node::new(ROOT_NETWORK, Implementation::ProtoNode(resource), input_count);
for slot in 0..input_count {
node.inputs_mut()[slot].input = self.input_for(declaration, slot, None, ROOT_NETWORK);
node.inputs_mut()[slot].input = self.input_for(declaration, slot, None);
}
let id = self.session.next_node_id();
self.commit(RegistryDelta::AddNode { id, node });
@@ -340,18 +203,19 @@ impl Generator<'_> {
}
let index = self.random.below(node.inputs().len());
let new_input = self.input_for(declaration, index, Some(id), node.network());
let new_input = self.input_for(declaration, index, Some(id));
if node.inputs()[index].input == new_input {
return;
}
self.commit(RegistryDelta::ChangeNodeInput { id, index: index as u32, new_input });
}
7 if !root_nodes.is_empty() => {
let id = self.random.pick(&root_nodes);
self.remove(id);
7 if !nodes.is_empty() => {
let id = self.random.pick(&nodes);
let snapshot = self.session.registry().node_instances[&id].clone();
self.commit(RegistryDelta::RemoveNode { id, snapshot });
}
8 | 9 if !root_nodes.is_empty() => {
let id = self.random.pick(&root_nodes);
8 | 9 if !nodes.is_empty() => {
let id = self.random.pick(&nodes);
let index = self.random.below(2) as u32;
let export = Some(NodeInput::Node { id, index: 0 });
@@ -366,11 +230,6 @@ 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 });
}
_ => {}
}
}
@@ -424,8 +283,7 @@ pub fn check_commutation_with(migration: &dyn NodeMigration, contract: &SourceCo
let rewritten = rewrite_history(migration, &history, &table, host, &HashSet::new(), &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
// A migration needing whole states maps a delta inside an interaction to the boundary before it, so only boundaries are comparable
for delta in history.iter().filter(|delta| !needs_whole_states(migration) || delta.is_interaction_end()) {
for delta in &history {
let original = registry_at(&history, Some(delta.id)).unwrap_or_else(|error| panic!("seed {seed}: {error}"));
let expected = apply_migration(migration, &original, &table, host, &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
let replayed = registry_at(&rewritten.deltas, rewritten.revs[&delta.id]).unwrap_or_else(|error| panic!("seed {seed}: {error}"));
@@ -1,137 +0,0 @@
//! 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,18 +33,6 @@ 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,14 +1,11 @@
mod attributes;
mod blobs;
mod compiler;
mod examples;
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, BoundingBoxOwnPath, ExtractXyToSplit, OpacityToggles, ROTATION, Tagged, TransformDegrees};
use examples::{AngleBetweenDegrees, Axis, ExtractXyToSplit, OpacityToggles, ROTATION, Tagged, TransformDegrees};
use migration_core::{decl, literal, literal_of};
use migration_runner::RunnerError;
use migration_runner::testing::{Fixture, registered};
@@ -59,19 +56,6 @@ 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);
@@ -1,125 +0,0 @@
//! Network definitions as migration sources: a built-in subgraph collapsing into a proto node, and a version step of one.
use crate::{Tagged, inputs, wire};
use document_graph_storage::attributes::attr::node::ui::REFERENCE;
use document_graph_storage::{AttributeDelta, Implementation, NetworkId, NetworkReference, NodeId, NodeInput, RegistryDelta};
use migration_core::{NewNode, Upstream, decl, literal, migration, rename};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo, registered};
use migration_runner::{DeclarationTable, RunnerError, references};
// The Merge subgraph became the `merge` proto node, which takes the instance's inputs as they are. Inner edits are dropped with the subgraph
rename!(network "Merge"@1 => "graphic_nodes::merge"@2);
rename!(network "Artboard"@1 => @2);
/// Adds a node of a network definition, which the runner rejects since only proto nodes can be added.
#[migration(network "Frame"@1 => @2)]
pub fn add_network_definition(upstream: &mut Upstream) {
upstream.add_node(NewNode {
declaration: decl!(network "Merge"@1),
inputs: Vec::new(),
});
}
const MERGE: migration_core::Declaration = decl!(network "Merge"@1);
/// A Merge instance in the root network whose subgraph holds the frozen shape, plus `extra_inner_nodes` the user added.
fn merge_fixture(extra_inner_nodes: usize) -> (Fixture, NodeId, NetworkId, NodeId) {
let mut fixture = Fixture::new(registered(MERGE));
let (merge, network) = fixture.add_network(MERGE, vec![literal(Tagged::Number(1.)), literal(Tagged::Number(2.))]);
let into_group = fixture.add_in(network, decl!("graphic_nodes::into_group"@1), vec![NodeInput::Import { index: 0 }]);
fixture.export_from(network, wire(into_group, 0));
for _ in 0..extra_inner_nodes {
fixture.add_in(network, decl!("graphic_nodes::into_group"@1), vec![NodeInput::Import { index: 1 }]);
}
(fixture, merge, network, into_group)
}
#[test]
fn network_anchor_collapses_into_proto_node() {
let (fixture, merge, network, into_group) = merge_fixture(0);
let migrated = fixture.migrate(registered(MERGE)).unwrap();
assert_eq!(fixture.declaration_of(&migrated, merge), Some(decl!("graphic_nodes::merge"@2)));
assert_eq!(inputs(&migrated, merge), inputs(&fixture.registry, merge));
assert!(!migrated.networks.contains_key(&network));
assert!(!migrated.node_instances.contains_key(&into_group));
}
#[test]
fn edited_subgraph_collapses_too() {
let (fixture, merge, network, _) = merge_fixture(1);
let migrated = fixture.migrate(registered(MERGE)).unwrap();
assert_eq!(fixture.declaration_of(&migrated, merge), Some(decl!("graphic_nodes::merge"@2)));
assert!(!migrated.networks.contains_key(&network));
assert!(migrated.node_instances.values().all(|node| node.network() != network));
}
#[test]
fn adding_a_network_definition_fails() {
let migration = registered(decl!(network "Frame"@1));
let mut fixture = Fixture::new(migration);
let (frame, _) = fixture.add_network(decl!(network "Frame"@1), Vec::new());
let result = fixture.migrate(migration);
assert!(matches!(result, Err(RunnerError::AddedNetworkDefinition { anchor, .. }) if anchor == frame));
}
#[test]
fn network_of_another_version_is_no_anchor() {
let mut fixture = Fixture::new(registered(MERGE));
fixture.add_network(decl!(network "Merge"@2), Vec::new());
let migrated = fixture.migrate(registered(MERGE)).unwrap();
assert_eq!(migrated, fixture.registry);
}
#[test]
fn network_version_step_names_the_new_version() {
let migration = registered(decl!(network "Artboard"@1));
let mut fixture = Fixture::new(migration);
let (artboard, network) = fixture.add_network(decl!(network "Artboard"@1), vec![literal(Tagged::Number(1.))]);
let migrated = fixture.migrate(migration).unwrap();
assert_eq!(NetworkReference::read(&migrated.networks[&network].attributes), Some(decl!(network "Artboard"@2).network_reference()));
assert_eq!(migrated.node_instances[&artboard].implementation(), &Implementation::Network(network));
}
#[test]
fn reference_write_is_pending_for_network_definition() {
let delta = RegistryDelta::ChangeNetworkAttribute {
id: NetworkId(1),
delta: AttributeDelta {
key: REFERENCE.to_string(),
value: Some(MERGE.network_reference().to_value()),
},
};
assert!(references(&delta, MERGE, &DeclarationTable::default()));
assert!(!references(&delta, decl!(network "Merge"@2), &DeclarationTable::default()));
assert!(!references(&delta, decl!(network "Artboard"@1), &DeclarationTable::default()));
}
fn numbers(input_count: usize) -> SourceContract {
SourceContract::new(input_count, |random, _| literal(Tagged::Number(random.below(10) as f64)))
}
#[test]
fn collapse_commutes() {
check_commutation(registered(MERGE), &numbers(2));
check_undo(registered(MERGE), &numbers(2));
}
#[test]
fn network_version_step_commutes() {
check_commutation(registered(decl!(network "Artboard"@1)), &numbers(1));
check_undo(registered(decl!(network "Artboard"@1)), &numbers(1));
}
@@ -13,9 +13,6 @@ 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),
@@ -23,9 +20,6 @@ fn every_migration_registers_once() {
decl!("choice::toggle"@1),
decl!("choice::unnamed"@1),
decl!("graphene_core::ops::AddNode"@1),
decl!(network "Artboard"@1),
decl!(network "Frame"@1),
decl!(network "Merge"@1),
decl!("math_nodes::multiply"@1),
decl!("order::asking"@1),
decl!("order::inspector"@1),
@@ -33,7 +27,6 @@ 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, BoundingBoxOwnPath, ExtractXyToSplit, OpacityToggles, Tagged, TransformDegrees};
use crate::examples::{AngleBetweenDegrees, Axis, ExtractXyToSplit, OpacityToggles, Tagged, TransformDegrees};
use migration_core::{decl, literal};
use migration_runner::testing::{Random, SourceContract, check_commutation, check_undo, registered};
@@ -18,11 +18,6 @@ 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));
+7 -55
View File
@@ -4,61 +4,34 @@ use std::collections::BTreeSet;
use std::path::Path;
use syn::parse::{Parse, ParseStream};
/// `identifier@version`. A network definition's identifier starts with [`NETWORK`], which no node's identifier does.
/// `identifier@version`.
pub(crate) type Declaration = (String, u32);
/// Starts the identifier of a network definition, which the editor's catalog declares instead of a node crate.
const NETWORK: &str = "network ";
/// The source and target of one migration in `migration-nodes`.
pub(crate) struct MigrationStep {
pub source: Declaration,
pub target: Declaration,
}
/// `"id"@1 => @2` or `"id"@1 => "other"@2`, as `#[migration]` and `rename!` take it. Either side may be a `network` definition.
/// `"id"@1 => @2` or `"id"@1 => "other"@2`, as `#[migration]` and `rename!` take it.
impl Parse for MigrationStep {
fn parse(input: ParseStream) -> syn::Result<Self> {
let source_network = parse_network_keyword(input)?;
let identifier: syn::LitStr = input.parse()?;
input.parse::<syn::Token![@]>()?;
let version: syn::LitInt = input.parse()?;
input.parse::<syn::Token![=>]>()?;
// A version step keeps the identifier and its kind
let (target_identifier, target_network) = if input.peek(syn::LitStr) || input.peek(syn::Ident) {
let network = parse_network_keyword(input)?;
(input.parse::<syn::LitStr>()?.value(), network)
} else {
(identifier.value(), source_network)
};
let target_identifier = if input.peek(syn::LitStr) { input.parse::<syn::LitStr>()?.value() } else { identifier.value() };
input.parse::<syn::Token![@]>()?;
let target_version: syn::LitInt = input.parse()?;
Ok(Self {
source: (named(identifier.value(), source_network), version.base10_parse()?),
target: (named(target_identifier, target_network), target_version.base10_parse()?),
source: (identifier.value(), version.base10_parse()?),
target: (target_identifier, target_version.base10_parse()?),
})
}
}
/// Consumes a leading `network` keyword, returning whether it was there.
fn parse_network_keyword(input: ParseStream) -> syn::Result<bool> {
if !input.peek(syn::Ident) {
return Ok(false);
}
let keyword: syn::Ident = input.parse()?;
if keyword != "network" {
return Err(syn::Error::new(keyword.span(), "expected `network` or a declaration identifier string"));
}
Ok(true)
}
fn named(identifier: String, network: bool) -> String {
if network { format!("{NETWORK}{identifier}") } else { identifier }
}
/// Every migration step the crate at `directory` compiles, following its modules from `lib.rs` so a file no `mod` declares doesn't count.
pub(crate) fn find_migrations(directory: &Path) -> Result<Vec<MigrationStep>, String> {
let mut steps = Vec::new();
@@ -137,8 +110,8 @@ pub(crate) fn lineage_problems(nodes: &[Declaration], migrations: &[MigrationSte
}
}
// A target is a current declaration, or a step on the way to one. Network definitions aren't checked, since the editor declares them
for step in migrations.iter().filter(|step| !step.target.0.starts_with(NETWORK)) {
// A target is a current declaration, or a step on the way to one
for step in migrations {
if !current.contains(&step.target) && !sources.contains(&step.target) {
let ((source, from), (target, to)) = (&step.source, &step.target);
problems.push(format!(
@@ -171,27 +144,6 @@ mod tests {
assert_eq!((replacement.source, replacement.target), (declaration("a::B", 2), declaration("c::D", 3)));
}
#[test]
fn parses_network_definitions_on_either_side() {
let version_step: MigrationStep = syn::parse_str(r#"network "A"@1 => @2"#).unwrap();
assert_eq!((version_step.source, version_step.target), (declaration("network A", 1), declaration("network A", 2)));
let collapse: MigrationStep = syn::parse_str(r#"network "A"@1 => "c::D"@2"#).unwrap();
assert_eq!((collapse.source, collapse.target), (declaration("network A", 1), declaration("c::D", 2)));
assert!(syn::parse_str::<MigrationStep>(r#"subgraph "A"@1 => @2"#).is_err());
}
#[test]
fn network_steps_lead_to_nodes_and_to_definitions_this_check_cannot_see() {
let nodes = [declaration("c::D", 2)];
let migrations = [
step(declaration("network A", 1), declaration("c::D", 2)),
step(declaration("network B", 1), declaration("network B", 2)),
];
assert!(lineage_problems(&nodes, &migrations).is_empty());
}
#[test]
fn whole_lineages_pass() {
let nodes = [declaration("a", 1), declaration("b", 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`, `&mut Downstream`, or `&mut Attributes`\");\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\
}}\n\n\
#[cfg(test)]\n\
mod tests {{\n\
-1
View File
@@ -80,4 +80,3 @@ env_logger = { workspace = true }
futures = { workspace = true }
node-macro = { workspace = true }
core-types = { workspace = true }
migration-core = { workspace = true, features = ["typed"] }
@@ -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_proto_node_type;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_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_proto_node_type(graphene_std::vector::path::IDENTIFIER) else {
let Some(node_type) = resolve_network_node_type("Path") else {
error!("Path node does not exist");
continue;
};
@@ -65,9 +65,9 @@ const DEFAULT_ROWS_IN_VIEW: Range<usize> = 0..100;
impl MessageHandler<DataPanelMessage, DataPanelMessageContext<'_>> for DataPanelMessageHandler {
fn process_message(&mut self, message: DataPanelMessage, responses: &mut VecDeque<Message>, context: DataPanelMessageContext) {
match message {
DataPanelMessage::UpdateLayout { inspect_result } => {
self.introspected_data = inspect_result.data;
self.introspected_node_path = inspect_result.node_path;
DataPanelMessage::UpdateLayout { mut inspect_result } => {
self.introspected_data = inspect_result.take_data();
self.introspected_node_path = inspect_result.inspect_node_path;
self.context = inspect_result.context;
self.update_layout(responses, context);
}
@@ -618,7 +618,7 @@ impl<T: TableItemLayout> TableItemLayout for Item<T> {
}
}
let attribute_keys: Vec<String> = self.attributes().keys().filter(|key| !key.starts_with(INTERNAL_ATTRIBUTE_PREFIX)).map(str::to_string).collect();
let attribute_keys: Vec<String> = self.attributes().keys().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,6 +262,9 @@ 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,7 +2232,6 @@ 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,
@@ -4895,7 +4894,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 must not leave a dangling reference that crashes compilation.
// Inspecting it via the Data panel (which splices in a monitor node) 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();
@@ -4910,7 +4909,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
// Simulate the Data panel inspecting the merged node, which compiles the graph with a monitor node spliced in
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: stack it `y_offset` below its previous sibling, based on that sibling's subtree extent
// Below top: set `Stack` with `y_offset` based on previous 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::stacked(y_offset), &[]);
network_interface.set_layer_position_for_import(&child_layer.to_node(), LayerPosition::Stack(y_offset), &[]);
}
// Recurse into group children to set their descendants' positions
@@ -137,9 +137,7 @@ 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_proto_node_type(graphene_std::vector::path::IDENTIFIER)
.expect("Path node does not exist")
.default_node_template();
let path = resolve_network_node_type("Path").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);
@@ -152,7 +150,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_proto_node_type(graphene_std::vector::path::IDENTIFIER)
let shape = resolve_network_node_type("Path")
.expect("Path node does not exist")
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::VectorModification(modification), false))]);
let shape_id = NodeId::new();
@@ -412,7 +410,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 *reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER) {
if node_definition.identifier == "Path" {
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 {
@@ -996,7 +994,7 @@ impl<'a> ModifyInputsContext<'a> {
}
pub fn vector_modify(&mut self, modification_type: VectorModificationType) {
let Some(path_node_id) = self.existing_proto_node_id(graphene_std::vector::path::IDENTIFIER, true) else {
let Some(path_node_id) = self.existing_network_node_id("Path", true) else {
return;
};
self.network_interface.vector_modify(&path_node_id, modification_type);
@@ -1110,7 +1108,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.place_at(&node_id, *position, network_path);
network_interface.set_absolute_position(&node_id, *position, network_path);
}
}
@@ -124,10 +124,6 @@ pub struct DocumentNodeDefinition {
/// Used to create the [`DefinitionIdentifier::Network`] identifier.
pub identifier: &'static str,
/// The definition's position in its lineage. Bump it, with a `network` migration, when a change would load existing instances wrongly.
/// Instances store it next to their reference. Proto-node definitions take theirs from the node macro.
pub version: u32,
/// The default [`NodeTemplate`] this definition instantiates.
pub node_template: NodeTemplate,
@@ -158,7 +154,6 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
let custom = vec![
DocumentNodeDefinition {
identifier: "Custom Node",
version: 1,
category: "Routing",
icon: Some("NodeCustomNode"),
node_template: NodeTemplate {
@@ -170,7 +165,6 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Merge",
version: 1,
category: "Graphic",
icon: Some("NodeMerge"),
node_template: NodeTemplate {
@@ -239,7 +233,6 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Artboard",
version: 1,
category: "Graphic",
icon: Some("NodeArtboard"),
node_template: NodeTemplate {
@@ -340,7 +333,6 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Blend",
version: 1,
category: "Vector: Deform",
icon: Some("NodeBlend"),
node_template: NodeTemplate {
@@ -525,7 +517,6 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Origins to Polyline",
version: 1,
category: "Vector: Path",
icon: Some("NodeOriginsToPolyline"),
node_template: NodeTemplate {
@@ -607,7 +598,6 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Load Image",
version: 1,
category: "Data: I/O",
icon: Some("NodeLoadImage"),
node_template: NodeTemplate {
@@ -648,7 +638,6 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
#[cfg(feature = "gpu")]
DocumentNodeDefinition {
identifier: "Rasterize",
version: 1,
category: "Raster",
icon: Some("NodeRasterize"),
node_template: NodeTemplate {
@@ -677,7 +666,6 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Extract",
version: 1,
category: "",
icon: None,
node_template: NodeTemplate {
@@ -693,7 +681,6 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Regex Find",
version: 1,
category: "String: Regex",
icon: Some("NodeRegexFind"),
node_template: NodeTemplate {
@@ -769,6 +756,55 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Path",
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)
@@ -802,6 +838,10 @@ 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
}
@@ -1430,11 +1470,6 @@ pub fn resolve_document_node_type(identifier: &DefinitionIdentifier) -> Option<&
DOCUMENT_NODE_TYPES.get(identifier)
}
/// The current version of the network definition `identifier`, or 1 for a reference that names no definition.
pub fn network_definition_version(identifier: &str) -> u32 {
resolve_network_node_type(identifier).map_or(1, |definition| definition.version)
}
impl InputTypeConstraint {
#[must_use]
fn type_name(ty: &Type) -> String {
@@ -1644,7 +1679,7 @@ impl DocumentNodeDefinition {
#[cfg(test)]
mod test {
use super::{DOCUMENT_NODE_TYPES, DefinitionIdentifier, resolve_network_node_type};
use super::resolve_network_node_type;
use crate::test_utils::test_prelude::*;
use graph_craft::document::NodeId;
@@ -1720,20 +1755,6 @@ mod test {
let empty: Vec<_> = CATEGORY_ORDER.iter().filter(|category| !categories.contains(*category)).collect();
assert!(empty.is_empty(), "`CATEGORY_ORDER` lists categories with no nodes: {empty:?}");
}
#[test]
fn every_bumped_network_definition_has_a_migration_leading_to_it() {
let targets: Vec<_> = migration_core::registered_migrations().iter().map(|migration| migration.target()).collect();
for (identifier, definition) in DOCUMENT_NODE_TYPES.iter() {
if !matches!(identifier, DefinitionIdentifier::Network(_)) || definition.version == 1 {
continue;
}
let declaration = migration_core::Declaration::network(definition.identifier, definition.version);
assert!(targets.contains(&declaration), "{declaration} has no migration leading to it");
}
}
}
#[cfg(test)]
@@ -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) bypass that registration but are wired up manually in
// `skip_impl` nodes (e.g. Cache, Monitor) 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;
@@ -43,7 +43,6 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
description,
inspector,
output_fields,
version,
..
} = metadata;
@@ -86,7 +85,6 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
identifier,
DocumentNodeDefinition {
identifier: display_name,
version: *version,
node_template: NodeTemplate {
inputs,
call_argument: input_type.clone(),
@@ -89,8 +89,6 @@ 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.
@@ -185,7 +183,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::ProtoNode(graphene_std::vector::path::IDENTIFIER),
node_type: DefinitionIdentifier::Network("Path".into()),
layer,
});
responses.add(EventMessage::SelectionChanged);
@@ -1439,8 +1437,6 @@ 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;
@@ -1626,7 +1622,6 @@ 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);
@@ -2170,7 +2165,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, self.keep_upstream_in_place, selection_network_path);
network_interface.shift_selected_nodes(direction, self.shift_without_push, selection_network_path);
if !rubber_band {
network_interface.clear_drag_offsets(selection_network_path);
@@ -4081,7 +4076,6 @@ 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 or filled in by the compiler
if let Some(NodeInput::Scope(_) | NodeInput::Reflection(_)) = context
// Hide inputs that are connected to a scope
if let Some(NodeInput::Scope(_)) = context
.network_interface
.input_from_connector(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
{
@@ -6,6 +6,5 @@
mod lifecycle_tests;
mod metadata_tests;
mod relative_positions_tests;
mod round_trip_tests;
pub(crate) mod test_support;
@@ -1,87 +0,0 @@
//! 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::ProtoNode(graphene_std::vector::path::IDENTIFIER);
let path_definition = DefinitionIdentifier::Network("Path".into());
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::ProtoNode(graphene_std::vector::path::IDENTIFIER);
let identifier = DefinitionIdentifier::Network("Path".into());
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_stack(&current_node, network_path) {
if self.is_layer(&current_node, network_path) && self.is_absolute(&current_node, network_path) {
stack_tops.insert(current_node);
break;
};
@@ -1,6 +1,6 @@
use super::{
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition, NodeTemplate,
NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, NodeNetworkInterface, NodeNetworkTemplate, 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_stack(&lower, &[]), "a layer feeding a dot rather than a layer is no longer stacked");
assert!(network_interface.is_absolute(&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,163 +315,6 @@ 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;
@@ -1,4 +1,4 @@
use super::storage_metadata::{input_metadata_entry_from_runtime, position_from_runtime, versioned_reference};
use super::storage_metadata::{input_metadata_entry_from_runtime, position_from_runtime};
use super::{DocumentNodePersistentMetadata, LayerPosition, NodePosition, NodeTypePersistentMetadata};
use super::{InputMetadata, InputPersistentMetadata};
use document_graph_storage::attr::network as network_attr;
@@ -280,7 +280,7 @@ impl EditorDelta {
let delta = match change {
NetworkMetadataChange::Reference(reference) => AttributeDelta {
key: node_attr::ui::REFERENCE.to_string(),
value: reference.clone().map(|identifier| versioned_reference(identifier).to_value()),
value: reference.clone().map(Value::Str),
},
NetworkMetadataChange::PinnedOrder(order) => {
let stored: Vec<_> = order.iter().map(|node_id| storage_node_id(*node_id)).collect();
@@ -889,12 +889,10 @@ 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,12 +101,6 @@ 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.
///
/// 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.
/// 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.
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`
/// holds the nodes on the current walk, which stops it on a cyclic graph that concurrent edits can produce.
/// stops the walk on a cyclic graph, which concurrent edits can produce, rather than recursing forever.
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,7 +53,6 @@ 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);
}
@@ -70,7 +69,6 @@ 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| {
@@ -93,12 +91,10 @@ 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
@@ -126,7 +122,7 @@ impl NodeNetworkInterface {
.map(|layer_position| layer_position + IVec2::new(-node_distance_from_layer * NODE_CHAIN_WIDTH, 0));
}
if !chain_visited.insert(downstream_node_id) {
if !visited.insert(downstream_node_id) {
log::error!("Cycle reached while resolving the chain position of node {node_id}");
return None;
}
@@ -138,127 +134,6 @@ 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 {
@@ -432,19 +307,19 @@ impl NodeNetworkInterface {
}
}
/// 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]) {
/// 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]) {
let Some(downstream_layer) = self.downstream_layer_for_chain_node(node_id, network_path) else {
log::error!("Could not get downstream layer in unchain_upstream");
log::error!("Could not get downstream layer in set_upstream_chain_to_absolute");
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 unchain_upstream");
log::error!("Could not get position in set_upstream_chain_to_absolute");
return;
};
if self.is_chain(upstream_id, network_path) {
self.place_at(upstream_id, previous_position, network_path);
self.set_absolute_position(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);
}
@@ -455,44 +330,52 @@ impl NodeNetworkInterface {
}
}
/// 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.
/// 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.
///
/// 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 {
if self.position(upstream_node_id, network_path).is_none() {
let Some(current_position) = self.position(upstream_node_id, network_path) else {
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;
}
let feeds_bottom_of_layer = match input_connector {
InputConnector::Node { node_id, input_index: 0 } => self.is_layer(node_id, network_path),
_ => false,
// 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 single_outward_wire = self
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
.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 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)
{
if multiple_outward_wires {
self.set_absolute_position(upstream_node_id, current_position, network_path);
} else {
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 absolute
/// layer is placed at `previous_position`.
/// 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`.
///
/// 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 {
@@ -515,8 +398,8 @@ impl NodeNetworkInterface {
}
} else if !is_layer {
self.try_set_node_to_chain(node_id, network_path);
} else if !self.is_relative(node_id, network_path) {
self.place_at(node_id, previous_position, network_path);
} else {
self.set_absolute_position(node_id, previous_position, network_path);
}
true
@@ -553,8 +436,7 @@ impl NodeNetworkInterface {
self.invalidate_position(layer, network_path);
}
/// 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]) {
pub fn shift_selected_nodes(&mut self, direction: Direction, shift_without_push: 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<_>>())
@@ -562,90 +444,7 @@ impl NodeNetworkInterface {
log::error!("Could not get selected nodes in shift_selected_nodes");
return;
};
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);
}
self.shift_nodes(node_ids, direction, shift_without_push, network_path);
}
pub(crate) fn shift_nodes(&mut self, node_ids: HashSet<NodeId>, direction: Direction, shift_without_push: bool, network_path: &[NodeId]) {
@@ -711,15 +510,6 @@ 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
}
@@ -728,7 +518,14 @@ 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(offset) = self.stack_offset(node_id, network_path) else { continue };
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(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");
@@ -740,7 +537,7 @@ impl NodeNetworkInterface {
continue;
}
if offset <= 0 {
if offset == 0 {
return true;
}
}
@@ -765,9 +562,9 @@ impl NodeNetworkInterface {
return;
}
// Walk down the stack to its top layer, which anchors the rest
// Walk down the stack to the layer holding an absolute position, which anchors the rest
let mut downstream_absolute_layer = *node_id;
while self.is_stack(&downstream_absolute_layer, network_path) {
while !self.is_absolute(&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)))
@@ -805,7 +602,8 @@ impl NodeNetworkInterface {
}
}
/// Shifts one node vertically, pushing whatever it collides with unless the caller asked for a bare shift.
/// 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.
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);
@@ -820,6 +618,18 @@ 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
@@ -902,6 +712,18 @@ 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) {
@@ -1023,7 +845,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.unchain_upstream(node_id, network_path);
self.set_upstream_chain_to_absolute(node_id, network_path);
self.shift_node(node_id, shift, network_path);
}
@@ -1455,7 +1277,6 @@ 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");
@@ -1470,26 +1291,20 @@ 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_chain(node_id, network_path) {
if !self.is_absolute(node_id, network_path) {
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 };
// 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 };
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_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);
if !self.is_absolute(&feeder, 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 leaves the chain while that layer is still reachable
// 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
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,24 +453,9 @@ impl NodeNetworkInterface {
})
.filter(|upstream_node_id| self.is_chain(upstream_node_id, network_path));
if let Some(upstream_node_id) = disconnected_chain_node {
self.unchain_upstream(&upstream_node_id, network_path);
self.set_upstream_chain_to_absolute(&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;
@@ -478,10 +463,6 @@ 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)
}
@@ -619,17 +600,13 @@ 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.unchain_upstream(chain_node_id, network_path);
self.set_upstream_chain_to_absolute(chain_node_id, network_path);
}
}
@@ -798,7 +775,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.unchain_upstream(upstream_node_id, network_path);
self.set_upstream_chain_to_absolute(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) {
@@ -910,17 +887,10 @@ 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
@@ -1351,20 +1321,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, take its chain out of the chain and its upstream sibling out of the stack where they are drawn
// If a layer is set to a node, set upstream nodes to absolute position, and upstream siblings to absolute position
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.unchain_upstream(&child_id, network_path);
self.set_upstream_chain_to_absolute(&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.place_at(&upstream_sibling_id, upstream_sibling_position, network_path);
self.set_absolute_position(&upstream_sibling_id, upstream_sibling_position, network_path);
}
}
(false, true) => {
@@ -1379,7 +1349,7 @@ impl NodeNetworkInterface {
{
self.set_stack_position_calculated_offset(&upstream_sibling_id, node_id, network_path);
} else {
self.unchain_upstream(&upstream_sibling_id, network_path);
self.set_upstream_chain_to_absolute(&upstream_sibling_id, network_path);
}
}
}
@@ -1402,7 +1372,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 switch between layer and node where it is drawn
// First set the position to absolute
let absolute = match is_layer {
true => NodeTypePersistentMetadata::layer(position),
false => NodeTypePersistentMetadata::node(position),
@@ -1412,7 +1382,6 @@ impl NodeNetworkInterface {
return;
};
node.set_node_type(absolute);
self.place_at(node_id, position, network_path);
// Try build the chain
if is_layer {
@@ -62,19 +62,6 @@ 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 {
@@ -954,27 +941,8 @@ 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.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)
self.query(network_path, "is_stack", |view| view.is_stack(node_id)).unwrap_or_default()
}
/// Whether the node is an Artboard node by identity, regardless of whether it currently participates in the scene.
@@ -1241,6 +1209,7 @@ 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 {
let deltas = if current.implementation == target.implementation && current.skip_deduplication == target.skip_deduplication {
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 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 Monitor and 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 Memoize) 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 Monitor) 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,48 +768,25 @@ 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, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::test_utils::test_prelude::*;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let merge = editor.create_node_by_name_at(DefinitionIdentifier::Network("Merge".into()), 0, 0).await;
let path_node_id = editor.create_node_by_name(DefinitionIdentifier::Network("Path".into())).await;
// 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:?}");
// 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:?}");
assert!(
!content_types.iter().any(|ty| ty == "Color"),
"the input should not accept a color just because its Memoize does, found {content_types:?}"
"Path's content should not accept a color just because its Monitor does, found {content_types:?}"
);
}
@@ -8,16 +8,15 @@
use std::collections::{BTreeMap, HashMap};
use document_graph_storage::attr::session;
use document_graph_storage::{InputMetadataEntry, NetworkMetadataEntry, NetworkReference, NodeMetadataEntry, NodeMetadataSource, Position, Value, from_value, to_value};
use document_graph_storage::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry, NodeMetadataSource, Position, Value, from_value, to_value};
use glam::IVec2;
use graph_craft::document::{DocumentNodeImplementation, NetworkLocation, NodeId, NodeNetwork};
use graphene_std::vector::style::RenderMode;
use super::{
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface,
NodeNetworkMetadata, NodeNetworkPersistentMetadata, NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing,
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, 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;
use crate::messages::portfolio::document::utility_types::misc::SnappingState;
use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
@@ -132,9 +131,8 @@ impl NodeMetadataSource for StorageMetadataView<'_> {
self.subnetwork_persistent(network).map(|persistent| persistent.export_descriptions.clone()).unwrap_or_default()
}
fn reference(&self, network: NetworkLocation) -> Option<NetworkReference> {
let identifier = self.network_persistent(network)?.reference.clone()?;
Some(versioned_reference(identifier))
fn reference(&self, network: NetworkLocation) -> Option<&str> {
self.network_persistent(network)?.reference.as_deref()
}
fn pinned_order(&self, network: NetworkLocation) -> Vec<NodeId> {
@@ -168,24 +166,16 @@ impl DocumentSettings<'_> {
}
}
/// The stored form of a network's reference. Opening a document migrates every instance to its definition's current version, so that is the version it holds.
pub(super) fn versioned_reference(identifier: String) -> NetworkReference {
let version = network_definition_version(&identifier);
NetworkReference { identifier, version }
}
/// The stored position of a node, which pairs with `is_layer` to reconstruct the runtime node type.
pub fn position_from_runtime(node_type: &NodeTypePersistentMetadata) -> Position {
match node_type {
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]),
},
}
}
@@ -204,10 +194,6 @@ 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,31 +144,14 @@ impl NodeMut<'_> {
self.set_node_type(node_type)
}
/// 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.
/// Offsets a node that is absolutely 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,
@@ -182,7 +165,7 @@ impl NodeMut<'_> {
return false;
}
self.set_node_type(NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::stacked(y_offset),
position: LayerPosition::Stack(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::ProtoNode(graphene_std::vector::path::IDENTIFIER))
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))
&& 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::ProtoNode(graphene_std::vector::path::IDENTIFIER))?;
graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))?;
self.compute_modified_vector(layer)
}
@@ -21,6 +21,8 @@ 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`.
@@ -55,6 +57,7 @@ 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(),
@@ -107,6 +110,7 @@ impl NodeTemplate {
call_argument,
implementation,
visible,
skip_deduplication,
compile_metadata: _,
original_location: _,
} = document_node;
@@ -157,6 +161,7 @@ impl NodeTemplate {
call_argument,
implementation,
visible,
skip_deduplication,
display_name,
input_metadata,
output_names,
@@ -174,6 +179,7 @@ impl NodeTemplate {
call_argument,
implementation,
visible,
skip_deduplication,
display_name,
mut input_metadata,
mut output_names,
@@ -205,6 +211,7 @@ 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 be Absolute or Relative, or Stack in older documents
/// Stores the position of a layer node, which can either be Absolute or Stack
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 be Absolute, Chain, or Relative
/// Stores the position of a non layer node, which can either be Absolute or Chain
pub(crate) position: NodePosition,
}
@@ -1136,33 +1136,22 @@ impl NodePersistentMetadata {
}
}
/// 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.
/// A layer can either be position as Absolute or in a Stack
#[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),
}
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
/// A node can either be position as Absolute or in a Chain
#[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,22 +237,10 @@ impl<'a, 'p> NetworkView<'a, 'p> {
})
}
pub fn is_relative(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
pub fn is_stack(&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::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,
NodeTypePersistentMetadata::Layer(layer_metadata) => matches!(layer_metadata.position, LayerPosition::Stack(_)),
_ => false,
})
}
@@ -117,6 +117,10 @@ 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"],
@@ -940,9 +944,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
aliases: &["graphene_core::vector::PathLengthNode"],
},
NodeReplacement {
node: graphene_std::vector::path::IDENTIFIER,
node: graphene_std::vector::path_modify::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",
@@ -1159,14 +1162,6 @@ 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 {
@@ -1182,7 +1177,7 @@ fn is_monitored_transform_subgraph(node: &DocumentNode, document_network: &graph
_ => false,
})
};
let Some((monitor_id, monitor)) = find_proto_node(&MONITOR_IDENTIFIER) else {
let Some((monitor_id, monitor)) = find_proto_node(&graphene_std::memo::monitor::IDENTIFIER) else {
return false;
};
let Some((transform_id, transform)) = find_proto_node(&graphene_std::transform_nodes::transform::IDENTIFIER) else {
@@ -1375,28 +1370,6 @@ 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
@@ -1408,7 +1381,8 @@ 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 has_monitor = network.nodes.values().any(|inner_node| is_monitor(&inner_node.implementation));
let monitor = DocumentNodeImplementation::ProtoNode(graphene_std::memo::monitor::IDENTIFIER);
let has_monitor = network.nodes.values().any(|inner_node| inner_node.implementation == monitor);
(is_merge_or_artboard && has_monitor).then_some((*node_id, path, reference))
})
@@ -1418,23 +1392,6 @@ 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
@@ -1910,9 +1867,6 @@ 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.
@@ -3509,7 +3463,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::ProtoNode(graphene_std::vector::path::IDENTIFIER) {
if reference == DefinitionIdentifier::Network("Path".into()) {
let input_0 = node.inputs.first()?;
if let NodeInput::Value { tagged_value, exposed } = input_0
&& let TaggedValue::VectorModification(modification) = &**tagged_value
@@ -4964,7 +4918,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(MONITOR_IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::memo::monitor::IDENTIFIER),
..Default::default()
};
network_template.nodes.insert(monitor_id, monitor_template);
@@ -4979,34 +4933,14 @@ mod tests {
else {
panic!("{name} should stay a network 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");
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"
);
}
}
// 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::proto_node(graphene_std::vector::path::IDENTIFIER, Insertion::BesideVectorLayer)
Self::network_node("Path", Insertion::BesideVectorLayer)
}
/// The Fill node, which paint edits insert under any Stroke node beside a layer with vector content when it's missing.
@@ -23,11 +23,7 @@ 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::ProtoNode(graphene_std::vector::path::IDENTIFIER))
})
.take_while(|(reference, _)| reference.as_ref().is_some_and(|node_ref| node_ref != &DefinitionIdentifier::Network("Path".into())))
.find(|(reference, _)| {
reference
.as_ref()
@@ -119,7 +115,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_proto_node_type(graphene_std::vector::path::IDENTIFIER)
let path_node = document_node_definitions::resolve_network_node_type("Path")
.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>(&[ellipse_node], &editor.runtime).unwrap(),
radius_y: instrumented.grab_ranked_input::<ellipse::RadiusYInput, f64>(&[ellipse_node], &editor.runtime).unwrap(),
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(),
transform: document.metadata().transform_to_document(layer),
})
})
@@ -635,8 +635,7 @@ 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::ProtoNode(graphene_std::vector::path::IDENTIFIER), 1)
if let Some(TaggedValue::VectorModification(modifications)) = NodeGraphLayer::new(first_layer, network_interface).find_input(&DefinitionIdentifier::Network("Path".into()), 1)
&& modifications.is_empty()
{
return None;
@@ -280,25 +280,18 @@ 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, which reach the paint input embedded as `Graphic` items
// The Fill tool writes solid colors, whose stored values the input monitor records as `Item<Color>` wires
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<Graphic>>(&editor.runtime)
.filter_map(|paint| match paint.into_element() {
Graphic::Color(color) => Some(color),
_ => None,
})
.collect()
instrumented.grab_all_input::<fill::PaintInput, Item<Color>>(&editor.runtime).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_proto_node_type;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_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_proto_node_type(graphene_std::vector::path::IDENTIFIER).expect("Path node does not exist");
let node_type = resolve_network_node_type("Path").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::ProtoNode(graphene_std::vector::path::IDENTIFIER))?;
let _ = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))?;
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_proto_node_type;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_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_proto_node_type(graphene_std::vector::path::IDENTIFIER) else {
let Some(node_type) = resolve_network_node_type("Path") 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_proto_node_type;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_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_proto_node_type(graphene_std::vector::path::IDENTIFIER).expect("Path node does not exist");
let node_type = resolve_network_node_type("Path").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::ProtoNode(graphene_std::vector::path::IDENTIFIER);
let path_identifier = DefinitionIdentifier::Network("Path".into());
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_proto_node_type;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{resolve_network_node_type, 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_proto_node_type(graphene_std::vector::path::IDENTIFIER).expect("Path node does not exist");
let path_node_type = resolve_network_node_type("Path").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))]);
+114 -162
View File
@@ -1,8 +1,7 @@
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, NodeNetworkInterface};
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
@@ -11,12 +10,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::{Item, List};
use graphene_std::list::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, path, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter};
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, Graphic};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use std::any::Any;
use std::sync::Arc;
@@ -39,20 +38,9 @@ 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>,
/// The latest result of each observation.
observations: HashMap<ObservationKey, InspectResult>,
}
/// Names an observation so it can be changed or stopped without touching the others.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
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,
vector_modify: HashMap<NodeId, VectorGeometry>,
/// The resulting value from the temporary inspected during execution
inspect_result: Option<InspectResult>,
}
#[derive(Debug)]
@@ -93,16 +81,9 @@ pub enum NodeGraphUpdate {
ExecutionResponse(Box<ExecutionResponse>),
CompilationResponse(CompilationResponse),
EyedropperPreview(Raster<CPU>),
Thumbnails {
responses: VecDeque<FrontendMessage>,
document_id: DocumentId,
},
/// The latest result of each observation, sent outside an execution after one of them changed.
Observations(HashMap<ObservationKey, InspectResult>),
ClipboardSvg {
id: u64,
svg: Option<String>,
},
Thumbnails { responses: VecDeque<FrontendMessage>, document_id: DocumentId },
InspectResult(Box<InspectResult>),
ClipboardSvg { id: u64, svg: Option<String> },
}
#[derive(Debug)]
@@ -117,8 +98,6 @@ pub struct NodeGraphExecutor {
node_graph_document: Option<DocumentId>,
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
previous_node_to_inspect: Vec<NodeId>,
/// The context overrides the Data panel evaluates its inspected node with, reset when another node is inspected.
inspect_context_overrides: ContextOverrides,
/// The canvas images the frontend holds, so a render sends only those it lacks.
canvas_images_sent: HashSet<u64>,
/// Evaluation errors of the last evaluation, used in tests
@@ -173,7 +152,6 @@ impl NodeGraphExecutor {
node_graph_hash: 0,
node_graph_document: None,
previous_node_to_inspect: Vec::new(),
inspect_context_overrides: ContextOverrides::default(),
canvas_images_sent: HashSet::new(),
#[cfg(test)]
evaluation_errors: None,
@@ -210,16 +188,8 @@ impl NodeGraphExecutor {
execution_id
}
pub fn submit_inspect_context_overrides(&mut self, overrides: ContextOverrides) {
self.inspect_context_overrides = overrides;
let Some(observation) = self.data_panel_observation() else { return };
self.sender
.send(GraphRuntimeRequest::Observe {
key: ObservationKey::DataPanel,
observation: Some(observation),
})
.expect("Failed to send the context overrides");
pub fn submit_inspect_context_overrides(&self, overrides: graphene_std::ContextOverrides) {
self.sender.send(GraphRuntimeRequest::InspectContextOverrides(overrides)).expect("Failed to send the context overrides");
}
pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message {
@@ -243,14 +213,14 @@ impl NodeGraphExecutor {
.expect("Failed to send the thumbnails in view");
}
/// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received.
/// Updates the network to monitor all inputs. Useful for the testing.
#[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(&network);
let instrumented = Instrumented::new(&mut network);
let resources = document.resources.registry.clone();
@@ -258,9 +228,9 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect: Vec::new(),
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
Ok(instrumented)
@@ -268,17 +238,12 @@ impl NodeGraphExecutor {
/// Update the cached network if necessary.
fn update_node_graph(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, node_to_inspect: Vec<NodeId>, ignore_hash: bool) -> Result<(), String> {
let inspected_node_changed = self.previous_node_to_inspect != node_to_inspect;
if inspected_node_changed {
self.previous_node_to_inspect = node_to_inspect;
self.inspect_context_overrides = ContextOverrides::default();
}
let network_hash = document.network_interface.network_hash();
if network_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash {
let network = document.network_interface.document_network().clone();
let previewed = document.network_interface.previewed_nodes();
let layers = document.network_interface.layer_paths();
self.previous_node_to_inspect.clone_from(&node_to_inspect);
self.node_graph_hash = network_hash;
self.node_graph_document = Some(document_id);
@@ -288,39 +253,19 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect,
previewed,
layers,
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
} else if inspected_node_changed {
let observation = self.data_panel_observation();
self.sender
.send(GraphRuntimeRequest::Observe {
key: ObservationKey::DataPanel,
observation,
})
.map_err(|e| e.to_string())?;
} else if self.previous_node_to_inspect != node_to_inspect {
self.previous_node_to_inspect.clone_from(&node_to_inspect);
self.sender.send(GraphRuntimeRequest::Inspect(node_to_inspect)).map_err(|e| e.to_string())?;
}
Ok(())
}
/// What the Data panel reads back, if it inspects a node.
fn data_panel_observation(&self) -> Option<Observation> {
(!self.previous_node_to_inspect.is_empty()).then(|| Observation {
node_path: self.previous_node_to_inspect.clone(),
connector: ObservedConnector::Output,
overrides: self.inspect_context_overrides.clone(),
})
}
/// Every observation a graph update of the document starts with.
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.
pub(crate) fn submit_current_node_graph_evaluation(
&mut self,
@@ -484,9 +429,9 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect: Vec::new(),
previewed,
layers: document.network_interface.layer_paths(),
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
let execution_id = self.queue_execution(render_config);
@@ -521,7 +466,8 @@ impl NodeGraphExecutor {
result,
responses: existing_responses,
dropped_thumbnails,
mut observations,
vector_modify,
inspect_result,
} = *execution_response;
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
@@ -557,8 +503,7 @@ impl NodeGraphExecutor {
// Apply only to the active document's in-progress migration, dropping responses left over from a document switch.
if let Some(bake_target) = execution_context.measure_fill {
if execution_context.document_id == document_id && self.gradient_migration.as_ref().is_some_and(|migration| migration.document_id == document_id) {
let measured = observations.remove(&ObservationKey::FillMeasurement);
let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Fallback(..)).then_some(measured).flatten();
let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Fallback(..)).then_some(inspect_result).flatten();
self.handle_gradient_measurement(document, document_id, bake_target, inspect_result, responses);
}
continue;
@@ -647,7 +592,7 @@ impl NodeGraphExecutor {
None => responses.add(response),
}
}
document.network_interface.update_vector_modify(path_contents(&observations));
document.network_interface.update_vector_modify(vector_modify);
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),
@@ -660,7 +605,6 @@ impl NodeGraphExecutor {
});
// Update the Data panel on the frontend using the value of the inspect result.
let inspect_result = observations.remove(&ObservationKey::DataPanel);
if let Some(inspect_result) = (!self.previous_node_to_inspect.is_empty()).then_some(inspect_result).flatten() {
responses.add(DataPanelMessage::UpdateLayout {
inspect_result: Box::new(inspect_result),
@@ -717,13 +661,9 @@ impl NodeGraphExecutor {
let (data, width, height) = raster.to_flat_u8();
responses.add(EyedropperToolMessage::PreviewImage { data, width, height });
}
NodeGraphUpdate::Observations(mut observations) => {
if let Some(inspect_result) = observations.remove(&ObservationKey::DataPanel)
&& inspect_result.node_path == self.previous_node_to_inspect
{
responses.add(DataPanelMessage::UpdateLayout {
inspect_result: Box::new(inspect_result),
});
NodeGraphUpdate::InspectResult(inspect_result) => {
if inspect_result.inspect_node_path == self.previous_node_to_inspect {
responses.add(DataPanelMessage::UpdateLayout { inspect_result });
}
}
NodeGraphUpdate::Thumbnails {
@@ -849,19 +789,14 @@ impl NodeGraphExecutor {
}
let resources = document.resources.registry.clone();
let fill_measurement = Observation {
node_path: full_path,
connector: ObservedConnector::Output,
overrides: ContextOverrides::default(),
};
if self
.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect: full_path.clone(),
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
}))
.is_err()
{
@@ -872,6 +807,7 @@ impl NodeGraphExecutor {
// Force the next normal render to recompile and re-send the real, non-redirected network
self.node_graph_hash = 0;
self.previous_node_to_inspect = full_path;
let viewport = Footprint {
transform: document.metadata().document_to_viewport,
@@ -922,7 +858,7 @@ impl NodeGraphExecutor {
return;
}
match inspect_result.and_then(|result| result.data).and_then(|data| measure_fill_geometry(&data)) {
match inspect_result.and_then(|mut result| result.take_data()).and_then(|data| measure_fill_geometry(&data)) {
Some((bounding_box, item_transform)) => {
// Skip the bake if the user already placed this gradient themselves, but drop the now-superseded entry either way
if fill_transform_unbaked(document, &network_path, fill_node_id) {
@@ -968,9 +904,10 @@ impl NodeGraphExecutor {
}
// TODO: Eventually remove this document upgrade code
/// Tear down the in-progress migration and clear the hash so the next normal render recompiles the real network.
/// Tear down the in-progress migration and clear the stale inspect target and hash so the next normal render recompiles the real network.
fn cancel_gradient_migration(&mut self) {
self.gradient_migration = None;
self.previous_node_to_inspect = Vec::new();
self.node_graph_hash = 0;
}
@@ -1181,110 +1118,125 @@ 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::NodeNetwork;
use graph_craft::document::{DocumentNode, NodeNetwork};
use graphene_std::Context;
use graphene_std::NodeParameter;
use graphene_std::list::Item;
use graphene_std::memo::IORecord;
use test_prelude::LayerNodeIdentifier;
/// The path of each proto node in an evaluated graph, by which tests read the values its inputs received.
/// Stores all of the monitor nodes that have been attached to a graph
#[derive(Default)]
pub struct Instrumented {
protonodes_by_name: HashMap<ProtoNodeIdentifier, Vec<Vec<NodeId>>>,
protonodes_by_name: HashMap<ProtoNodeIdentifier, Vec<Vec<Vec<NodeId>>>>,
protonodes_by_path: HashMap<Vec<NodeId>, Vec<Vec<NodeId>>>,
}
impl Instrumented {
/// 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()),
_ => {}
/// 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();
}
path.pop();
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);
}
}
pub fn new(network: &NodeNetwork) -> Self {
/// Instrument a graph and return a new [Instrumented] state.
pub fn new(network: &mut NodeNetwork) -> Self {
let mut instrumented = Self::default();
instrumented.add(network, &mut Vec::new());
instrumented
}
/// 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()
/// 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())
}
}
/// 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 {
/// 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 {
self.protonodes_by_name
.get(&Input::NODE_IDENTIFIER)
.map_or([].as_slice(), |paths| paths.as_slice())
.map_or([].as_slice(), |x| x.as_slice())
.iter()
.filter_map(|path| Self::grab_input::<Output>(path, Input::INDEX, runtime))
.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>)
}
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)
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)
}
/// 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)
/// 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())
}
pub fn grab_input_from_layer<Input: NodeParameter, Output: Clone + 'static>(
pub fn grab_input_from_layer<Input: NodeParameter, Output: Send + Sync + Clone + 'static>(
&self,
layer: LayerNodeIdentifier,
network_interface: &NodeNetworkInterface,
@@ -1292,7 +1244,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>(&[node], runtime)
self.grab_protonode_input::<Input, Output>(&vec![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 graph before it.
/// for one more update, so a first update clears those of the test harness's instrumented graph.
async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> {
compile_and_run(editor).await;
compile_and_run(editor).await;
+222 -53
View File
@@ -2,7 +2,7 @@ use super::*;
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::portfolio::document::utility_types::network_interface::RootNode;
use crate::task::{Spawn, Spawner, Task};
use glam::UVec2;
use glam::{DVec2, UVec2};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
@@ -11,23 +11,23 @@ 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::{Context, NodeError, Poll};
use graphene_std::vector::{Vector, VectorGeometry, paths_from_list_row_attributes};
use graphene_std::{Context, ContextFeatures, ContextOverrides, NodeError, OwnedContextImpl, Poll};
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::util::wrap_network_in_scope;
use observer::Observer;
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender};
use thumbnails::Thumbnails;
mod observer;
mod thumbnails;
/// Persistent data between graph executions. It's updated via message passing from the editor thread with [`GraphRuntimeRequest`]`.
@@ -54,13 +54,17 @@ 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.
observations_changed: bool,
/// The node the Data panel inspects.
inspect_state: Option<InspectState>,
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,
@@ -74,31 +78,22 @@ pub struct NodeRuntime {
pub enum GraphRuntimeRequest {
GraphUpdate(GraphUpdate),
ExecutionRequest(ExecutionRequest),
ThumbnailsInView {
layers: HashSet<NodeId>,
document_id: DocumentId,
},
/// Starts, changes, or with `None` stops one observation without a graph update.
Observe {
key: ObservationKey,
observation: Option<Observation>,
},
ClipboardSvg {
id: u64,
layers: Vec<NodeId>,
},
ThumbnailsInView { layers: HashSet<NodeId>, document_id: DocumentId },
Inspect(Vec<NodeId>),
InspectContextOverrides(ContextOverrides),
ClipboardSvg { id: u64, layers: Vec<NodeId> },
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct GraphUpdate {
pub(super) network: NodeNetwork,
pub(super) resources: ResourceRegistry,
/// Full path from the root network to the node the Data panel inspects.
pub(super) node_to_inspect: Vec<NodeId>,
/// The node each network renders in place of its export, paired with that network's path.
pub(super) previewed: Vec<(Vec<NodeId>, RootNode)>,
/// Full path from the root network to every layer, which are the nodes with thumbnails.
pub(super) layers: Vec<Vec<NodeId>>,
/// The connectors whose values are sent back after each evaluation, replacing those observed before.
pub(super) observations: HashMap<ObservationKey, Observation>,
}
/// Replaces each network's primary export with its previewed node.
@@ -148,12 +143,14 @@ 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(),
inspect_state: None,
#[cfg(all(target_family = "wasm", feature = "gpu"))]
wasm_canvas_cache: CanvasSurfaceHandle::new(),
#[cfg(all(target_family = "wasm", feature = "gpu"))]
@@ -184,15 +181,17 @@ impl NodeRuntime {
self.thumbnails.set_in_view(layers);
self.pending_thumbnails = Some(document_id);
}
// A graph update applied after this loop would otherwise replace this with what it observed before
GraphRuntimeRequest::Observe { key, observation } => match (&mut graph, observation) {
(Some(update), Some(observation)) => _ = update.observations.insert(key, observation),
(Some(update), None) => _ = update.observations.remove(&key),
(None, observation) => {
self.observer.set(key, observation);
self.observations_changed = true;
}
// A graph update applied after this loop would otherwise inspect what was selected before
GraphRuntimeRequest::Inspect(node_to_inspect) => match &mut graph {
Some(update) => update.node_to_inspect = node_to_inspect,
None => self.inspect_state = InspectState::new(node_to_inspect),
},
GraphRuntimeRequest::InspectContextOverrides(overrides) => {
if let Some(inspect_state) = &mut self.inspect_state {
inspect_state.overrides = overrides;
inspect_state.overrides_changed = true;
}
}
GraphRuntimeRequest::ClipboardSvg { id, layers } => {
let svg = self.old_graph.as_ref().and_then(|network| thumbnails::layers_svg(&layers, network, &self.executor));
self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response");
@@ -203,16 +202,21 @@ impl NodeRuntime {
let Some(GraphUpdate {
mut network,
resources,
node_to_inspect,
previewed,
layers,
observations,
}) = graph
else {
return;
};
apply_previews(&mut network, &previewed);
self.observer.replace_all(observations);
match &mut self.inspect_state {
Some(inspect_state) if inspect_state.inspect_node_path == node_to_inspect => inspect_state.last_evaluation = None,
_ => self.inspect_state = InspectState::new(node_to_inspect),
}
self.resources = resources;
self.node_graph_errors.clear();
@@ -255,9 +259,12 @@ impl NodeRuntime {
}
}
if std::mem::take(&mut self.observations_changed) && viewport.is_none() {
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
self.sender.send(NodeGraphUpdate::Observations(observations)).expect("Failed to send response");
if let Some(inspect_state) = &mut self.inspect_state
&& std::mem::take(&mut inspect_state.overrides_changed)
&& viewport.is_none()
{
let inspect_result = inspect_state.access(&self.executor, self.old_graph.as_ref());
self.sender.send(NodeGraphUpdate::InspectResult(Box::new(inspect_result))).expect("Failed to send response");
}
if let Some(eyedropper) = self.pending_eyedropper.take() {
@@ -366,7 +373,8 @@ impl NodeRuntime {
result: ExecutionResult::Panic(payload),
responses: VecDeque::new(),
dropped_thumbnails: Vec::new(),
observations: HashMap::new(),
vector_modify: HashMap::new(),
inspect_result: None,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
return None;
@@ -377,27 +385,20 @@ impl NodeRuntime {
async fn respond(&mut self, execution_id: u64, result: ExecutionResult) {
let mut responses = VecDeque::new();
let dropped_thumbnails = self.update_thumbnails(&mut responses).await;
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
let dropped_thumbnails = self.process_monitor_nodes(&mut responses).await;
let inspect_result = self.inspect_state.as_mut().map(|state| state.access(&self.executor, self.old_graph.as_ref()));
let response = ExecutionResponse {
execution_id,
result,
responses,
dropped_thumbnails,
observations,
vector_modify: self.vector_modify.clone(),
inspect_result,
};
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");
@@ -425,6 +426,12 @@ 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)| {
@@ -455,9 +462,41 @@ impl NodeRuntime {
EvaluationErrors(errors.into())
}
/// 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> {
/// 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> {
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
@@ -472,6 +511,35 @@ 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 context_features(context: &OwnedContextImpl) -> InspectedContext {
use graphene_std::{ExtractAnimationTime, ExtractFootprint, ExtractIndex, ExtractPointerPosition, ExtractPosition, ExtractRealTime, ExtractVarArgs};
InspectedContext {
features: ContextOverrides {
footprint: context.try_footprint().copied(),
real_time: context.try_real_time(),
animation_time: context.try_animation_time(),
pointer_position: context.try_pointer_position(),
index: context.try_index().map(|index| index.collect()),
},
positions: context.try_position().map(|positions| positions.collect()).unwrap_or_default(),
variables: context.varargs_len().unwrap_or_default(),
..Default::default()
}
}
fn evaluated_output(poll: Poll<graphene_std::registry::Any>) -> Option<graphene_std::registry::Any> {
match poll {
Poll::Final(output) | Poll::Partial(output) => Some(output),
@@ -526,11 +594,112 @@ impl Spawn for NodeTaskExecutor {
}
}
/// The node the Data panel inspects, which is evaluated again from the context it was last evaluated with.
struct InspectState {
inspect_node_path: Vec<NodeId>,
overrides: ContextOverrides,
last_evaluation: Option<(NodeId, u64, Option<InspectedData>)>,
overrides_changed: bool,
}
type InspectedData = Arc<dyn std::any::Any + Send + Sync + 'static>;
/// The resulting value from the temporary inspected during execution
#[derive(Clone, Debug, Default)]
pub struct InspectResult {
introspected_data: Option<Arc<dyn std::any::Any + Send + Sync + 'static>>,
/// Full path from the root network to the inspected node, with the node itself as the last element.
/// The parent slice (`split_last().1`) is the network the node lives in, which downstream consumers
/// (e.g. the Data panel) need when looking the node up via `network_interface.is_layer(...)` etc.
pub inspect_node_path: Vec<NodeId>,
pub context: InspectedContext,
}
/// The features of the context an inspected node was evaluated with, after the overrides replaced some of them.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct InspectedContext {
pub features: ContextOverrides,
/// The positions the context carries, from the outermost level in.
pub positions: Vec<DVec2>,
pub variables: usize,
pub overrides: ContextOverrides,
pub dependencies: ContextFeatures,
}
impl InspectResult {
pub fn take_data(&mut self) -> Option<Arc<dyn std::any::Any + Send + Sync + 'static>> {
self.introspected_data.clone()
}
}
// This is very ugly but is required to be inside a message
impl PartialEq for InspectResult {
fn eq(&self, other: &Self) -> bool {
self.inspect_node_path == other.inspect_node_path
}
}
impl InspectState {
fn new(inspect_node_path: Vec<NodeId>) -> Option<Self> {
(!inspect_node_path.is_empty()).then_some(Self {
inspect_node_path,
overrides: ContextOverrides::default(),
last_evaluation: None,
overrides_changed: false,
})
}
fn access(&mut self, executor: &DynamicExecutor, network: Option<&NodeNetwork>) -> InspectResult {
let node = network.and_then(|network| executor.tree().output_node(network, &self.inspect_node_path));
let context = node.and_then(|node| executor.tree().last_context(node).ok().flatten()).map(|context| self.with_overrides(context));
let introspected_data = node.zip(context.clone()).and_then(|(node, context)| self.evaluate(executor, node, context));
let features = context.as_ref().and_then(|context| context.as_deref()).map(context_features).unwrap_or_default();
let context = InspectedContext {
overrides: self.overrides.clone(),
dependencies: node.map(|node| executor.tree().context_features(node)).unwrap_or_default(),
..features
};
InspectResult {
introspected_data,
inspect_node_path: self.inspect_node_path.clone(),
context,
}
}
fn with_overrides(&self, context: Context<'static>) -> Context<'static> {
if self.overrides.is_empty() {
return context;
}
let context = context
.as_deref()
.map(|context| context.with_overrides(&self.overrides))
.unwrap_or_else(|| OwnedContextImpl::empty().with_overrides(&self.overrides));
Some(Arc::new(context))
}
/// Evaluates the node with the context, reusing the last result if neither changed.
fn evaluate(&mut self, executor: &DynamicExecutor, node: NodeId, context: Context<'static>) -> Option<Arc<dyn std::any::Any + Send + Sync + 'static>> {
let context_hash = context_hash(&context);
if let Some((last_node, last_context_hash, data)) = &self.last_evaluation
&& (*last_node, *last_context_hash) == (node, context_hash)
{
return data.clone();
}
let output = evaluated_output(executor.tree().evaluate(node, &context).ok()?)?;
// Output the Data panel can't show is remembered too, so it isn't evaluated again for nothing
let data = crate::messages::portfolio::document::data_panel::shareable_inspect_output(output);
self.last_evaluation = Some((node, context_hash, data.clone()));
data
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::EditorTestUtils;
use glam::DVec2;
use graph_craft::document::DocumentNode;
use graphene_std::SourceId;
use graphene_std::runtime::Runtime;
@@ -1,185 +0,0 @@
use super::{context_hash, evaluated_output};
use crate::messages::portfolio::document::data_panel::shareable_inspect_output;
use glam::DVec2;
use graph_craft::document::{NodeId, NodeNetwork};
use graphene_std::{Context, ContextFeatures, ContextOverrides, OwnedContextImpl};
use interpreted_executor::dynamic_executor::{BorrowTree, DynamicExecutor};
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::Arc;
pub type ObservedValue = Arc<dyn std::any::Any + Send + Sync + 'static>;
/// A connector of a document node whose value the editor reads back after each evaluation.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Observation {
pub node_path: Vec<NodeId>,
pub connector: ObservedConnector,
/// Replaces parts of the context the value is evaluated with.
pub overrides: ContextOverrides,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ObservedConnector {
Input(usize),
Output,
}
/// The value an observation read, with the context it was evaluated with.
#[derive(Clone, Debug, Default)]
pub struct InspectResult {
pub data: Option<ObservedValue>,
pub node_path: Vec<NodeId>,
pub context: InspectedContext,
}
/// The features of the context an inspected node was evaluated with, after the overrides replaced some of them.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct InspectedContext {
pub features: ContextOverrides,
pub positions: Vec<DVec2>,
pub variables: usize,
pub overrides: ContextOverrides,
pub dependencies: ContextFeatures,
}
// This is very ugly but is required to be inside a message
impl PartialEq for InspectResult {
fn eq(&self, other: &Self) -> bool {
self.node_path == other.node_path
}
}
/// Evaluates each observed connector again from the context its node was last evaluated with.
pub struct Observer<Key> {
observations: HashMap<Key, ObservationState>,
}
struct ObservationState {
observation: Observation,
last_evaluation: Option<Evaluation>,
}
struct Evaluation {
source: NodeId,
context_hash: u64,
value: Option<ObservedValue>,
}
impl<Key> Default for Observer<Key> {
fn default() -> Self {
Self { observations: HashMap::new() }
}
}
impl<Key: Clone + Eq + Hash> Observer<Key> {
/// Replaces every observation, keeping the last evaluation of those that stayed the same.
pub fn replace_all(&mut self, observations: HashMap<Key, Observation>) {
let mut previous = std::mem::take(&mut self.observations);
self.observations = observations
.into_iter()
.map(|(key, observation)| {
let state = ObservationState::new(observation, previous.remove(&key));
(key, state)
})
.collect();
}
/// Starts, changes, or with `None` stops the observation under this key.
pub fn set(&mut self, key: Key, observation: Option<Observation>) {
let previous = self.observations.remove(&key);
let Some(observation) = observation else { return };
self.observations.insert(key, ObservationState::new(observation, previous));
}
/// Evaluates the observations whose source or context changed, giving back the latest result of each.
pub fn evaluate(&mut self, executor: &DynamicExecutor, network: Option<&NodeNetwork>) -> HashMap<Key, InspectResult> {
let tree = executor.tree();
self.observations.iter_mut().map(|(key, state)| (key.clone(), state.evaluate(tree, network))).collect()
}
}
impl ObservationState {
fn new(observation: Observation, previous: Option<ObservationState>) -> Self {
let last_evaluation = previous.filter(|previous| previous.observation == observation).and_then(|previous| previous.last_evaluation);
Self { observation, last_evaluation }
}
fn evaluate(&mut self, tree: &BorrowTree, network: Option<&NodeNetwork>) -> InspectResult {
let Observation { node_path, connector, overrides } = &self.observation;
let source = match connector {
ObservedConnector::Input(index) => tree.input_node(node_path, *index).ok(),
ObservedConnector::Output => network.and_then(|network| tree.output_node(network, node_path)),
};
let context = source.and_then(|source| tree.last_context(source).ok().flatten()).map(|context| with_overrides(context, overrides));
let introspected_data = source
.zip(context.clone())
.and_then(|(source, context)| evaluate_value(&mut self.last_evaluation, tree, source, context));
let features = context.as_ref().and_then(|context| context.as_deref()).map(context_features).unwrap_or_default();
let context = InspectedContext {
overrides: overrides.clone(),
dependencies: source.map(|source| tree.context_features(source)).unwrap_or_default(),
..features
};
InspectResult {
data: introspected_data,
node_path: node_path.clone(),
context,
}
}
}
/// Evaluates the node with the context, reusing the last result if neither changed.
fn evaluate_value(last_evaluation: &mut Option<Evaluation>, tree: &BorrowTree, source: NodeId, context: Context<'static>) -> Option<ObservedValue> {
let context_hash = context_hash(&context);
if let Some(evaluation) = last_evaluation
&& (evaluation.source, evaluation.context_hash) == (source, context_hash)
{
return evaluation.value.clone();
}
let output = evaluated_output(tree.evaluate(source, &context).ok()?)?;
// Output that can't be shared is remembered too, so it isn't evaluated again for nothing
let value = shareable_inspect_output(output);
*last_evaluation = Some(Evaluation {
source,
context_hash,
value: value.clone(),
});
value
}
fn with_overrides(context: Context<'static>, overrides: &ContextOverrides) -> Context<'static> {
if overrides.is_empty() {
return context;
}
let context = context
.as_deref()
.map(|context| context.with_overrides(overrides))
.unwrap_or_else(|| OwnedContextImpl::empty().with_overrides(overrides));
Some(Arc::new(context))
}
fn context_features(context: &OwnedContextImpl) -> InspectedContext {
use graphene_std::{ExtractAnimationTime, ExtractFootprint, ExtractIndex, ExtractPointerPosition, ExtractPosition, ExtractRealTime, ExtractVarArgs};
InspectedContext {
features: ContextOverrides {
footprint: context.try_footprint().copied(),
real_time: context.try_real_time(),
animation_time: context.try_animation_time(),
pointer_position: context.try_pointer_position(),
index: context.try_index().map(|index| index.collect()),
},
positions: context.try_position().map(|positions| positions.collect()).unwrap_or_default(),
variables: context.varargs_len().unwrap_or_default(),
..Default::default()
}
}
+2 -1
View File
@@ -14,6 +14,7 @@ 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,
}
@@ -138,7 +139,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 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.
## 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 observing node values.
/// 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.
///
/// 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,6 +28,7 @@ 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,6 +44,11 @@ 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.
@@ -77,6 +82,7 @@ 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(),
}
@@ -811,6 +817,7 @@ 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,6 +88,11 @@ 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,6 +124,7 @@ 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,
@@ -136,6 +137,7 @@ 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(),
}
@@ -144,12 +146,16 @@ 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);
@@ -167,6 +173,7 @@ impl ProtoNode {
path: Some(path),
..Default::default()
},
skip_deduplication: false,
compile_metadata: Default::default(),
upstream_context_features: ContextFeatures::empty(),
}
@@ -348,6 +355,7 @@ impl ProtoNetwork {
},
compile_metadata: forwarding,
upstream_context_features: features,
..Default::default()
},
));
@@ -379,6 +387,7 @@ impl ProtoNetwork {
},
compile_metadata: forwarding,
upstream_context_features: features,
..Default::default()
},
));
nullification_node_id
@@ -73,3 +73,8 @@ harness = false
name = "brush_stroke_gungraun"
harness = false
required-features = ["gpu"]
[[bench]]
name = "artwork_gungraun"
harness = false
required-features = ["gpu"]
@@ -0,0 +1,190 @@
//! Counts the instructions for editing and viewing the demo artwork once it has been rendered, as the editor renders it after each change:
//! drawing a rectangle on top of it, which recompiles the graph and renders the viewport,
//! and zooming in, which renders the viewport anew since none of the cached tiles match the new zoom.
mod gpu_util;
use glam::{DAffine2, DVec2};
use gpu_util::{GpuDocument, VIEWPORT, callgrind};
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use graphene_std::transform_nodes::transform;
use graphene_std::vector::generator_nodes::rectangle;
use graphene_std::vector::{GradientForm, GradientRamp};
use graphene_std::vector_nodes::fill;
use graphene_std::{Color, Context};
use gungraun::prelude::*;
use std::path::Path;
/// The zoom step the measured render takes, about the viewport center.
const ZOOM: f64 = 1.5;
/// The new rectangle's nodes, numbered clear of the document's own so every run builds the same graph.
const RECTANGLE: NodeId = NodeId(u64::MAX - 3);
const TRANSFORM: NodeId = NodeId(u64::MAX - 2);
const FILL: NodeId = NodeId(u64::MAX - 1);
const LAYER: NodeId = NodeId(u64::MAX);
pub struct Session {
gpu: GpuDocument,
/// Where the viewport shows the artwork.
view: DAffine2,
/// The document graph for the measured update.
document: NodeNetwork,
}
/// Opens lavapipe and renders the demo artwork `name` fitted into the viewport, so the measured step meets the caches the editor would have.
fn open(name: &str) -> (Session, NodeNetwork) {
let network = futures::executor::block_on(document_loader::open_document(Path::new(&format!("../../demo-artwork/{name}.graphite"))))
.expect("Failed to open the demo artwork")
.network;
let view = fit(&network);
let mut gpu = GpuDocument::new();
gpu.compile(network.clone());
gpu.render(view);
let session = Session {
gpu,
view,
document: NodeNetwork::default(),
};
(session, network)
}
fn setup_add_rectangle(name: &str) -> Session {
let (mut session, network) = open(name);
session.document = with_rectangle(network);
session
}
/// The artwork viewed after zooming out and back, so the device has the shaders for a zoom change while no tiles at the measured zoom are cached.
fn setup_zoom(name: &str) -> Session {
let (session, _) = open(name);
session.gpu.render(zoomed(session.view, 1. / ZOOM));
session.gpu.render(session.view);
session
}
/// The view zoomed by `factor` about the viewport center.
fn zoomed(view: DAffine2, factor: f64) -> DAffine2 {
let center = VIEWPORT.as_dvec2() / 2.;
DAffine2::from_translation(center) * DAffine2::from_scale(DVec2::splat(factor)) * DAffine2::from_translation(-center) * view
}
/// The view that fits the document's root artboard into the viewport with a margin, as zooming to fit does.
fn fit(network: &NodeNetwork) -> DAffine2 {
let artboard = root(network);
let location = vec_input(artboard, 2);
let size = vec_input(artboard, 3);
let scale = (VIEWPORT.as_dvec2() / size).min_element() * 0.9;
let offset = (VIEWPORT.as_dvec2() - size * scale) / 2. - location * scale;
DAffine2::from_translation(offset) * DAffine2::from_scale(DVec2::splat(scale))
}
/// The document with a rectangle layer on top of its artboard's other layers, with the nodes the Rectangle tool creates.
fn with_rectangle(mut network: NodeNetwork) -> NodeNetwork {
let artboard = root(&network);
let location = vec_input(artboard, 2);
let size = vec_input(artboard, 3);
let NodeInput::Node { node_id: top, .. } = artboard.inputs[1] else {
panic!("The artboard has no layers");
};
// The top layer serves as the template for the new one, sharing the document's layer definition
let mut layer = network.nodes[&top].clone();
assert!(matches!(layer.implementation, DocumentNodeImplementation::Definition(_)), "The artboard's top layer is no layer node");
layer.inputs[0] = NodeInput::node(top, 0);
layer.inputs[1] = NodeInput::node(FILL, 0);
let node = |implementation, inputs| DocumentNode {
inputs,
call_argument: concrete!(Context),
implementation: DocumentNodeImplementation::ProtoNode(implementation),
..Default::default()
};
let value = |value| NodeInput::value(value, false);
let rectangle = node(
rectangle::IDENTIFIER,
vec![
value(TaggedValue::None),
value(TaggedValue::Number(size.x / 3.)),
value(TaggedValue::Number(size.y / 3.)),
value(TaggedValue::BoxCorners(vec![0.])),
value(TaggedValue::Bool(true)),
value(TaggedValue::Bool(false)),
],
);
let transform = node(
transform::IDENTIFIER,
vec![
NodeInput::node(RECTANGLE, 0),
value(TaggedValue::DVec2(location + size / 2.)),
value(TaggedValue::Number(0.)),
value(TaggedValue::DVec2(DVec2::ONE)),
value(TaggedValue::DVec2(DVec2::ZERO)),
],
);
let color = Color::from_rgbaf32_unchecked(0.9, 0.3, 0.2, 1.);
let fill = node(
fill::IDENTIFIER,
vec![
NodeInput::node(TRANSFORM, 0),
value(TaggedValue::Color(color)),
value(TaggedValue::Color(color)),
value(TaggedValue::GradientRamp(GradientRamp::default())),
value(TaggedValue::GradientForm(GradientForm::Linear)),
value(TaggedValue::Bool(false)),
value(TaggedValue::DAffine2(DAffine2::IDENTITY)),
],
);
let NodeInput::Node { node_id: root_id, .. } = network.exports[0] else { unreachable!() };
network.nodes.extend([(RECTANGLE, rectangle), (TRANSFORM, transform), (FILL, fill), (LAYER, layer)]);
network.nodes.get_mut(&root_id).expect("The document has no root node").inputs[1] = NodeInput::node(LAYER, 0);
network
}
/// The artboard the document exports, which every demo artwork has.
fn root(network: &NodeNetwork) -> &DocumentNode {
let NodeInput::Node { node_id, .. } = network.exports[0] else {
panic!("The document exports no node");
};
&network.nodes[&node_id]
}
fn vec_input(node: &DocumentNode, index: usize) -> DVec2 {
match node.inputs[index].as_value() {
Some(TaggedValue::DVec2(value)) => *value,
other => panic!("The artboard's input {index} is {other:?} rather than a vector"),
}
}
#[library_benchmark]
#[benches::artwork(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_add_rectangle)]
pub fn add_rectangle(mut session: Session) -> Session {
let document = std::mem::take(&mut session.document);
callgrind::start();
session.gpu.compile(document);
session.gpu.render(session.view);
callgrind::stop();
// Return the session so its teardown happens outside the measured section
session
}
#[library_benchmark]
#[benches::artwork(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_zoom)]
pub fn zoom(session: Session) -> Session {
let view = zoomed(session.view, ZOOM);
callgrind::start();
session.gpu.render(view);
callgrind::stop();
session
}
library_benchmark_group!(name = artwork_group; benchmarks = add_rectangle, zoom);
main!(
config = gpu_util::config();
library_benchmark_groups = artwork_group
);
@@ -1,33 +1,21 @@
//! Counts the instructions a document update costs when one stroke is added to its brush layer, the way the Brush tool appends strokes:
//! wrapping and compiling the changed graph, updating the executor and rendering the viewport, as the editor's runtime does for each change.
//! Rendering the same document with an empty brush cache is measured alongside, showing how much of the earlier render the cache saves.
//!
//! The graph renders on a software Vulkan device (lavapipe), so CI runners without a GPU can measure it and the counts include the "GPU" work.
use core_types::transform::{Footprint, RenderQuality};
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
mod gpu_util;
use glam::{DAffine2, DVec2};
use gpu_util::{GpuDocument, VIEWPORT, callgrind};
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
use graph_craft::graphene_compiler::Compiler;
use graphene_std::application_io::RenderConfig;
use graphene_std::brush::basic_brush::{basic_brush, basic_brush_pipeline};
use graphene_std::brush::{BrushCache, Channel, Stroke, brush_strokes};
use graphene_std::graphic;
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use graphene_std::uuid::NodeId;
use graphene_std::{Color, Context};
use gungraun::prelude::*;
use gungraun::{Callgrind, EntryPoint};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope;
use std::hint::black_box;
use std::sync::Arc;
use wgpu_executor::{WgpuContextBuilder, WgpuExecutor};
/// Small enough to keep Valgrind runs short, since the full-frame passes scale with it.
const VIEWPORT: UVec2 = UVec2::new(960, 540);
/// Samples in the added stroke.
const STROKE_SAMPLES: usize = 128;
/// Samples in each stroke already in the document.
@@ -38,11 +26,7 @@ const SAMPLE_SPACING: f64 = 4.;
const STROKES_PER_GROUP: usize = 8;
pub struct Session {
gpu: WgpuExecutor,
editor_api: Arc<PlatformEditorApi>,
runtime: AsyncRuntime,
preprocessor: preprocessor::Preprocessor,
executor: DynamicExecutor,
gpu: GpuDocument,
/// The document graph for the measured update.
document: NodeNetwork,
}
@@ -51,42 +35,18 @@ impl Session {
/// Opens lavapipe and renders the finished document once through a brush cache that is then discarded,
/// so that the device's shaders are compiled and its textures allocated before anything is measured.
fn open(after: &[Group]) -> Self {
let gpu = lavapipe();
let mut session = Self {
editor_api: Arc::new(PlatformEditorApi {
application_io: Some(Arc::new(PlatformApplicationIo::new_with_executor(gpu.clone()))),
}),
gpu,
runtime: AsyncRuntime::new(Arc::new(BlockingSpawner)),
preprocessor: preprocessor::Preprocessor::new(),
executor: DynamicExecutor::default(),
gpu: GpuDocument::new(),
document: NodeNetwork::default(),
};
session.update(brush_layer(&BrushCache::default(), after));
session
}
/// Recompiles the document graph into the executor and renders the viewport, as the runtime does after an edit.
/// Recompiles the document graph and renders the viewport, as the runtime does after an edit.
fn update(&mut self, document: NodeNetwork) {
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle());
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
self.executor.update(proto_network).expect("Failed to update the executor");
let render_config = RenderConfig {
viewport: Footprint {
transform: DAffine2::IDENTITY,
resolution: VIEWPORT,
quality: RenderQuality::Full,
},
scale: 1.,
..Default::default()
};
let output = self.executor.tree().eval_tagged_value(self.executor.output(), &render_config.into_context());
assert!(matches!(output, Ok(graphene_std::Poll::Final(_))), "Failed to render the document: {output:?}");
// Waiting for the device puts its rasterization inside the measurement, rather than only the encoding of its commands
let _ = self.gpu.context().device.poll(wgpu::PollType::wait_indefinitely());
let _ = black_box(output);
self.gpu.compile(document);
self.gpu.render(DAffine2::IDENTITY);
}
}
@@ -110,29 +70,6 @@ fn setup_render_layer(existing: usize) -> Session {
session
}
/// Opens lavapipe, refusing a hardware device, whose work Callgrind can't see.
fn lavapipe() -> WgpuExecutor {
let context = futures::executor::block_on(WgpuContextBuilder::new().with_backends(wgpu::Backends::VULKAN).build())
.expect("No Vulkan device; install lavapipe (mesa-vulkan-drivers) and point VK_DRIVER_FILES at its ICD");
let info = context.adapter.get_info();
assert_eq!(
info.device_type,
wgpu::DeviceType::Cpu,
"Picked {} instead of a software device, which would make the counts meaningless; point VK_DRIVER_FILES at lavapipe's ICD",
info.name
);
WgpuExecutor::with_context(context).expect("Failed to create the GPU executor")
}
/// Runs spawned work to completion on the spot, so everything the graph starts happens in the measured section.
struct BlockingSpawner;
impl Spawn for BlockingSpawner {
fn spawn(&self, task: Task) {
futures::executor::block_on(task);
}
}
/// The `Brush Strokes` settings of a group, as the Brush tool starts a new group whenever its settings change.
#[derive(Clone, Copy)]
struct Style {
@@ -279,47 +216,6 @@ impl Random {
}
}
/// Callgrind's client requests for switching instrumentation, which unlike collection applies to every thread.
/// Outside Valgrind these are a few no-op rotations.
mod callgrind {
/// `VG_USERREQ_TOOL_BASE('C', 'T')` in `callgrind.h`, followed by `DUMP_STATS`, `ZERO_STATS`, `TOGGLE_COLLECT` and `DUMP_STATS_AT`
const START_INSTRUMENTATION: u64 = ((b'C' as u64) << 24 | (b'T' as u64) << 16) + 4;
const STOP_INSTRUMENTATION: u64 = START_INSTRUMENTATION + 1;
pub fn start() {
request(START_INSTRUMENTATION);
}
pub fn stop() {
request(STOP_INSTRUMENTATION);
}
/// The x86-64 form of `VALGRIND_DO_CLIENT_REQUEST_EXPR` in `valgrind.h`, which Valgrind recognizes by the preamble's rotations of `rdi` (adding up to a full turn).
#[cfg(target_arch = "x86_64")]
fn request(code: u64) {
let args = [code, 0, 0, 0, 0, 0];
// SAFETY: The rotations leave `rdi` as it was and `xchg rbx, rbx` changes nothing, so natively this only reads `args`; under Valgrind, the request writes `rdx`
unsafe {
std::arch::asm!(
"rol rdi, 3",
"rol rdi, 13",
"rol rdi, 61",
"rol rdi, 51",
"xchg rbx, rbx",
in("rax") args.as_ptr(),
inout("rdx") 0_u64 => _,
out("rdi") _,
options(nostack),
);
}
}
#[cfg(not(target_arch = "x86_64"))]
fn request(_code: u64) {
panic!("This benchmark only knows how to reach Valgrind on x86-64");
}
}
#[library_benchmark]
#[benches::existing_strokes(args = [0, 16, 256], setup = setup_add_stroke)]
pub fn add_stroke(session: Session) -> Session {
@@ -345,12 +241,6 @@ fn measure(mut session: Session) -> Session {
library_benchmark_group!(name = brush_stroke_group; benchmarks = add_stroke, render_layer);
main!(
// Only what runs between `callgrind::start` and `callgrind::stop` is measured, on every thread,
// since the device works on its own queue thread, which the default entry point (collecting on the benchmark's thread alone) would leave out
config = LibraryBenchmarkConfig::default()
.pass_through_env("VK_DRIVER_FILES")
// Rasterizing on the queue thread alone keeps the counts independent of the runner's core count
.env("LP_NUM_THREADS", "0")
.tool(Callgrind::with_args(["--instr-atstart=no"]).entry_point(EntryPoint::None));
config = gpu_util::config();
library_benchmark_groups = brush_stroke_group
);
@@ -0,0 +1,148 @@
//! Shared by the benchmarks that render documents the way the editor does, through Vello on a software Vulkan device (lavapipe),
//! so CI runners without a GPU can measure them and the counts include the "GPU" work.
use core_types::transform::{Footprint, RenderQuality};
use glam::{DAffine2, UVec2};
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::NodeNetwork;
use graph_craft::graphene_compiler::Compiler;
use graphene_std::application_io::{ExportFormat, RenderConfig};
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use gungraun::{Callgrind, EntryPoint, LibraryBenchmarkConfig};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope;
use std::hint::black_box;
use std::sync::Arc;
use wgpu_executor::{WgpuContextBuilder, WgpuExecutor};
/// Small enough to keep Valgrind runs short, since the full-frame passes scale with it.
pub const VIEWPORT: UVec2 = UVec2::new(960, 540);
/// Measures only what runs between [`callgrind::start`] and [`callgrind::stop`], on every thread,
/// since the device works on its own queue thread, which the default entry point (collecting on the benchmark's thread alone) would leave out.
pub fn config() -> LibraryBenchmarkConfig {
let mut config = LibraryBenchmarkConfig::default();
config
.pass_through_env("VK_DRIVER_FILES")
// Rasterizing on the queue thread alone keeps the counts independent of the runner's core count
.env("LP_NUM_THREADS", "0")
// Shaders compiled by an earlier run, such as the baseline's, would otherwise load from disk and lower the counts
.env("MESA_SHADER_CACHE_DISABLE", "true")
.tool(Callgrind::with_args(["--instr-atstart=no"]).entry_point(EntryPoint::None));
config
}
/// A document compiled into an executor that renders it through the editor's render chain, as the editor's runtime does.
pub struct GpuDocument {
gpu: WgpuExecutor,
editor_api: Arc<PlatformEditorApi>,
runtime: AsyncRuntime,
preprocessor: preprocessor::Preprocessor,
executor: DynamicExecutor,
}
impl GpuDocument {
pub fn new() -> Self {
let gpu = lavapipe();
Self {
editor_api: Arc::new(PlatformEditorApi {
application_io: Some(Arc::new(PlatformApplicationIo::new_with_executor(gpu.clone()))),
}),
gpu,
runtime: AsyncRuntime::new(Arc::new(BlockingSpawner)),
preprocessor: preprocessor::Preprocessor::new(),
executor: DynamicExecutor::default(),
}
}
/// Wraps and compiles the document graph into the executor, as the runtime does after an edit.
pub fn compile(&mut self, document: NodeNetwork) {
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle());
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
self.executor.update(proto_network).expect("Failed to update the executor");
}
/// Renders the viewport with the document placed by `transform`, waiting for the device to finish.
pub fn render(&self, transform: DAffine2) {
let render_config = RenderConfig {
viewport: Footprint {
transform,
resolution: VIEWPORT,
quality: RenderQuality::Full,
},
scale: 1.,
export_format: ExportFormat::Raster,
..Default::default()
};
let output = self.executor.tree().eval_tagged_value(self.executor.output(), &render_config.into_context());
assert!(matches!(output, Ok(graphene_std::Poll::Final(_))), "Failed to render the document: {output:?}");
// Waiting for the device puts its rasterization inside the measurement, rather than only the encoding of its commands
let _ = self.gpu.context().device.poll(wgpu::PollType::wait_indefinitely());
let _ = black_box(output);
}
}
/// Opens lavapipe, refusing a hardware device, whose work Callgrind can't see.
fn lavapipe() -> WgpuExecutor {
let context = futures::executor::block_on(WgpuContextBuilder::new().with_backends(wgpu::Backends::VULKAN).build())
.expect("No Vulkan device; install lavapipe (mesa-vulkan-drivers) and point VK_DRIVER_FILES at its ICD");
let info = context.adapter.get_info();
assert_eq!(
info.device_type,
wgpu::DeviceType::Cpu,
"Picked {} instead of a software device, which would make the counts meaningless; point VK_DRIVER_FILES at lavapipe's ICD",
info.name
);
WgpuExecutor::with_context(context).expect("Failed to create the GPU executor")
}
/// Runs spawned work to completion on the spot, so everything the graph starts happens in the measured section.
struct BlockingSpawner;
impl Spawn for BlockingSpawner {
fn spawn(&self, task: Task) {
futures::executor::block_on(task);
}
}
/// Callgrind's client requests for switching instrumentation, which unlike collection applies to every thread.
/// Outside Valgrind these are a few no-op rotations.
pub mod callgrind {
/// `VG_USERREQ_TOOL_BASE('C', 'T')` in `callgrind.h`, followed by `DUMP_STATS`, `ZERO_STATS`, `TOGGLE_COLLECT` and `DUMP_STATS_AT`
const START_INSTRUMENTATION: u64 = ((b'C' as u64) << 24 | (b'T' as u64) << 16) + 4;
const STOP_INSTRUMENTATION: u64 = START_INSTRUMENTATION + 1;
pub fn start() {
request(START_INSTRUMENTATION);
}
pub fn stop() {
request(STOP_INSTRUMENTATION);
}
/// The x86-64 form of `VALGRIND_DO_CLIENT_REQUEST_EXPR` in `valgrind.h`, which Valgrind recognizes by the preamble's rotations of `rdi` (adding up to a full turn).
#[cfg(target_arch = "x86_64")]
fn request(code: u64) {
let args = [code, 0, 0, 0, 0, 0];
// SAFETY: The rotations leave `rdi` as it was and `xchg rbx, rbx` changes nothing, so natively this only reads `args`; under Valgrind, the request writes `rdx`
unsafe {
std::arch::asm!(
"rol rdi, 3",
"rol rdi, 13",
"rol rdi, 61",
"rol rdi, 51",
"xchg rbx, rbx",
in("rax") args.as_ptr(),
inout("rdx") 0_u64 => _,
out("rdi") _,
options(nostack),
);
}
}
#[cfg(not(target_arch = "x86_64"))]
fn request(_code: u64) {
panic!("The GPU benchmarks only know how to reach Valgrind on x86-64");
}
}
@@ -113,6 +113,11 @@ 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())
}
@@ -306,6 +311,13 @@ 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)
}
@@ -321,19 +333,10 @@ impl BorrowTree {
self.context_features.get(&id).copied().unwrap_or_default()
}
/// The node feeding an input of the proto node at this path, looking past the nodes wrapping it under the same path such as 'Memoize'.
pub fn input_node(&self, node_path: &[NodeId], input_index: usize) -> Result<NodeId, IntrospectError> {
let (mut id, _) = *self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
loop {
let (_, _, inputs) = self.nodes.get(&id).ok_or(IntrospectError::ProtoNodeNotFound(id))?;
let wrapped = inputs.first().filter(|first| self.nodes.get(first).is_some_and(|(_, path, _)| **path == *node_path));
match wrapped {
Some(&wrapped) => id = wrapped,
None => return inputs.get(input_index).copied().ok_or(IntrospectError::NoData),
}
}
let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
let (_, _, inputs) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?;
inputs.get(input_index).copied().ok_or(IntrospectError::NoData)
}
/// The context this node was last evaluated with in the graph.
@@ -34,6 +34,50 @@ 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>]),
@@ -254,8 +298,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/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.
// 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.
macro_rules! ranked_value_types {
($register:ident) => {
$register!(
@@ -310,7 +354,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
)
};
}
// Primary element types (graphical data and scalars) get promotion adapters here; their memoize rows are the
// Primary element types (graphical data and scalars) get promotion adapters here; their monitor/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,
@@ -394,12 +438,14 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
));
#[cfg(feature = "gpu")]
node_types.extend(bundle_adapter_nodes!(Raster<GPU>));
// The memoize + context-nullification pair the compiler wraps a ranked connector's broadcast sibling in, for each value type in the shared list above.
// 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.
// 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,6 +55,11 @@ 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;
@@ -102,6 +107,9 @@ 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;
@@ -112,6 +120,9 @@ 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;
@@ -122,6 +133,9 @@ 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,6 +4,13 @@ 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,6 +17,10 @@ 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,7 +76,6 @@ pub enum RegistryValueSource {
Default(&'static str),
Scope(&'static str),
SourceId,
NodePath,
}
#[derive(Clone, Debug)]
@@ -351,6 +350,10 @@ 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 {
@@ -382,6 +385,10 @@ 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 the editor observes on 'Path' nodes.
// TODO: Click targets can be removed from the render output, since the vector data is available in the vector modify data from Monitor 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))]
+20 -1
View File
@@ -205,7 +205,6 @@ 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();
@@ -524,6 +523,18 @@ 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;
@@ -635,6 +646,8 @@ 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! {
@@ -648,6 +661,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
};
#fold
}
#serialize_impl
}
};
@@ -741,6 +756,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
};
__cell.run(__kernel)
}
#serialize_impl
}
});
@@ -814,6 +831,8 @@ 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
// Memoize lets the node's outputs share one evaluation, and Monitor lets the editor inspect the struct
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() {
#graphene_core::memo::register_memoize::<#struct_ident>();
#graphene_core::memo::register_memoize::<#mapped_ident>();
fn register_memoize_and_monitor() {
#graphene_core::memo::register_memoize_and_monitor::<#struct_ident>();
#graphene_core::memo::register_memoize_and_monitor::<#mapped_ident>();
}
#[cfg(target_family = "wasm")]
#[unsafe(no_mangle)]
extern "C" fn #wasm_registration() {
register_memoize();
register_memoize_and_monitor();
}
}
};
+21 -39
View File
@@ -65,6 +65,8 @@ 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>,
@@ -79,7 +81,6 @@ pub enum ParsedValueSource {
Default(TokenStream2),
Scope(Box<Expr>),
SourceId,
NodePath,
}
// #[widget(ParsedWidgetOverride::Hidden)]
@@ -173,10 +174,10 @@ impl ParsedField {
}
}
/// 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.
/// Whether the field is environment rather than an argument: `#[data]` state or a `#[scope]`-injected wire.
/// 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 | ParsedValueSource::NodePath)
self.is_data_field || matches!(self.ty.value_source(), ParsedValueSource::Scope(_) | ParsedValueSource::SourceId)
}
}
@@ -439,6 +440,7 @@ 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;
@@ -541,6 +543,20 @@ 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.
//
@@ -604,7 +620,7 @@ impl Parse for NodeFnAttributes {
indoc!(
r#"
Unsupported attribute in `node`.
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', 'no_partial', and 'version'.
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'serialize', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', 'no_partial', and 'version'.
Example usage:
#[node_macro::node(..., name("Test Node"), ...)]
"#
@@ -634,6 +650,7 @@ impl Parse for NodeFnAttributes {
path,
inspector_string,
cfg,
serialize,
flags,
placeholder,
version,
@@ -862,9 +879,6 @@ 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() {
@@ -891,18 +905,6 @@ 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(
@@ -914,11 +916,9 @@ 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,24 +1880,6 @@ 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() {
+37 -3
View File
@@ -1,6 +1,7 @@
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, NodeIO, NodeIOTypes, Poll, WasmNotSend, concrete, fn_type};
use core_types::{Context, Interrupt, NodeIO, NodeIOTypes, Poll, WasmNotSend, concrete, fn_type};
use dyn_any::StaticType;
use std::hash::DefaultHasher;
use std::hash::Hasher;
@@ -35,13 +36,39 @@ fn memoize<I: CacheHash + Clone + Send, T: Clone + WasmNotSend>(input: I, conten
state
}
/// 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>() {
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>() {
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());
@@ -49,9 +76,16 @@ pub fn register_memoize<T: Clone + Send + Sync + StaticType<Static: Sized> + 'st
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)]
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff. Show more