Compare commits

...
25 changed files with 553 additions and 44 deletions

No files matched your search

Generated
+2 -2
View File
@@ -4842,9 +4842,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
View File
@@ -271,7 +271,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};
@@ -326,6 +327,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,
}
@@ -461,6 +461,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.
@@ -533,6 +535,7 @@ impl LayoutGroup {
node_reference: false,
content_wire: None,
content_wire_continues: false,
progress: None,
expanded,
id,
layout,
@@ -647,6 +650,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,
@@ -663,6 +667,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,
@@ -682,6 +687,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
{
@@ -697,6 +703,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);
@@ -714,6 +721,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,
@@ -224,6 +224,9 @@ pub enum DocumentMessage {
layers: Vec<NodeId>,
layers_missing_details: Vec<NodeId>,
},
CancelNodeWork {
node_id: NodeId,
},
SetNodePinned {
node_id: NodeId,
pinned: bool,
@@ -1577,6 +1577,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,
@@ -457,6 +461,7 @@ impl NodeGraphMessage {
| Self::UpdateNewNodeGraph
| Self::UpdateTypes { .. }
| Self::UpdateEvaluationErrors { .. }
| Self::UpdateNodeProgress { .. }
| Self::UpdateActionButtons
| Self::UpdateGraphBarRight
| Self::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.
@@ -2074,6 +2076,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
responses.add(FrontendMessage::UpdateNetworkReadOnly {
read_only: network_interface.is_read_only(breadcrumb_network_path),
});
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);
@@ -2680,6 +2684,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);
@@ -3900,6 +3913,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(
@@ -4109,6 +4138,7 @@ impl Default for NodeGraphMessageHandler {
frontend_nodes: Vec::new(),
frontend_wires: HashSet::new(),
evaluation_errors: Vec::new(),
node_progress: Vec::new(),
}
}
}
@@ -3316,6 +3316,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>,
@@ -41,6 +41,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,
@@ -285,6 +285,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 });
+59 -9
View File
@@ -41,6 +41,8 @@ pub struct ExecutionResponse {
dropped_thumbnails: Vec<NodeId>,
/// The latest result of each observation.
observations: HashMap<ObservationKey, 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)>,
}
/// Names an observation so it can be changed or stopped without touching the others.
@@ -59,6 +61,8 @@ pub enum ObservationKey {
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>),
@@ -123,6 +127,8 @@ pub struct NodeGraphExecutor {
inspect_context_overrides: ContextOverrides,
/// 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>,
@@ -177,6 +183,7 @@ impl NodeGraphExecutor {
previous_node_to_inspect: Vec::new(),
inspect_context_overrides: ContextOverrides::default(),
canvas_images_sent: HashSet::new(),
node_progress: Vec::new(),
#[cfg(test)]
evaluation_errors: None,
gradient_migration: None,
@@ -212,6 +219,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_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}");
@@ -531,6 +548,7 @@ impl NodeGraphExecutor {
responses: existing_responses,
dropped_thumbnails,
mut observations,
progress,
} = *execution_response;
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
@@ -575,14 +593,24 @@ 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();
self.update_node_progress(node_progress, responses);
}
// 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)| {
@@ -599,7 +627,7 @@ impl NodeGraphExecutor {
})
.collect()
}
ExecutionResult::Pending | ExecutionResult::Value(_) | ExecutionResult::Panic(_) | ExecutionResult::Uncompiled => Vec::new(),
ExecutionResult::Pending | ExecutionResult::Value(_) | ExecutionResult::Partial(_) | ExecutionResult::Panic(_) | ExecutionResult::Uncompiled => Vec::new(),
};
responses.add(NodeGraphMessage::UpdateEvaluationErrors { errors });
}
@@ -608,9 +636,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(_) | ExecutionResult::Uncompiled => 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)]
{
@@ -664,7 +697,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 {
@@ -712,6 +745,7 @@ impl NodeGraphExecutor {
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());
self.update_node_progress(Vec::new(), responses);
// The graph only shows errors tied to nodes, so the console gets the others
if node_graph_errors.is_empty() {
@@ -786,6 +820,16 @@ impl NodeGraphExecutor {
all_dropped_thumbnails
}
/// Sends the active document's node progress to its graph, which keeps its own copy, and refreshes the Properties panel when it changed.
fn update_node_progress(&mut self, node_progress: Vec<(Vec<NodeId>, f64)>, responses: &mut VecDeque<Message>) {
responses.add(NodeGraphMessage::UpdateNodeProgress { progress: node_progress.clone() });
if self.node_progress != node_progress {
self.node_progress = node_progress;
responses.add(InspectorMessage::Refresh);
}
}
fn receive_thumbnails(document: &mut DocumentMessageHandler, thumbnails: VecDeque<FrontendMessage>, responses: &mut VecDeque<Message>) {
for thumbnail in thumbnails {
match LayersInView::thumbnail_layer(&thumbnail) {
@@ -999,7 +1043,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 });
@@ -1081,7 +1125,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>) {
@@ -1139,6 +1183,12 @@ impl NodeGraphExecutor {
}
}
/// 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())
}
// 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.
+76 -5
View File
@@ -11,6 +11,7 @@ use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler};
use graph_craft::proto::{GraphError, GraphErrorType, GraphErrors};
use graphene_hash::CacheHash;
use graphene_std::SourceId;
use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture};
use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
@@ -62,6 +63,8 @@ pub struct NodeRuntime {
resources: ResourceRegistry,
node_graph_errors: GraphErrors,
node_graph_warnings: GraphErrors,
/// Each source of the compiled network, with the path of the value node injecting it.
source_paths: Vec<(SourceId, Vec<NodeId>)>,
thumbnails: Thumbnails,
observer: Observer<ObservationKey>,
/// Whether an observation changed since its results were last sent.
@@ -104,6 +107,8 @@ pub enum GraphRuntimeRequest {
layers: Vec<NodeId>,
},
RenderOverlays(OverlayContext),
/// 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)]
@@ -188,6 +193,7 @@ impl NodeRuntime {
node_graph_errors: Vec::new(),
node_graph_warnings: Vec::new(),
source_paths: Vec::new(),
thumbnails: Thumbnails::new(),
observer: Observer::default(),
observations_changed: false,
@@ -245,6 +251,15 @@ impl NodeRuntime {
self.overlays = Some(context);
self.overlays_stale = 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);
}
}
}
}
@@ -458,7 +473,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))
@@ -472,6 +488,7 @@ impl NodeRuntime {
responses: VecDeque::new(),
dropped_thumbnails: Vec::new(),
observations: HashMap::new(),
progress: Vec::new(),
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
return None;
@@ -486,12 +503,23 @@ impl NodeRuntime {
// While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did
let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await };
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,
responses,
dropped_thumbnails,
observations,
progress,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
}
@@ -561,6 +589,7 @@ impl NodeRuntime {
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
};
self.node_graph_warnings.extend(warnings);
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)| {
@@ -602,7 +631,9 @@ impl NodeRuntime {
impl ExecutionResult {
fn render_output(&mut self) -> Option<&mut RenderOutput> {
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(output) = value else { return None };
Some(output)
}
@@ -665,6 +696,7 @@ impl Spawn for NodeTaskExecutor {
#[cfg(test)]
mod tests {
use super::*;
use crate::messages::frontend::utility_types::RenderStatus;
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::test_utils::EditorTestUtils;
use glam::DVec2;
@@ -686,12 +718,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();
}
@@ -721,8 +758,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};
@@ -747,6 +784,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.
@@ -1107,6 +1145,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);
+19 -1
View File
@@ -718,9 +718,14 @@
<div bind:this={textInput} style:transform="matrix({textInputMatrix})" on:scroll={preventTextEditingScroll}></div>
{/if}
</div>
{#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 $document.renderStatus === "Partial"}
<div class="render-status-outline"></div>
{:else if ["Fallback", "Error", "Panic"].includes($document.renderStatus)}
<div class="render-status-outline failed"></div>
{/if}
{#if $document.renderStatus === "Error"}
<LayoutCol class="render-status-overlay">
<TextLabel>
@@ -983,6 +988,19 @@
}
}
.render-status-outline {
position: absolute;
inset: 0;
// Above the error overlays so the outline frames them too
z-index: 1;
box-shadow: inset 0 0 0 1px var(--color-warning-yellow);
pointer-events: none;
&.failed {
box-shadow: inset 0 0 0 1px var(--color-error-red);
}
}
.render-status-overlay {
position: absolute;
inset: 0;
@@ -973,10 +973,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)}
@@ -992,6 +994,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}
@@ -1515,6 +1520,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
@@ -1900,6 +1909,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={Math.min(Math.max(fraction, 0), 1)}
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>
+10
View File
@@ -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>;
@@ -48,6 +49,7 @@ const initialState: NodeGraphStoreState = {
clickTargets: undefined,
contextMenuInformation: undefined,
errors: [],
progress: new Map(),
layerWidths: new Map(),
chainWidths: new Map(),
hasLeftInputWire: new Map(),
@@ -236,6 +238,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);
@@ -360,6 +369,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");
+5
View File
@@ -750,6 +750,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()
+6 -1
View File
@@ -385,9 +385,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,
+91 -4
View File
@@ -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());
+70 -12
View File
@@ -89,19 +89,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
}
@@ -135,14 +148,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).map(|tracing| (tracing, pixels_to_document))
};
@@ -404,4 +416,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");
}
}
+29 -7
View File
@@ -1,6 +1,6 @@
use core_types::Poll;
use core_types::list::List;
use core_types::runtime::Instant;
use core_types::{NodeError, Poll};
use glam::DAffine2;
use graphic_types::Graphic;
use ollev::model::Model;
@@ -23,13 +23,15 @@ 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>,
/// Places the traced image's pixels in the document.
pixels_to_document: DAffine2,
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 {
@@ -54,6 +56,7 @@ impl TraceSlot {
pixels_to_document,
shown: List::new(),
revision: None,
progress: 0.,
},
Err(error) => return Poll::fallback(List::new(), error),
},
@@ -61,7 +64,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, trace.pixels_to_document);
@@ -69,7 +76,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()
@@ -84,8 +91,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),
};
@@ -93,6 +100,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();