Compare commits

...
Author SHA1 Message Date
Dennis Kobert 40a9600f03 Fix swapped legacy aliases of the logic nodes 2026-11-15 23:40:11 +01:00
Dennis Kobert dc1856a5a7 Show the matched old name in the node catalog with the typed part highlighted 2026-11-15 23:39:56 +01:00
Dennis Kobert fb9f48e7db Find nodes in the catalog search by their names from before migrations 2026-11-15 22:52:09 +01:00
Dennis Kobert 48ff126082 Add a generic observation mechanism to the node runtime (#4961)
Add a keyed observation mechanism to the node runtime and move the Data panel onto it
2026-11-15 21:36:14 +01:00
12 changed files with 463 additions and 214 deletions

No files matched your search

Generated
+1
View File
@@ -2846,6 +2846,7 @@ dependencies = [
"bitflags 2.13.2",
"blake3",
"color",
"convert_case 0.12.0",
"core-types",
"derivative",
"document-container",
+2 -1
View File
@@ -26,6 +26,7 @@ document-format = { workspace = true, features = ["migrations", "network"] }
migration-formats = { workspace = true }
migration-compiled = { workspace = true }
migration-nodes = { workspace = true }
migration-core = { workspace = true, features = ["typed"] }
document-graph-storage = { workspace = true, features = ["conversion"] }
document-container = { workspace = true }
peer-transport = { workspace = true }
@@ -49,6 +50,7 @@ kurbo = { workspace = true }
futures = { workspace = true }
glam = { workspace = true }
derivative = { workspace = true }
convert_case = { workspace = true }
tsify = { workspace = true }
dyn-any = { workspace = true }
num_enum = { workspace = true }
@@ -80,4 +82,3 @@ env_logger = { workspace = true }
futures = { workspace = true }
node-macro = { workspace = true }
core-types = { workspace = true }
migration-core = { workspace = true, features = ["typed"] }
@@ -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 { mut inspect_result } => {
self.introspected_data = inspect_result.take_data();
self.introspected_node_path = inspect_result.inspect_node_path;
DataPanelMessage::UpdateLayout { inspect_result } => {
self.introspected_data = inspect_result.data;
self.introspected_node_path = inspect_result.node_path;
self.context = inspect_result.context;
self.update_layout(responses, context);
}
@@ -8,9 +8,11 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::network_interface::{
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
};
use crate::messages::portfolio::document_migration::legacy_aliases;
use crate::messages::portfolio::ingest::utility_types::TypeFilter;
use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
use crate::node_graph_executor::NodeGraphExecutor;
use convert_case::{Boundary, Case, Casing};
use glam::DVec2;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::*;
@@ -21,6 +23,7 @@ use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color,
use graphene_std::transform::Footprint;
use graphene_std::vector::Vector;
use graphene_std::*;
use migration_core::{DeclarationKind, NodeMigration};
use std::collections::{HashMap, VecDeque};
pub struct NodeInspectorContext<'a> {
@@ -1620,6 +1623,8 @@ impl InputTypeConstraint {
/// The node catalog's entries, ordered by category and then by name.
pub fn collect_node_types() -> Vec<FrontendNodeType> {
let migrations = migration_core::registered_migrations();
let mut node_types: Vec<FrontendNodeType> = DOCUMENT_NODE_TYPES
.iter()
// A Passthrough is placed as a redirect dot on a wire, so it isn't offered as a node
@@ -1633,6 +1638,7 @@ pub fn collect_node_types() -> Vec<FrontendNodeType> {
FrontendNodeType {
identifier: identifier.serialized(),
input_types: InputTypeConstraint::constraints_for_all_inputs(&definition.node_template, &name),
search_aliases: former_names(identifier, &name, &migrations),
name,
category: definition.category.to_string(),
}
@@ -1647,6 +1653,51 @@ pub fn collect_node_types() -> Vec<FrontendNodeType> {
node_types
}
/// The display names of every declaration that migrates, directly or through others, to the node of `identifier`, and of its legacy aliases.
fn former_names(identifier: &DefinitionIdentifier, current_name: &str, migrations: &[&'static dyn NodeMigration]) -> Vec<String> {
let (current, legacy_aliases): (_, Vec<&str>) = match identifier {
DefinitionIdentifier::ProtoNode(proto_node_identifier) => ((proto_node_identifier.as_str(), DeclarationKind::Proto), legacy_aliases(proto_node_identifier).collect()),
DefinitionIdentifier::Network(name) => ((name.as_str(), DeclarationKind::Network), Vec::new()),
};
let mut visited = vec![current];
let mut pending = vec![current];
while let Some((identifier, kind)) = pending.pop() {
for migration in migrations {
let (source, target) = (migration.source(), migration.target());
let predecessor = (source.identifier, source.kind);
if target.identifier == identifier && target.kind == kind && !visited.contains(&predecessor) {
visited.push(predecessor);
pending.push(predecessor);
}
}
}
let mut names: Vec<String> = visited
.into_iter()
.skip(1)
.chain(legacy_aliases.into_iter().map(|alias| (alias, DeclarationKind::Proto)))
.map(|(identifier, kind)| declaration_display_name(identifier, kind))
.filter(|name| !name.eq_ignore_ascii_case(current_name))
.collect();
names.sort();
names.dedup();
names
}
/// A network definition's identifier is its display name, and a proto node's is approximated from its type name, like `MathFxNode` becoming "Math Fx".
fn declaration_display_name(identifier: &str, kind: DeclarationKind) -> String {
match kind {
DeclarationKind::Network => identifier.to_string(),
DeclarationKind::Proto => {
let type_name = identifier.rsplit("::").next().unwrap_or(identifier);
let name = type_name.strip_suffix("Node").unwrap_or(type_name);
name.set_boundaries(&[Boundary::LowerUpper, Boundary::DigitUpper, Boundary::Acronym]).to_case(Case::Title)
}
}
}
pub fn collect_node_descriptions() -> Vec<(String, String)> {
DOCUMENT_NODE_TYPES
.iter()
@@ -120,6 +120,9 @@ pub struct FrontendNodeType {
pub category: String,
#[serde(rename = "inputTypes")]
pub input_types: Vec<InputTypeConstraint>,
/// Names the node went by before migrations replaced it, which the catalog search also matches.
#[serde(rename = "searchAliases")]
pub search_aliases: Vec<String>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -55,6 +55,14 @@ fn into_group_aliases() -> impl Iterator<Item = &'static &'static str> {
.flat_map(|replacement| replacement.aliases)
}
/// The identifiers and display names that legacy documents use for `node`.
pub fn legacy_aliases(node: &ProtoNodeIdentifier) -> impl Iterator<Item = &'static str> + '_ {
NODE_REPLACEMENTS
.iter()
.filter(move |replacement| replacement.node == *node)
.flat_map(|replacement| replacement.aliases.iter().copied())
}
/// Clears a migrated node's stored display name if it was only the replaced node's default name, so it shows its new node's name instead.
fn reset_default_display_name(document: &mut DocumentMessageHandler, node_id: &NodeId, network_path: &[NodeId], old_default_name: &str) {
if document.network_interface.display_name(node_id, network_path) == old_default_name {
@@ -353,8 +361,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::math_nodes::logical_and::IDENTIFIER,
aliases: &[
"graphene_core::ops::LogicalAndNode",
"graphene_core::ops::LogicNotNode",
"graphene_core::logic::LogicNotNode",
"graphene_core::ops::LogicAndNode",
"graphene_core::logic::LogicAndNode",
"graphene_math_nodes::LogicalAndNode",
],
},
@@ -362,8 +370,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::math_nodes::logical_not::IDENTIFIER,
aliases: &[
"graphene_core::ops::LogicalNotNode",
"graphene_core::ops::LogicOrNode",
"graphene_core::logic::LogicOrNode",
"graphene_core::ops::LogicNotNode",
"graphene_core::logic::LogicNotNode",
"graphene_math_nodes::LogicalNotNode",
],
},
@@ -371,8 +379,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::math_nodes::logical_or::IDENTIFIER,
aliases: &[
"graphene_core::ops::LogicalOrNode",
"graphene_core::ops::LogicAndNode",
"graphene_core::logic::LogicAndNode",
"graphene_core::ops::LogicOrNode",
"graphene_core::logic::LogicOrNode",
"graphene_math_nodes::LogicalOrNode",
],
},
@@ -1933,8 +1941,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
&& inner.nodes.values().any(|n| {
matches!(&n.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::floor::IDENTIFIER)
&& n.inputs.iter().any(|input| matches!(input, NodeInput::Import { import_index: 1, .. }))
})
&& let Some(node_definition) = resolve_network_node_type("Blend")
}) && let Some(node_definition) = resolve_network_node_type("Blend")
{
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
}
@@ -1946,8 +1953,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
n.inputs
.iter()
.any(|input| matches!(input, NodeInput::Import { import_type, import_index: 2 } if *import_type == item!(f64)))
})
&& let Some(node_definition) = resolve_network_node_type("Regex Find")
}) && let Some(node_definition) = resolve_network_node_type("Regex Find")
{
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
}
+86 -25
View File
@@ -15,7 +15,7 @@ use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint;
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, Graphic};
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use std::any::Any;
use std::sync::Arc;
@@ -39,8 +39,18 @@ pub struct ExecutionResponse {
/// The layers whose thumbnails the runtime let go of, which it renders anew if they have content to show again.
dropped_thumbnails: Vec<NodeId>,
vector_modify: HashMap<NodeId, VectorGeometry>,
/// The resulting value from the temporary inspected during execution
inspect_result: Option<InspectResult>,
/// 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,
// TODO: Eventually remove this document upgrade code
/// The "Fill" node whose geometry a gradient migration measures.
FillMeasurement,
}
#[derive(Debug)]
@@ -81,9 +91,16 @@ pub enum NodeGraphUpdate {
ExecutionResponse(Box<ExecutionResponse>),
CompilationResponse(CompilationResponse),
EyedropperPreview(Raster<CPU>),
Thumbnails { responses: VecDeque<FrontendMessage>, document_id: DocumentId },
InspectResult(Box<InspectResult>),
ClipboardSvg { id: u64, svg: Option<String> },
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>,
},
}
#[derive(Debug)]
@@ -98,6 +115,8 @@ 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
@@ -152,6 +171,7 @@ 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,
@@ -188,8 +208,16 @@ impl NodeGraphExecutor {
execution_id
}
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_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_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message {
@@ -228,9 +256,9 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect: Vec::new(),
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
observations: HashMap::new(),
}))
.map_err(|e| e.to_string())?;
Ok(instrumented)
@@ -238,12 +266,17 @@ 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);
@@ -253,19 +286,38 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect,
previewed,
layers,
observations: self.observations(),
}))
.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())?;
} 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())?;
}
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) -> HashMap<ObservationKey, Observation> {
self.data_panel_observation().map(|observation| (ObservationKey::DataPanel, observation)).into_iter().collect()
}
/// Adds an evaluate request for whatever current network is cached.
pub(crate) fn submit_current_node_graph_evaluation(
&mut self,
@@ -429,9 +481,9 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect: Vec::new(),
previewed,
layers: document.network_interface.layer_paths(),
observations: self.observations(),
}))
.map_err(|e| e.to_string())?;
let execution_id = self.queue_execution(render_config);
@@ -467,7 +519,7 @@ impl NodeGraphExecutor {
responses: existing_responses,
dropped_thumbnails,
vector_modify,
inspect_result,
mut observations,
} = *execution_response;
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
@@ -503,7 +555,8 @@ 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 inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Fallback(..)).then_some(inspect_result).flatten();
let measured = observations.remove(&ObservationKey::FillMeasurement);
let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Fallback(..)).then_some(measured).flatten();
self.handle_gradient_measurement(document, document_id, bake_target, inspect_result, responses);
}
continue;
@@ -605,6 +658,7 @@ 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),
@@ -661,9 +715,13 @@ impl NodeGraphExecutor {
let (data, width, height) = raster.to_flat_u8();
responses.add(EyedropperToolMessage::PreviewImage { data, width, height });
}
NodeGraphUpdate::InspectResult(inspect_result) => {
if inspect_result.inspect_node_path == self.previous_node_to_inspect {
responses.add(DataPanelMessage::UpdateLayout { inspect_result });
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::Thumbnails {
@@ -789,14 +847,19 @@ 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()
{
@@ -807,7 +870,6 @@ 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,
@@ -858,7 +920,7 @@ impl NodeGraphExecutor {
return;
}
match inspect_result.and_then(|mut result| result.take_data()).and_then(|data| measure_fill_geometry(&data)) {
match inspect_result.and_then(|result| result.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) {
@@ -904,10 +966,9 @@ impl NodeGraphExecutor {
}
// TODO: Eventually remove this document upgrade code
/// Tear down the in-progress migration and clear the stale inspect target and hash so the next normal render recompiles the real network.
/// Tear down the in-progress migration and clear the 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;
}
+42 -157
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::{DVec2, UVec2};
use glam::UVec2;
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
@@ -20,14 +20,17 @@ use graphene_std::raster_types::Raster;
use graphene_std::runtime::AsyncRuntime;
use graphene_std::vector::style::RenderMode;
use graphene_std::vector::{Vector, VectorGeometry, paths_from_list_row_attributes};
use graphene_std::{Context, ContextFeatures, ContextOverrides, NodeError, OwnedContextImpl, Poll};
use graphene_std::{Context, NodeError, 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`]`.
@@ -56,9 +59,9 @@ pub struct NodeRuntime {
node_graph_warnings: GraphErrors,
monitor_nodes: Vec<(Vec<NodeId>, NodeId)>,
thumbnails: Thumbnails,
/// The node the Data panel inspects.
inspect_state: Option<InspectState>,
observer: Observer<ObservationKey>,
/// Whether an observation changed since its results were last sent.
observations_changed: bool,
preprocessor: preprocessor::Preprocessor,
@@ -78,22 +81,31 @@ pub struct NodeRuntime {
pub enum GraphRuntimeRequest {
GraphUpdate(GraphUpdate),
ExecutionRequest(ExecutionRequest),
ThumbnailsInView { layers: HashSet<NodeId>, document_id: DocumentId },
Inspect(Vec<NodeId>),
InspectContextOverrides(ContextOverrides),
ClipboardSvg { id: u64, layers: Vec<NodeId> },
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>,
},
}
#[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.
@@ -145,12 +157,13 @@ impl NodeRuntime {
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"))]
@@ -181,17 +194,15 @@ impl NodeRuntime {
self.thumbnails.set_in_view(layers);
self.pending_thumbnails = Some(document_id);
}
// 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;
// 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;
}
}
},
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");
@@ -202,21 +213,16 @@ impl NodeRuntime {
let Some(GraphUpdate {
mut network,
resources,
node_to_inspect,
previewed,
layers,
observations,
}) = graph
else {
return;
};
apply_previews(&mut network, &previewed);
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.observer.replace_all(observations);
self.resources = resources;
self.node_graph_errors.clear();
@@ -259,12 +265,9 @@ impl NodeRuntime {
}
}
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 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(eyedropper) = self.pending_eyedropper.take() {
@@ -374,7 +377,7 @@ impl NodeRuntime {
responses: VecDeque::new(),
dropped_thumbnails: Vec::new(),
vector_modify: HashMap::new(),
inspect_result: None,
observations: HashMap::new(),
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
return None;
@@ -386,7 +389,7 @@ impl NodeRuntime {
async fn respond(&mut self, execution_id: u64, result: ExecutionResult) {
let mut responses = VecDeque::new();
let dropped_thumbnails = self.process_monitor_nodes(&mut responses).await;
let inspect_result = self.inspect_state.as_mut().map(|state| state.access(&self.executor, self.old_graph.as_ref()));
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
let response = ExecutionResponse {
execution_id,
@@ -394,7 +397,7 @@ impl NodeRuntime {
responses,
dropped_thumbnails,
vector_modify: self.vector_modify.clone(),
inspect_result,
observations,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
}
@@ -523,23 +526,6 @@ fn records_vector(executor: &DynamicExecutor, monitor_node_path: &[NodeId]) -> b
.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),
@@ -594,112 +580,11 @@ 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;
@@ -0,0 +1,185 @@
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()
}
}
@@ -21,8 +21,36 @@
$: nodeCategories = buildNodeCategories(searchTerm);
type TextSegment = {
text: string;
highlighted: boolean;
};
type NodeCatalogEntry = {
nodeType: FrontendNodeType;
matchedAliasSegments: TextSegment[] | undefined;
};
// Splits `text` into runs that are highlighted where one of the lowercase `terms` occurs
function highlightTerms(text: string, terms: string[]): TextSegment[] {
const lowercaseText = text.toLowerCase();
const highlighted = new Array<boolean>(text.length).fill(false);
terms.forEach((term) => {
const start = lowercaseText.indexOf(term);
if (term.length > 0 && start !== -1) highlighted.fill(true, start, start + term.length);
});
const segments: TextSegment[] = [];
highlighted.forEach((isHighlighted, index) => {
const last = segments.at(-1);
if (last?.highlighted === isHighlighted) last.text += text[index];
else segments.push({ text: text[index], highlighted: isHighlighted });
});
return segments;
}
type NodeCategoryDetails = {
nodes: FrontendNodeType[];
nodes: NodeCatalogEntry[];
open: boolean;
};
@@ -43,23 +71,24 @@
nodeTypes.forEach((node) => {
let matchesTypeSearch = true;
let matchesRemainingTerms = true;
if (isTypeSearch && typeSearchTerm) {
matchesTypeSearch = node.inputTypes?.some((constraint) => constraint === "All" || constraint.Limited.some((inputType) => inputType.toLowerCase().includes(typeSearchTerm))) || false;
}
if (remainingSearchTerms.length > 0) {
matchesRemainingTerms = remainingSearchTerms.every((term) => {
const nameMatch = node.name.toLowerCase().includes(term);
const categoryMatch = node.category.toLowerCase().includes(term);
const termsUnmatchedByName = remainingSearchTerms.filter((term) => {
const nameMatch = node.name.toLowerCase().includes(term);
const categoryMatch = node.category.toLowerCase().includes(term);
// Quick and dirty hack to alias "Layer" to "Merge" in the search
const layerAliasMatch = node.name === "Merge" && "layer".includes(term);
// Quick and dirty hack to alias "Layer" to "Merge" in the search
const layerAliasMatch = node.name === "Merge" && "layer".includes(term);
return nameMatch || categoryMatch || layerAliasMatch;
});
}
return !nameMatch && !categoryMatch && !layerAliasMatch;
});
const matchedAlias = termsUnmatchedByName.length > 0 ? node.searchAliases.find((alias) => termsUnmatchedByName.every((term) => alias.toLowerCase().includes(term))) : undefined;
const matchesRemainingTerms = termsUnmatchedByName.length === 0 || matchedAlias !== undefined;
const matchedAliasSegments = matchedAlias !== undefined ? highlightTerms(matchedAlias, termsUnmatchedByName) : undefined;
// Node matches if it passes both type search and remaining terms filters
const includesSearchTerm = matchesTypeSearch && matchesRemainingTerms;
@@ -76,11 +105,11 @@
if (category) {
category.open = category.open || open;
category.nodes.push(node);
category.nodes.push({ nodeType: node, matchedAliasSegments });
} else {
categories.set(node.category, {
open,
nodes: [node],
nodes: [{ nodeType: node, matchedAliasSegments }],
});
}
});
@@ -102,14 +131,20 @@
<summary>
<TextLabel>{nodeCategory[0]}</TextLabel>
</summary>
{#each nodeCategory[1].nodes as nodeType}
{#each nodeCategory[1].nodes as { nodeType, matchedAliasSegments }}
<TextButton
{disabled}
label={nodeType.name}
tooltipLabel={nodeType.name}
tooltipDescription={nodeType.identifier ? $nodeGraph.nodeDescriptions.get(nodeType.identifier) : undefined}
action={() => dispatch("selectNodeType", nodeType.identifier)}
/>
>
{#if matchedAliasSegments}
<span class="matched-alias"
>{#each matchedAliasSegments as segment}<span class:highlighted={segment.highlighted}>{segment.text}</span>{/each}</span
>
{/if}
</TextButton>
{/each}
</details>
{:else}
@@ -172,6 +207,17 @@
&:last-child .text-button {
margin-bottom: 0;
}
.matched-alias {
margin-left: 8px;
overflow: hidden;
text-overflow: ellipsis;
color: var(--color-8-uppergray);
.highlighted {
color: var(--button-text-color);
}
}
}
}
}
@@ -88,6 +88,7 @@
{#if label}
<TextLabel>{label}</TextLabel>
{/if}
<slot />
</button>
{#if menuListChildrenExists}
<MenuList
@@ -333,10 +333,19 @@ 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 (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)
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),
}
}
}
/// The context this node was last evaluated with in the graph.