Utilize executor multi-output capabilities in runtime (#5084)

* Free executor nodes once no output reaches them, and let an export keep its output instead of blocking the runtime

* Answer an export on a channel of its own, so the viewport's answers stay in order

* Render a copy's SVG as an export of the copied layers' own network

* Record in the executor which paths' types changed, to be taken with take_type_changes

* Prepare every network in the node graph executor, and send the runtime the thumbnail sources instead of the previews and layers
This commit is contained in:
Timon authored and GitHub committed 2026-12-06 13:48:46 +00:00
1 parent d5fdb12320
commit 27cded81af
17 files changed
+1010 -471

No files matched your search

@@ -665,6 +665,18 @@ mod test {
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
}
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_leaves_out_the_layers_that_are_not_copied() {
let mut editor = create_editor_with_three_layers().await;
let top = editor.active_document().metadata().all_layers().next().expect("the document has layers").to_node();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![top] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the copied layer should render an SVG");
assert_eq!(svg.matches("<path").count(), 1, "only the copied layer should be drawn: {svg}");
}
/// - paste
/// - assert that ellipse was copied
#[tokio::test]
@@ -997,7 +997,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
artboard_name,
artboard_count,
};
let result = self.executor.submit_document_export(document, document_id, export_config);
let result = self.executor.submit_document_export(document, export_config);
if let Err(description) = result {
responses.add(DialogMessage::DisplayDialogError {
@@ -1124,18 +1124,14 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
}
}
PortfolioMessage::SubmitClipboardSvg { id } => {
let layers = self.active_document().map(|document| {
let selected = document.partition_selection().layers;
let mut layers = document
.metadata()
.all_layers()
.filter(|layer| selected.contains(layer))
.map(|layer| layer.to_node())
.collect::<Vec<_>>();
layers.reverse();
layers
});
responses.add(self.executor.submit_clipboard_svg(self.active_document_id, id, layers.unwrap_or_default()));
let Some(document) = self.active_document_id.and_then(|document_id| self.documents.get(&document_id)) else {
responses.add(ClipboardMessage::Rendered { id, svg: None });
return;
};
let selected = document.partition_selection().layers;
let mut layers = document.metadata().all_layers().filter(|layer| selected.contains(layer)).collect::<Vec<_>>();
layers.reverse();
responses.add(self.executor.submit_clipboard_svg(document, id, &layers));
}
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
+205 -130
View File
@@ -1,23 +1,28 @@
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::document_metadata::LayerNodeIdentifier;
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, NodeNetworkInterface, RootNode};
use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use graph_craft::list;
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::math::quad::Quad;
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::{ATTR_TRANSFORM, Artboard, ContextOverrides, Graphic, NodeParameter};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use interpreted_executor::layer_paths::{layer_content, write_layer_paths};
use std::any::Any;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender};
@@ -97,7 +102,8 @@ impl std::fmt::Display for EvaluationErrors {
#[derive(serde::Serialize, serde::Deserialize)]
pub struct CompilationResponse {
result: Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)>,
result: Result<(), String>,
resolved_types: ResolvedDocumentNodeTypesDelta,
node_graph_errors: GraphErrors,
node_graph_warnings: GraphErrors,
}
@@ -112,19 +118,24 @@ pub enum NodeGraphUpdate {
},
/// The latest result of each observation, sent outside an execution after one of them changed.
Observations(HashMap<ObservationKey, InspectResult>),
ClipboardSvg {
Export {
id: u64,
svg: Option<String>,
result: Box<ExecutionResult>,
},
}
#[derive(Debug)]
pub struct NodeGraphExecutor {
sender: Sender<GraphRuntimeRequest>,
receiver: Receiver<NodeGraphUpdate>,
current_execution_id: u64,
futures: VecDeque<(u64, ExecutionContext)>,
pending: Option<(u64, ExecutionContext)>,
current_export_id: u64,
exports: HashMap<u64, ExportTarget>,
node_graph_hash: u64,
/// The document whose network the graph runtime was last sent.
node_graph_document: Option<DocumentId>,
@@ -146,9 +157,14 @@ pub struct NodeGraphExecutor {
gradient_migration_attempted: HashSet<DocumentId>,
}
#[derive(Debug)]
enum ExportTarget {
File(ExportConfig),
Clipboard(u64),
}
#[derive(Debug, Clone)]
struct ExecutionContext {
export_config: Option<ExportConfig>,
document_id: DocumentId,
/// The view the render was asked for, which the footprints it reports back are measured in.
document_to_viewport: DAffine2,
@@ -183,6 +199,8 @@ impl NodeGraphExecutor {
futures: Default::default(),
pending: None,
current_execution_id: 0,
current_export_id: 0,
exports: HashMap::new(),
node_graph_hash: 0,
node_graph_document: None,
previous_node_to_inspect: Vec::new(),
@@ -211,6 +229,21 @@ impl NodeGraphExecutor {
execution_id
}
fn queue_export(&mut self, network: NodeNetwork, resources: ResourceRegistry, render_config: RenderConfig, target: ExportTarget) -> Result<(), String> {
let id = self.current_export_id;
self.current_export_id += 1;
let request = GraphRuntimeRequest::Export {
id,
render_config,
network,
resources,
};
self.sender.send(request).map_err(|e| e.to_string())?;
self.exports.insert(id, target);
Ok(())
}
pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) {
if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) {
log::error!("Failed to send the overlays: {error}");
@@ -229,13 +262,29 @@ impl NodeGraphExecutor {
.expect("Failed to send the context overrides");
}
pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message {
if document_id.is_none() || self.node_graph_document != document_id {
return ClipboardMessage::Rendered { id, svg: None }.into();
}
pub fn submit_clipboard_svg(&mut self, document: &DocumentMessageHandler, id: u64, layers: &[LayerNodeIdentifier]) -> Message {
let no_svg = ClipboardMessage::Rendered { id, svg: None }.into();
let Some((network, [min, max])) = copied_layers(&document.network_interface, layers) else {
return no_svg;
};
self.sender.send(GraphRuntimeRequest::ClipboardSvg { id, layers }).expect("Failed to send runtime request");
Message::NoOp
let viewport = Footprint {
resolution: (max - min).round().as_uvec2(),
transform: DAffine2::from_translation(-min),
..Default::default()
};
let render_config = RenderConfig {
viewport,
scale: 1.,
export_format: ExportFormat::Svg,
for_export: true,
..Default::default()
};
match self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::Clipboard(id)) {
Ok(()) => Message::NoOp,
Err(_) => no_svg,
}
}
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
@@ -260,9 +309,11 @@ impl NodeGraphExecutor {
let graph_hash = document.network_interface.network_hash().wrapping_add(document.resources.resolved_hash());
if graph_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash {
let network = document.network_interface.document_network().clone();
let mut network = document.network_interface.document_network().clone();
let previewed = document.network_interface.previewed_nodes();
let layers = document.network_interface.layer_paths();
prepare_network(&mut network, &previewed, &layers);
let thumbnails = thumbnail_sources(&network, &layers);
self.node_graph_hash = graph_hash;
self.node_graph_document = Some(document_id);
@@ -272,8 +323,7 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
previewed,
layers,
thumbnails,
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
@@ -337,7 +387,6 @@ impl NodeGraphExecutor {
self.futures.push_back((
execution_id,
ExecutionContext {
export_config: None,
document_id,
document_to_viewport: viewport.transform,
measure_fill: None,
@@ -404,7 +453,6 @@ impl NodeGraphExecutor {
self.futures.push_back((
execution_id,
ExecutionContext {
export_config: None,
document_id,
document_to_viewport: viewport.transform,
measure_fill: None,
@@ -415,10 +463,9 @@ impl NodeGraphExecutor {
}
/// Evaluates a node graph for export
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, export_config: ExportConfig) -> Result<(), String> {
let network = document.network_interface.document_network().clone();
let previewed = document.network_interface.previewed_nodes();
let resources = document.resources.registry.clone();
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, export_config: ExportConfig) -> Result<(), String> {
let mut network = document.network_interface.document_network().clone();
prepare_network(&mut network, &document.network_interface.previewed_nodes(), &document.network_interface.layer_paths());
let export_format = if export_config.file_type == FileType::Svg {
graphene_std::application_io::ExportFormat::Svg
@@ -452,34 +499,12 @@ impl NodeGraphExecutor {
time: Default::default(),
pointer: DVec2::ZERO,
export_format,
// The viewport's render mode is only a way of viewing the artwork, which exports show as it is
render_mode: graphene_std::vector::style::RenderMode::Normal,
for_export: true,
for_eyedropper: false,
};
// Execute the node graph
self.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
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);
self.futures.push_back((
execution_id,
ExecutionContext {
export_config: Some(export_config),
document_id,
document_to_viewport: viewport.transform,
measure_fill: None,
},
));
Ok(())
self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::File(export_config))
}
/// Applies the graph runtime's responses to the active document, giving back the layers whose thumbnails the runtime dropped meanwhile.
@@ -491,8 +516,8 @@ impl NodeGraphExecutor {
}
let mut all_dropped_thumbnails = Vec::new();
let mut results = self.receiver.try_iter().collect::<Vec<_>>().into_iter();
for response in results.by_ref() {
let results = self.receiver.try_iter().collect::<Vec<_>>();
for response in results {
match response {
NodeGraphUpdate::ExecutionResponse(execution_response) => {
let ExecutionResponse {
@@ -516,7 +541,7 @@ impl NodeGraphExecutor {
let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
let (_, execution_context) = self.futures.pop_front().expect("the front was just checked");
if execution_context.export_config.is_none() && execution_context.measure_fill.is_none() {
if execution_context.measure_fill.is_none() {
self.pending = Some((execution_id, execution_context.clone()));
}
execution_context
@@ -571,7 +596,7 @@ impl NodeGraphExecutor {
responses.add(OverlaysMessage::Draw);
// A pending graph keeps the last frame, and the errors shown with it
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) {
if !matches!(result, ExecutionResult::Pending) {
let errors = match &result {
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
let in_document = |path: &&[NodeId]| {
@@ -644,11 +669,8 @@ impl NodeGraphExecutor {
log::error!("Node graph evaluation failed:\n{message}");
}
if execution_context.export_config.is_some() {
responses.add(export_failure_dialog(message));
}
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
break;
continue;
}
};
@@ -666,10 +688,8 @@ impl NodeGraphExecutor {
}
document.network_interface.update_vector_modify(path_contents(&observations));
match (node_graph_output, execution_context.export_config) {
(Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses),
(Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses),
(None, _) => {}
if let Some(node_graph_output) = node_graph_output {
self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses);
}
responses.add(DeferMessage::TriggerGraphRun {
execution_id,
@@ -691,49 +711,42 @@ impl NodeGraphExecutor {
node_graph_errors,
node_graph_warnings,
result,
resolved_types,
} = execution_response;
// TODO: Eventually remove this document upgrade code
// The migration's temporary redirected-export compilations must not push types or a graph view to the frontend
if self.gradient_migration.is_some() {
if let Err((_, e)) = &result {
if let Err(e) = &result {
log::trace!("Gradient migration measurement compile: {e}");
}
continue;
}
let type_delta = match result {
Err((incomplete_delta, e)) => {
// Clear the click targets while the graph is in an un-renderable state
if let Err(e) = &result {
// Clear the click targets while the graph is in an un-renderable state
document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
document.network_interface.update_outlines(HashMap::new());
document.network_interface.update_vector_modify(HashMap::new());
document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
document.network_interface.update_outlines(HashMap::new());
document.network_interface.update_vector_modify(HashMap::new());
// The graph only shows errors tied to nodes, so the console gets the others
if node_graph_errors.is_empty() {
log::error!("The node graph failed to compile:\n{e}");
} else {
log::trace!("{e}");
}
responses.add(NodeGraphMessage::UpdateTypes {
resolved_types: incomplete_delta,
node_graph_errors,
node_graph_warnings,
});
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
break;
// The graph only shows errors tied to nodes, so the console gets the others
if node_graph_errors.is_empty() {
log::error!("The node graph failed to compile:\n{e}");
} else {
log::trace!("{e}");
}
Ok(result) => result,
};
}
responses.add(NodeGraphMessage::UpdateTypes {
resolved_types: type_delta,
resolved_types,
node_graph_errors,
node_graph_warnings,
});
if result.is_err() {
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
}
}
NodeGraphUpdate::EyedropperPreview(raster) => {
let (data, width, height) = raster.to_flat_u8();
@@ -756,33 +769,7 @@ impl NodeGraphExecutor {
Self::receive_thumbnails(document, thumbnails, responses);
}
}
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
}
}
// An error leaves the later responses unapplied, but the runtime still dropped and rendered their thumbnails
for response in results {
match response {
NodeGraphUpdate::ExecutionResponse(execution_response) => {
let execution_context = self.execution_context(execution_response.execution_id);
if execution_context.is_some_and(|context| context.document_id == document_id) {
document.layers_in_view.forget_thumbnails(&execution_response.dropped_thumbnails, responses);
}
if matches!(execution_response.result, ExecutionResult::Uncompiled) && execution_context.is_some_and(|context| context.export_config.is_some()) {
responses.add(export_failure_dialog(None));
}
all_dropped_thumbnails.extend(execution_response.dropped_thumbnails);
}
NodeGraphUpdate::Thumbnails {
responses: thumbnails,
document_id: thumbnails_document,
} if thumbnails_document == document_id => {
Self::receive_thumbnails(document, thumbnails, responses);
}
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
_ => {}
NodeGraphUpdate::Export { id: export_id, result } => self.receive_export(export_id, *result, document, responses),
}
}
@@ -798,15 +785,6 @@ impl NodeGraphExecutor {
}
}
/// What an execution was submitted for, while it's still queued or pending.
fn execution_context(&self, execution_id: u64) -> Option<&ExecutionContext> {
self.futures
.iter()
.chain(&self.pending)
.find(|(queued_execution_id, _)| *queued_execution_id == execution_id)
.map(|(_, execution_context)| execution_context)
}
// TODO: Eventually remove this document upgrade code
/// Kick off the one-time pre-pass converting legacy bounding-box gradients to absolute space, or no-op if already running.
/// Returns false when the render should proceed normally instead: the pass already ran this session, so any entries still
@@ -876,6 +854,10 @@ impl NodeGraphExecutor {
return;
}
let layers = document.network_interface.layer_paths();
prepare_network(&mut network, &[], &layers);
let thumbnails = thumbnail_sources(&network, &layers);
let resources = document.resources.registry.clone();
let fill_measurement = Observation {
node_path: full_path,
@@ -887,8 +869,7 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
thumbnails,
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
}))
.is_err()
@@ -920,7 +901,6 @@ impl NodeGraphExecutor {
self.futures.push_back((
execution_id,
ExecutionContext {
export_config: None,
document_id,
document_to_viewport: viewport.transform,
measure_fill: Some((network_path, fill_node_id, gradient)),
@@ -1080,6 +1060,51 @@ impl NodeGraphExecutor {
responses.add(FrontendMessage::UpdateRenderStatus { status: render_status });
}
fn receive_export(&mut self, export_id: u64, result: ExecutionResult, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
let Some(target) = self.exports.remove(&export_id) else { return };
let failure = match (result, &target) {
(ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _), _) => {
return match target {
ExportTarget::File(export_config) => self.process_export(value, export_config, document, responses),
ExportTarget::Clipboard(id) => {
let svg = match value {
TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Svg { svg, .. },
..
}) => Some(svg),
_ => None,
};
responses.add(ClipboardMessage::Rendered { id, svg });
}
};
}
(ExecutionResult::Error(errors), _) => Some(errors.to_string()),
(ExecutionResult::Panic(payload), _) => {
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
Some(format!("Panicked: {}", message.unwrap_or("no message")))
}
(ExecutionResult::Pending | ExecutionResult::Partial(_) | ExecutionResult::Uncompiled, _) => None,
};
if let Some(message) = &failure {
log::error!("Node graph evaluation failed:\n{message}");
}
match target {
ExportTarget::File(_) => responses.add(DialogMessage::DisplayDialogError {
title: "Unable to export document".to_string(),
description: failure.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
}),
ExportTarget::Clipboard(id) => {
responses.add(ClipboardMessage::Rendered { id, svg: None });
if let Some(description) = failure {
let title = "Unable to copy as SVG".to_string();
responses.add(DialogMessage::DisplayDialogError { title, description });
}
}
}
}
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
let ExportConfig {
file_type,
@@ -1179,6 +1204,61 @@ pub(crate) fn redirect_export_chain(network: &mut NodeNetwork, full_path: &[Node
}
}
fn prepare_network(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)], layers: &[Vec<NodeId>]) {
apply_previews(network, previewed);
write_layer_paths(network, layers);
}
/// Replaces each network's primary export with its previewed node.
pub(crate) fn apply_previews(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)]) {
for (network_path, previewed) in previewed {
let Some(nested) = network.nested_network_mut(network_path) else { continue };
let Some(export) = nested.exports.first_mut() else { continue };
*export = NodeInput::node(previewed.node_id, previewed.output_index);
}
}
/// The node giving the content each layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
fn thumbnail_sources(network: &NodeNetwork, layers: &[Vec<NodeId>]) -> Vec<(NodeId, Vec<NodeId>)> {
// O(layers * depth)
let source = |layer: &Vec<NodeId>| Some((*layer.last()?, layer_content(layer, network)?.source(network)?));
layers.iter().filter_map(source).collect()
}
fn copied_layers(interface: &NodeNetworkInterface, layers: &[LayerNodeIdentifier]) -> Option<(NodeNetwork, [DVec2; 2])> {
let metadata = interface.document_metadata();
let is_artboard = |layer: &LayerNodeIdentifier| interface.is_artboard(&layer.to_node(), &[]);
let stack = match layers.iter().filter(|layer| is_artboard(layer)).count() {
0 if layers.iter().all(|layer| interface.is_merge(&layer.to_node(), &[])) => list!(Graphic),
artboards if artboards == layers.len() => list!(Artboard),
_ => return None,
};
let mut network = interface.document_network().clone();
prepare_network(&mut network, &interface.previewed_nodes(), &interface.layer_paths());
let mut below = NodeInput::type_default(stack, true);
let mut bounds = None;
for &layer in layers {
let mut node = network.nodes.get(&layer.to_node())?.clone();
*node.inputs.first_mut()? = below;
let copy = NodeId::new();
network.nodes.insert(copy, node);
below = NodeInput::node(copy, 0);
let from_document = match metadata.upstream_footprints.contains_key(&layer.to_node()) {
true => metadata.downstream_transform_to_document(layer).inverse(),
false => DAffine2::IDENTITY,
};
let in_document = metadata.bounding_box_document_with_stroke_and_effects(layer);
let own = in_document.map(|bounds| (from_document * Quad::from_box(bounds)).bounding_box());
bounds = [bounds, own].into_iter().flatten().reduce(Quad::combine_bounds);
}
network.exports = vec![below];
Some((network, bounds?))
}
// TODO: Eventually remove this document upgrade code
/// Turn a measured fill node's evaluated geometry into a `[0,1]² -> bounding box` affine plus the geometry's item transform.
fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> {
@@ -1200,14 +1280,6 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
None
}
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
DialogMessage::DisplayDialogError {
title: "Unable to export document".to_string(),
description: evaluation_error.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
}
}
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));
@@ -1273,14 +1345,17 @@ mod test {
network.inline_definitions().map_err(|error| error.to_string())?;
let instrumented = Instrumented::new(&network);
let layers = document.network_interface.layer_paths();
prepare_network(&mut network, &[], &layers);
let thumbnails = thumbnail_sources(&network, &layers);
let resources = document.resources.registry.clone();
self.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
thumbnails,
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
@@ -18,8 +18,8 @@ async fn compile_and_run(editor: &mut EditorTestUtils) {
editor.dispatch(Message::Wake);
}
/// 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.
/// The proto node IDs compiled for the document node paths that pass `keep`. The runtime keeps the output of the network
/// an update replaces for one more update, so a first update clears the nodes of the graph before it.
async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> {
compile_and_run(editor).await;
compile_and_run(editor).await;
File diff suppressed because it is too large. Load diff
@@ -3,7 +3,7 @@ use crate::messages::frontend::FrontendMessage;
use atlas::ThumbnailAtlasLayout;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::document::NodeId;
use graphene_std::application_io::{ApplicationIo, Texture};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::gradient::Gradient;
@@ -12,12 +12,11 @@ use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
use graphene_std::transform::{Footprint, RenderQuality};
use graphene_std::renderer::Render;
use graphene_std::transform::Footprint;
use graphene_std::vector::Vector;
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::layer_paths::layer_content;
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;
@@ -83,12 +82,9 @@ impl Thumbnails {
}
/// Finds the proto node giving each layer's content in the newly compiled graph, marking the layers whose proto node changed as stale.
pub fn update_sources(&mut self, layer_paths: &[Vec<NodeId>], network: &NodeNetwork, executor: &DynamicExecutor) {
// O(layers * depth)
let sources: HashMap<NodeId, NodeId> = layer_paths
.iter()
.filter_map(|layer_path| Some((*layer_path.last()?, thumbnail_source(layer_path, network, executor)?)))
.collect();
pub fn update_sources(&mut self, layers: &[(NodeId, Vec<NodeId>)], executor: &DynamicExecutor) {
let source_map = executor.tree().source_map();
let sources: HashMap<NodeId, NodeId> = layers.iter().filter_map(|(layer, source)| Some((*layer, source_map.get(source.as_slice())?.0))).collect();
// A proto node's ID hashes everything upstream of it, so a layer whose source kept its ID shows the same content
let changed = sources.iter().filter(|(layer, source)| self.sources.get(layer) != Some(source));
@@ -276,11 +272,11 @@ impl ThumbnailContent {
}
}
/// The area the content covers once rendered, counting the effects drawn through maps and images only if they're `maps_resolved`, which the clipboard's SVG leaves out.
fn content_bounds(&self, maps_resolved: bool) -> RenderBoundingBox {
/// The area the content covers once rendered, counting the effects drawn through maps and images.
fn content_bounds(&self) -> RenderBoundingBox {
match self {
// Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, maps_resolved),
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, true),
// The clipping rectangles rather than the content, since the renderer clips content to them
Self::Artboards(artboards) => artboard_clip_bounds(artboards),
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
@@ -289,7 +285,7 @@ impl ThumbnailContent {
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
fn bounds(&self) -> [DVec2; 2] {
let bounds = match self.content_bounds(true) {
let bounds = match self.content_bounds() {
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
_ => [DVec2::ZERO, DVec2::ONE],
};
@@ -297,45 +293,6 @@ impl ThumbnailContent {
}
}
/// Renders what each of these document layers adds, painted in the given order, as one SVG framed to their combined bounds, or `None` if they render nothing.
pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<String> {
let contents: Vec<ThumbnailContent> = layers
.iter()
.filter_map(|&layer| ThumbnailContent::evaluate(executor, thumbnail_source(&[layer], network, executor)?))
.collect();
let bounds = contents
.iter()
.filter_map(|content| match content.content_bounds(false) {
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => Some(bounds),
_ => None,
})
.reduce(|[min, max], [other_min, other_max]| [min.min(other_min), max.max(other_max)])?;
let render_params = RenderParams {
footprint: Footprint::from_bounds(bounds, RenderQuality::Full),
thumbnail: true,
..Default::default()
};
let mut render = SvgRender::new();
for content in &contents {
content.graphic().render_svg(&mut render, &render_params);
}
if render.svg.is_empty() {
return None;
}
render.format_svg(bounds[0], bounds[1]);
Some(render.svg.to_svg_string())
}
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
let source = layer_content(layer_path, network)?.source(network)?;
executor.tree().source_map().get(source.as_slice()).map(|(id, _)| *id)
}
/// Converts the other kinds of graphical content into a graphic.
fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> {
macro_rules! downcast_into_graphic {
+1 -1
View File
@@ -128,7 +128,7 @@ pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocume
impl CompiledDocument {
pub fn into_renderer(self) -> Result<Renderer, Box<dyn Error>> {
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(self.proto_network).map_err(|(_, errors)| {
let output = executor.insert(self.proto_network).map_err(|errors| {
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
messages.join("\n")
})?;
+3 -3
View File
@@ -133,13 +133,13 @@ impl Viewer {
Err(error) => return log::error!("Compile failed: {error}"),
};
let mut executor = DynamicExecutor::default();
match executor.update(proto) {
Ok((output, _)) => {
match executor.insert(proto) {
Ok(output) => {
self.graph_runtime.update_sources(executor.sources());
log::info!("Document compiled");
self.executor = Some((executor, output));
}
Err((_, errors)) => {
Err(errors) => {
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
log::error!("Executor creation failed: {}", messages.join("\n"));
}
@@ -18,7 +18,7 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork
preprocessor.preprocess(&mut network, &|_| None).unwrap();
let proto_network = compile(network);
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(proto_network.clone()).unwrap();
let output = executor.insert(proto_network.clone()).unwrap();
(executor, output, proto_network)
}
@@ -73,7 +73,7 @@ impl Session {
let mut network = wrap_network_with_render_node_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.output, _) = self.executor.update(proto_network).expect("Failed to update the executor");
self.output = self.executor.insert(proto_network).expect("Failed to update the executor");
let render_config = RenderConfig {
viewport: Footprint {
@@ -16,7 +16,7 @@ fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
c.bench_function(name, |b| {
b.iter_batched(
|| (executor.clone(), proto_network.clone()),
|(mut executor, network)| executor.update(std::hint::black_box(network)),
|(mut executor, network)| executor.insert(std::hint::black_box(network)),
criterion::BatchSize::SmallInput,
)
});
@@ -36,7 +36,7 @@ fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
let proto_network = compile(network);
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(proto_network).unwrap();
let output = executor.insert(proto_network).unwrap();
let footprint = Footprint::default();
c.bench_function(name, |b| b.iter(|| executor.execute(&output, footprint)));
@@ -13,7 +13,7 @@ fn update_executor(c: &mut Criterion) {
let (_, _, proto_network) = setup_network(name);
(DynamicExecutor::default(), proto_network)
},
|(mut executor, network)| executor.update(std::hint::black_box(network)),
|(mut executor, network)| executor.insert(std::hint::black_box(network)),
criterion::BatchSize::SmallInput,
)
});
@@ -15,7 +15,7 @@ fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)]
pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor {
let (mut executor, network) = setup;
let _ = black_box(executor.update(black_box(network)));
let _ = black_box(executor.insert(black_box(network)));
// Return the executor so its teardown happens outside the measured section
executor
@@ -19,8 +19,7 @@ pub struct DynamicExecutor {
typing_context: TypingContext,
/// The outputs of the networks, kept alive by the executor as long as there are handles to them.
outputs: Vec<Weak<NodeId>>,
// Kept for one more update, so a node that comes back is reused
orphaned_nodes: HashSet<NodeId>,
type_deltas: TypeDeltaCollector,
}
#[derive(Clone, Debug, Default)]
@@ -38,7 +37,7 @@ impl Default for DynamicExecutor {
tree: Default::default(),
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
outputs: Vec::new(),
orphaned_nodes: HashSet::new(),
type_deltas: Default::default(),
}
}
}
@@ -64,19 +63,37 @@ impl DynamicExecutor {
/// Adds the [`ProtoNetwork`] to the existing [`BorrowTree`], reusing nodes where possible.
#[cfg_attr(debug_assertions, inline(never))]
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
let (output, add) = self.insert_nodes(proto_network)?;
let remove = self.free_orphaned_nodes();
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove }))
pub fn insert(&mut self, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
let output = self.insert_nodes(proto_network)?;
self.free_orphaned_nodes();
Ok(output)
}
pub fn update_without_freeing(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
let (output, add) = self.insert_nodes(proto_network)?;
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }))
pub fn replace(&mut self, output: OutputHandle, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
let inserted = self.insert_nodes(proto_network)?;
let Some(replaced) = Arc::into_inner(output.0) else { return Ok(inserted) };
let live: Vec<NodeId> = self.outputs.iter().filter_map(Weak::upgrade).map(|output| *output).collect();
let mut pending = vec![replaced];
while let Some(node) = pending.pop() {
let Some((container, _, inputs)) = self.tree.nodes.get(&node) else { continue };
if Arc::strong_count(container) > 1 || live.contains(&node) {
continue;
}
pending.extend(inputs.iter());
if let Some(path) = self.tree.free_node(node) {
self.type_deltas.remove(path);
}
self.typing_context.remove_inference(node);
}
Ok(inserted)
}
fn insert_nodes(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, Vec<(Path, NodeTypes)>), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
self.typing_context.update(&proto_network).map_err(|e| {
pub fn take_type_deltas(&mut self) -> Option<ResolvedDocumentNodeTypesDelta> {
self.type_deltas.take()
}
fn insert_nodes(&mut self, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
self.typing_context.update(&proto_network).inspect_err(|_| {
// If there is an error then get types that have been resolved before the error
let add = proto_network
.nodes
@@ -94,11 +111,13 @@ impl DynamicExecutor {
)
})
.collect::<Vec<_>>();
(ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }, e)
self.type_deltas.add(add);
})?;
let output = proto_network.output;
let add = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
let add = self.tree.update(proto_network, &self.typing_context)?;
self.outputs.retain(|output| output.strong_count() > 0);
let held = self.outputs.iter().filter_map(Weak::upgrade).find(|held| **held == output);
let output = held.unwrap_or_else(|| {
@@ -107,11 +126,11 @@ impl DynamicExecutor {
output
});
let add = self.document_node_types(add.into_iter()).collect();
Ok((OutputHandle(output), add))
self.type_deltas.add(self.tree.node_types(add.into_iter()));
Ok(OutputHandle(output))
}
fn free_orphaned_nodes(&mut self) -> Vec<Path> {
fn free_orphaned_nodes(&mut self) {
let mut kept = HashSet::new();
let mut pending: Vec<NodeId> = self.outputs.iter().filter_map(Weak::upgrade).map(|output| *output).collect();
while let Some(node) = pending.pop() {
@@ -121,19 +140,14 @@ impl DynamicExecutor {
pending.extend(inputs.iter());
}
}
let orphaned = self.tree.nodes.keys().filter(|node| !kept.contains(node)).copied().collect();
let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned);
let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len()));
for node_id in old_to_remove {
if self.orphaned_nodes.contains(&node_id) {
let path = self.tree.free_node(node_id);
self.typing_context.remove_inference(node_id);
if let Some(path) = path {
remove.push(path);
}
let orphaned: Vec<NodeId> = self.tree.nodes.keys().filter(|node| !kept.contains(node)).copied().collect();
for node_id in orphaned {
let path = self.tree.free_node(node_id);
self.typing_context.remove_inference(node_id);
if let Some(path) = path {
self.type_deltas.remove(path);
}
}
remove
}
pub fn execute<I: 'static + WasmNotSend>(&self, output: &OutputHandle, input: I) -> Result<Poll<TaggedValue>, Box<dyn Error>> {
@@ -153,7 +167,7 @@ impl DynamicExecutor {
}
pub fn document_node_types<'a>(&'a self, nodes: impl Iterator<Item = Path> + 'a) -> impl Iterator<Item = (Path, NodeTypes)> + 'a {
nodes.flat_map(|id| self.tree.source_map().get(&id).map(|(_, b)| (id, b.clone())))
self.tree.node_types(nodes)
// TODO: https://github.com/GraphiteEditor/Graphite/issues/1767
// TODO: Non exposed inputs are not added to the inputs_source_map, so they are not included in the resolved_document_node_types. The type is still available in the typing_context. This only affects the UI-only "Import" node.
}
@@ -559,6 +573,39 @@ impl BorrowTree {
pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> {
&self.source_map
}
pub fn node_types<'a>(&'a self, nodes: impl Iterator<Item = Path> + 'a) -> impl Iterator<Item = (Path, NodeTypes)> + 'a {
nodes.flat_map(|id| self.source_map().get(&id).map(|(_, b)| (id, b.clone())))
}
}
#[derive(Clone, Default)]
struct TypeDeltaCollector {
changes: HashMap<Path, Option<NodeTypes>>,
}
impl TypeDeltaCollector {
fn add(&mut self, types: impl IntoIterator<Item = (Path, NodeTypes)>) {
self.changes.extend(types.into_iter().map(|(path, types)| (path, Some(types))));
}
fn remove(&mut self, path: Path) {
self.changes.insert(path, None);
}
fn take(&mut self) -> Option<ResolvedDocumentNodeTypesDelta> {
if self.changes.is_empty() {
return None;
}
let mut delta = ResolvedDocumentNodeTypesDelta::default();
for (path, types) in self.changes.drain() {
match types {
Some(types) => delta.add.push((path, types)),
None => delta.remove.push(path),
}
}
Some(delta)
}
}
#[cfg(test)]
@@ -876,7 +876,7 @@ fn error_traced_through(indices: &[usize]) -> NodeError {
#[test]
fn a_trace_leads_to_the_node_that_raised_the_error() {
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
let output = executor.insert(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
assert!(executor.trace_error(output.node(), &error_traced_through(&[])).is_empty());
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0])), [NodeId(0)]);
@@ -899,7 +899,7 @@ fn a_trace_steps_over_the_index_of_a_promotion_adapter() {
nodes: vec![(NodeId(0), value_node), (NodeId(1), box_corners_node)],
};
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).unwrap();
let output = executor.insert(network).unwrap();
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0, 0])), [NodeId(0)]);
}
@@ -936,7 +936,7 @@ fn chained_fallbacks_both_reach_the_root() {
.concat(),
};
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).unwrap();
let output = executor.insert(network).unwrap();
let context: Context = None;
let Ok(Poll::Fallback(boxed)) = executor.execute(&output, context) else {
@@ -966,7 +966,7 @@ fn an_error_after_a_fallback_keeps_both() {
.concat(),
};
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).unwrap();
let output = executor.insert(network).unwrap();
let context: Context = None;
let Ok(Poll::Error(error)) = executor.execute(&output, context) else {
@@ -995,7 +995,7 @@ fn a_node_error_names_the_node_that_raised_it() {
.concat(),
};
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).expect("The Throw Error nodes should resolve");
let output = executor.insert(network).expect("The Throw Error nodes should resolve");
let context: Context = None;
let Ok(Poll::Error(error)) = executor.execute(&output, context) else {
@@ -1050,7 +1050,7 @@ fn handled_error_network(handler: ProtoNodeIdentifier, handler_inputs: &[u64], k
.concat(),
};
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).expect("The error handling nodes should resolve");
let output = executor.insert(network).expect("The error handling nodes should resolve");
(executor, output)
}
@@ -1190,16 +1190,6 @@ fn source_network(node: u64) -> ProtoNetwork {
}
}
#[test]
fn update_without_freeing_keeps_the_nodes_the_network_leaves_out() {
let mut executor = DynamicExecutor::default();
executor.update(source_network(0)).unwrap();
executor.update_without_freeing(source_network(1)).unwrap();
executor.update_without_freeing(source_network(1)).unwrap();
assert!(executor.tree().get(NodeId(0)).is_some());
}
#[test]
fn networks_are_executed_side_by_side_by_their_handles() {
let network = |node: u64| ProtoNetwork {
@@ -1208,8 +1198,8 @@ fn networks_are_executed_side_by_side_by_their_handles() {
nodes: vec![value_node(node, TaggedValue::Number(node as f64))],
};
let mut executor = DynamicExecutor::default();
let (first, _) = executor.update(network(0)).unwrap();
let (second, _) = executor.update(network(1)).unwrap();
let first = executor.insert(network(0)).unwrap();
let second = executor.insert(network(1)).unwrap();
let context: Context = None;
assert_eq!(executor.execute(&first, context.clone()).unwrap(), Poll::Final(TaggedValue::Number(0.)));
@@ -1219,9 +1209,9 @@ fn networks_are_executed_side_by_side_by_their_handles() {
#[test]
fn an_output_that_is_already_held_shares_its_handle() {
let mut executor = DynamicExecutor::default();
let (first, _) = executor.update(source_network(0)).unwrap();
let (second, _) = executor.update(source_network(0)).unwrap();
let (other, _) = executor.update(source_network(1)).unwrap();
let first = executor.insert(source_network(0)).unwrap();
let second = executor.insert(source_network(0)).unwrap();
let other = executor.insert(source_network(1)).unwrap();
assert!(Arc::ptr_eq(&first.0, &second.0));
assert!(!Arc::ptr_eq(&first.0, &other.0));
@@ -1230,28 +1220,123 @@ fn an_output_that_is_already_held_shares_its_handle() {
#[test]
fn a_handle_keeps_its_output_and_the_nodes_that_feed_it() {
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
let output = executor.insert(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
let kept = |executor: &DynamicExecutor| [0, 1].map(|node| executor.tree().get(NodeId(node)).is_some());
for _ in 0..3 {
executor.update(source_network(2)).unwrap();
executor.insert(source_network(2)).unwrap();
}
assert_eq!(kept(&executor), [true; 2]);
drop(output);
executor.update(source_network(2)).unwrap();
assert_eq!(kept(&executor), [true; 2], "orphaned for one more update");
executor.update(source_network(2)).unwrap();
executor.insert(source_network(2)).unwrap();
assert_eq!(kept(&executor), [false; 2]);
}
#[test]
fn a_source_is_listed_for_as_long_as_its_node_lives() {
let mut executor = DynamicExecutor::default();
executor.update(source_network(0)).unwrap();
let output = executor.insert(source_network(0)).unwrap();
let listed = |executor: &DynamicExecutor| executor.sources().any(|source| *source == SourceId(0));
for _ in 0..3 {
executor.update(source_network(1)).unwrap();
assert_eq!(executor.sources().any(|source| *source == SourceId(0)), executor.tree().get(NodeId(0)).is_some());
executor.insert(source_network(1)).unwrap();
assert!(listed(&executor));
drop(output);
executor.insert(source_network(1)).unwrap();
assert!(!listed(&executor));
}
fn changed_paths(executor: &mut DynamicExecutor) -> Option<[Vec<u64>; 2]> {
let changes = executor.take_type_deltas()?;
let added = changes.add.iter().map(|(path, _)| path[0].0);
let removed = changes.remove.iter().map(|path| path[0].0);
let mut paths = [added.collect::<Vec<_>>(), removed.collect()];
paths.iter_mut().for_each(|paths| paths.sort_unstable());
Some(paths)
}
#[test]
fn take_type_deltas_gives_the_paths_inserted_and_freed_since_the_last_take() {
let mut executor = DynamicExecutor::default();
let held = [executor.insert(source_network(0)).unwrap(), executor.insert(source_network(1)).unwrap()];
assert_eq!(changed_paths(&mut executor), Some([vec![0, 1], vec![]]));
assert_eq!(changed_paths(&mut executor), None);
drop(held);
executor.insert(source_network(2)).unwrap();
assert_eq!(changed_paths(&mut executor), Some([vec![2], vec![0, 1]]));
}
#[test]
fn a_path_freed_and_inserted_again_between_two_takes_is_given_with_its_types() {
let mut executor = DynamicExecutor::default();
executor.insert(source_network(0)).unwrap();
executor.take_type_deltas();
executor.insert(source_network(1)).unwrap();
executor.insert(source_network(0)).unwrap();
let path: Path = [NodeId(0)].into();
let types = executor.tree().source_map()[&path].1.clone();
assert_eq!(executor.take_type_deltas().unwrap().add, [(path, types)]);
}
#[test]
fn a_path_typed_before_a_type_error_is_given() {
let mut executor = DynamicExecutor::default();
executor.insert(bounding_box_network(TaggedValue::Number(1.))).unwrap_err();
assert_eq!(changed_paths(&mut executor), Some([vec![0], vec![]]));
}
#[test]
fn replace_frees_what_only_the_replaced_output_reached() {
let mut executor = DynamicExecutor::default();
let replaced = executor.insert(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
executor.replace(replaced, source_network(2)).unwrap();
for node in [NodeId(0), NodeId(1)] {
assert!(executor.tree().get(node).is_none());
assert!(executor.typing_context.type_of(node).is_none());
}
let delta = executor.take_type_deltas().unwrap();
let mut removed: Vec<_> = delta.remove.iter().map(|path| path.to_vec()).collect();
removed.sort();
assert_eq!(removed, [vec![NodeId(0)], vec![NodeId(1)]]);
assert_eq!(executor.tree().source_map().keys().map(|path| path.to_vec()).collect::<Vec<_>>(), [vec![NodeId(2)]]);
}
#[test]
fn replace_keeps_what_the_new_network_or_another_output_still_reaches() {
let content = TaggedValue::TypeDefault(item!(Vector));
let value_network = |(output, node)| ProtoNetwork {
inputs: vec![],
output,
nodes: vec![(output, node)],
};
let mut executor = DynamicExecutor::default();
let _document = executor.insert(value_network(value_node(0, content.clone()))).unwrap();
let replaced = executor.insert(offset_points_network(content)).unwrap();
executor.replace(replaced, value_network(value_node(1, TaggedValue::Number(10.)))).unwrap();
assert_eq!([0, 1, 2, 3].map(|node| executor.tree().get(NodeId(node)).is_some()), [true, true, false, false]);
}
#[test]
fn replace_frees_nothing_while_the_replaced_handle_is_held_elsewhere() {
let mut executor = DynamicExecutor::default();
let held = executor.insert(source_network(0)).unwrap();
executor.replace(held.clone(), source_network(1)).unwrap();
assert!(executor.tree().get(NodeId(0)).is_some());
}
#[test]
fn repeated_replacing_keeps_the_node_count_and_the_source_map_size_constant() {
let mut executor = DynamicExecutor::default();
let mut output = executor.insert(source_network(0)).unwrap();
for node in 1..=4 {
output = executor.replace(output, source_network(node)).unwrap();
assert_eq!([executor.tree().nodes.len(), executor.tree().source_map().len()], [1, 1]);
}
}
+1 -1
View File
@@ -49,6 +49,6 @@ mod tests {
let compiler = Compiler {};
let protograph = compiler.compile_single(network).expect("Graph should be generated").network;
let _exec = DynamicExecutor::default().update(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
let _exec = DynamicExecutor::default().insert(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
}
}
+2 -2
View File
@@ -552,7 +552,7 @@ mod destructure_tests {
fn assert_execution_result(network: NodeNetwork, expected: TaggedValue) {
let proto_network = Compiler {}.compile_single(network).expect("Compilation should succeed").network;
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(proto_network).expect("The executor should type check and build");
let output = executor.insert(proto_network).expect("The executor should type check and build");
let context: core_types::Context = None;
let result = executor.tree().eval_tagged_value(output.node(), &context).expect("Execution should succeed");
@@ -932,7 +932,7 @@ mod tests {
let proto_network = Compiler {}.compile_single(network).unwrap().network;
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(proto_network).unwrap();
let output = executor.insert(proto_network).unwrap();
let context: core_types::Context = None;
let Ok(core_types::Poll::Fallback(boxed)) = executor.execute(&output, context) else {
panic!("The color lookup should evaluate with an error");