mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bedc211954 | ||
|
|
65c04a49f1 | ||
|
|
63981ffa62 | ||
|
|
c4a2c93d57 | ||
|
|
abf6e599a9 |
No files matched your search
Generated
+2
-2
@@ -4826,9 +4826,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ollev"
|
||||
version = "0.1.2"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d77164e6c8fb386ee064104ab480578451b0fd106ca4c0a6988eb7ca4ed9ec4b"
|
||||
checksum = "9e858a872f7e5f74992f283fe52d9c184234e8505f316e6aa7822fa394b39d0a"
|
||||
dependencies = [
|
||||
"glam",
|
||||
]
|
||||
|
||||
+1
-1
@@ -268,7 +268,7 @@ tinyvec = { version = "1", features = ["std"] }
|
||||
criterion = { version = "0.8", features = ["html_reports"] }
|
||||
gungraun = { version = "0.20" }
|
||||
ndarray = "0.17"
|
||||
ollev = "0.1.2"
|
||||
ollev = "0.2.0"
|
||||
dirs = "7.0"
|
||||
cef = "156"
|
||||
cef-dll-sys = "156"
|
||||
|
||||
@@ -6,7 +6,8 @@ use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
||||
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeProgress, FrontendNodeType, FrontendRemoteCursor,
|
||||
NodeGraphErrorDiagnostic,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
|
||||
@@ -272,6 +273,10 @@ pub enum FrontendMessage {
|
||||
UpdateDocumentArtwork {
|
||||
svg: String,
|
||||
},
|
||||
/// How far the work in progress of the active document has come from 0 to 1 (none when it has no work in progress).
|
||||
UpdateDocumentProgress {
|
||||
progress: Option<f64>,
|
||||
},
|
||||
UpdateRenderStatus {
|
||||
status: RenderStatus,
|
||||
},
|
||||
@@ -326,6 +331,9 @@ pub enum FrontendMessage {
|
||||
UpdateNodeGraphErrorDiagnostics {
|
||||
errors: Vec<NodeGraphErrorDiagnostic>,
|
||||
},
|
||||
UpdateNodeGraphProgress {
|
||||
progress: Vec<FrontendNodeProgress>,
|
||||
},
|
||||
UpdateVisibleNodes {
|
||||
nodes: Vec<NodeId>,
|
||||
},
|
||||
|
||||
@@ -58,6 +58,10 @@ pub enum MouseCursorIcon {
|
||||
pub enum RenderStatus {
|
||||
#[default]
|
||||
Rendering,
|
||||
/// Rendering a frame computed from provisional data, while async work is in progress.
|
||||
Partial,
|
||||
/// Rendering a frame computed from substitute data, because part of the graph failed.
|
||||
Fallback,
|
||||
Error,
|
||||
Panic,
|
||||
}
|
||||
|
||||
@@ -437,6 +437,8 @@ pub struct NodeSection {
|
||||
/// Whether the content wire also continues up past its turn, to the section above that takes it from the bottom.
|
||||
#[serde(rename = "contentWireContinues")]
|
||||
pub content_wire_continues: bool,
|
||||
/// How far the work in progress of the node has come from 0 to 1, shown in the section header with a button to cancel it (none when it has no work in progress).
|
||||
pub progress: Option<f64>,
|
||||
/// Whether this section is expanded to show its contents, as opposed to being collapsed down to just its header.
|
||||
pub expanded: bool,
|
||||
/// The ID of the node whose Inspector section this is.
|
||||
@@ -490,6 +492,7 @@ impl LayoutGroup {
|
||||
node_reference: false,
|
||||
content_wire: None,
|
||||
content_wire_continues: false,
|
||||
progress: None,
|
||||
expanded,
|
||||
id,
|
||||
layout,
|
||||
@@ -597,6 +600,7 @@ impl Diffable for LayoutGroup {
|
||||
node_reference: current_node_reference,
|
||||
content_wire: current_content_wire,
|
||||
content_wire_continues: current_content_wire_continues,
|
||||
progress: current_progress,
|
||||
expanded: current_expanded,
|
||||
id: current_id,
|
||||
layout: current_layout,
|
||||
@@ -613,6 +617,7 @@ impl Diffable for LayoutGroup {
|
||||
node_reference: new_node_reference,
|
||||
content_wire: new_content_wire,
|
||||
content_wire_continues: new_content_wire_continues,
|
||||
progress: new_progress,
|
||||
expanded: new_expanded,
|
||||
id: new_id,
|
||||
layout: new_layout,
|
||||
@@ -632,6 +637,7 @@ impl Diffable for LayoutGroup {
|
||||
|| *current_node_reference != new_node_reference
|
||||
|| *current_content_wire != new_content_wire
|
||||
|| *current_content_wire_continues != new_content_wire_continues
|
||||
|| *current_progress != new_progress
|
||||
|| *current_expanded != new_expanded
|
||||
|| *current_id != new_id
|
||||
{
|
||||
@@ -647,6 +653,7 @@ impl Diffable for LayoutGroup {
|
||||
*current_node_reference = new_node_reference;
|
||||
*current_content_wire = new_content_wire;
|
||||
*current_content_wire_continues = new_content_wire_continues;
|
||||
*current_progress = new_progress;
|
||||
*current_expanded = new_expanded;
|
||||
*current_id = new_id;
|
||||
current_layout.clone_from(&new_layout);
|
||||
@@ -664,6 +671,7 @@ impl Diffable for LayoutGroup {
|
||||
node_reference: new_node_reference,
|
||||
content_wire: new_content_wire,
|
||||
content_wire_continues: new_content_wire_continues,
|
||||
progress: new_progress,
|
||||
expanded: new_expanded,
|
||||
id: new_id,
|
||||
layout: new_layout,
|
||||
|
||||
@@ -217,6 +217,9 @@ pub enum DocumentMessage {
|
||||
layers: Vec<NodeId>,
|
||||
layers_missing_details: Vec<NodeId>,
|
||||
},
|
||||
CancelNodeWork {
|
||||
node_id: NodeId,
|
||||
},
|
||||
SetNodePinned {
|
||||
node_id: NodeId,
|
||||
pinned: bool,
|
||||
|
||||
@@ -1550,6 +1550,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(NodeGraphMessage::SendLayerPanelDetails { layers: layers_missing_details });
|
||||
}
|
||||
}
|
||||
DocumentMessage::CancelNodeWork { node_id } => {
|
||||
let node_path = [self.selection_network_path.as_slice(), &[node_id]].concat();
|
||||
responses.add(PortfolioMessage::CancelNodeWork { node_path });
|
||||
}
|
||||
DocumentMessage::SetNodePinned { node_id, pinned } => {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::SetPinned { node_id, pinned });
|
||||
|
||||
@@ -345,6 +345,10 @@ pub enum NodeGraphMessage {
|
||||
UpdateEvaluationErrors {
|
||||
errors: Vec<NodeEvaluationError>,
|
||||
},
|
||||
/// The progress of the nodes with work in progress, by their full path from the root network.
|
||||
UpdateNodeProgress {
|
||||
progress: Vec<(Vec<NodeId>, f64)>,
|
||||
},
|
||||
UpdateActionButtons,
|
||||
UpdateGraphBarRight,
|
||||
UpdateInSelectedNetwork,
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, FrontendNodeProgress, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
||||
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::misc::GroupFolderType;
|
||||
@@ -136,6 +136,8 @@ pub struct NodeGraphMessageHandler {
|
||||
/// Used to keep track of what wires are sent to the frontend so the old ones can be removed
|
||||
frontend_wires: HashSet<(NodeId, usize)>,
|
||||
evaluation_errors: Vec<NodeEvaluationError>,
|
||||
/// The progress of the nodes with work in progress, by their full path from the root network.
|
||||
node_progress: Vec<(Vec<NodeId>, f64)>,
|
||||
}
|
||||
|
||||
/// NodeGraphMessageHandler always modifies the network which the selected nodes are in. No GraphOperationMessages should be added here, since those messages will always affect the document network.
|
||||
@@ -2058,6 +2060,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
|
||||
let errors = self.node_graph_errors(network_interface, breadcrumb_network_path);
|
||||
responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors });
|
||||
let progress = self.node_graph_progress(breadcrumb_network_path);
|
||||
responses.add(FrontendMessage::UpdateNodeGraphProgress { progress });
|
||||
let (layer_widths, chain_widths, has_left_input_wire) = network_interface.collect_layer_widths(breadcrumb_network_path);
|
||||
|
||||
responses.add(NodeGraphMessage::UpdateImportsExports);
|
||||
@@ -2664,6 +2668,15 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
}
|
||||
}
|
||||
NodeGraphMessage::UpdateNodeProgress { progress } => {
|
||||
if self.node_progress != progress {
|
||||
self.node_progress = progress;
|
||||
if breadcrumb_network_path == selection_network_path && graph_view_overlay_open {
|
||||
let progress = self.node_graph_progress(breadcrumb_network_path);
|
||||
responses.add(FrontendMessage::UpdateNodeGraphProgress { progress });
|
||||
}
|
||||
}
|
||||
}
|
||||
NodeGraphMessage::UpdateActionButtons => {
|
||||
if selection_network_path == breadcrumb_network_path {
|
||||
self.update_graph_bar_left(network_interface, breadcrumb_network_path, responses);
|
||||
@@ -3871,6 +3884,22 @@ impl NodeGraphMessageHandler {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The progress of the nodes in the network at `breadcrumb_network_path`, where a node shows the first work in progress within it.
|
||||
fn node_graph_progress(&self, breadcrumb_network_path: &[NodeId]) -> Vec<FrontendNodeProgress> {
|
||||
let depth = breadcrumb_network_path.len();
|
||||
|
||||
let mut shown = HashSet::new();
|
||||
self.node_progress
|
||||
.iter()
|
||||
.filter(|(path, _)| path.starts_with(breadcrumb_network_path) && path.len() > depth)
|
||||
.filter(|(path, _)| shown.insert(path[depth]))
|
||||
.map(|(path, progress)| FrontendNodeProgress {
|
||||
node_id: path[depth],
|
||||
progress: *progress,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Sends the Layers panel the details of the given layers, which it needs only for the rows it has in view.
|
||||
// O(given layers × nesting depth), apart from what the active tool would edit in the selected layers
|
||||
fn update_layer_panel(
|
||||
@@ -4080,6 +4109,7 @@ impl Default for NodeGraphMessageHandler {
|
||||
frontend_nodes: Vec::new(),
|
||||
frontend_wires: HashSet::new(),
|
||||
evaluation_errors: Vec::new(),
|
||||
node_progress: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3284,6 +3284,7 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
let mut section = LayoutGroup::section(name, icon, description, visible, pinned, expanded, node_id.0, Layout(layout));
|
||||
if let LayoutGroup::NodeSection(node_section) = &mut section {
|
||||
node_section.chain_wire = chain_wire;
|
||||
node_section.progress = context.executor.node_progress(&[network_path, &[node_id]].concat());
|
||||
}
|
||||
section
|
||||
}
|
||||
|
||||
@@ -202,6 +202,15 @@ pub struct NodeGraphErrorDiagnostic {
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FrontendNodeProgress {
|
||||
#[serde(rename = "nodeId")]
|
||||
pub node_id: NodeId,
|
||||
/// How much of the work within the node is done, from 0 to 1.
|
||||
pub progress: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct NodeEvaluationError {
|
||||
pub node_path: Vec<NodeId>,
|
||||
|
||||
@@ -40,6 +40,10 @@ pub enum PortfolioMessage {
|
||||
AutoSaveDocument {
|
||||
document_id: DocumentId,
|
||||
},
|
||||
/// Cancels the work in progress of the active document's node at this full path from the root network.
|
||||
CancelNodeWork {
|
||||
node_path: Vec<graphene_std::uuid::NodeId>,
|
||||
},
|
||||
CloseActiveDocumentWithConfirmation,
|
||||
CloseAllDocuments,
|
||||
CloseAllDocumentsWithConfirmation,
|
||||
|
||||
@@ -283,6 +283,9 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
}
|
||||
responses.add(PersistentStateMessage::WriteState);
|
||||
}
|
||||
PortfolioMessage::CancelNodeWork { node_path } => {
|
||||
self.executor.cancel_node_work(node_path);
|
||||
}
|
||||
PortfolioMessage::CloseActiveDocumentWithConfirmation => {
|
||||
if let Some(document_id) = self.active_document_id {
|
||||
responses.add(PortfolioMessage::CloseDocumentWithConfirmation { document_id });
|
||||
|
||||
@@ -41,12 +41,16 @@ pub struct ExecutionResponse {
|
||||
vector_modify: HashMap<NodeId, VectorGeometry>,
|
||||
/// The resulting value from the temporary inspected during execution
|
||||
inspect_result: Option<InspectResult>,
|
||||
/// The progress of each source with work in progress, by the path of the value node injecting the source.
|
||||
progress: Vec<(Vec<NodeId>, f64)>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ExecutionResult {
|
||||
Pending,
|
||||
Value(TaggedValue),
|
||||
/// A value computed from provisional data, which is evaluated again once that data is final.
|
||||
Partial(TaggedValue),
|
||||
Fallback(TaggedValue, EvaluationErrors),
|
||||
Error(EvaluationErrors),
|
||||
Panic(Box<dyn Any + Send>),
|
||||
@@ -99,6 +103,8 @@ pub struct NodeGraphExecutor {
|
||||
previous_node_to_inspect: Vec<NodeId>,
|
||||
/// The canvas images the frontend holds, so a render sends only those it lacks.
|
||||
canvas_images_sent: HashSet<u64>,
|
||||
/// The progress of the active document's nodes with work in progress, by their full path from the root network.
|
||||
node_progress: Vec<(Vec<NodeId>, f64)>,
|
||||
/// Evaluation errors of the last evaluation, used in tests
|
||||
#[cfg(test)]
|
||||
evaluation_errors: Option<EvaluationErrors>,
|
||||
@@ -152,6 +158,7 @@ impl NodeGraphExecutor {
|
||||
node_graph_document: None,
|
||||
previous_node_to_inspect: Vec::new(),
|
||||
canvas_images_sent: HashSet::new(),
|
||||
node_progress: Vec::new(),
|
||||
#[cfg(test)]
|
||||
evaluation_errors: None,
|
||||
gradient_migration: None,
|
||||
@@ -187,6 +194,16 @@ impl NodeGraphExecutor {
|
||||
execution_id
|
||||
}
|
||||
|
||||
/// The progress of the work of the node at this full path from the root network, if it has work in progress.
|
||||
pub fn node_progress(&self, node_path: &[NodeId]) -> Option<f64> {
|
||||
self.node_progress.iter().find(|(path, _)| path == node_path).map(|(_, progress)| *progress)
|
||||
}
|
||||
|
||||
/// Cancels the work in progress of the node at this full path from the root network.
|
||||
pub fn cancel_node_work(&self, node_path: Vec<NodeId>) {
|
||||
self.sender.send(GraphRuntimeRequest::Cancel(node_path)).expect("Failed to send the cancellation");
|
||||
}
|
||||
|
||||
pub fn submit_inspect_context_overrides(&self, overrides: graphene_std::ContextOverrides) {
|
||||
self.sender.send(GraphRuntimeRequest::InspectContextOverrides(overrides)).expect("Failed to send the context overrides");
|
||||
}
|
||||
@@ -458,6 +475,7 @@ impl NodeGraphExecutor {
|
||||
dropped_thumbnails,
|
||||
vector_modify,
|
||||
inspect_result,
|
||||
progress,
|
||||
} = *execution_response;
|
||||
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
|
||||
|
||||
@@ -501,14 +519,33 @@ impl NodeGraphExecutor {
|
||||
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
// The deepest document node containing each source shows its progress
|
||||
if execution_context.document_id == document_id {
|
||||
let node_progress: Vec<_> = progress
|
||||
.into_iter()
|
||||
.filter_map(|(path, progress)| {
|
||||
let node_path = (1..=path.len()).rev().map(|length| &path[..length]).find(|path| is_document_node(document, path))?;
|
||||
Some((node_path.to_vec(), progress))
|
||||
})
|
||||
.collect();
|
||||
|
||||
if self.node_progress != node_progress {
|
||||
responses.add(NodeGraphMessage::UpdateNodeProgress { progress: node_progress.clone() });
|
||||
|
||||
// The document as a whole shows the mean progress of its nodes with work in progress
|
||||
let document_progress = (!node_progress.is_empty()).then(|| node_progress.iter().map(|(_, progress)| progress).sum::<f64>() / node_progress.len() as f64);
|
||||
responses.add(FrontendMessage::UpdateDocumentProgress { progress: document_progress });
|
||||
|
||||
self.node_progress = node_progress;
|
||||
responses.add(InspectorMessage::Refresh);
|
||||
}
|
||||
}
|
||||
|
||||
// A pending graph keeps the last frame, and the errors shown with it
|
||||
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) {
|
||||
let errors = match &result {
|
||||
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
|
||||
let in_document = |path: &&[NodeId]| {
|
||||
path.split_last()
|
||||
.is_some_and(|(node, network)| document.network_interface.view(network).and_then(|view| view.node(node)).is_ok())
|
||||
};
|
||||
let in_document = |path: &&[NodeId]| is_document_node(document, path);
|
||||
errors
|
||||
.iter()
|
||||
.flat_map(|(error, trace)| {
|
||||
@@ -525,7 +562,7 @@ impl NodeGraphExecutor {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
ExecutionResult::Pending | ExecutionResult::Value(_) | ExecutionResult::Panic(_) => Vec::new(),
|
||||
ExecutionResult::Pending | ExecutionResult::Value(_) | ExecutionResult::Partial(_) | ExecutionResult::Panic(_) => Vec::new(),
|
||||
};
|
||||
responses.add(NodeGraphMessage::UpdateEvaluationErrors { errors });
|
||||
}
|
||||
@@ -534,9 +571,14 @@ impl NodeGraphExecutor {
|
||||
{
|
||||
self.evaluation_errors = None;
|
||||
}
|
||||
let render_status = match result {
|
||||
ExecutionResult::Partial(_) => RenderStatus::Partial,
|
||||
ExecutionResult::Fallback(..) => RenderStatus::Fallback,
|
||||
ExecutionResult::Pending | ExecutionResult::Value(_) | ExecutionResult::Error(_) | ExecutionResult::Panic(_) => RenderStatus::Rendering,
|
||||
};
|
||||
let node_graph_output = match result {
|
||||
ExecutionResult::Pending => Ok(None),
|
||||
ExecutionResult::Value(value) => Ok(Some(value)),
|
||||
ExecutionResult::Value(value) | ExecutionResult::Partial(value) => Ok(Some(value)),
|
||||
ExecutionResult::Fallback(value, _errors) => {
|
||||
#[cfg(test)]
|
||||
{
|
||||
@@ -586,7 +628,7 @@ impl NodeGraphExecutor {
|
||||
|
||||
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, responses),
|
||||
(Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses),
|
||||
(None, _) => {}
|
||||
}
|
||||
responses.add(DeferMessage::TriggerGraphRun {
|
||||
@@ -899,7 +941,7 @@ impl NodeGraphExecutor {
|
||||
self.node_graph_hash = 0;
|
||||
}
|
||||
|
||||
fn process_node_graph_output(&mut self, node_graph_output: TaggedValue, document_to_viewport: DAffine2, responses: &mut VecDeque<Message>) {
|
||||
fn process_node_graph_output(&mut self, node_graph_output: TaggedValue, document_to_viewport: DAffine2, render_status: RenderStatus, responses: &mut VecDeque<Message>) {
|
||||
let TaggedValue::RenderOutput(render_output) = node_graph_output else {
|
||||
log::error!("Invalid node graph output type: {node_graph_output:#?}");
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||
@@ -979,7 +1021,7 @@ impl NodeGraphExecutor {
|
||||
responses.add(DocumentMessage::RenderRulers);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Rendering });
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: render_status });
|
||||
}
|
||||
|
||||
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
@@ -1041,6 +1083,12 @@ impl NodeGraphExecutor {
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Whether the fill node's `_has_transform` is still `false`, meaning its gradient placement has not yet been baked
|
||||
/// (or set by the user), so a measured bake may safely be written.
|
||||
/// Whether the node at this full path from the root network exists in the document.
|
||||
fn is_document_node(document: &DocumentMessageHandler, path: &[NodeId]) -> bool {
|
||||
path.split_last()
|
||||
.is_some_and(|(node, network)| document.network_interface.view(network).and_then(|view| view.node(node)).is_ok())
|
||||
}
|
||||
|
||||
fn fill_transform_unbaked(document: &DocumentMessageHandler, network_path: &[NodeId], fill_node_id: NodeId) -> bool {
|
||||
let Some(network) = document.network_interface.document_network().nested_network(network_path) else {
|
||||
return false;
|
||||
|
||||
@@ -10,6 +10,7 @@ use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler};
|
||||
use graph_craft::proto::GraphErrors;
|
||||
use graphene_hash::CacheHash;
|
||||
use graphene_std::SourceId;
|
||||
use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture};
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::memo::IORecord;
|
||||
@@ -55,6 +56,8 @@ pub struct NodeRuntime {
|
||||
node_graph_errors: GraphErrors,
|
||||
node_graph_warnings: GraphErrors,
|
||||
monitor_nodes: Vec<(Vec<NodeId>, NodeId)>,
|
||||
/// Each source of the compiled network, with the path of the value node injecting it.
|
||||
source_paths: Vec<(SourceId, Vec<NodeId>)>,
|
||||
thumbnails: Thumbnails,
|
||||
|
||||
/// The node the Data panel inspects.
|
||||
@@ -85,6 +88,8 @@ pub enum GraphRuntimeRequest {
|
||||
/// The full path from the root network to the node the Data panel inspects, or empty for none.
|
||||
Inspect(Vec<NodeId>),
|
||||
InspectContextOverrides(ContextOverrides),
|
||||
/// Cancels the work in progress of the sources within the node at this full path from the root network.
|
||||
Cancel(Vec<NodeId>),
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -147,6 +152,7 @@ impl NodeRuntime {
|
||||
node_graph_errors: Vec::new(),
|
||||
node_graph_warnings: Vec::new(),
|
||||
monitor_nodes: Vec::new(),
|
||||
source_paths: Vec::new(),
|
||||
thumbnails: Thumbnails::new(),
|
||||
|
||||
preprocessor: preprocessor::Preprocessor::new(),
|
||||
@@ -195,6 +201,15 @@ impl NodeRuntime {
|
||||
inspect_state.overrides_changed = true;
|
||||
}
|
||||
}
|
||||
GraphRuntimeRequest::Cancel(node_path) => {
|
||||
let mut canceled = false;
|
||||
for (source, _) in self.source_paths.iter().filter(|(_, path)| path.starts_with(&node_path)) {
|
||||
canceled |= self.async_runtime().cancel(*source);
|
||||
}
|
||||
if canceled {
|
||||
self.dirty.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -359,7 +374,8 @@ impl NodeRuntime {
|
||||
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.executor.output(), &context))) {
|
||||
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Final(value) | Poll::Partial(value))) => ExecutionResult::Value(value),
|
||||
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
|
||||
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
|
||||
Ok(Ok(Poll::Fallback(boxed))) => {
|
||||
let (value, error) = *boxed;
|
||||
ExecutionResult::Fallback(value, self.resolve_errors(&error))
|
||||
@@ -374,6 +390,7 @@ impl NodeRuntime {
|
||||
dropped_thumbnails: Vec::new(),
|
||||
vector_modify: HashMap::new(),
|
||||
inspect_result: None,
|
||||
progress: Vec::new(),
|
||||
};
|
||||
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
||||
return None;
|
||||
@@ -387,6 +404,16 @@ impl NodeRuntime {
|
||||
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 progress = self
|
||||
.async_runtime()
|
||||
.progress()
|
||||
.into_iter()
|
||||
.filter_map(|(source, progress)| {
|
||||
let (_, path) = self.source_paths.iter().find(|(candidate, _)| *candidate == source)?;
|
||||
Some((path.clone(), progress))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let response = ExecutionResponse {
|
||||
execution_id,
|
||||
result,
|
||||
@@ -394,6 +421,7 @@ impl NodeRuntime {
|
||||
dropped_thumbnails,
|
||||
vector_modify: self.vector_modify.clone(),
|
||||
inspect_result,
|
||||
progress,
|
||||
};
|
||||
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
||||
}
|
||||
@@ -431,6 +459,7 @@ impl NodeRuntime {
|
||||
.filter(|(_, node)| node.identifier == graphene_std::memo::monitor::IDENTIFIER)
|
||||
.map(|(id, node)| (node.original_location.path.clone().unwrap_or_default(), *id))
|
||||
.collect();
|
||||
self.source_paths = proto_network.source_paths().map(|(source, path)| (*source, path.to_vec())).collect();
|
||||
|
||||
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
|
||||
let result = self.executor.update(proto_network).map_err(|(types, e)| {
|
||||
@@ -504,7 +533,9 @@ impl NodeRuntime {
|
||||
|
||||
impl ExecutionResult {
|
||||
fn render_output(&mut self) -> Option<&mut RenderOutputType> {
|
||||
let (Self::Value(value) | Self::Fallback(value, _)) = self else { return None };
|
||||
let (Self::Value(value) | Self::Partial(value) | Self::Fallback(value, _)) = self else {
|
||||
return None;
|
||||
};
|
||||
let TaggedValue::RenderOutput(RenderOutput { data, .. }) = value else { return None };
|
||||
Some(data)
|
||||
}
|
||||
@@ -698,6 +729,7 @@ impl InspectState {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::messages::frontend::utility_types::RenderStatus;
|
||||
use crate::test_utils::EditorTestUtils;
|
||||
use graph_craft::document::DocumentNode;
|
||||
use graphene_std::SourceId;
|
||||
@@ -717,12 +749,17 @@ mod tests {
|
||||
|
||||
/// Sends a network update and a request to evaluate it, as the editor does for a change to the graph.
|
||||
fn send_update(editor: &mut EditorTestUtils) {
|
||||
send_update_at(editor, UVec2::ONE);
|
||||
}
|
||||
|
||||
/// Sends a network update and a request to evaluate it at a viewport of `resolution` pixels.
|
||||
fn send_update_at(editor: &mut EditorTestUtils, resolution: UVec2) {
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||
let document = documents.get_mut(&document_id).unwrap();
|
||||
executor
|
||||
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), Vec::new(), true, DVec2::ZERO)
|
||||
.submit_node_graph_evaluation(document, document_id, resolution, 1., Default::default(), Vec::new(), true, DVec2::ZERO)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
@@ -752,8 +789,8 @@ mod tests {
|
||||
editor.dispatch(Message::Wake).iter().any(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }))
|
||||
}
|
||||
|
||||
/// Fills the document's layer with a trace of noise, which an export has to wait on over several evaluations.
|
||||
fn vectorize_layer(editor: &mut EditorTestUtils) {
|
||||
/// Fills the document's layer with a trace of noise, which an export has to wait on over several evaluations. Returns the Vectorize node.
|
||||
fn vectorize_layer(editor: &mut EditorTestUtils) -> NodeId {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
|
||||
@@ -778,6 +815,7 @@ mod tests {
|
||||
output_connector: OutputConnector::primary_output(vectorize),
|
||||
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
|
||||
});
|
||||
vectorize
|
||||
}
|
||||
|
||||
/// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one.
|
||||
@@ -888,6 +926,39 @@ mod tests {
|
||||
assert!(!evaluated(&mut editor), "the requests of the older network updates evaluated again");
|
||||
}
|
||||
|
||||
/// A trace renders partial frames and shows its progress on its node until it is canceled, which keeps the shapes traced so far.
|
||||
#[tokio::test]
|
||||
async fn a_trace_shows_its_progress_until_it_is_canceled() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
|
||||
editor.draw_rect(0., 0., 512., 512.).await;
|
||||
let vectorize = vectorize_layer(&mut editor);
|
||||
|
||||
send_update_at(&mut editor, UVec2::splat(512));
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
let messages = editor.dispatch(Message::Wake);
|
||||
assert!(
|
||||
messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Partial }),
|
||||
"the trace's frame isn't partial"
|
||||
);
|
||||
assert!(editor.portfolio_message_handler_mut().executor.node_progress(&[vectorize]).is_some(), "the trace shows no progress");
|
||||
|
||||
editor.dispatch(PortfolioMessage::CancelNodeWork { node_path: vec![vectorize] });
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
let messages = editor.dispatch(Message::Wake);
|
||||
assert!(
|
||||
messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Fallback }),
|
||||
"the canceled trace's frame isn't a fallback"
|
||||
);
|
||||
assert!(
|
||||
editor.portfolio_message_handler_mut().executor.node_progress(&[vectorize]).is_none(),
|
||||
"the canceled trace still shows progress"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_preview_replaces_the_export_of_the_graph_being_compiled() {
|
||||
let previewed_node = NodeId(1);
|
||||
|
||||
@@ -739,9 +739,12 @@
|
||||
>
|
||||
</canvas>
|
||||
{/if}
|
||||
{#if isWeb && $document.renderStatus === "Rendering"}
|
||||
{#if isWeb && !["Error", "Panic"].includes($document.renderStatus)}
|
||||
<TextLabel class="shader-compiling-overlay" italic={true} classes={{ show: !firstArtworkReceived }}>Initializing Renderer…</TextLabel>
|
||||
{/if}
|
||||
{#if typeof $document.progress === "number"}
|
||||
<div class="render-progress" style:width={`${Math.min(Math.max($document.progress, 0), 1) * 100}%`}></div>
|
||||
{/if}
|
||||
{#if $document.renderStatus === "Error"}
|
||||
<LayoutCol class="render-status-overlay">
|
||||
<TextLabel>
|
||||
@@ -1005,6 +1008,18 @@
|
||||
}
|
||||
}
|
||||
|
||||
.render-progress {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
// Above the error overlays
|
||||
z-index: 1;
|
||||
height: 2px;
|
||||
background: var(--color-warning-yellow);
|
||||
pointer-events: none;
|
||||
transition: width 0.1s linear;
|
||||
}
|
||||
|
||||
.render-status-overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
|
||||
@@ -965,10 +965,12 @@
|
||||
{@const clipPathId = String(Math.random()).substring(2)}
|
||||
{@const description = node.reference ? $nodeGraph.nodeDescriptions.get(node.reference) : undefined}
|
||||
{@const icon = (node.reference && $nodeGraph.nodeIcons.get(node.reference)) || "NodeCustomNode"}
|
||||
{@const progress = $nodeGraph.progress.get(node.id)}
|
||||
<div
|
||||
class="node"
|
||||
class:selected={$nodeGraph.selected.includes(node.id)}
|
||||
class:previewed={node.previewed}
|
||||
class:in-progress={progress !== undefined}
|
||||
class:disabled={!node.visible}
|
||||
style:--offset-left={(node.position?.[0] || 0) + glideCells($nodeGlideOffsets.nodes.get(node.id), 0)}
|
||||
style:--offset-top={(node.position?.[1] || 0) + glideCells($nodeGlideOffsets.nodes.get(node.id), 1)}
|
||||
@@ -984,6 +986,9 @@
|
||||
<IconLabel {icon} />
|
||||
<!-- TODO: Allow the user to edit the name, just like in the Layers panel -->
|
||||
<TextLabel>{node.displayName}</TextLabel>
|
||||
{#if progress !== undefined}
|
||||
<div class="progress" style:width={`${Math.min(Math.max(progress, 0), 1) * 100}%`}></div>
|
||||
{/if}
|
||||
</div>
|
||||
<!-- Secondary rows -->
|
||||
{#if exposedInputsOutputs.length > 0}
|
||||
@@ -1492,6 +1497,10 @@
|
||||
border: 1px dashed var(--color-e-nearwhite);
|
||||
}
|
||||
|
||||
&.in-progress::after {
|
||||
border-color: var(--color-warning-yellow);
|
||||
}
|
||||
|
||||
.connectors {
|
||||
position: absolute;
|
||||
// Keeps the connectors above the wires
|
||||
@@ -1877,6 +1886,15 @@
|
||||
margin-left: 0;
|
||||
margin-right: 4px;
|
||||
}
|
||||
|
||||
.progress {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
height: 3px;
|
||||
background: var(--color-e-nearwhite);
|
||||
transition: width 0.1s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.secondary {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
|
||||
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
|
||||
import ProgressBar from "/src/components/widgets/labels/ProgressBar.svelte";
|
||||
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
|
||||
import NodeSection from "/src/components/widgets/NodeSection.svelte";
|
||||
import WidgetSpan from "/src/components/widgets/WidgetSpan.svelte";
|
||||
@@ -93,6 +94,18 @@
|
||||
<div class="expand-arrow"></div>
|
||||
</div>
|
||||
<TextLabel tooltipLabel={widgetData.name} tooltipDescription={widgetData.description}>{widgetData.name}</TextLabel>
|
||||
{#if typeof widgetData.progress === "number"}
|
||||
<ProgressBar fraction={widgetData.progress} label={`${Math.floor(Math.min(Math.max(widgetData.progress, 0), 1) * 100)}%`} />
|
||||
<IconButton
|
||||
icon="CloseX"
|
||||
tooltipDescription="Stop the work in progress, keeping its result so far."
|
||||
size={24}
|
||||
action={(e) => {
|
||||
editor.cancelNodeWork(widgetData.id);
|
||||
e?.stopPropagation();
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
<IconButton
|
||||
icon={widgetData.visible ? "EyeVisible" : "EyeHidden"}
|
||||
hoverIcon={widgetData.visible ? "EyeHide" : "EyeShow"}
|
||||
@@ -461,6 +474,12 @@
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
margin-left: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
// Hovering the chain sections within doesn't count
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<script lang="ts">
|
||||
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
let className = "";
|
||||
export { className as class };
|
||||
export let classes: Record<string, boolean> = {};
|
||||
|
||||
// Content
|
||||
export let fraction: number;
|
||||
export let label = "";
|
||||
// Tooltips
|
||||
export let tooltipLabel: string | undefined = undefined;
|
||||
export let tooltipDescription: string | undefined = undefined;
|
||||
export let tooltipShortcut: ActionShortcut | undefined = undefined;
|
||||
|
||||
$: extraClasses = Object.entries(classes)
|
||||
.flatMap(([className, stateName]) => (stateName ? [className] : []))
|
||||
.join(" ");
|
||||
$: percent = `${Math.min(Math.max(fraction, 0), 1) * 100}%`;
|
||||
</script>
|
||||
|
||||
<div
|
||||
class={`progress-bar ${className} ${extraClasses}`.trim()}
|
||||
role="progressbar"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={1}
|
||||
aria-valuenow={fraction}
|
||||
data-tooltip-label={tooltipLabel}
|
||||
data-tooltip-description={tooltipDescription}
|
||||
data-tooltip-shortcut={tooltipShortcut?.shortcut ? JSON.stringify(tooltipShortcut.shortcut) : undefined}
|
||||
>
|
||||
<div class="track">
|
||||
<div class="fill" style:width={percent}></div>
|
||||
</div>
|
||||
{#if label}
|
||||
<span class="label">{label}</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style lang="scss">
|
||||
.progress-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex: 1 1 100%;
|
||||
height: 24px;
|
||||
|
||||
.track {
|
||||
position: relative;
|
||||
flex: 1 1 100%;
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
overflow: hidden;
|
||||
background: var(--color-1-nearblack);
|
||||
}
|
||||
|
||||
.fill {
|
||||
position: absolute;
|
||||
inset: 0 auto 0 0;
|
||||
background: var(--color-e-nearwhite);
|
||||
transition: width 0.1s linear;
|
||||
}
|
||||
|
||||
.label {
|
||||
flex: 0 0 auto;
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
color: var(--color-a-softgray);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -16,6 +16,8 @@ type DocumentStoreState = {
|
||||
graphViewOverlayOpen: boolean;
|
||||
fadeArtwork: number;
|
||||
renderStatus: RenderStatus;
|
||||
// How far the work in progress of the document has come from 0 to 1, if it has any
|
||||
progress: number | undefined;
|
||||
};
|
||||
const initialState: DocumentStoreState = {
|
||||
toolOptionsLayout: createLayout(),
|
||||
@@ -26,6 +28,7 @@ const initialState: DocumentStoreState = {
|
||||
graphViewOverlayOpen: false,
|
||||
fadeArtwork: 100,
|
||||
renderStatus: "Rendering",
|
||||
progress: undefined,
|
||||
};
|
||||
|
||||
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
|
||||
@@ -92,6 +95,13 @@ export function createDocumentStore(subscriptions: SubscriptionsRouter) {
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateDocumentProgress", (data) => {
|
||||
update((state) => {
|
||||
state.progress = data.progress;
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
return { subscribe, remoteCursorsStore };
|
||||
}
|
||||
|
||||
@@ -102,6 +112,7 @@ export function destroyDocumentStore() {
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateGraphFadeArtwork");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateGraphViewOverlay");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateRenderStatus");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateDocumentProgress");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateDocumentCursors");
|
||||
subscriptions.unsubscribeLayoutUpdate("ToolOptions");
|
||||
subscriptions.unsubscribeLayoutUpdate("DocumentBar");
|
||||
|
||||
@@ -25,6 +25,7 @@ type NodeGraphStoreState = {
|
||||
clickTargets: FrontendClickTargets | undefined;
|
||||
contextMenuInformation: ContextMenuInformation | undefined;
|
||||
errors: NodeGraphErrorDiagnostic[];
|
||||
progress: Map<bigint, number>;
|
||||
layerWidths: Map<bigint, number>;
|
||||
chainWidths: Map<bigint, number>;
|
||||
hasLeftInputWire: Map<bigint, boolean>;
|
||||
@@ -47,6 +48,7 @@ const initialState: NodeGraphStoreState = {
|
||||
clickTargets: undefined,
|
||||
contextMenuInformation: undefined,
|
||||
errors: [],
|
||||
progress: new Map(),
|
||||
layerWidths: new Map(),
|
||||
chainWidths: new Map(),
|
||||
hasLeftInputWire: new Map(),
|
||||
@@ -227,6 +229,13 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateNodeGraphProgress", (data) => {
|
||||
update((state) => {
|
||||
state.progress = new Map(data.progress.map(({ nodeId, progress }) => [nodeId, progress]));
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateVisibleNodes", (data) => {
|
||||
const newNodes = new Set<bigint>(data.nodes);
|
||||
|
||||
@@ -350,6 +359,7 @@ export function destroyNodeGraphStore() {
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateLayerWidths");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphNodes");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphErrorDiagnostics");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphProgress");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateVisibleNodes");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateGlideOffsets");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphWires");
|
||||
|
||||
@@ -761,6 +761,11 @@ mod editor_commands {
|
||||
DocumentMessage::ToggleNodeVisibility { node_id: NodeId(id) }.into()
|
||||
}
|
||||
|
||||
/// Stop the work in progress of a node shown in the Inspector, which may be in a subgraph
|
||||
fn cancel_node_work(id: u64) -> Message {
|
||||
DocumentMessage::CancelNodeWork { node_id: NodeId(id) }.into()
|
||||
}
|
||||
|
||||
/// Pin or unpin a node given its node ID
|
||||
fn set_node_pinned(id: u64, pinned: bool) -> Message {
|
||||
DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned }.into()
|
||||
|
||||
@@ -394,9 +394,14 @@ impl ProtoNetwork {
|
||||
}
|
||||
|
||||
pub fn source_ids(&self) -> impl Iterator<Item = &SourceId> {
|
||||
self.source_paths().map(|(source, _)| source)
|
||||
}
|
||||
|
||||
/// Each source with the path of the value node that injects it, which lies within the node that owns the source.
|
||||
pub fn source_paths(&self) -> impl Iterator<Item = (&SourceId, &[NodeId])> {
|
||||
self.nodes.iter().filter_map(|(_, node)| match &node.construction_args {
|
||||
ConstructionArgs::Value(value) => match &**value {
|
||||
TaggedValue::SourceId(source) => Some(source),
|
||||
TaggedValue::SourceId(source) => Some((source, node.original_location.path.as_deref().unwrap_or_default())),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
|
||||
@@ -2,11 +2,11 @@ use crate::poll::Poll;
|
||||
use crate::uuid::NodeId;
|
||||
use dyn_any::WasmNotSend;
|
||||
use futures::future::{AbortHandle, Abortable};
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::future::Future;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::task::{Context, Waker};
|
||||
pub use web_time::Instant;
|
||||
|
||||
@@ -34,7 +34,12 @@ impl SourceId {
|
||||
pub type Generations = Arc<[(SourceId, u64)]>;
|
||||
|
||||
pub trait Runtime {
|
||||
/// Runs `task` outside of the graph, bumping the generation of `source` once it finishes.
|
||||
fn spawn(&self, source: SourceId, task: Task);
|
||||
/// Sets how far the work of `source` has come from 0 to 1, or with `None` clears it along with any cancellation request.
|
||||
fn report_progress(&self, source: SourceId, progress: Option<f64>);
|
||||
/// Whether cancellation of the work of `source` was requested since this was last called.
|
||||
fn take_cancellation(&self, source: SourceId) -> bool;
|
||||
}
|
||||
|
||||
#[derive(Clone, dyn_any::DynAny)]
|
||||
@@ -44,6 +49,14 @@ impl Runtime for RuntimeHandle {
|
||||
fn spawn(&self, source: SourceId, task: Task) {
|
||||
self.0.spawn(source, task);
|
||||
}
|
||||
|
||||
fn report_progress(&self, source: SourceId, progress: Option<f64>) {
|
||||
self.0.report_progress(source, progress);
|
||||
}
|
||||
|
||||
fn take_cancellation(&self, source: SourceId) -> bool {
|
||||
self.0.take_cancellation(source)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RuntimeHandle {
|
||||
@@ -68,16 +81,42 @@ impl AsyncRuntime {
|
||||
pub fn new(spawner: Arc<dyn Spawn + Send + Sync>) -> Self {
|
||||
Self(Arc::new(RuntimeInner {
|
||||
generations: Mutex::default(),
|
||||
progress: Mutex::default(),
|
||||
cancellations: Mutex::default(),
|
||||
spawner,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn update_sources(&self, live: &[SourceId]) {
|
||||
let mut generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut generations = lock(&self.0.generations);
|
||||
generations.retain(|source, _| live.contains(source));
|
||||
for source in live {
|
||||
generations.entry(*source).or_insert(0);
|
||||
}
|
||||
|
||||
lock(&self.0.progress).retain(|source, _| live.contains(source));
|
||||
lock(&self.0.cancellations).retain(|source| live.contains(source));
|
||||
}
|
||||
|
||||
/// The progress of every source that reported some and has not cleared it, sorted by source.
|
||||
pub fn progress(&self) -> Vec<(SourceId, f64)> {
|
||||
let mut progress: Vec<_> = lock(&self.0.progress).iter().map(|(source, progress)| (*source, *progress)).collect();
|
||||
progress.sort_unstable_by_key(|(source, _)| *source);
|
||||
progress
|
||||
}
|
||||
|
||||
/// Requests cancellation of the work of `source` and bumps its generation, so the node is evaluated again to see the request.
|
||||
/// Only work that reports progress can be canceled, so a request can't outlive the work it was meant for. Returns whether there was any.
|
||||
pub fn cancel(&self, source: SourceId) -> bool {
|
||||
if !lock(&self.0.progress).contains_key(&source) {
|
||||
return false;
|
||||
}
|
||||
lock(&self.0.cancellations).insert(source);
|
||||
|
||||
if let Some(generation) = lock(&self.0.generations).get_mut(&source) {
|
||||
*generation += 1;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Generations {
|
||||
@@ -97,10 +136,20 @@ impl Runtime for AsyncRuntime {
|
||||
fn spawn(&self, source: SourceId, task: Task) {
|
||||
self.0.spawn(source, task);
|
||||
}
|
||||
|
||||
fn report_progress(&self, source: SourceId, progress: Option<f64>) {
|
||||
self.0.report_progress(source, progress);
|
||||
}
|
||||
|
||||
fn take_cancellation(&self, source: SourceId) -> bool {
|
||||
self.0.take_cancellation(source)
|
||||
}
|
||||
}
|
||||
|
||||
struct RuntimeInner {
|
||||
generations: Mutex<HashMap<SourceId, u64>>,
|
||||
progress: Mutex<HashMap<SourceId, f64>>,
|
||||
cancellations: Mutex<HashSet<SourceId>>,
|
||||
spawner: Arc<dyn Spawn + Send + Sync>,
|
||||
}
|
||||
|
||||
@@ -109,11 +158,31 @@ impl RuntimeInner {
|
||||
let inner = Arc::clone(self);
|
||||
self.spawner.spawn(Box::pin(async move {
|
||||
task.await;
|
||||
if let Some(generation) = inner.generations.lock().unwrap_or_else(PoisonError::into_inner).get_mut(&source) {
|
||||
if let Some(generation) = lock(&inner.generations).get_mut(&source) {
|
||||
*generation += 1;
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
fn report_progress(&self, source: SourceId, progress: Option<f64>) {
|
||||
match progress {
|
||||
Some(progress) => {
|
||||
lock(&self.progress).insert(source, progress);
|
||||
}
|
||||
None => {
|
||||
lock(&self.progress).remove(&source);
|
||||
lock(&self.cancellations).remove(&source);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn take_cancellation(&self, source: SourceId) -> bool {
|
||||
lock(&self.cancellations).remove(&source)
|
||||
}
|
||||
}
|
||||
|
||||
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
mutex.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
pub struct Slots<T>(Arc<Mutex<HashMap<u64, Slot<T>>>>);
|
||||
@@ -289,6 +358,24 @@ mod tests {
|
||||
assert!(runtime.snapshot().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_work_in_progress_can_be_canceled() {
|
||||
let runtime = AsyncRuntime::new(Arc::new(CollectSpawner::default()));
|
||||
runtime.update_sources(&[SOURCE]);
|
||||
assert!(!runtime.cancel(SOURCE));
|
||||
|
||||
runtime.report_progress(SOURCE, Some(0.5));
|
||||
assert!(runtime.cancel(SOURCE));
|
||||
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1)], "a cancellation bumps the generation");
|
||||
assert!(runtime.take_cancellation(SOURCE));
|
||||
assert!(!runtime.take_cancellation(SOURCE));
|
||||
|
||||
runtime.cancel(SOURCE);
|
||||
runtime.report_progress(SOURCE, None);
|
||||
assert!(!runtime.take_cancellation(SOURCE), "clearing the progress drops the request");
|
||||
assert!(runtime.progress().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slot_serves_the_placeholder_until_the_response_lands() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
|
||||
@@ -88,19 +88,32 @@ fn vectorize(
|
||||
instancing: *instancing.element(),
|
||||
path_gradients: *path_gradients.element(),
|
||||
};
|
||||
let runtime = runtime.element();
|
||||
let source = *source.element();
|
||||
|
||||
let max_megabytes = Some(*max_memory.element()).filter(|&megabytes| megabytes > 0.);
|
||||
if cfg!(target_family = "wasm") && !*exceed_browser_limit.element() && max_megabytes.is_none_or(|megabytes| megabytes > BROWSER_MAX_MEGABYTES) {
|
||||
trace.clear();
|
||||
runtime.report_progress(source, None);
|
||||
return Poll::error(format!(
|
||||
"A memory limit above {BROWSER_MAX_MEGABYTES} MB, or none, can crash the editor in the browser. Lower the limit or turn on \"Exceed Browser Limit\"."
|
||||
));
|
||||
}
|
||||
let max_pixels = max_megabytes.map(|megabytes| (megabytes * 1e6 / BYTES_PER_PIXEL) as usize);
|
||||
let runtime = runtime.element();
|
||||
|
||||
if runtime.take_cancellation(source) {
|
||||
trace.cancel();
|
||||
}
|
||||
|
||||
let state = trace_slice(&image, *detail.element(), *tolerance.element(), stages, max_pixels, trace, SLICE);
|
||||
if let Poll::Partial(_) = state {
|
||||
// Finishing an empty task bumps the node's generation, which re-evaluates it for the next slice
|
||||
runtime.spawn(*source.element(), Box::pin(async {}));
|
||||
match state {
|
||||
Poll::Partial(_) => {
|
||||
runtime.report_progress(source, trace.progress());
|
||||
|
||||
// Finishing an empty task bumps the node's generation, which re-evaluates it for the next slice
|
||||
runtime.spawn(source, Box::pin(async {}));
|
||||
}
|
||||
_ => runtime.report_progress(source, None),
|
||||
}
|
||||
state
|
||||
}
|
||||
@@ -130,14 +143,13 @@ fn trace_slice(image: &Item<Raster<CPU>>, detail: f64, tolerance: f64, stages: o
|
||||
width,
|
||||
height,
|
||||
};
|
||||
let options = ollev::TraceOptions {
|
||||
tolerance,
|
||||
detail: ollev::Detail::Scaled(detail),
|
||||
max_pixels,
|
||||
host: CAPABILITIES,
|
||||
stages,
|
||||
..Default::default()
|
||||
};
|
||||
let mut options = ollev::TraceOptions::default();
|
||||
options.tolerance = tolerance;
|
||||
options.detail = ollev::Detail::Scaled(detail);
|
||||
options.max_pixels = max_pixels;
|
||||
options.host = CAPABILITIES;
|
||||
options.stages = stages;
|
||||
|
||||
ollev::Tracing::new(&source, &options)
|
||||
};
|
||||
|
||||
@@ -400,4 +412,50 @@ mod test {
|
||||
assert_eq!(spawner.drain(), 2);
|
||||
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 2)]);
|
||||
}
|
||||
|
||||
/// A running trace reports progress that never goes down until it is done.
|
||||
#[test]
|
||||
fn a_trace_reports_progress_until_it_is_done() {
|
||||
let (spawner, runtime) = collecting_runtime();
|
||||
let (image, slot) = (busy(96), TraceSlot::default());
|
||||
|
||||
let mut previous = 0.;
|
||||
while matches!(evaluate(&slot, &image, &runtime), Poll::Partial(_)) {
|
||||
let progress = runtime.progress();
|
||||
let [(source, fraction)] = progress.as_slice() else { panic!("the trace reported {progress:?}") };
|
||||
assert_eq!(*source, SOURCE);
|
||||
assert!((previous..=1.).contains(fraction), "progress went from {previous} to {fraction}");
|
||||
|
||||
previous = *fraction;
|
||||
spawner.drain();
|
||||
}
|
||||
assert!(previous > 0., "the trace never reported any progress");
|
||||
assert!(runtime.progress().is_empty(), "a finished trace still reports progress");
|
||||
}
|
||||
|
||||
/// A canceled trace keeps its shapes so far, with an error, until its inputs change.
|
||||
#[test]
|
||||
fn a_canceled_trace_keeps_its_shapes_until_the_inputs_change() {
|
||||
let (_spawner, runtime) = collecting_runtime();
|
||||
let slot = TraceSlot::default();
|
||||
let image = busy(96);
|
||||
let shown = loop {
|
||||
match evaluate(&slot, &image, &runtime) {
|
||||
Poll::Partial(shown) if !shown.is_empty() => break shown,
|
||||
Poll::Partial(_) => {}
|
||||
state => panic!("the trace ended in {state:?} before showing shapes"),
|
||||
}
|
||||
};
|
||||
|
||||
assert!(runtime.cancel(SOURCE));
|
||||
let Poll::Fallback(boxed) = evaluate(&slot, &image, &runtime) else {
|
||||
panic!("the canceled trace went on")
|
||||
};
|
||||
assert!(boxed.0.len() >= shown.len(), "the canceled trace dropped its shapes");
|
||||
assert!(runtime.progress().is_empty());
|
||||
assert!(!runtime.cancel(SOURCE), "a canceled trace can be canceled again");
|
||||
|
||||
assert!(matches!(evaluate(&slot, &image, &runtime), Poll::Fallback(_)), "the canceled trace was started again");
|
||||
assert!(matches!(evaluate(&slot, &busy(128), &runtime), Poll::Partial(_)), "new inputs were not traced");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use core_types::Poll;
|
||||
use core_types::list::List;
|
||||
use core_types::runtime::Instant;
|
||||
use core_types::{NodeError, Poll};
|
||||
use graphic_types::Graphic;
|
||||
use ollev::model::Model;
|
||||
use std::ops::ControlFlow;
|
||||
@@ -22,11 +22,13 @@ struct Trace {
|
||||
inputs: u64,
|
||||
/// `None` once the trace is done and `shown` is its result, or once it failed.
|
||||
tracing: Option<ollev::Tracing>,
|
||||
/// Why the trace failed, kept so the same inputs are not traced again.
|
||||
failed: Option<ollev::TraceError>,
|
||||
/// Why the trace failed or was canceled, kept so the same inputs are not traced again.
|
||||
failed: Option<NodeError>,
|
||||
shown: List<Graphic>,
|
||||
/// The revision of the scene in `shown`.
|
||||
revision: Option<u64>,
|
||||
/// How much of the trace is done from 0 to 1, as ollev last reported it.
|
||||
progress: f64,
|
||||
}
|
||||
|
||||
impl TraceSlot {
|
||||
@@ -44,6 +46,7 @@ impl TraceSlot {
|
||||
failed: None,
|
||||
shown: List::new(),
|
||||
revision: None,
|
||||
progress: 0.,
|
||||
},
|
||||
Err(error) => return Poll::fallback(List::new(), error),
|
||||
},
|
||||
@@ -51,7 +54,11 @@ impl TraceSlot {
|
||||
|
||||
if let Some(tracing) = &mut trace.tracing {
|
||||
let deadline = Instant::now() + slice;
|
||||
let step = tracing.step(|_| if Instant::now() >= deadline { ControlFlow::Break(()) } else { ControlFlow::Continue(()) });
|
||||
let progress = &mut trace.progress;
|
||||
let step = tracing.step(|checkpoint| {
|
||||
*progress = checkpoint.overall;
|
||||
if Instant::now() >= deadline { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
|
||||
});
|
||||
match step {
|
||||
Ok(ollev::Step::Done(model)) => {
|
||||
trace.shown = convert(&model);
|
||||
@@ -59,7 +66,7 @@ impl TraceSlot {
|
||||
}
|
||||
Err(error) => {
|
||||
trace.tracing = None;
|
||||
trace.failed = Some(error);
|
||||
trace.failed = Some(error.into());
|
||||
}
|
||||
Ok(ollev::Step::Paused(progress)) => {
|
||||
if progress.showable()
|
||||
@@ -74,8 +81,8 @@ impl TraceSlot {
|
||||
}
|
||||
|
||||
let shown = trace.shown.clone();
|
||||
let state = match trace.failed {
|
||||
Some(error) => Poll::fallback(shown, error),
|
||||
let state = match &trace.failed {
|
||||
Some(error) => Poll::Fallback(Box::new((shown, error.clone()))),
|
||||
None if trace.tracing.is_some() => Poll::Partial(shown),
|
||||
None => Poll::Final(shown),
|
||||
};
|
||||
@@ -83,6 +90,21 @@ impl TraceSlot {
|
||||
state
|
||||
}
|
||||
|
||||
/// How much of the slot's trace is done from 0 to 1, while it is not yet done.
|
||||
pub fn progress(&self) -> Option<f64> {
|
||||
let held = self.lock();
|
||||
held.as_ref().filter(|trace| trace.tracing.is_some()).map(|trace| trace.progress)
|
||||
}
|
||||
|
||||
/// Stops the slot's trace, keeping the scene traced so far as the result for its inputs.
|
||||
pub fn cancel(&self) {
|
||||
let mut held = self.lock();
|
||||
let Some(trace) = held.as_mut().filter(|trace| trace.tracing.is_some()) else { return };
|
||||
|
||||
trace.tracing = None;
|
||||
trace.failed = Some(NodeError::new("The trace was canceled"));
|
||||
}
|
||||
|
||||
/// Drops the slot's trace.
|
||||
pub fn clear(&self) {
|
||||
self.lock().take();
|
||||
|
||||
Reference in new issue
Block a user