Compare commits

..
28 changed files with 2189 additions and 644 deletions

No files matched your search

Generated
+1
View File
@@ -8586,6 +8586,7 @@ dependencies = [
"raster-kernels",
"raster-types",
"rendering",
"svg-convert",
"thiserror 2.0.21",
"vello_gpu",
"web-sys",
@@ -13,7 +13,7 @@ pub enum ClipboardMessage {
CopyLayers,
CutLayers,
WriteItems { items: Vec<ApplicationDataItem> },
Rendered { id: u64, svg: Option<String> },
Rendered { id: u64, svg: Result<Option<String>, String> },
Loaded { id: u64, content: DataTransfer },
PasteItems { items: Vec<ApplicationDataItem> },
PasteLayers { entries: Vec<ApplicationDataLayer> },
@@ -246,6 +246,15 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
let Some(PendingCopy::Rendering { items, loads, .. }) = self.pending_copy.take_if(|pending| pending.id() == id) else {
return;
};
// The layers still copy, without an SVG
let svg = svg.unwrap_or_else(|error| {
responses.add(DialogMessage::DisplayDialogError {
title: "Unable to copy as SVG".to_string(),
description: error,
});
None
});
self.finish_copy(items, loads, svg, resource_storage, responses);
}
ClipboardMessage::Loaded { id, content } => {
@@ -665,6 +674,212 @@ mod test {
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
}
/// The bounds of what the SVG draws, strokes included, and the size of its frame.
fn drawn_bounds_and_frame(svg: &str) -> (usvg::Rect, usvg::Size) {
let tree = usvg::Tree::from_str(svg, &usvg::Options::default()).unwrap_or_else(|error| panic!("the SVG should parse ({error}): {svg}"));
(tree.root().abs_stroke_bounding_box(), tree.size())
}
// A layer is copied as what it adds to the group holding it, so the group's move is left out of both its frame and what it draws
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_frames_a_grouped_layer_without_its_groups_transform() {
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use glam::DAffine2;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 50.).await;
let rectangle = editor.active_document().metadata().all_layers().next().expect("the drawn rectangle");
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
})
.await;
let group = rectangle.parent(editor.active_document().metadata()).expect("the rectangle should be grouped");
editor
.handle_message(GraphOperationMessage::TransformChange {
layer: group,
transform: DAffine2::from_translation(DVec2::new(500., 300.)),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![rectangle.to_node()] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the grouped rectangle should render an SVG");
// The frame grows past the stroke by as far as its miter joins could reach
let (drawn, frame) = drawn_bounds_and_frame(svg);
let within_frame = drawn.left() >= 0. && drawn.top() >= 0. && drawn.right() <= frame.width() && drawn.bottom() <= frame.height();
assert!(within_frame, "the rectangle should be drawn within the frame, at {drawn:?} in {frame:?}: {svg}");
assert!(frame.width() < 120. && frame.height() < 70., "the frame should hold only the rectangle: {svg}");
}
// Any node can be shown as a layer, which adds everything it outputs
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_draws_a_layer_that_is_not_a_merge() {
use crate::messages::portfolio::document::utility_types::network_interface::FlowType;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 50.).await;
let rectangle = editor.active_document().metadata().all_layers().next().expect("the drawn rectangle").to_node();
let network_interface = &mut editor.active_document_mut().network_interface;
let content_node = network_interface
.upstream_flow_back_from_nodes(vec![rectangle], &[], FlowType::HorizontalFlow)
.nth(1)
.expect("the layer should have a content chain");
network_interface.set_to_node_or_layer(&content_node, &[], true);
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![content_node] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the layer should render an SVG");
assert!(svg.contains("<path"), "the SVG should draw the rectangle: {svg}");
}
// An artboard holds its own content, so the other layers copied with it are left out of the SVG
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_of_artboards_and_other_layers_draws_only_the_artboards() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Artboard, 0., 0., 200., 100., ModifierKeys::empty()).await;
editor.draw_rect(500., 500., 600., 600.).await;
let layers = editor.active_document().metadata().all_layers().map(|layer| layer.to_node()).collect();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: layers }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the artboard should render an SVG");
let (_, frame) = drawn_bounds_and_frame(svg);
assert!(
(frame.width() - 200.).abs() < 1. && (frame.height() - 100.).abs() < 1.,
"the SVG should be framed to the artboard alone: {svg}"
);
}
// The frame keeps the content's exact size, rather than whole pixels that would round a fifth of a unit away to nothing
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_keeps_a_fractional_frame() {
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use glam::DAffine2;
use graphene_std::vector::style::Stroke;
// A square shrunk to a fifth of a unit across, with only a fill
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let layer = editor.active_document().metadata().all_layers().next().expect("the drawn rectangle");
editor
.handle_message(GraphOperationMessage::StrokeSet {
layer,
color: None,
stroke: Stroke::default(),
})
.await;
editor
.handle_message(GraphOperationMessage::TransformSet {
layer,
transform: DAffine2::from_scale(DVec2::splat(0.002)),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the square should render an SVG");
let (drawn, frame) = drawn_bounds_and_frame(svg);
assert!(
(frame.width() - 0.2).abs() < 1e-4 && (frame.height() - 0.2).abs() < 1e-4,
"the frame should be the square's size: {svg}"
);
assert!((drawn.width() - 0.2).abs() < 1e-4 && drawn.left().abs() < 1e-4, "the square should fill the frame: {svg}");
}
/// Sets the viewport to `size` pixels and gives back the size of the part of the document it shows.
async fn view_of_size(editor: &mut EditorTestUtils, size: DVec2) -> DVec2 {
use graphene_std::math::quad::Quad;
editor.set_viewport_size(DVec2::ZERO, size).await;
let viewport_to_document = editor.active_document().metadata().document_to_viewport.inverse();
let [min, max] = (viewport_to_document * Quad::from_box([DVec2::ZERO, size])).bounding_box();
max - min
}
// Content drawn for its view, like a brush stroke's image or tiles covering the view, is framed to the view it was copied in
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_frames_content_drawn_for_its_view_to_that_view() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let view = view_of_size(&mut editor, DVec2::new(400., 300.)).await;
let framed_to_view = |svg: &str| {
let (_, frame) = drawn_bounds_and_frame(svg);
(frame.width() as f64 - view.x).abs() < 1e-3 && (frame.height() as f64 - view.y).abs() < 1e-3
};
// A brush stroke
editor.handle_message(PreferencesMessage::BrushTool { enabled: true }).await;
editor.drag_tool(ToolType::Brush, 50., 50., 150., 100., ModifierKeys::empty()).await;
let brush = editor.active_document().metadata().all_layers().next().expect("the brush layer");
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![brush.to_node()] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the brush layer should render an SVG");
assert!(framed_to_view(svg), "the brush layer should be framed to the {view} view: {svg}");
assert!(svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"), "the stroke should be the GPU's image: {svg}");
// A rectangle tiled across the view
editor.draw_rect(0., 0., 20., 20.).await;
let tiled = editor.active_document().metadata().all_layers().next().expect("the rectangle");
let tile = DefinitionIdentifier::ProtoNode(graphene_std::repeat::tile::IDENTIFIER);
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type: tile, layer: tiled }).await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![tiled.to_node()] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the tiled layer should render an SVG");
assert!(framed_to_view(svg), "the tiled layer should be framed to the {view} view: {svg}");
assert!(svg.matches("<path").count() > 1, "the view should hold several tiles: {svg}");
}
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_draws_generators_as_the_gpus_render() {
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
use graph_craft::document::NodeId;
// A Mandelbrot layer, made from an image layer by feeding the fractal into its content instead
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.create_raster_image(graphene_std::raster::Image::new(1, 1, Color::BLACK), None).await;
let layer = editor.active_document().metadata().all_layers().next().expect("the image layer").to_node();
let mandelbrot = NodeId::new();
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
node_id: Some(mandelbrot),
node_type: DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER),
xy: None,
add_transaction: true,
});
editor.dispatch(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(mandelbrot),
input_connector: InputConnector::node_at_index(layer, 1),
});
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] }).await;
// The SVG frames the fractal's body, hundreds of units across rather than the image's one, and embeds the GPU's image of it where its placeholder stood
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the Mandelbrot layer should render an SVG");
let (_, frame) = drawn_bounds_and_frame(svg);
assert!(frame.width() > 100., "{svg}");
assert!(svg.matches("data:image/png;base64,").count() == 1 && !svg.contains("deferred-image"), "{svg}");
}
/// - paste
/// - assert that ellipse was copied
#[tokio::test]
@@ -1123,20 +1123,10 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
self.executor.submit_thumbnails_in_view(document, document_id);
}
}
PortfolioMessage::SubmitClipboardSvg { id } => {
let layers = self.active_document().map(|document| {
let selected = document.partition_selection().layers;
let mut layers = document
.metadata()
.all_layers()
.filter(|layer| selected.contains(layer))
.map(|layer| layer.to_node())
.collect::<Vec<_>>();
layers.reverse();
layers
});
responses.add(self.executor.submit_clipboard_svg(self.active_document_id, id, layers.unwrap_or_default()));
}
PortfolioMessage::SubmitClipboardSvg { id } => match self.active_document_id.and_then(|document_id| self.documents.get(&document_id)) {
Some(document) => self.executor.submit_clipboard_svg(document, viewport.size().into_dvec2(), id),
None => responses.add(ClipboardMessage::Rendered { id, svg: Ok(None) }),
},
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
responses.add(MenuBarMessage::SendLayout);
+48 -30
View File
@@ -12,6 +12,7 @@ use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::color::SRGBA8;
use graphene_std::list::{Item, List};
use graphene_std::math::quad::Quad;
use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint;
@@ -114,7 +115,8 @@ pub enum NodeGraphUpdate {
Observations(HashMap<ObservationKey, InspectResult>),
ClipboardSvg {
id: u64,
svg: Option<String>,
/// The SVG, `None` if the layers add nothing, or why it couldn't be rendered.
svg: Result<Option<String>, String>,
},
}
@@ -229,13 +231,28 @@ impl NodeGraphExecutor {
.expect("Failed to send the context overrides");
}
pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message {
if document_id.is_none() || self.node_graph_document != document_id {
return ClipboardMessage::Rendered { id, svg: None }.into();
}
/// Has the runtime render what the selected layers add as an SVG, which it sends back once their content is final.
/// The `viewport_size` is in viewport pixels.
pub fn submit_clipboard_svg(&self, document: &DocumentMessageHandler, viewport_size: DVec2, id: u64) {
let network_interface = &document.network_interface;
let view = (document.metadata().document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, viewport_size])).bounding_box();
self.sender.send(GraphRuntimeRequest::ClipboardSvg { id, layers }).expect("Failed to send runtime request");
Message::NoOp
// Painted from the bottom up
let selected = document.partition_selection().layers;
let mut layers: Vec<_> = document.metadata().all_layers().filter(|layer| selected.contains(layer)).map(|layer| layer.to_node()).collect();
layers.reverse();
// The network as it is now, since the runtime applies a graph update sent before this one only after it reads this
let request = ClipboardSvgRequest {
id,
network: network_interface.document_network().clone(),
resources: document.resources.registry.clone(),
previewed: network_interface.previewed_nodes(),
layer_paths: network_interface.layer_paths(),
layers,
view,
};
self.sender.send(GraphRuntimeRequest::ClipboardSvg(request)).expect("Failed to send runtime request");
}
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
@@ -435,28 +452,7 @@ impl NodeGraphExecutor {
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
}
.ok_or_else(|| "No bounding box".to_string())?;
let resolution_in_document_space = bounds[1] - bounds[0];
let export_resolution = resolution_in_document_space * export_config.scale_factor;
let resolution = export_resolution.round().as_uvec2();
let transform = DAffine2::from_translation(bounds[0]).inverse();
let viewport = Footprint {
resolution,
transform,
..Default::default()
};
let render_config = RenderConfig {
viewport,
scale: export_config.scale_factor,
time: Default::default(),
pointer: DVec2::ZERO,
export_format,
// The viewport's render mode is only a way of viewing the artwork, which exports show as it is
render_mode: graphene_std::vector::style::RenderMode::Normal,
for_export: true,
for_eyedropper: false,
};
let render_config = export_render_config(bounds, export_config.scale_factor, export_format);
// Execute the node graph
self.sender
@@ -474,7 +470,7 @@ impl NodeGraphExecutor {
ExecutionContext {
export_config: Some(export_config),
document_id,
document_to_viewport: viewport.transform,
document_to_viewport: render_config.viewport.transform,
measure_fill: None,
},
));
@@ -1200,6 +1196,28 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
None
}
/// The render of an export framed to these bounds in document space, drawn at `scale` pixels per unit.
fn export_render_config(bounds: [DVec2; 2], scale: f64, export_format: ExportFormat) -> RenderConfig {
let resolution = ((bounds[1] - bounds[0]) * scale).round().as_uvec2();
let viewport = Footprint {
resolution,
transform: DAffine2::from_translation(bounds[0]).inverse(),
..Default::default()
};
RenderConfig {
viewport,
scale,
time: Default::default(),
pointer: DVec2::ZERO,
export_format,
// The viewport's render mode is only a way of viewing the artwork, which exports show as it is
render_mode: graphene_std::vector::style::RenderMode::Normal,
for_export: true,
for_eyedropper: false,
}
}
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
DialogMessage::DisplayDialogError {
+490 -42
View File
@@ -17,9 +17,9 @@ use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface,
use graphene_std::raster_types::Raster;
use graphene_std::runtime::AsyncRuntime;
use graphene_std::vector::style::RenderMode;
use graphene_std::{Context, NodeError, Poll};
use graphene_std::{Artboard, Context, ContextFeatures, Generations, NodeError, OwnedContextImpl, Poll};
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::layer_paths::write_layer_paths;
use interpreted_executor::layer_paths::{export_layers, write_layer_paths};
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
use observer::Observer;
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
@@ -52,6 +52,8 @@ pub struct NodeRuntime {
pending_export: Option<ExecutionRequest>,
pending_eyedropper: Option<ExecutionRequest>,
pending_thumbnails: Option<DocumentId>,
/// The latest copy's SVG, evaluated from its own network until its content is final.
pending_clipboard: Option<PendingClipboard>,
/// The network the executor last compiled successfully, with previews applied.
old_graph: Option<NodeNetwork>,
/// Whether the latest network failed to compile, leaving the executor with an older one that mustn't be shown in its place.
@@ -59,7 +61,6 @@ pub struct NodeRuntime {
async_runtime: Option<AsyncRuntime>,
editor_api: Arc<PlatformEditorApi>,
resources: ResourceRegistry,
node_graph_errors: GraphErrors,
node_graph_warnings: GraphErrors,
thumbnails: Thumbnails,
@@ -107,13 +108,39 @@ pub enum GraphRuntimeRequest {
key: ObservationKey,
observation: Option<Observation>,
},
ClipboardSvg {
id: u64,
layers: Vec<NodeId>,
},
ClipboardSvg(ClipboardSvgRequest),
RenderOverlays(OverlayContext),
}
/// The layers a copy renders as an SVG, with the document network as it was when they were copied.
#[derive(Debug)]
pub struct ClipboardSvgRequest {
pub(super) id: u64,
pub(super) network: NodeNetwork,
pub(super) resources: ResourceRegistry,
/// The node each network renders in place of its export, paired with that network's path.
pub(super) previewed: Vec<(Vec<NodeId>, RootNode)>,
/// Full path from the root network to every layer.
pub(super) layer_paths: Vec<Vec<NodeId>>,
/// The copied layers, in the order they're painted.
pub(super) layers: Vec<NodeId>,
/// The part of the document in view, which frames content drawn for its view.
pub(super) view: [DVec2; 2],
}
/// A copy's SVG, held until its content is final.
struct PendingClipboard {
id: u64,
/// The output of the network made for the copy, which keeps its nodes compiled through a cut that removes the layers from the document's.
output: OutputHandle,
/// The compiled node giving what the copied layers add, whose bounds frame the SVG.
content: NodeId,
/// The part of the document in view when they were copied.
view: [DVec2; 2],
/// The SVG's frame, once it's known.
frame: Option<[DVec2; 2]>,
}
#[derive(Debug)]
pub struct GraphUpdate {
pub(super) network: NodeNetwork,
@@ -158,9 +185,9 @@ impl NodeRuntime {
pending_export: None,
pending_eyedropper: None,
pending_thumbnails: None,
pending_clipboard: None,
old_graph: None,
compile_failed: false,
resources: ResourceRegistry::default(),
async_runtime: None,
editor_api: PlatformEditorApi {
@@ -197,6 +224,7 @@ impl NodeRuntime {
}
let mut graph = None;
let mut clipboard = None;
for request in self.receiver.try_iter() {
match request {
GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update),
@@ -223,10 +251,8 @@ impl NodeRuntime {
self.observations_changed = true;
}
},
GraphRuntimeRequest::ClipboardSvg { id, layers } => {
let svg = self.old_graph.as_ref().and_then(|network| thumbnails::layers_svg(&layers, network, &self.executor));
self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response");
}
// The clipboard waits only for its latest copy
GraphRuntimeRequest::ClipboardSvg(request) => clipboard = Some(request),
GraphRuntimeRequest::RenderOverlays(context) => {
self.overlays = Some(context);
self.overlays_stale = true;
@@ -234,6 +260,11 @@ impl NodeRuntime {
}
}
// Compiled before a graph update that cuts the copied layers lets their nodes go
if let Some(request) = clipboard {
self.compile_clipboard_svg(request);
}
let Some(GraphUpdate {
mut network,
resources,
@@ -248,11 +279,8 @@ impl NodeRuntime {
apply_previews(&mut network, &previewed);
write_layer_paths(&mut network, &layers);
self.observer.replace_all(observations);
self.resources = resources;
self.node_graph_errors.clear();
self.node_graph_warnings.clear();
let result = self.update_network(network.clone());
let result = self.update_network(network.clone(), &resources);
self.compile_failed = result.is_err();
if result.is_ok() {
self.thumbnails.update_sources(&layers, &network, &self.executor);
@@ -305,6 +333,10 @@ impl NodeRuntime {
self.run_viewport(viewport).await;
}
if dirty && let Some(clipboard) = self.pending_clipboard.take() {
self.run_clipboard(clipboard);
}
// Overlays that changed without new artwork are drawn over the artwork already shown
if self.overlays_stale {
texture = self.composite_viewport_frame();
@@ -398,6 +430,70 @@ impl NodeRuntime {
self.respond(request, result, observations).await;
}
/// Evaluates the copy's network as an export framed to its content, sending its SVG once that's final, and otherwise keeping it to evaluate again when a task lands.
fn run_clipboard(&mut self, mut clipboard: PendingClipboard) {
let generations = self.async_runtime().snapshot();
let frame = match clipboard.frame {
Some(frame) => frame,
None => {
let Some(frame) = self.clipboard_frame(&clipboard, &generations) else {
self.pending_clipboard = Some(clipboard);
return;
};
match frame {
Ok(Some(frame)) => *clipboard.frame.insert(frame),
Ok(None) => return self.send_clipboard_svg(clipboard.id, Ok(None)),
Err(message) => return self.send_clipboard_svg(clipboard.id, Err(message)),
}
}
};
// The render covers whole pixels, rounded outward, while the SVG's frame keeps the content's exact size
let size = frame[1] - frame[0];
let covered = size.ceil();
let context = export_render_config([frame[0], frame[0] + covered], 1., ExportFormat::Svg).into_context_with_generations(generations);
match self.settled(clipboard.output.node(), || self.executor.execute(&clipboard.output, context).map_err(|error| error.to_string())) {
Some(output) => self.send_clipboard_svg(clipboard.id, output.and_then(svg_text).map(|svg| svg.map(|svg| with_frame_size(svg, covered, size)))),
None => self.pending_clipboard = Some(clipboard),
}
}
/// The frame of the copy's SVG once it's known, unless it has no area.
/// Content drawn for its view is framed to the view it was copied in, while other content is framed to its bounds, which are the same in any view.
fn clipboard_frame(&self, clipboard: &PendingClipboard, generations: &Generations) -> Option<Result<Option<[DVec2; 2]>, String>> {
let has_area = |[min, max]: &[DVec2; 2]| (*max - *min).cmpgt(DVec2::ZERO).all();
if self.executor.tree().context_features(clipboard.content).contains(ContextFeatures::FOOTPRINT) {
return Some(Ok(Some(clipboard.view).filter(has_area)));
}
let context = OwnedContextImpl::default()
.with_footprint(export_render_config(clipboard.view, 1., ExportFormat::Svg).viewport)
.with_real_time(0.)
.with_animation_time(0.)
.with_generations(generations.clone())
.into_context();
let content = self.settled(clipboard.content, || self.executor.tree().evaluate(clipboard.content, &context).map_err(|error| error.to_string()))?;
Some(content.map(|content| exported_bounds(content).filter(has_area)))
}
/// The value an evaluation of the node gives once it's final, `None` while it's pending or partial, or else what went wrong.
fn settled<T>(&self, node: NodeId, evaluate: impl FnOnce() -> Result<Poll<T>, String>) -> Option<Result<T, String>> {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(evaluate)).unwrap_or_else(|payload| {
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
Err(format!("Panicked: {}", message.unwrap_or("no message")))
});
match result {
Ok(Poll::Pending | Poll::Partial(_)) => None,
Ok(Poll::Final(value)) => Some(Ok(value)),
Ok(Poll::Fallback(boxed)) => Some(Ok(boxed.0)),
Ok(Poll::Error(error)) => Some(Err(self.resolve_errors(node, &error).to_string())),
Err(message) => Some(Err(message)),
}
}
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
// Eyedropper should use the same time and pointer to not invalidate the cache
if let Some(viewport) = self.pending {
@@ -436,9 +532,9 @@ impl NodeRuntime {
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
Ok(Ok(Poll::Fallback(boxed))) => {
let (value, error) = *boxed;
ExecutionResult::Fallback(value, self.resolve_errors(&error))
ExecutionResult::Fallback(value, self.resolve_errors(self.output.node(), &error))
}
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)),
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(self.output.node(), &error)),
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error.to_string()).error()), NodeErrorTrace::default())]))),
Err(payload) => {
let response = ExecutionResponse {
@@ -506,42 +602,121 @@ impl NodeRuntime {
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
}
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
fn update_network(&mut self, graph: NodeNetwork, resources: &ResourceRegistry) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
self.node_graph_errors.clear();
self.node_graph_warnings.clear();
let CompiledNetwork { network: proto_network, warnings } = match self.compile_network(graph, resources) {
Ok(compiled_network) => compiled_network,
Err((message, errors)) => {
self.node_graph_errors = errors;
return Err((ResolvedDocumentNodeTypesDelta::default(), message));
}
};
self.node_graph_warnings = warnings;
let result = match self.executor.update(proto_network) {
Ok((output, types)) => {
self.output = output;
Ok(types)
}
Err((types, errors)) => {
let message = format!("{errors:?}");
self.node_graph_errors = errors;
Err((types, message))
}
};
// Every held output's sources, so the tasks they spawn bump their generations when they land
self.async_runtime().update_sources(self.executor.sources());
result
}
/// Compiles the network of the copied layers beside the document's, to be evaluated until its SVG is final.
fn compile_clipboard_svg(&mut self, request: ClipboardSvgRequest) {
let ClipboardSvgRequest {
id,
mut network,
resources,
previewed,
layer_paths,
layers,
view,
} = request;
self.pending_clipboard = None;
// Made as the document's network is, so it shares the document's compiled nodes
apply_previews(&mut network, &previewed);
write_layer_paths(&mut network, &layer_paths);
let Some(content_node) = export_layers(&mut network, &layers) else {
self.send_clipboard_svg(id, Ok(None));
return;
};
let proto_network = match self.compile_network(network, &resources) {
Ok(compiled_network) => compiled_network.network,
Err((message, _)) => {
self.send_clipboard_svg(id, Err(message));
return;
}
};
// The last of the proto nodes at the stack's path, which may wrap it, gives what the stack outputs
let content_path = Some(vec![content_node]);
let Some(&(content, _)) = proto_network.nodes.iter().rev().find(|(_, node)| node.original_location.path == content_path) else {
self.send_clipboard_svg(id, Err("The copied layers' content didn't compile".to_string()));
return;
};
// The document's updates keep the source map, so the types they send the editor stay whole
let output = match self.executor.insert_beside(proto_network) {
Ok(output) => output,
Err(errors) => {
self.send_clipboard_svg(id, Err(format!("{errors:?}")));
return;
}
};
self.async_runtime().update_sources(self.executor.sources());
self.pending_clipboard = Some(PendingClipboard {
id,
output,
content,
view,
frame: None,
});
self.dirty.store(true, Ordering::Release);
}
fn send_clipboard_svg(&self, id: u64, svg: Result<Option<String>, String>) {
self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response");
}
/// Wraps the network with the render node in its scope, then preprocesses and compiles it, or else gives back why it failed with the errors on its nodes.
fn compile_network(&self, graph: NodeNetwork, resources: &ResourceRegistry) -> Result<CompiledNetwork, (String, GraphErrors)> {
let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| resources.hash(&resource_id)) {
return Err((e.to_string(), Vec::new()));
}
// We assume only one output
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
let c = Compiler {};
let CompiledNetwork { network: proto_network, warnings } = match c.compile_single(scoped_network) {
let compiled_network = match c.compile_single(scoped_network) {
Ok(compiled_network) => compiled_network,
Err(CompileError::Graph(errors)) => {
let message = format!("{errors:?}");
self.node_graph_errors = errors;
return Err((ResolvedDocumentNodeTypesDelta::default(), message));
}
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
Err(CompileError::Graph(errors)) => return Err((format!("{errors:?}"), errors)),
Err(CompileError::Message(message)) => return Err((message, Vec::new())),
};
self.node_graph_warnings = warnings;
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
let updated = self.executor.update(proto_network).map(|(output, types)| {
self.output = output;
types
});
let result = updated.map_err(|(types, e)| {
self.node_graph_errors.clone_from(&e);
(types, format!("{e:?}"))
});
self.async_runtime().update_sources(self.executor.sources());
result
assert_ne!(compiled_network.network.nodes.len(), 0, "No proto nodes exist?");
Ok(compiled_network)
}
fn resolve_errors(&self, error: &NodeError) -> EvaluationErrors {
/// The errors of an evaluation of the `output` node, each traced through the nodes it passed.
fn resolve_errors(&self, output: NodeId, error: &NodeError) -> EvaluationErrors {
let source_map = self.executor.tree().source_map();
let paths = |node: NodeId| -> NodePaths {
let mut paths: Vec<_> = source_map.iter().filter(|(_, (id, _))| *id == node).map(|(path, _)| path.clone()).collect();
@@ -549,7 +724,6 @@ impl NodeRuntime {
paths.into()
};
let mut errors = Vec::new();
let output = self.output.node();
let mut pending = vec![(vec![paths(output)], output, error)];
while let Some((mut trace, node, error)) = pending.pop() {
let passed = self.executor.trace_error(node, error);
@@ -580,6 +754,54 @@ impl ExecutionResult {
}
}
/// The area an export of the copied layers' content shows, unless it's endless, like a lone noise pattern, while a fractal's is the body a thumbnail shows.
fn exported_bounds(content: graphene_std::registry::Any) -> Option<[DVec2; 2]> {
let bounds = match content.downcast_ref::<List<Graphic>>() {
Some(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics),
None => artboard_clip_bounds(content.downcast_ref::<List<Artboard>>()?),
};
match bounds {
RenderBoundingBox::Rectangle([min, max]) if min.is_finite() && max.is_finite() => Some([min, max]),
_ => None,
}
}
/// The SVG with its frame narrowed from the whole pixels its render `covered` to the content's exact `size`.
fn with_frame_size(svg: String, covered: DVec2, size: DVec2) -> String {
let frame = |size: DVec2| format!(r#"viewBox="0 0 {} {}" width="{}" height="{}""#, size.x, size.y, size.x, size.y);
svg.replacen(&frame(covered), &frame(size), 1)
}
/// The union of the artboards' clipping rectangles, which frames what's visible of them better than their unclipped content does.
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
let mut combined: Option<[DVec2; 2]> = None;
for index in 0..artboards.len() {
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
let bounds = [location, location + dimensions];
combined = Some(match combined {
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
None => bounds,
});
}
match combined {
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
None => RenderBoundingBox::None,
}
}
/// The text of an SVG render's output.
fn svg_text(value: TaggedValue) -> Result<Option<String>, String> {
match value {
TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Svg { svg, .. },
..
}) => Ok(Some(svg)),
_ => Err("The render gave no SVG".to_string()),
}
}
fn evaluated_output(poll: Poll<graphene_std::registry::Any>) -> Option<graphene_std::registry::Any> {
match poll {
Poll::Final(output) | Poll::Partial(output) => Some(output),
@@ -1018,6 +1240,232 @@ mod tests {
assert!(!svg.contains("deferred-image"), "the markup standing in for the image should be replaced: {svg}");
}
#[tokio::test]
async fn an_svg_export_of_a_generator_settles_once_its_image_is_read_back() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use graphene_std::raster::Image;
use graphene_std::raster::color::Color;
// A Mandelbrot layer, made from an image layer by feeding the fractal into its content instead, over a rectangle framing the export
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 64., 64.).await;
editor.create_raster_image(Image::new(1, 1, Color::BLACK), None).await;
let layer = editor.get_selected_layer().await.expect("the pasted image should be selected").to_node();
let mandelbrot = NodeId::new();
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
node_id: Some(mandelbrot),
node_type: DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER),
xy: None,
add_transaction: true,
});
editor.dispatch(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(mandelbrot),
input_connector: InputConnector::node_at_index(layer, 1),
});
editor.eval_graph_until_finished().await.expect("the graph evaluates");
// The evaluation the readback wakes draws the same placeholders again, so the image it read back fills them and the export finishes
send_export(&mut editor, FileType::Svg);
let mut saved = None;
for _ in 0..100 {
editor.runtime.update();
editor.runtime.run().await;
saved = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
FrontendMessage::TriggerSaveFile { content, .. } => Some(content),
_ => None,
});
if saved.is_some() {
break;
}
}
let Some(saved) = saved else { panic!("the export never finished") };
let svg = String::from_utf8(saved.into_vec()).expect("the export should be SVG text");
assert!(
svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"),
"the fractal's image should fill its placeholder: {svg}"
);
}
/// Lets the runtime handle what's queued until the clipboard is written, giving back the SVG written with the copied layers, if any.
async fn clipboard_svg_once_written(editor: &mut EditorTestUtils, mut messages: Vec<FrontendMessage>) -> Option<String> {
use crate::messages::portfolio::ingest::utility_types::TransferData;
for _ in 0..1000 {
let written = messages.iter().find_map(|message| match message {
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
_ => None,
});
if let Some(content) = written {
return content.0.iter().find_map(|item| match &item.data {
TransferData::Svg(svg) => Some(svg.clone()),
_ => None,
});
}
editor.runtime.update();
editor.runtime.run().await;
messages = editor.dispatch(Message::Wake);
}
panic!("the clipboard was never written");
}
#[tokio::test]
async fn a_cut_waits_through_document_updates_for_its_outstanding_tasks_then_writes_once() {
use crate::messages::portfolio::ingest::utility_types::TransferData;
/// Runs each task at once, or holds it while `holding` until the test runs it.
#[derive(Default)]
struct HeldTasks {
holding: AtomicBool,
held: std::sync::Mutex<Vec<Task>>,
}
impl Spawn for HeldTasks {
fn spawn(&self, task: Task) {
match self.holding.load(Ordering::Relaxed) {
true => self.held.lock().unwrap().push(task),
false => futures::executor::block_on(task),
}
}
}
let svgs_written = |messages: &[FrontendMessage]| -> Vec<String> {
let written = messages.iter().filter_map(|message| match message {
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
_ => None,
});
let svgs = written.flat_map(|content| &content.0).filter_map(|item| match &item.data {
TransferData::Svg(svg) => Some(svg.clone()),
_ => None,
});
svgs.collect()
};
let tasks = Arc::new(HeldTasks::default());
let mut editor = EditorTestUtils::create();
editor.runtime.replace_task_executor(tasks.clone(), Arc::new(|| {}));
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
// The traced layer's tasks are held from the start, so it's still unfinished when it's cut
tasks.holding.store(true, Ordering::Relaxed);
add_traced_noise_layer(&mut editor).await;
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
editor.dispatch(Message::Wake);
assert!(!tasks.held.lock().unwrap().is_empty(), "the layer should have tasks out");
let layer = editor.active_document().metadata().all_layers().next().unwrap().to_node();
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] });
let mut messages = editor.dispatch(ClipboardMessage::CutLayers);
assert_eq!(editor.active_document().metadata().all_layers().count(), 0, "the layer should be cut");
// Document updates after the cut leave the copy's network alone, outliving the executor's grace for orphaned nodes
for _ in 0..3 {
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
messages.extend(editor.dispatch(Message::Wake));
}
assert!(svgs_written(&messages).is_empty(), "nothing should be written while the tasks are out");
assert!(editor.runtime.pending_clipboard.is_some(), "the copy should hold its network");
// Released, the tasks land and the trace runs to its end
tasks.holding.store(false, Ordering::Relaxed);
let held = std::mem::take(&mut *tasks.held.lock().unwrap());
held.into_iter().for_each(futures::executor::block_on);
for _ in 0..1000 {
editor.runtime.update();
editor.runtime.run().await;
messages.extend(editor.dispatch(Message::Wake));
}
let svgs = svgs_written(&messages);
assert_eq!(svgs.len(), 1, "the SVG should be written once");
assert!(svgs[0].contains("<path"), "the SVG should hold the traced shapes: {}", svgs[0]);
assert!(editor.runtime.pending_clipboard.is_none(), "the copy should let its network go");
}
// The copy's network is compiled ahead of the edit sent with it, so the edit's node is compiled before the document's update reaches it
#[tokio::test]
async fn the_types_of_an_edit_sent_with_a_copy_reach_the_editor() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use graphene_std::blending_nodes::effects::drop_shadow;
let mut editor = editor().await;
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
editor.dispatch(Message::Wake);
let layer = editor.active_document().metadata().all_layers().next().unwrap();
let shadow_type = DefinitionIdentifier::ProtoNode(drop_shadow::IDENTIFIER);
editor.dispatch(NodeGraphMessage::CreateNodeInLayerWithTransaction {
node_type: shadow_type.clone(),
layer,
});
let interface = &editor.active_document().network_interface;
let shadow = interface
.document_network()
.nodes
.keys()
.copied()
.find(|node_id| interface.reference(node_id, &[]) == Some(shadow_type.clone()));
let shadow = shadow.expect("the shadow should be added");
send_update(&mut editor);
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] });
let messages = editor.dispatch(ClipboardMessage::CopyLayers);
clipboard_svg_once_written(&mut editor, messages).await.expect("the layer should render an SVG");
let types = &editor.active_document().network_interface.resolved_types.types;
assert!(types.keys().any(|path| path.first() == Some(&shadow)), "the shadow's types should reach the editor");
}
// The edit, the copy, and the cut taking the edited layer away all reach the runtime in one queue
#[tokio::test]
async fn a_copy_renders_the_document_as_it_was_when_copied() {
use graphene_std::raster::color::Color;
let mut editor = editor().await;
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
editor.dispatch(Message::Wake);
let layer = editor.active_document().metadata().all_layers().next().unwrap();
editor.dispatch(GraphOperationMessage::FillColorSet { layer, color: Some(Color::RED) });
send_update(&mut editor);
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] });
let mut messages = editor.dispatch(ClipboardMessage::CopyLayers);
messages.extend(editor.dispatch(ClipboardMessage::CutLayers));
let svg = clipboard_svg_once_written(&mut editor, messages).await.expect("the cut layer should render an SVG");
assert!(svg.to_lowercase().contains("#ff0000"), "the SVG should show the edited fill: {svg}");
}
#[tokio::test]
async fn a_copy_renders_while_another_layer_fails_to_compile() {
let mut editor = editor().await;
editor.draw_rect(200., 0., 300., 100.).await;
let copied = editor.active_document().metadata().all_layers().nth(1).expect("the first rectangle drawn").to_node();
// The top layer fails to compile
break_compile(&mut editor);
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
editor.dispatch(Message::Wake);
assert!(editor.runtime.compile_failed, "the document should fail to compile");
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![copied] });
let messages = editor.dispatch(ClipboardMessage::CopyLayers);
let svg = clipboard_svg_once_written(&mut editor, messages).await.expect("the copied layer should render an SVG");
assert!(svg.contains("<path"), "the SVG should draw the rectangle: {svg}");
}
#[tokio::test]
async fn exporting_a_graph_that_fails_to_compile_says_it_failed() {
let mut editor = editor().await;
@@ -1,4 +1,4 @@
use super::evaluated_output;
use super::{artboard_clip_bounds, evaluated_output};
use crate::messages::frontend::FrontendMessage;
use atlas::ThumbnailAtlasLayout;
use glam::{DAffine2, DVec2, UVec2};
@@ -12,8 +12,8 @@ use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
use graphene_std::transform::{Footprint, RenderQuality};
use graphene_std::renderer::Render;
use graphene_std::transform::Footprint;
use graphene_std::vector::Vector;
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
use interpreted_executor::dynamic_executor::DynamicExecutor;
@@ -276,11 +276,11 @@ impl ThumbnailContent {
}
}
/// The area the content covers once rendered, counting the effects drawn through maps and images only if they're `maps_resolved`, which the clipboard's SVG leaves out.
fn content_bounds(&self, maps_resolved: bool) -> RenderBoundingBox {
/// The area the content covers once rendered.
fn content_bounds(&self) -> RenderBoundingBox {
match self {
// Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, maps_resolved),
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics),
// The clipping rectangles rather than the content, since the renderer clips content to them
Self::Artboards(artboards) => artboard_clip_bounds(artboards),
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
@@ -289,7 +289,7 @@ impl ThumbnailContent {
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
fn bounds(&self) -> [DVec2; 2] {
let bounds = match self.content_bounds(true) {
let bounds = match self.content_bounds() {
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
_ => [DVec2::ZERO, DVec2::ONE],
};
@@ -297,38 +297,6 @@ impl ThumbnailContent {
}
}
/// Renders what each of these document layers adds, painted in the given order, as one SVG framed to their combined bounds, or `None` if they render nothing.
pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<String> {
let contents: Vec<ThumbnailContent> = layers
.iter()
.filter_map(|&layer| ThumbnailContent::evaluate(executor, thumbnail_source(&[layer], network, executor)?))
.collect();
let bounds = contents
.iter()
.filter_map(|content| match content.content_bounds(false) {
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => Some(bounds),
_ => None,
})
.reduce(|[min, max], [other_min, other_max]| [min.min(other_min), max.max(other_max)])?;
let render_params = RenderParams {
footprint: Footprint::from_bounds(bounds, RenderQuality::Full),
thumbnail: true,
..Default::default()
};
let mut render = SvgRender::new();
for content in &contents {
content.graphic().render_svg(&mut render, &render_params);
}
if render.svg.is_empty() {
return None;
}
render.format_svg(bounds[0], bounds[1]);
Some(render.svg.to_svg_string())
}
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
let source = layer_content(layer_path, network)?.source(network)?;
@@ -361,25 +329,6 @@ fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> {
None
}
/// Returns the union of the artboards' clipping rectangles, used as the thumbnail bounds for an artboard layer so the
/// framing matches what's actually visible after clipping rather than the unclipped content extents.
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
let mut combined: Option<[DVec2; 2]> = None;
for index in 0..artboards.len() {
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
let bounds = [location, location + dimensions];
combined = Some(match combined {
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
None => bounds,
});
}
match combined {
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
None => RenderBoundingBox::None,
}
}
/// Expands an AABB outward (centered) to match the Layers panel thumbnail's 3:2 aspect ratio, padding the smaller axis
/// so the input's extent is always preserved.
fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
@@ -63,7 +63,6 @@ pub fn draw_atlas(scene: &mut VelloSceneBuilder, layout: &ThumbnailAtlasLayout,
let render_params = RenderParams {
footprint: Footprint::BOUNDLESS,
render_output_type: RenderOutputType::Vello,
thumbnail: true,
..Default::default()
};
let cell_size = layout.cell_size.as_dvec2();
+10 -3
View File
@@ -117,10 +117,17 @@ impl EditorTestUtils {
panic!("Failed to evaluate graph: {e}");
}
// The copied layers' SVG waits for the readbacks of the GPU images it holds, each landing before a later run
let mut frontend_messages = self.dispatch(message);
self.runtime.update();
self.runtime.run().await;
frontend_messages.extend(self.dispatch(Message::Wake));
for _ in 0..100 {
self.runtime.update();
self.runtime.run().await;
frontend_messages.extend(self.dispatch(Message::Wake));
if frontend_messages.iter().any(|message| matches!(message, FrontendMessage::TriggerClipboardWrite { .. })) {
break;
}
}
frontend_messages
.into_iter()
@@ -65,17 +65,23 @@ impl DynamicExecutor {
/// Adds the [`ProtoNetwork`] to the existing [`BorrowTree`], reusing nodes where possible.
#[cfg_attr(debug_assertions, inline(never))]
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
let (output, add) = self.insert_nodes(proto_network)?;
let (output, add) = self.insert_nodes(proto_network, true)?;
let remove = self.free_orphaned_nodes();
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove }))
}
pub fn update_without_freeing(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
let (output, add) = self.insert_nodes(proto_network)?;
let (output, add) = self.insert_nodes(proto_network, true)?;
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }))
}
fn insert_nodes(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, Vec<(Path, NodeTypes)>), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
/// Adds the [`ProtoNetwork`] of an output held beside the one the editor shows, reusing nodes where possible.
/// The source map and the type deltas stay those of the networks given to [`Self::update`], so this records no document paths and frees nothing.
pub fn insert_beside(&mut self, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
self.insert_nodes(proto_network, false).map(|(output, _)| output).map_err(|(_, errors)| errors)
}
fn insert_nodes(&mut self, proto_network: ProtoNetwork, records_paths: bool) -> Result<(OutputHandle, Vec<(Path, NodeTypes)>), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
self.typing_context.update(&proto_network).map_err(|e| {
// If there is an error then get types that have been resolved before the error
let add = proto_network
@@ -98,7 +104,10 @@ impl DynamicExecutor {
})?;
let output = proto_network.output;
let add = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
let add = self
.tree
.update(proto_network, &self.typing_context, records_paths)
.map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
self.outputs.retain(|output| output.strong_count() > 0);
let held = self.outputs.iter().filter_map(Weak::upgrade).find(|held| **held == output);
let output = held.unwrap_or_else(|| {
@@ -292,20 +301,22 @@ impl BorrowTree {
pub fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> {
let mut nodes = BorrowTree::default();
for (id, node) in proto_network.nodes {
nodes.push_node(id, node, typing_context)?
nodes.push_node(id, node, typing_context, true)?
}
Ok(nodes)
}
/// Pushes new nodes into the tree
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<Vec<Path>, GraphErrors> {
/// Pushes new nodes into the tree, giving back the document paths whose entries in the source map changed, if it `records_paths`.
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext, records_paths: bool) -> Result<Vec<Path>, GraphErrors> {
let mut new_nodes: Vec<_> = Vec::new();
// TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type.
for (id, node) in proto_network.nodes {
if !self.nodes.contains_key(&id) {
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
self.push_node(id, node, typing_context)?;
} else if self.update_source_map(id, typing_context, &node) {
if records_paths {
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
}
self.push_node(id, node, typing_context, records_paths)?;
} else if records_paths && self.update_source_map(id, typing_context, &node) {
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
}
}
@@ -512,14 +523,16 @@ impl BorrowTree {
///
/// # Notes
///
/// - Updates the source map using [`update_source_map`](BorrowTree::update_source_map) before inserting the node.
/// - Updates the source map using [`update_source_map`](BorrowTree::update_source_map) before inserting the node, if it `records_path`.
/// - Handles different types of construction arguments:
/// - `Value`: Creates a node from a `TaggedValue`, with special handling for `EditorApi` values.
/// - `Nodes`: Constructs a node using other nodes as dependencies.
/// - Uses the constructor function from the `typing_context` for `Nodes` construction arguments.
/// - Returns an error if no constructor is found for the given node ID.
fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), GraphErrors> {
self.update_source_map(id, typing_context, &proto_node);
fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext, records_path: bool) -> Result<(), GraphErrors> {
if records_path {
self.update_source_map(id, typing_context, &proto_node);
}
self.context_features.insert(id, proto_node.upstream_context_features);
let path = proto_node.original_location.path.clone().unwrap_or_default();
@@ -11,7 +11,7 @@ fn push_node_sync() {
let mut tree = BorrowTree::default();
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Integer(2_i64).into()), vec![]);
let context = TypingContext::default();
tree.push_node(NodeId(0), val_1_protonode, &context).unwrap();
tree.push_node(NodeId(0), val_1_protonode, &context, true).unwrap();
let _node = tree.get(NodeId(0)).unwrap();
let result: Option<Item<i64>> = tree.eval(NodeId(0), &());
assert_eq!(result.map(|item| *item.element()), Some(2_i64));
@@ -1,12 +1,12 @@
//! Writes each layer's path onto what it renders, so what's rendered can be traced back to its layer.
use crate::node_registry::NODE_REGISTRY;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeId, NodeInput, NodeNetwork};
use graphene_std::NodeParameter;
use graphene_std::graphic::{extend, write_layer_path};
use graph_craft::{ProtoNodeIdentifier, Type, concrete, list};
use graphene_std::graphic::{as_graphic, extend, write_layer_path};
use graphene_std::list::NodeIdPath;
use graphene_std::{Artboard, Graphic, NodeParameter};
use std::collections::HashMap;
use std::hash::{DefaultHasher, Hash, Hasher};
@@ -108,6 +108,112 @@ pub fn write_layer_paths(network: &mut NodeNetwork, layer_paths: &[Vec<NodeId>])
}
}
/// Replaces the network's export with the stack of what these layers add, in the given order, giving back the root node making it, or `None` if they add nothing.
/// An artboard holds its own content, so when any of the layers adds one, only the artboards are stacked.
pub fn export_layers(network: &mut NodeNetwork, layers: &[NodeId]) -> Option<NodeId> {
// O(layers * depth)
let mut added = Vec::new();
for &layer in layers {
let Some(content) = layer_content(&[layer], network) else { continue };
let Some(source) = content.source(network) else { continue };
let artboard = outputs_artboards(source, network);
let Some(root_input) = surface_layer_content(network, layer, content) else { continue };
added.push((layer, root_input, artboard));
}
let artboards = added.iter().any(|&(_, _, artboard)| artboard);
let seed = if artboards { list!(Artboard) } else { list!(Graphic) };
let mut stack = NodeInput::type_default(seed, false);
for (layer, root_input, _) in added.into_iter().filter(|&(_, _, artboard)| artboard == artboards) {
// Extend joins lists of one type, so what other layers add is converted to graphics as the base input of 'Merge' does
let content = if artboards {
root_input
} else {
let as_graphic_id = exported_layer_node_id("as graphic", layer);
network.nodes.insert(as_graphic_id, proto_node(as_graphic::IDENTIFIER, vec![root_input]));
NodeInput::node(as_graphic_id, 0)
};
let extend_id = exported_layer_node_id("extend", layer);
network.nodes.insert(extend_id, proto_node(extend::IDENTIFIER, vec![stack, content]));
stack = NodeInput::node(extend_id, 0);
}
let stack_node = stack.as_node();
network.exports = vec![stack];
stack_node
}
/// Makes what the layer adds an output of the layer node at the root, giving back the input that refers to it there.
fn surface_layer_content(network: &mut NodeNetwork, layer: NodeId, content: LayerContent) -> Option<NodeInput> {
let LayerContent::Added { network_path, extend } = content else {
return Some(NodeInput::node(layer, 0));
};
let mut passed_on = network.nested_network(&network_path)?.nodes.get(&extend)?.inputs.get(extend::NewInput::INDEX)?.clone();
// Each network from the Extend node's out to the layer's gives it as an extra export, which layers made from the same network share
for depth in (1..=network_path.len()).rev() {
let holder = network_mut(network, &network_path[..depth])?;
let output_index = match holder.exports.iter().position(|export| *export == passed_on) {
Some(index) => index,
None => {
holder.exports.push(passed_on);
holder.exports.len() - 1
}
};
passed_on = NodeInput::node(network_path[depth - 1], output_index);
}
Some(passed_on)
}
/// Whether every type the proto node at this path may output is an artboard type, looking through nodes that output what their first input is given.
fn outputs_artboards(mut source: Vec<NodeId>, network: &NodeNetwork) -> bool {
let is_artboard = |ty: &Type| matches!(ty.nested_type(), Type::Item(element) | Type::List(element) if **element == concrete!(Artboard));
loop {
let Some((node_id, network_path)) = source.split_last() else { return false };
let Some(node) = network.nested_network(network_path).and_then(|network| network.nodes.get(node_id)) else {
return false;
};
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return false };
let Some(implementations) = NODE_REGISTRY.get(identifier) else { return false };
if implementations.keys().all(|types| is_artboard(&types.return_value)) {
return true;
}
let passes_first_input_on = |types: &graphene_std::NodeIOTypes| types.inputs.first().is_some_and(|input| input.nested_type() == types.return_value.nested_type());
if !implementations.keys().all(passes_first_input_on) {
return false;
}
let Some(input_source) = node.inputs.first().and_then(|input| network.input_source(network_path, input)) else {
return false;
};
source = input_source;
}
}
/// The ID of a node that `export_layers` adds at the root for the layer with this ID.
fn exported_layer_node_id(purpose: &str, layer: NodeId) -> NodeId {
let mut hasher = DefaultHasher::new();
"exported layer".hash(&mut hasher);
purpose.hash(&mut hasher);
layer.hash(&mut hasher);
NodeId(hasher.finish())
}
fn proto_node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
DocumentNode {
inputs,
implementation: DocumentNodeImplementation::ProtoNode(identifier),
..Default::default()
}
}
/// How the layer path writer fares with what a proto node outputs.
#[derive(Clone, Copy)]
enum CarriesLayerPath {
@@ -236,14 +342,6 @@ mod tests {
assert_eq!(network, unchanged);
}
fn proto_node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
DocumentNode {
inputs,
implementation: DocumentNodeImplementation::ProtoNode(identifier),
..Default::default()
}
}
fn definition_node(id: NetworkId) -> DocumentNode {
DocumentNode {
implementation: DocumentNodeImplementation::Definition(id),
@@ -321,4 +419,110 @@ mod tests {
assert!(matches!(output_can_carry_layer_path(&identifier), CarriesLayerPath::Always), "{identifier:?} should carry a layer path");
}
}
/// What the exported stack's Extend nodes are given at the root, bottom up, each with whether it's converted to a graphic, and what the stack starts from.
fn exported_stack(network: &NodeNetwork) -> (Vec<(NodeInput, bool)>, NodeInput) {
let mut added = Vec::new();
let mut stack = network.exports[0].clone();
while let Some(extend_node) = stack.as_node().and_then(|node_id| network.nodes.get(&node_id)) {
assert_eq!(extend_node.implementation, DocumentNodeImplementation::ProtoNode(extend::IDENTIFIER));
let content = &extend_node.inputs[extend::NewInput::INDEX];
let as_graphic_node = content.as_node().map(|node_id| &network.nodes[&node_id]);
added.push(match as_graphic_node {
Some(node) if node.implementation == DocumentNodeImplementation::ProtoNode(as_graphic::IDENTIFIER) => (node.inputs[0].clone(), true),
_ => (content.clone(), false),
});
stack = extend_node.inputs[extend::BaseInput::INDEX].clone();
}
added.reverse();
(added, stack)
}
#[test]
fn exported_layers_stack_as_graphics_in_the_order_given() {
let merge = NetworkId(1);
let rectangle = || proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new());
let mut network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(20), 0)],
nodes: [(NodeId(10), definition_node(merge)), (NodeId(20), definition_node(merge)), (NodeId(30), rectangle())]
.into_iter()
.collect(),
definitions: [(merge, merge_like(rectangle()))].into_iter().collect(),
..Default::default()
};
assert!(export_layers(&mut network, &[NodeId(20), NodeId(30), NodeId(10)]).is_some());
// The network both 'Merge' layers are made from gives what its Extend node adds as one extra export, while the plain node gives its output
assert_eq!(network.definitions[&merge].exports, vec![NodeInput::node(NodeId(1), 0), NodeInput::node(NodeId(2), 0)]);
let (added, start) = exported_stack(&network);
assert_eq!(start, NodeInput::type_default(list!(Graphic), false));
assert_eq!(
added,
[(NodeInput::node(NodeId(20), 1), true), (NodeInput::node(NodeId(30), 0), true), (NodeInput::node(NodeId(10), 1), true)]
);
}
// A layer made from a network holding a 'Merge' node passes what that node's Extend node adds out through both networks
#[test]
fn a_nested_extend_nodes_content_is_exported_through_each_network_around_it() {
let (merge, outer) = (NetworkId(1), NetworkId(2));
let rectangle = proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new());
let outer_network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(30), 0)],
nodes: [(NodeId(30), definition_node(merge))].into_iter().collect(),
..Default::default()
};
let mut network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(10), 0)],
nodes: [(NodeId(10), definition_node(outer))].into_iter().collect(),
definitions: [(merge, merge_like(rectangle)), (outer, outer_network)].into_iter().collect(),
..Default::default()
};
assert!(export_layers(&mut network, &[NodeId(10)]).is_some());
assert_eq!(network.definitions[&merge].exports[1], NodeInput::node(NodeId(2), 0));
assert_eq!(network.definitions[&outer].exports[1], NodeInput::node(NodeId(30), 1));
assert_eq!(exported_stack(&network).0, [(NodeInput::node(NodeId(10), 1), true)]);
}
// An artboard holds its own content, so the other layers copied with it are left out
#[test]
fn exported_artboards_leave_out_the_other_layers() {
let (merge, artboard) = (NetworkId(1), NetworkId(2));
let rectangle = proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new());
let create_artboard = proto_node(graphene_std::artboard::create_artboard::IDENTIFIER, Vec::new());
let mut network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(20), 0)],
nodes: [(NodeId(10), definition_node(merge)), (NodeId(20), definition_node(artboard))].into_iter().collect(),
definitions: [(merge, merge_like(rectangle)), (artboard, merge_like(create_artboard))].into_iter().collect(),
..Default::default()
};
assert!(export_layers(&mut network, &[NodeId(10), NodeId(20)]).is_some());
let (added, start) = exported_stack(&network);
assert_eq!(start, NodeInput::type_default(list!(Artboard), false));
assert_eq!(added, [(NodeInput::node(NodeId(20), 1), false)]);
}
#[test]
fn hidden_layers_export_nothing() {
let rectangle = DocumentNode {
visible: false,
..proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new())
};
let mut network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(10), 0)],
nodes: [(NodeId(10), rectangle)].into_iter().collect(),
..Default::default()
};
assert_eq!(export_layers(&mut network, &[NodeId(10)]), None);
assert_eq!(exported_stack(&network), (Vec::new(), NodeInput::type_default(list!(Graphic), false)));
}
}
@@ -240,6 +240,9 @@ impl EffectCapture {
/// Not an effect's coverage but the share of each pixel within the content that its fill lets what lies beneath show through,
/// which the parts of interior pieces blending with what lies beneath are cut to (see [`crate::effect_layers::PiecePlace::Through`]).
pub const THROUGH_MASK: Self = Self { index: usize::MAX, plane: 0 };
/// The plane of a paint overlay or outline holding its drawn paint as the GPU renders it, for an SVG that can't draw the paint whole as markup.
pub const DRAWN_PAINT_PLANE: usize = usize::MAX;
}
/// The offset a shadow cast by light from `angle` (in degrees counterclockwise from the right) falls at `distance` from the content, in the document's y-down space.
@@ -1,14 +1,17 @@
use crate::deferred_image::{self, DeferredContent, DeferredImage};
use crate::renderer::{
ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, paint_draws_by_its_colors, painted_gradient,
spread_adjusted_samples, svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint,
};
use crate::{Render, RenderSvgSegmentList, SvgRender};
use core_types::blending::BlendMode;
use core_types::color::SRGBA8;
use core_types::list::List;
use core_types::uuid::generate_uuid;
use core_types::{ATTR_TRANSFORM, Color};
use glam::{DAffine2, DVec2};
use graphic_types::Graphic;
use graphic_types::resampling::frame_of_bounds;
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use std::fmt::Write;
use vector_types::Gradient;
@@ -39,13 +42,11 @@ impl PaintTarget {
pub trait RenderExt {
type Output;
/// `user_to_document` maps the user space the painted element sits in, before its `element_transform`, into the document, and the filters reading the element read it `paint_reach` past the view, in document pixels.
/// The `render` draws the painted element in its user space before the `element_transform`, taking the paint's defs and any images the GPU renders for it.
#[allow(clippy::too_many_arguments)]
fn render(
&self,
svg_defs: &mut String,
user_to_document: DAffine2,
paint_reach: f64,
render: &mut SvgRender,
item_transform: DAffine2,
element_transform: DAffine2,
stroke_transform: DAffine2,
@@ -72,9 +73,7 @@ impl RenderExt for List<Color> {
fn render(
&self,
_svg_defs: &mut String,
_user_to_document: DAffine2,
_paint_reach: f64,
_render: &mut SvgRender,
_item_transform: DAffine2,
_element_transform: DAffine2,
_stroke_transform: DAffine2,
@@ -199,12 +198,10 @@ fn render_gradient_paint(
impl RenderExt for List<Gradient> {
type Output = Option<u64>;
/// Adds the gradient def through mutating the first argument, returning the gradient ID, or `None` when the list is empty.
/// Adds the gradient def to the render's defs, returning the gradient ID, or `None` when the list is empty.
fn render(
&self,
svg_defs: &mut String,
_user_to_document: DAffine2,
_paint_reach: f64,
render: &mut SvgRender,
item_transform: DAffine2,
element_transform: DAffine2,
stroke_transform: DAffine2,
@@ -214,7 +211,7 @@ impl RenderExt for List<Gradient> {
) -> Self::Output {
render_gradient_paint(
(!self.is_empty()).then_some(ItemRef::ListItem(self, 0)),
svg_defs,
&mut render.svg_defs,
item_transform,
element_transform,
stroke_transform,
@@ -230,9 +227,7 @@ impl RenderExt for Stroke {
/// Provide the shape-related SVG attributes for the stroke. The paint-related attributes for the stroke are generated from `Graphic::render` with `PaintTarget::Stroke`.
fn render(
&self,
_svg_defs: &mut String,
_user_to_document: DAffine2,
_paint_reach: f64,
_render: &mut SvgRender,
_item_transform: DAffine2,
_element_transform: DAffine2,
_stroke_transform: DAffine2,
@@ -291,9 +286,7 @@ impl RenderExt for Graphic {
fn render(
&self,
svg_defs: &mut String,
user_to_document: DAffine2,
paint_reach: f64,
render: &mut SvgRender,
item_transform: DAffine2,
element_transform: DAffine2,
stroke_transform: DAffine2,
@@ -306,33 +299,21 @@ impl RenderExt for Graphic {
match self {
Graphic::Color(item) if by_colors => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
Graphic::ColorList(color_list) if by_colors => color_list.render(
svg_defs,
user_to_document,
paint_reach,
Graphic::ColorList(color_list) if by_colors => color_list.render(render, item_transform, element_transform, stroke_transform, bounds, render_params, target),
Graphic::Gradient(item) if by_colors => render_gradient_paint(
Some(ItemRef::Item(item)),
&mut render.svg_defs,
item_transform,
element_transform,
stroke_transform,
bounds,
render_params,
target,
),
Graphic::Gradient(item) if by_colors => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params.for_mask)
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
render_params.for_mask,
)
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
// One gradient resolves to a paint server; stacking several needs them composited, which only the pattern below can do
Graphic::GradientList(gradient_list) if by_colors => gradient_list
.render(
svg_defs,
user_to_document,
paint_reach,
item_transform,
element_transform,
stroke_transform,
bounds,
render_params,
target,
)
.render(render, item_transform, element_transform, stroke_transform, bounds, render_params, target)
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
Graphic::None(_) | Graphic::NoneList(_) => format!(r#" {paint_attr}="none""#),
@@ -363,8 +344,7 @@ impl RenderExt for Graphic {
} else {
bounds
};
let content_to_document = user_to_document * element_transform * stroke_transform;
render_svg_pattern(svg_defs, self, content_to_document, paint_reach, stroke_transform, bounds, render_params)
render_svg_pattern(render, self, element_transform * stroke_transform, stroke_transform, bounds, render_params)
.map(|id| format!(r##" {paint_attr}="url(#{id})""##))
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#))
}
@@ -372,18 +352,10 @@ impl RenderExt for Graphic {
}
}
/// Emits an SVG `<pattern>` paint server into `svg_defs` that renders the given graphic as the paint content, and returns the pattern ID.
/// Emits an SVG `<pattern>` paint server into the render's defs that renders the given graphic as the paint content, and returns the pattern ID.
/// Currently, this function is only used for clipping-based filling and stroking, not considering tiling yet.
/// `content_to_document` maps the paint's own space, which `stroke_transform` places inside the painted element's `element_transform`, into the document, and the filters reading the element read it `paint_reach` past the view.
fn render_svg_pattern(
svg_defs: &mut String,
paint: &Graphic,
content_to_document: DAffine2,
paint_reach: f64,
stroke_transform: DAffine2,
bounds: DAffine2,
render_params: &RenderParams,
) -> Option<String> {
/// `content_transform` places the paint's own space in the render's user space, where `stroke_transform` places it inside the painted element's transform.
fn render_svg_pattern(render: &mut SvgRender, paint: &Graphic, content_transform: DAffine2, stroke_transform: DAffine2, bounds: DAffine2, render_params: &RenderParams) -> Option<String> {
let min = bounds.transform_point2(DVec2::ZERO);
let max = bounds.transform_point2(DVec2::ONE);
let size = max - min;
@@ -392,12 +364,42 @@ fn render_svg_pattern(
}
// Render the pattern content recursively
let content_to_document = render.transform * content_transform;
let paint_params = render_params.for_pattern();
let mut content = SvgRender::new();
content.transform = content_to_document;
content.ancestors_reach = paint_reach;
paint.render_svg(&mut content, &render_params.for_pattern());
content.ancestors_reach = render.ancestors_reach;
paint.render_svg(&mut content, &paint_params);
let mut markup = content.svg.to_svg_string();
// A paint leaving out what only the GPU draws becomes the GPU's image of it, where something fills that
if content.paint_needs_gpu {
if render.drawing_deferred_markup || render_params.inside_pattern {
render.leave_out_for_gpu(render_params);
} else {
let id = generate_uuid();
render.deferred_images.push(DeferredImage {
id,
content: DeferredContent::Item(paint.clone()),
// Seen within the shape it fills, as Vello paints it
render_params: RenderParams {
paint_frame: Some(frame_of_bounds([min, max], content_to_document)),
..paint_params
},
user_to_document: content_to_document,
bounds: [min, max],
margin: render.ancestors_reach,
opacity: 1.,
blend_mode: BlendMode::Normal,
mask: None,
});
let (opening, closing) = deferred_image::image_markers(id);
markup = format!("{opening}{markup}{closing}");
}
}
// Unwrap the inner def element
let svg_defs = &mut render.svg_defs;
write!(svg_defs, "{}", content.svg_defs).unwrap();
let pattern_transform = stroke_transform * DAffine2::from_translation(min);
@@ -417,7 +419,7 @@ fn render_svg_pattern(
.unwrap();
let content_shift = format_transform_matrix(DAffine2::from_translation(-min));
write!(svg_defs, r##"<g transform="{content_shift}">{}</g></pattern>"##, content.svg.to_svg_string()).unwrap();
write!(svg_defs, r##"<g transform="{content_shift}">{markup}</g></pattern>"##).unwrap();
Some(pattern_id)
}
File diff suppressed because it is too large. Load diff
@@ -74,21 +74,32 @@ pub(super) fn holds_effects(graphic: &Graphic) -> bool {
}
}
/// Whether the graphic or anything nested in it is a GPU image, which SVG markup can't draw.
fn holds_gpu_image(graphic: &Graphic) -> bool {
/// Whether the graphic, anything nested in it, or any paint its appearance fills or strokes them with, is a GPU image or a generator, which only the GPU draws.
fn holds_gpu_content(graphic: &Graphic) -> bool {
fn paints_hold(appearance: Option<&Appearance>) -> bool {
appearance.is_some_and(|appearance| appearance.covers_with_paints().any(|(_, paint)| paint.is_some_and(holds_gpu_content)))
}
fn list_paints_hold<T>(list: &List<T>) -> bool {
(0..list.len()).any(|index| paints_hold(list.attribute(ATTR_APPEARANCE, index)))
}
match graphic {
Graphic::RasterGPU(_) => true,
Graphic::RasterGPU(_) | Graphic::Generator(_) => true,
Graphic::RasterGPUList(list) => !list.is_empty(),
Graphic::Graphic(item) => holds_gpu_image(item.element()),
Graphic::GraphicList(list) => list.iter_element_values().any(holds_gpu_image),
Graphic::GeneratorList(list) => !list.is_empty(),
Graphic::Graphic(item) => paints_hold(item.attribute(ATTR_APPEARANCE)) || holds_gpu_content(item.element()),
Graphic::GraphicList(list) => list_paints_hold(list) || list.iter_element_values().any(holds_gpu_content),
Graphic::Vector(item) => paints_hold(item.attribute(ATTR_APPEARANCE)),
Graphic::VectorList(list) => list_paints_hold(list),
Graphic::Text(item) => paints_hold(item.attribute(ATTR_APPEARANCE)),
Graphic::TextList(list) => list_paints_hold(list),
_ => false,
}
}
/// Whether SVG draws a blur's `radius_mask` as markup in its filter, keeping the blur resolution-independent, rather than taking its luminance as the GPU's map.
/// Markup embedded as an image reaches no maps of the radius mask's own effects.
pub(super) fn radius_mask_draws_as_markup(radius_mask: &Graphic) -> bool {
!holds_effects(radius_mask) && !holds_gpu_image(radius_mask)
/// Whether markup embedded as an image draws the graphic whole, which no map or image of the GPU's reaches, so it holds neither effects nor what only the GPU draws.
pub(super) fn draws_as_embedded_markup(graphic: &Graphic) -> bool {
!holds_effects(graphic) && !holds_gpu_content(graphic)
}
/// A mask's graphic placed by its content's `placement`, which it follows.
@@ -187,8 +198,7 @@ pub(super) fn write_endless_content_mask(render: &mut SvgRender, effects: &Effec
mask_render.transform = render.transform;
mask_render.ancestors_reach = render.ancestors_reach + feather_reach;
mask.render_svg(&mut mask_render, &live_params);
render.effect_maps.append(&mut mask_render.effect_maps);
render.deferred_images.append(&mut mask_render.deferred_images);
render.take_gpu_images(&mut mask_render, render_params);
let markup = format!("<defs>{}</defs>{}", mask_render.svg_defs, mask_render.svg.to_svg_string());
let sigma = svg_feather_sigma(feather, length_scale);
@@ -7,6 +7,8 @@ use graphic_types::effects::{EffectCapture, GRADIENT_TABLE_SIZE, GlowFill};
pub(super) enum OutlineBandColors {
/// The markup of a drawn paint.
Drawn(String),
/// A drawn paint that embedding its markup as an image can't draw whole, which the GPU's map gives.
DrawnOnGpu,
ContourGradient(GlowFill),
/// The primitive holding the colors, once made.
Made(String),
@@ -18,6 +20,10 @@ impl SvgFilterPrimitives {
let made = match colors {
OutlineBandColors::Made(made) => return made.clone(),
OutlineBandColors::Drawn(markup) => self.paint_image(markup, region),
OutlineBandColors::DrawnOnGpu => self.map(EffectCapture {
index,
plane: EffectCapture::DRAWN_PAINT_PLANE,
}),
OutlineBandColors::ContourGradient(gradient) => {
let positions = self.map(EffectCapture { index, plane: 2 });
self.contour_gradient_colors(&positions, gradient)
@@ -219,7 +219,7 @@ impl SvgRender {
/// Whether the markup drawn since the backdrop `root` draws through canvases, as images and the GPU's images of content do in the viewport the `render_params` draw in,
/// even where the content reading it embeds its own images. O(segments drawn since the root).
fn draws_canvases_since(&self, root: usize, render_params: &RenderParams) -> bool {
let in_viewport = !(render_params.for_export || render_params.thumbnail || render_params.for_mask || render_params.inside_pattern);
let in_viewport = !(render_params.for_export || render_params.for_mask || render_params.inside_pattern);
let start = self.open_groups.groups[root].content_start;
let draws_canvas = |segment: &SvgSegment| segment.as_str().contains("data-canvas-placeholder") || deferred_image::holds_image_markers(segment.as_str());
in_viewport && self.svg[start..].iter().any(draws_canvas)
@@ -41,6 +41,7 @@ fastnoise-lite = { workspace = true, features = ["wgsl"] }
[dev-dependencies]
# Local dependencies
graphene-resource = { workspace = true }
svg-convert = { workspace = true }
# Required dependencies
# Turns on the shader translators of every backend for the tests, whichever of them the platform's own backends build with
@@ -1,64 +1,133 @@
use crate::WgpuExecutor;
use core_types::ops::ConvertAsync;
use core_types::transform::Footprint;
use raster_types::{CPU, Raster, Texture};
use raster_types::{Raster, Texture};
use rendering::CanvasImage;
use rendering::deferred_image::{DeferredImage, DeferredImagePlacement, EffectMap, EffectMapPlacement, MAX_DEFERRED_IMAGE_PIXELS, substitute_deferred_image, substitute_effect_map};
impl WgpuExecutor {
/// Renders the maps of effects' coverages that an SVG of the view `footprint` takes, with where its filters place each.
/// Maps out of view, or that fail to render, keep their placeholders.
pub fn render_effect_maps(&self, effect_maps: &[EffectMap], footprint: Footprint) -> Vec<(EffectMapPlacement, Texture)> {
let max_pixels = MAX_DEFERRED_IMAGE_PIXELS.min(self.context().device.limits().max_texture_dimension_2d);
/// The maps and images the GPU rendered for the placeholders of an SVG, with the first failure to render one in view, whose placeholder stays.
pub struct SvgPlaceholderRenders {
effect_maps: Vec<(EffectMapPlacement, Texture)>,
deferred_images: Vec<(DeferredImagePlacement, Texture)>,
failure: Option<anyhow::Error>,
}
effect_maps
impl SvgPlaceholderRenders {
/// Whether nothing was rendered and nothing failed to, as when every placeholder is out of view.
pub fn is_empty(&self) -> bool {
self.effect_maps.is_empty() && self.deferred_images.is_empty() && self.failure.is_none()
}
}
/// Whether any of the maps and images an SVG of the view `footprint` takes from the GPU lie in view, needing a GPU to fill their placeholders.
pub fn svg_placeholders_in_view(effect_maps: &[EffectMap], deferred_images: &[DeferredImage], footprint: Footprint) -> bool {
let (document_to_view, view_size) = (footprint.transform, footprint.resolution.as_dvec2());
effect_maps.iter().any(|map| map.layout(document_to_view, view_size, MAX_DEFERRED_IMAGE_PIXELS).is_some())
|| deferred_images.iter().any(|deferred| deferred.layout(document_to_view, view_size, MAX_DEFERRED_IMAGE_PIXELS).is_some())
}
/// Logs the `error`, keeping it as the `failure` if it's the first.
fn record_failure(failure: &mut Option<anyhow::Error>, error: anyhow::Error) {
log::error!("{error:#}");
failure.get_or_insert(error);
}
impl WgpuExecutor {
/// Renders the maps and images an SVG of the view `footprint` takes from the GPU. Those out of view keep their placeholders.
pub fn render_svg_placeholders(&self, effect_maps: &[EffectMap], deferred_images: &[DeferredImage], footprint: Footprint) -> SvgPlaceholderRenders {
let max_pixels = MAX_DEFERRED_IMAGE_PIXELS.min(self.context().device.limits().max_texture_dimension_2d);
let mut failure = None;
let effect_maps = effect_maps
.iter()
.filter_map(|map| {
let layout = map.layout(footprint.transform, footprint.resolution.as_dvec2(), max_pixels)?;
match self.render_vello(layout.size, layout.document_to_pixels, &mut |scene| map.draw(scene, &layout)) {
Ok(texture) => Some((layout.placement, texture)),
Err(error) => {
log::error!("Failed to render a map of an effect's coverage for an SVG filter: {error}");
record_failure(&mut failure, error.context("Failed to render a map of an effect's coverage for an SVG filter"));
None
}
}
})
.collect()
}
.collect();
/// Reads back the maps of effects' coverages, putting each in `svg` in place of its placeholder.
pub async fn resolve_effect_maps(&self, svg: &mut String, maps: Vec<(EffectMapPlacement, Texture)>) {
for (placement, texture) in maps {
let map: Raster<CPU> = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, self.clone()).await;
substitute_effect_map(svg, &placement, &map);
}
}
/// Renders images of the content an SVG of the view `footprint` describes defers to the GPU, with where the SVG draws each.
/// Content out of view, or that fails to render, keeps the markup standing in for it.
pub fn render_deferred_svg_images(&self, deferred_images: &[DeferredImage], footprint: Footprint) -> Vec<(DeferredImagePlacement, Texture)> {
let max_pixels = MAX_DEFERRED_IMAGE_PIXELS.min(self.context().device.limits().max_texture_dimension_2d);
deferred_images
let deferred_images = deferred_images
.iter()
.filter_map(|deferred| {
let layout = deferred.layout(footprint.transform, footprint.resolution.as_dvec2(), max_pixels)?;
match self.render_vello(layout.size, layout.document_to_pixels, &mut |scene| deferred.draw(scene, &layout)) {
Ok(texture) => Some((layout.placement, texture)),
Err(error) => {
log::error!("Failed to render an image of content with effects SVG can't express: {error}");
record_failure(&mut failure, error.context("Failed to render an image of content SVG can't draw"));
None
}
}
})
.collect()
}
.collect();
/// Reads back the images of deferred content, putting each in `svg` in place of the markup standing in for its content.
pub async fn resolve_deferred_svg_images(&self, svg: &mut String, image_data: &mut Vec<(u64, CanvasImage)>, images: Vec<(DeferredImagePlacement, Texture)>) {
for (placement, texture) in images {
let image: Raster<CPU> = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, self.clone()).await;
substitute_deferred_image(svg, image_data, &placement, &image);
SvgPlaceholderRenders {
effect_maps,
deferred_images,
failure,
}
}
/// Reads back the `renders`, putting each in `svg` in place of its placeholder. Images drawn to canvases are added to `image_data`.
/// Fails with the first map or image that failed to render or read back, after putting in place all that didn't.
pub async fn substitute_svg_placeholders(&self, svg: &mut String, image_data: &mut Vec<(u64, CanvasImage)>, renders: SvgPlaceholderRenders) -> anyhow::Result<()> {
let SvgPlaceholderRenders {
effect_maps,
deferred_images,
failure,
} = renders;
let maps_failure = self.resolve_effect_maps(svg, effect_maps).await.err();
let images_failure = self.resolve_deferred_svg_images(svg, image_data, deferred_images).await.err();
match failure.or(maps_failure).or(images_failure) {
Some(failure) => Err(failure),
None => Ok(()),
}
}
/// Renders the maps of effects' coverages that an SVG of the view `footprint` takes, with where its filters place each.
/// Maps out of view, or that fail to render, keep their placeholders.
pub fn render_effect_maps(&self, effect_maps: &[EffectMap], footprint: Footprint) -> Vec<(EffectMapPlacement, Texture)> {
self.render_svg_placeholders(effect_maps, &[], footprint).effect_maps
}
/// Reads back the maps of effects' coverages, putting each in `svg` in place of its placeholder.
/// Fails with the first that fails to read back, after putting in place all that didn't.
async fn resolve_effect_maps(&self, svg: &mut String, maps: Vec<(EffectMapPlacement, Texture)>) -> anyhow::Result<()> {
let mut failure = None;
for (placement, texture) in maps {
match self.try_download(Raster::new_gpu(texture)).await {
Ok(map) => substitute_effect_map(svg, &placement, &map),
Err(error) => {
record_failure(&mut failure, error.context("Failed to read back a map of an effect's coverage for an SVG filter"));
}
}
}
failure.map_or(Ok(()), Err)
}
/// Renders images of the content an SVG of the view `footprint` describes defers to the GPU, with where the SVG draws each.
/// Content out of view, or that fails to render, keeps the markup standing in for it.
pub fn render_deferred_svg_images(&self, deferred_images: &[DeferredImage], footprint: Footprint) -> Vec<(DeferredImagePlacement, Texture)> {
self.render_svg_placeholders(&[], deferred_images, footprint).deferred_images
}
/// Reads back the images of deferred content, putting each in `svg` in place of the markup standing in for its content. Images drawn to canvases are added to `image_data`.
/// Fails with the first that fails to read back, after putting in place all that didn't.
pub async fn resolve_deferred_svg_images(&self, svg: &mut String, image_data: &mut Vec<(u64, CanvasImage)>, images: Vec<(DeferredImagePlacement, Texture)>) -> anyhow::Result<()> {
let mut failure = None;
for (placement, texture) in images {
match self.try_download(Raster::new_gpu(texture)).await {
Ok(image) => substitute_deferred_image(svg, image_data, &placement, &image),
Err(error) => {
record_failure(&mut failure, error.context("Failed to read back an image of content SVG can't draw"));
}
}
}
failure.map_or(Ok(()), Err)
}
}
@@ -23,6 +23,7 @@ use wgpu::util::DeviceExt;
pub use buffer::Buffer;
pub use context::Context as WgpuContext;
pub use context::ContextBuilder as WgpuContextBuilder;
pub use deferred_svg_images::{SvgPlaceholderRenders, svg_placeholders_in_view};
pub use pipeline::Pipeline as WgpuPipeline;
pub use pipeline::PipelineCache as WgpuPipelineCache;
pub use pipeline::PipelineError as WgpuPipelineError;
@@ -622,6 +622,9 @@ impl EffectPasses {
},
_ => None,
};
if let Some(paint) = drawn_paint {
capture_plane(&mut recorder, EffectCapture::DRAWN_PAINT_PLANE, paint, true);
}
let (outside, inside) = outline_extents(weight * length_scale, align);
let contour_span = matches!(outline_fill, OutlineFill::ContourGradient(_))
@@ -792,6 +795,7 @@ impl EffectPasses {
}
EffectOperation::PaintOverlay { blend_mode, opacity, .. } => {
let Some(paint) = paints.next() else { continue };
capture_plane(&mut recorder, EffectCapture::DRAWN_PAINT_PLANE, paint, true);
let painted = recorder.scale(paint, (opacity / 100.) as f32);
recorder.place_within(layered.then_some((&mut pieces, piece(0))), content, &mut full, &mut filled, painted, None, blend_mode);
}
@@ -6903,7 +6903,7 @@ fn svgs_draw_content_with_effects_svg_cannot_express_as_images_the_gpu_renders()
// Its image replaces the markup standing in for it
let mut svg = render.svg.to_svg_string();
futures::executor::block_on(executor.resolve_deferred_svg_images(&mut svg, &mut Vec::new(), rendered));
futures::executor::block_on(executor.resolve_deferred_svg_images(&mut svg, &mut Vec::new(), rendered)).expect("the image reads back");
assert!(svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"), "{svg}");
}
@@ -8507,7 +8507,7 @@ fn svgs_draw_warps_on_groups_of_endless_content_as_the_gpu_does_masking_them_onc
// Nothing in the SVG masks the image again
let mut svg = render.svg.to_svg_string();
futures::executor::block_on(executor.resolve_deferred_svg_images(&mut svg, &mut Vec::new(), rendered));
futures::executor::block_on(executor.resolve_deferred_svg_images(&mut svg, &mut Vec::new(), rendered)).expect("the image reads back");
assert!(svg.contains("data:image/png;base64,") && !svg.contains("mask="), "{effects:?} draws {svg}");
}
}
@@ -12777,3 +12777,361 @@ fn blend_ifs_fade_a_layer_once_it_blends_by_a_mode_vello_lacks() {
}
}
}
/// The pixels of each image the GPU renders for an SVG's deferred content in the `view`, with the transform placing its unit square where its placeholder sits.
fn svg_image_pixels(executor: &WgpuExecutor, render: &rendering::SvgRender, view: core_types::transform::Footprint) -> Vec<(DAffine2, UVec2, Vec<u8>)> {
let _turn = take_turn();
let rendered = executor.render_deferred_svg_images(&render.deferred_images, view);
rendered
.iter()
.map(|(placement, texture)| {
let pixels = executor.read_texture_pixels(texture).expect("Failed to read back the image");
(placement.transform, UVec2::new(texture.width(), texture.height()), pixels)
})
.collect()
}
#[test]
fn svg_generators_are_placeholders_the_gpu_fills_as_vello_draws_them() {
use core_types::ATTR_TRANSFORM;
use core_types::list::{Item, List};
use core_types::transform::Footprint;
use glam::DVec2;
use graphic_types::{Generator, Graphic};
use rendering::deferred_image::DeferredContent;
use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
let Some(executor) = executor() else { return };
// Noise turned and scaled across a 64 pixel view
let mut generator = Item::new_from_element(Generator::Noise).with_attribute(ATTR_TRANSFORM, DAffine2::from_angle(0.3) * DAffine2::from_scale(DVec2::splat(1.5)));
noise_settings().stamp(&mut generator);
let generators = List::new_from_item(generator);
let size = UVec2::splat(64);
let view = Footprint {
transform: DAffine2::IDENTITY,
resolution: size,
..Default::default()
};
// SVG draws none of the pattern's pixels itself, only markers standing for the GPU's image of it
let mut render = SvgRender::new();
let export = RenderParams {
for_export: true,
view: Some(view),
..Default::default()
};
generators.render_svg(&mut render, &export);
let svg = render.svg.to_svg_string();
assert!(svg.contains("<!--deferred-image-") && !svg.contains("<image"), "{svg}");
assert!(matches!(render.deferred_images[..], [ref image] if matches!(image.content, DeferredContent::Item(Graphic::Generator(_)))));
// The image covers the view pixel for pixel, holding what Vello draws of the generator there
let [(placement, image_size, image_pixels)] = &svg_image_pixels(executor, &render, view)[..] else {
panic!("expected one image")
};
assert_eq!((*placement, *image_size), (DAffine2::from_scale(size.as_dvec2()), size));
let Some(drawn) = render_in_view(size, DAffine2::IDENTITY, |scene| generators.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
let worst = image_pixels.iter().zip(drawn.as_flattened()).map(|(image, drawn)| image.abs_diff(*drawn)).max().unwrap_or(0);
assert!(worst <= 1, "the image differs from Vello's render by up to {worst} levels");
// Read back, the image replaces its markers
let mut svg = svg;
let renders = executor.render_svg_placeholders(&render.effect_maps, &render.deferred_images, view);
futures::executor::block_on(executor.substitute_svg_placeholders(&mut svg, &mut Vec::new(), renders)).expect("the maps and images read back");
assert!(svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"), "{svg}");
}
#[test]
fn svg_paints_with_effects_needing_the_gpu_fill_their_patterns_with_its_render() {
use core_types::Color as GraphicColor;
use core_types::list::{ATTR_APPEARANCE, List};
use core_types::transform::Footprint;
use glam::DVec2;
use graphic_types::vector_types::vector::style::StrokeAlign;
use graphic_types::{Appearance, Coverage, Effect, EffectOperation, Graphic, Vector, stamp_effect};
use rendering::deferred_image::DeferredContent;
use rendering::{Render, RenderParams, SvgRender};
use vello_gpu::kurbo::Shape;
let Some(executor) = executor() else { return };
let filled = |rect: Rect, paint: Graphic| {
let mut item = Vector::item_from_bezpath(&rect.to_path(0.1));
item.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), paint));
item
};
let size = UVec2::splat(64);
let view = Footprint {
transform: DAffine2::IDENTITY,
resolution: size,
..Default::default()
};
let export = RenderParams {
for_export: true,
view: Some(view),
..Default::default()
};
// A view-filling rectangle painted with a white square at its middle, edged by a 4 pixel outside outline or a shadow cast 4 pixels left
let outline = EffectOperation::Outline {
paint: GraphicColor::BLACK.into(),
blend_mode: BlendMode::Normal,
weight: 4.,
align: StrokeAlign::Outside,
contour_gradient: false,
};
for (name, effect) in [("outline", outline), ("shadow", drop_shadow(GraphicColor::BLACK, DVec2::new(-4., 0.), 0., 0.))] {
let mut square = filled(Rect::new(20., 20., 44., 44.), Graphic::ColorList(List::new_from_element(GraphicColor::WHITE)));
stamp_effect(&mut square, Effect::new(&effect));
let paint = Graphic::VectorList(List::new_from_item(square));
let shape = List::new_from_item(filled(Rect::new(0., 0., 64., 64.), paint));
// The paint's pattern holds markers standing for the GPU's image of the whole paint, which no map of its effect could reach inside the pattern
let mut render = SvgRender::new();
shape.render_svg(&mut render, &export);
let [image] = &render.deferred_images[..] else {
panic!("{name}: expected the paint's image, got {}", render.deferred_images.len())
};
assert!(matches!(image.content, DeferredContent::Item(Graphic::VectorList(_))), "{name}");
let pattern = render.svg_defs.split("<pattern").nth(1).unwrap_or_default();
assert!(pattern.contains("<!--deferred-image-") && render.effect_maps.is_empty(), "{name}: {}", render.svg_defs);
// The image draws the effect 2 pixels left of the square, beside the white within it, as Vello draws the shape
let [(placement, image_size, image_pixels)] = &svg_image_pixels(executor, &render, view)[..] else {
panic!("{name}: expected one image")
};
assert_eq!((*placement, *image_size), (DAffine2::from_scale(size.as_dvec2()), size), "{name}");
let image_pixel = |x: u32, y: u32| pixel(image_pixels.as_chunks::<4>().0, size, x, y);
assert_eq!(image_pixel(18, 32), [0, 0, 0, 255], "{name} beside the square");
assert_eq!(image_pixel(32, 32), [255, 255, 255, 255], "{name}: the square");
let Some(drawn) = render_in_view(size, DAffine2::IDENTITY, |scene| shape.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
let worst = image_pixels.iter().zip(drawn.as_flattened()).map(|(image, drawn)| image.abs_diff(*drawn)).max().unwrap_or(0);
assert!(worst <= 1, "{name}: the image differs from Vello's render of the shape by up to {worst} levels");
}
}
#[test]
fn svg_paint_overlays_and_outlines_take_paints_only_the_gpu_draws_as_its_maps() {
use core_types::Color as GraphicColor;
use core_types::list::{ATTR_APPEARANCE, Item, List};
use core_types::transform::Footprint;
use graphic_types::effects::EffectCapture;
use graphic_types::vector_types::vector::style::StrokeAlign;
use graphic_types::{Appearance, Coverage, Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect};
use rendering::{Render, RenderParams, SvgRender};
use vello_gpu::kurbo::Shape;
let Some(executor) = executor() else { return };
let mut generator = Item::new_from_element(Generator::Noise);
noise_settings().stamp(&mut generator);
let noise = Graphic::GeneratorList(List::new_from_item(generator));
let size = UVec2::splat(64);
let view = Footprint {
transform: DAffine2::IDENTITY,
resolution: size,
..Default::default()
};
let export = RenderParams {
for_export: true,
view: Some(view),
..Default::default()
};
// A white square painted over by the noise, or outlined with it, which embedded markup can't draw
let overlay = EffectOperation::PaintOverlay {
paint: noise.clone(),
blend_mode: BlendMode::Normal,
opacity: 100.,
};
let outline = EffectOperation::Outline {
paint: noise.clone(),
blend_mode: BlendMode::Normal,
weight: 4.,
align: StrokeAlign::Outside,
contour_gradient: false,
};
let Some(drawn_noise) = render_in_view(size, DAffine2::IDENTITY, |scene| noise.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
for (name, effect) in [("paint overlay", overlay), ("outline", outline)] {
let mut square = Vector::item_from_bezpath(&Rect::new(20., 20., 44., 44.).to_path(0.1));
square.set_attribute(
ATTR_APPEARANCE,
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(GraphicColor::WHITE))),
);
stamp_effect(&mut square, Effect::new(&effect));
let mut render = SvgRender::new();
List::new_from_item(square).render_svg(&mut render, &export);
// The filter takes the paint as the GPU's map of it, which holds the noise as Vello draws it
let paint_maps: Vec<_> = render.effect_maps.iter().filter(|map| map.capture.plane == EffectCapture::DRAWN_PAINT_PLANE).cloned().collect();
assert_eq!(paint_maps.len(), 1, "{name}: {}", render.svg_defs);
assert!(!render.svg_defs.contains("data:image/svg+xml"), "{name} embeds no markup of the paint: {}", render.svg_defs);
let (placement, texture) = {
let _turn = take_turn();
let rendered = executor.render_effect_maps(&paint_maps, view);
let [(placement, texture)] = &rendered[..] else { panic!("{name}: expected one map") };
(placement.transform, texture.clone())
};
let map_pixels = executor.read_texture_pixels(&texture).unwrap();
let map_size = UVec2::new(texture.width(), texture.height());
let origin = placement.transform_point2(glam::DVec2::ZERO).round().as_uvec2();
for (x, y) in [(32, 32), (24, 40), (40, 22)] {
let mapped = pixel(map_pixels.as_chunks::<4>().0, map_size, x - origin.x, y - origin.y);
let expected = pixel(&drawn_noise, size, x, y);
assert!(mapped.iter().zip(expected).all(|(&a, b)| a.abs_diff(b) <= 1), "{name} at ({x}, {y}): {mapped:?} against {expected:?}");
}
}
}
/// What Vello draws in the `view` of the SVG export of `content`, finished as an export is with the GPU's renders in place of its placeholders, then read back in as graphics.
fn finished_svg_drawn(executor: &WgpuExecutor, content: &impl rendering::Render, view: core_types::transform::Footprint) -> Option<Vec<[u8; 4]>> {
use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
let export = RenderParams {
for_export: true,
view: Some(view),
..Default::default()
};
let mut render = SvgRender::new();
content.render_svg(&mut render, &export);
let (effect_maps, deferred_images) = (render.effect_maps.clone(), render.deferred_images.clone());
render.wrap_with_transform(view.transform, Some(view.resolution.as_dvec2()));
let mut svg = render.svg.to_svg_string();
let renders = {
let _turn = take_turn();
executor.render_svg_placeholders(&effect_maps, &deferred_images, view)
};
futures::executor::block_on(executor.substitute_svg_placeholders(&mut svg, &mut Vec::new(), renders)).expect("the maps and images read back");
assert!(svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"), "the placeholders should be filled: {svg}");
let graphics = svg_convert::convert(&svg, &svg_convert::Options::default()).expect("the finished SVG should parse");
render_in_view(view.resolution, DAffine2::IDENTITY, |scene| {
graphics.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())
})
}
/// How many of the pixels a finished SVG draws differ from those Vello `drawn` by more than `tolerance` in any channel, with the largest difference.
/// Pixels Vello covers only partly are left out, since the shapes clipping the SVG's paints cover the edges in another way.
fn pixels_differing(finished: &[[u8; 4]], drawn: &[[u8; 4]], tolerance: u8) -> (usize, u8) {
let compared = finished.iter().zip(drawn).filter(|(_, drawn)| [0, 255].contains(&drawn[3]));
let differences = compared.map(|(finished, drawn)| finished.iter().zip(drawn).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0));
differences.fold((0, 0), |(count, worst), difference| (count + usize::from(difference > tolerance), worst.max(difference)))
}
#[test]
fn svg_paints_the_gpu_draws_whole_keep_the_frame_of_the_shape_they_fill() {
use core_types::Color as GraphicColor;
use core_types::list::{ATTR_APPEARANCE, Item, List};
use core_types::transform::Footprint;
use glam::DVec2;
use graphic_types::vector_types::gradient::{Gradient, GradientStop};
use graphic_types::{Appearance, Coverage, Effect, EffectOperation, Graphic, Vector, stamp_effect};
use rendering::deferred_image::DeferredContent;
use rendering::{Render, RenderParams, SvgRender};
use vello_gpu::kurbo::Shape;
let Some(executor) = executor() else { return };
// A gradient pixelated in a group, which SVG takes as the GPU's image of the whole paint, filling a square turned and partly out of view
let stops = [(0., GraphicColor::RED), (1., GraphicColor::BLUE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
let mut gradient = Item::new_from_element(Gradient::new(stops)).with_attribute(core_types::ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(60.)));
stamp_effect(&mut gradient, Effect::new(&EffectOperation::Pixelate { cell_size: 7., offset: DVec2::ZERO }));
let paint = Graphic::GraphicList(List::new_from_element(Graphic::Gradient(gradient)));
let mut square = Vector::item_from_bezpath(&Rect::new(0., 0., 60., 60.).to_path(0.1));
square.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), paint));
square.set_attribute(core_types::ATTR_TRANSFORM, DAffine2::from_translation(DVec2::new(30., -10.)) * DAffine2::from_angle(0.4));
let shape = List::new_from_item(square);
let view = Footprint {
transform: DAffine2::IDENTITY,
resolution: UVec2::splat(64),
..Default::default()
};
let mut render = SvgRender::new();
let export = RenderParams {
for_export: true,
view: Some(view),
..Default::default()
};
shape.render_svg(&mut render, &export);
let [image] = &render.deferred_images[..] else {
panic!("expected the paint's image, got {}: {}", render.deferred_images.len(), render.svg_defs)
};
assert!(matches!(image.content, DeferredContent::Item(Graphic::GraphicList(_))), "{}", render.svg_defs);
// The finished SVG draws the cells where Vello does, clipped to the square
let Some(finished) = finished_svg_drawn(executor, &shape, view) else { return };
let Some(drawn) = render_in_view(view.resolution, DAffine2::IDENTITY, |scene| shape.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
let (differing, worst) = pixels_differing(&finished, &drawn, 2);
assert_eq!(differing, 0, "pixels differ from Vello's render, by up to {worst} levels");
}
#[test]
fn svg_gpu_images_draw_as_the_gpus_render_alone_or_as_paints() {
use core_types::list::{ATTR_APPEARANCE, Item, List};
use core_types::transform::Footprint;
use glam::DVec2;
use graphic_types::raster_types::Raster;
use graphic_types::{Appearance, Coverage, Graphic, Vector};
use rendering::{Render, RenderParams};
use vello_gpu::kurbo::Shape;
use wgpu::util::DeviceExt;
let Some(executor) = executor() else { return };
// A 2 by 2 image of four colors, which only the GPU holds
let descriptor = wgpu::TextureDescriptor {
label: Some("svg_gpu_image_test"),
size: wgpu::Extent3d {
width: 2,
height: 2,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
};
let texels = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 255]];
let texture = {
let _turn = take_turn();
let queue = executor.context().queue.lock();
(executor.context().device).create_texture_with_data(&queue, &descriptor, wgpu::util::TextureDataOrder::LayerMajor, texels.as_flattened())
};
let image = Item::new_from_element(Raster::new_gpu(texture)).with_attribute(core_types::ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(8.)) * DAffine2::from_scale(DVec2::splat(48.)));
let image = Graphic::RasterGPUList(List::new_from_item(image));
// Drawn alone, and as the paint of a disc it's clipped to
let mut disc = Vector::item_from_bezpath(&vello_gpu::kurbo::Circle::new((32., 32.), 20.).to_path(0.1));
disc.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), image.clone()));
let view = Footprint {
transform: DAffine2::IDENTITY,
resolution: UVec2::splat(64),
..Default::default()
};
for (name, content) in [
("alone", List::new_from_element(image)),
("as a paint", List::new_from_element(Graphic::VectorList(List::new_from_item(disc)))),
] {
let Some(finished) = finished_svg_drawn(executor, &content, view) else { return };
let Some(drawn) = render_in_view(view.resolution, DAffine2::IDENTITY, |scene| {
content.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())
}) else {
return;
};
let (differing, worst) = pixels_differing(&finished, &drawn, 2);
assert_eq!(differing, 0, "{name}: pixels differ from Vello's render, by up to {worst} levels");
}
}
@@ -47,7 +47,6 @@ pub struct CacheKey {
pub rotation: u64,
pub for_export: bool,
pub for_mask: bool,
pub thumbnail: bool,
pub aligned_strokes: bool,
pub stroke_below: bool,
pub animation_time_ms: i64,
@@ -64,7 +63,6 @@ impl CacheKey {
rotation: f64,
for_export: bool,
for_mask: bool,
thumbnail: bool,
aligned_strokes: bool,
stroke_below: bool,
animation_time: f64,
@@ -89,7 +87,6 @@ impl CacheKey {
rotation: quantized_rotation.to_bits(),
for_export,
for_mask,
thumbnail,
aligned_strokes,
stroke_below,
animation_time_ms: (animation_time * 1000.).round() as i64,
@@ -418,7 +415,6 @@ fn render_output_cache(
rotation,
render_params.for_export,
render_params.for_mask,
render_params.thumbnail,
render_params.aligned_strokes,
render_params.stroke_below,
ctx.try_animation_time().unwrap_or(0.),
+8 -6
View File
@@ -12,7 +12,7 @@ use graphic_types::{Artboard, Graphic, Vector};
use rendering::vello_scene_builder::VelloSceneBuilder;
use rendering::{Render, RenderMetadata, RenderOutputType as RenderOutputTypeRequest, RenderParams, SvgRender, SvgRenderOutput};
use std::sync::Arc;
use svg_readback::SvgReadbackSlot;
use svg_readback::{SvgInViewSlot, SvgReadbackSlot};
use vector_types::Gradient;
use wgpu_executor::WgpuExecutor;
@@ -91,6 +91,7 @@ fn render(
#[scope("runtime")] runtime: Item<RuntimeHandle>,
#[source_id] source: Item<SourceId>,
#[data] svg_readback: SvgReadbackSlot,
#[data] svg_in_view: SvgInViewSlot,
) -> Poll<Item<RenderOutput>> {
let footprint = ctx.footprint();
let render_params = ctx
@@ -105,15 +106,16 @@ fn render(
// Content drawing only the part of it in view draws its markup for this view
let ty = match ty {
RenderIntermediateType::SvgInView(content) => {
let mut render = SvgRender::new();
let in_view = RenderParams {
view: Some(*footprint),
..render_params.clone()
};
content.render_svg(&mut render, &in_view);
RenderIntermediateType::Svg(Arc::new(render.into()))
RenderIntermediateType::Svg(svg_in_view.render(&content, &in_view))
}
ty => {
svg_in_view.clear();
ty
}
ty => ty,
};
let mut render_params = render_params.clone();
@@ -131,7 +133,7 @@ fn render(
assert!(output.svg_defs.is_empty());
let executor = executor.eval(&Context::default()).value().map(Item::into_element);
svg_readback.poll(output, *footprint, executor, runtime.element(), *source.element())
svg_readback.poll(output, *footprint, executor, render_params.for_export, runtime.element(), *source.element())
}
(RenderOutputTypeRequest::Vello, RenderIntermediateType::Vello(data)) => {
// The latest SVG render isn't needed anymore, and a finished one holds a whole SVG export
@@ -3,10 +3,61 @@ use core_types::transform::Footprint;
use core_types::{CacheHash, Poll, RuntimeHandle, SourceId};
use futures::future::{AbortHandle, Abortable};
use graph_craft::document::value::RenderOutputType;
use rendering::SvgRenderOutput;
use rendering::{Render, RenderParams, SvgRender, SvgRenderOutput};
use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use wgpu_executor::WgpuExecutor;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use wgpu_executor::{NoGpuError, WgpuExecutor, svg_placeholders_in_view};
/// The latest SVG of content drawing only the part of it in view, which evaluations for the same content and view (like those its readbacks wake) reuse,
/// keeping the IDs of its placeholders as content drawing all of itself keeps those of its cached intermediate SVG.
#[derive(Clone, Debug, Default)]
pub struct SvgInViewSlot(Arc<Mutex<Option<SvgInView>>>);
struct SvgInView {
content: Weak<dyn Render + Send + Sync>,
/// Hashes the render parameters, which hold the view.
key: u64,
output: Arc<SvgRenderOutput>,
}
impl std::fmt::Debug for SvgInView {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.debug_struct("SvgInView").field("key", &self.key).finish_non_exhaustive()
}
}
impl SvgInViewSlot {
fn lock(&self) -> MutexGuard<'_, Option<SvgInView>> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Drops the latest SVG.
pub fn clear(&self) {
*self.lock() = None;
}
/// The SVG of the `content` drawn with the `render_params` that give it its view, drawn again only for other content or parameters.
pub fn render(&self, content: &Arc<dyn Render + Send + Sync>, render_params: &RenderParams) -> Arc<SvgRenderOutput> {
let mut hasher = DefaultHasher::new();
render_params.cache_hash(&mut hasher);
let key = hasher.finish();
let mut latest = self.lock();
if let Some(latest) = latest.as_ref().filter(|latest| latest.key == key && Weak::ptr_eq(&latest.content, &Arc::downgrade(content))) {
return latest.output.clone();
}
let mut render = SvgRender::new();
content.render_svg(&mut render, render_params);
let output = Arc::new(SvgRenderOutput::from(render));
*latest = Some(SvgInView {
content: Arc::downgrade(content),
key,
output: output.clone(),
});
output
}
}
/// The latest SVG render that needs maps and images from the GPU, kept across the render node's evaluations while a task reads them back.
/// A render of other content or for another view replaces it, cancelling the readback still underway for the one it replaced.
@@ -16,13 +67,16 @@ pub struct SvgReadbackSlot(Arc<Mutex<Option<SvgReadback>>>);
#[derive(Debug)]
struct SvgReadback {
key: u64,
finished: Option<RenderOutputType>,
task: AbortHandle,
finished: Option<Poll<RenderOutputType>>,
/// The task reading the maps and images back, which there's none of without a GPU.
task: Option<AbortHandle>,
}
impl Drop for SvgReadback {
fn drop(&mut self) {
self.task.abort();
if let Some(task) = &self.task {
task.abort();
}
}
}
@@ -37,8 +91,8 @@ impl SvgReadbackSlot {
}
/// The SVG `output` with the maps and images the GPU renders for it in place of their placeholders, partial with the placeholders while a task reads them back.
/// The task landing evaluates the render node again through its `source`.
pub fn poll(&self, output: SvgRenderOutput, footprint: Footprint, executor: Option<WgpuExecutor>, runtime: &RuntimeHandle, source: SourceId) -> Poll<RenderOutputType> {
/// The task landing evaluates the render node again through its `source`. Placeholders in view left unfilled fail the render if it's `for_export`.
pub fn poll(&self, output: SvgRenderOutput, footprint: Footprint, executor: Option<WgpuExecutor>, for_export: bool, runtime: &RuntimeHandle, source: SourceId) -> Poll<RenderOutputType> {
let svg = output.svg;
let image_data: Vec<_> = output.image_data.into_iter().collect();
@@ -51,27 +105,46 @@ impl SvgReadbackSlot {
let mut hasher = DefaultHasher::new();
svg.hash(&mut hasher);
footprint.cache_hash(&mut hasher);
for_export.hash(&mut hasher);
let key = hasher.finish();
if self.lock().as_ref().is_none_or(|readback| readback.key != key) {
let Some(executor) = executor else {
return Poll::Final(RenderOutputType::Svg { svg, image_data });
if !svg_placeholders_in_view(&output.effect_maps, &output.deferred_images, footprint) {
self.clear();
return Poll::Final(RenderOutputType::Svg { svg, image_data });
}
log::warn!("{NoGpuError}, so the SVG render can't fill the placeholders for its maps and images in view");
let finished = with_unfilled_placeholders(RenderOutputType::Svg { svg, image_data }, NoGpuError, for_export);
*self.lock() = Some(SvgReadback {
key,
finished: Some(finished.clone()),
task: None,
});
return finished;
};
let effect_maps = executor.render_effect_maps(&output.effect_maps, footprint);
let deferred_images = executor.render_deferred_svg_images(&output.deferred_images, footprint);
if effect_maps.is_empty() && deferred_images.is_empty() {
let renders = executor.render_svg_placeholders(&output.effect_maps, &output.deferred_images, footprint);
if renders.is_empty() {
self.clear();
return Poll::Final(RenderOutputType::Svg { svg, image_data });
}
let (task, registration) = AbortHandle::new_pair();
*self.lock() = Some(SvgReadback { key, finished: None, task });
*self.lock() = Some(SvgReadback {
key,
finished: None,
task: Some(task),
});
let (mut svg, mut image_data) = (svg.clone(), image_data.clone());
let readback = async move {
executor.resolve_effect_maps(&mut svg, effect_maps).await;
executor.resolve_deferred_svg_images(&mut svg, &mut image_data, deferred_images).await;
RenderOutputType::Svg { svg, image_data }
let filled = executor.substitute_svg_placeholders(&mut svg, &mut image_data, renders).await;
let output = RenderOutputType::Svg { svg, image_data };
match filled {
Ok(()) => Poll::Final(output),
Err(error) => with_unfilled_placeholders(output, error, for_export),
}
};
// Held weakly, the slot is dropped along with the render node, which cancels the readback
let slot = Arc::downgrade(&self.0);
@@ -89,10 +162,15 @@ impl SvgReadbackSlot {
}
let finished = self.lock().as_ref().filter(|readback| readback.key == key).and_then(|readback| readback.finished.clone());
match finished {
Some(finished) => Poll::Final(finished),
None => Poll::Partial(RenderOutputType::Svg { svg, image_data }),
}
finished.unwrap_or(Poll::Partial(RenderOutputType::Svg { svg, image_data }))
}
}
/// The SVG `output` with placeholders in view the GPU couldn't fill, which fail an export rather than leaving its content out, and which a view shows as they are.
fn with_unfilled_placeholders(output: RenderOutputType, error: impl std::fmt::Display, for_export: bool) -> Poll<RenderOutputType> {
match for_export {
true => Poll::error(format!("{error:#}")),
false => Poll::Final(output),
}
}
@@ -177,7 +255,7 @@ mod tests {
let runtime = AsyncRuntime::new(tasks.clone());
let slot = SvgReadbackSlot::default();
let output = deferred_svg();
let poll = || slot.poll(again(&output), view(32), Some(executor.clone()), &runtime.handle(), SourceId(1));
let poll = || slot.poll(again(&output), view(32), Some(executor.clone()), false, &runtime.handle(), SourceId(1));
// Until the readback lands, the SVG keeps its placeholders, and evaluating the same render again doesn't read it back again
for _ in 0..2 {
@@ -196,6 +274,60 @@ mod tests {
assert!(svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"), "{svg}");
}
#[test]
fn placeholders_left_unfilled_fail_an_export_but_show_in_a_view() {
let tasks = Arc::new(HeldTasks::default());
let runtime = AsyncRuntime::new(tasks.clone());
let slot = SvgReadbackSlot::default();
let output = deferred_svg();
// Without a GPU, an export fails rather than leaving out what the placeholder stands for
let export = slot.poll(again(&output), view(32), None, true, &runtime.handle(), SourceId(1));
assert!(matches!(export, Poll::Error(_)), "the export should fail");
let Poll::Final(RenderOutputType::Svg { svg, .. }) = slot.poll(again(&output), view(32), None, false, &runtime.handle(), SourceId(1)) else {
panic!("expected the view's SVG")
};
assert!(svg.contains("deferred-image"), "the view should show the placeholder: {svg}");
// An export with its placeholder out of view has nothing left out
let elsewhere = Footprint {
transform: DAffine2::from_translation(DVec2::splat(-1000.)),
..view(32)
};
assert!(matches!(slot.poll(again(&output), elsewhere, None, true, &runtime.handle(), SourceId(1)), Poll::Final(_)));
assert!(tasks.take().is_empty(), "nothing can be read back");
}
#[test]
fn evaluations_of_content_in_view_draw_the_same_placeholders_so_its_readback_finishes_them() {
let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return };
let tasks = Arc::new(HeldTasks::default());
let runtime = AsyncRuntime::new(tasks.clone());
let (slot, in_view) = (SvgReadbackSlot::default(), SvgInViewSlot::default());
let content: Arc<dyn Render + Send + Sync> = Arc::new(List::new_from_element(graphic_types::Generator::Noise));
let render_params = RenderParams {
for_export: true,
view: Some(view(32)),
..Default::default()
};
let evaluate = || {
let output = in_view.render(&content, &render_params);
slot.poll(again(&output), view(32), Some(executor.clone()), false, &runtime.handle(), SourceId(1))
};
// The first evaluation draws the generator's placeholder and reads its image back
assert!(matches!(evaluate(), Poll::Partial(_)));
tasks.take().into_iter().for_each(futures::executor::block_on);
// The evaluation the readback wakes draws the same placeholder, which the image fills
let Poll::Final(RenderOutputType::Svg { svg, .. }) = evaluate() else {
panic!("expected a finished SVG")
};
assert!(svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"), "{svg}");
assert!(tasks.take().is_empty(), "nothing should be read back again");
}
#[test]
fn a_render_for_another_view_cancels_the_readback_of_the_one_it_replaces() {
let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return };
@@ -203,7 +335,7 @@ mod tests {
let runtime = AsyncRuntime::new(tasks.clone());
let slot = SvgReadbackSlot::default();
let output = deferred_svg();
let poll = |size| slot.poll(again(&output), view(size), Some(executor.clone()), &runtime.handle(), SourceId(1));
let poll = |size| slot.poll(again(&output), view(size), Some(executor.clone()), false, &runtime.handle(), SourceId(1));
assert!(matches!(poll(32), Poll::Partial(_)));
assert!(matches!(poll(64), Poll::Partial(_)));
@@ -228,9 +360,9 @@ mod tests {
let runtime = AsyncRuntime::new(tasks.clone());
let slot = SvgReadbackSlot::default();
let render = slot.poll(deferred_svg(), view(32), Some(executor), &runtime.handle(), SourceId(1));
let render = slot.poll(deferred_svg(), view(32), Some(executor), false, &runtime.handle(), SourceId(1));
assert!(matches!(render, Poll::Partial(_)));
let readback = slot.lock().as_ref().unwrap().task.clone();
let readback = slot.lock().as_ref().unwrap().task.clone().unwrap();
// A render node that's removed drops its slot while the task reading back for it is still to run
drop(slot);
@@ -0,0 +1,130 @@
//! Networks whose export `export_layers` replaced with what their layers add, preprocessed, compiled, and evaluated as the editor's are.
use super::*;
use core_types::list::List;
use core_types::runtime::{AsyncRuntime, Spawn, Task};
use core_types::{Color, OwnedContextImpl, Poll};
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::graphene_compiler::Compiler;
use graphene_std::graphic::{as_graphic, extend, into_group};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::layer_paths::export_layers;
use interpreted_executor::util::wrap_network_in_scope;
use std::sync::Arc;
struct BlockingSpawner;
impl Spawn for BlockingSpawner {
fn spawn(&self, task: Task) {
futures::executor::block_on(task);
}
}
/// What the network outputs once it's preprocessed, compiled, and evaluated.
fn evaluated(network: NodeNetwork) -> List<Graphic> {
let runtime = AsyncRuntime::new(Arc::new(BlockingSpawner));
let mut network = wrap_network_in_scope(network, Arc::new(PlatformEditorApi { application_io: None }), runtime.handle());
Preprocessor::new().preprocess(&mut network, &|_| None).expect("preprocessing should succeed");
let proto_network = Compiler {}.compile_single(network).expect("the network should compile").network;
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(proto_network).expect("the network should type check and build");
let context = OwnedContextImpl::empty().into_context();
let Poll::Final(stack) = executor.tree().evaluate(output.node(), &context).expect("the output should evaluate") else {
panic!("the stack should be final")
};
*stack.downcast::<List<Graphic>>().expect("the stack should be graphics")
}
/// The color a stacked layer's group holds.
fn color_of(graphic: &Graphic) -> Option<Color> {
match graphic {
Graphic::Color(item) => Some(*item.element()),
Graphic::ColorList(list) => list.element(0).copied(),
Graphic::Graphic(item) => color_of(item.element()),
Graphic::GraphicList(list) => color_of(list.element(0)?),
_ => None,
}
}
fn proto_node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
DocumentNode {
inputs,
implementation: DocumentNodeImplementation::ProtoNode(identifier),
..Default::default()
}
}
/// A network shaped like 'Merge', adding the content it's given as a group onto the stack it's given.
fn merge_like() -> NodeNetwork {
NodeNetwork {
exports: vec![NodeInput::node(NodeId(2), 0)],
nodes: [
(NodeId(0), proto_node(as_graphic::IDENTIFIER, vec![NodeInput::import(generic!(T), 0)])),
(NodeId(1), proto_node(into_group::IDENTIFIER, vec![NodeInput::import(generic!(T), 1)])),
(NodeId(2), proto_node(extend::IDENTIFIER, vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)])),
]
.into_iter()
.collect(),
..Default::default()
}
}
/// A layer made from the network with this ID, adding a color onto the stack it's given.
fn layer(definition: NetworkId, base: NodeInput, color: Color) -> DocumentNode {
DocumentNode {
inputs: vec![base, NodeInput::value(TaggedValue::Color(color), false)],
implementation: DocumentNodeImplementation::Definition(definition),
..Default::default()
}
}
#[test]
fn layers_made_from_one_network_stack_in_the_order_given() {
let merge = NetworkId(1);
let empty = NodeInput::type_default(list!(Graphic), false);
let mut network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(20), 0)],
nodes: [(NodeId(10), layer(merge, empty, Color::RED)), (NodeId(20), layer(merge, NodeInput::node(NodeId(10), 0), Color::BLUE))]
.into_iter()
.collect(),
definitions: [(merge, merge_like())].into_iter().collect(),
..Default::default()
};
assert!(export_layers(&mut network, &[NodeId(20), NodeId(10)]).is_some());
let colors: Vec<_> = evaluated(network).iter_element_values().map(color_of).collect();
assert_eq!(colors, [Some(Color::BLUE), Some(Color::RED)]);
}
// The layer is made from a network holding a 'Merge' node, so what it adds is passed out through both networks
#[test]
fn a_layer_adding_content_from_a_nested_network_stacks_it() {
let (merge, outer) = (NetworkId(1), NetworkId(2));
let outer_network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(30), 0)],
nodes: [(
NodeId(30),
DocumentNode {
inputs: vec![NodeInput::import(generic!(T), 0), NodeInput::import(generic!(T), 1)],
implementation: DocumentNodeImplementation::Definition(merge),
..Default::default()
},
)]
.into_iter()
.collect(),
..Default::default()
};
let mut network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(10), 0)],
nodes: [(NodeId(10), layer(outer, NodeInput::type_default(list!(Graphic), false), Color::RED))].into_iter().collect(),
definitions: [(merge, merge_like()), (outer, outer_network)].into_iter().collect(),
..Default::default()
};
assert!(export_layers(&mut network, &[NodeId(10)]).is_some());
let colors: Vec<_> = evaluated(network).iter_element_values().map(color_of).collect();
assert_eq!(colors, [Some(Color::RED)]);
}
+2
View File
@@ -1,6 +1,8 @@
#[macro_use]
extern crate log;
#[cfg(test)]
mod export_layers_tests;
#[cfg(test)]
mod readback_tests;
mod value_types;