From 9517b006fa943892979d9dc1a7d256decb8920c6 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 3 Dec 2026 02:35:26 -0800 Subject: [PATCH] New node: 'Background Blur' (#5063) Add a Background Blur effect that blurs what lies beneath the content --- Cargo.lock | 1 + .../graphic-types/src/effect_layers.rs | 73 +- .../libraries/graphic-types/src/effects.rs | 75 +- .../libraries/graphic-types/src/resampling.rs | 1 + .../raster-kernels/src/raster_effects.rs | 7 +- node-graph/libraries/rendering/Cargo.toml | 1 + .../libraries/rendering/src/deferred_image.rs | 98 +- node-graph/libraries/rendering/src/lib.rs | 1 + .../libraries/rendering/src/renderer.rs | 1572 +++++++++++++++-- .../libraries/rendering/src/renderer/masks.rs | 2 +- .../libraries/rendering/src/svg_backdrop.rs | 406 +++++ .../rendering/src/vello_scene_builder.rs | 206 ++- .../wgpu-executor/src/vello_effects.rs | 104 +- .../wgpu-executor/src/vello_effects.wgsl | 15 +- .../wgpu-executor/src/vello_render.rs | 119 +- .../wgpu-executor/src/vello_render/tests.rs | 1169 +++++++++++- node-graph/nodes/blending/src/backdrop.rs | 38 + node-graph/nodes/blending/src/lib.rs | 1 + 18 files changed, 3702 insertions(+), 187 deletions(-) create mode 100644 node-graph/libraries/rendering/src/svg_backdrop.rs create mode 100644 node-graph/nodes/blending/src/backdrop.rs diff --git a/Cargo.lock b/Cargo.lock index b790401af9..a558d87206 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6021,6 +6021,7 @@ dependencies = [ "graphene-resource", "graphic-types", "kurbo", + "linesweeper", "log", "num-traits", "parley", diff --git a/node-graph/libraries/graphic-types/src/effect_layers.rs b/node-graph/libraries/graphic-types/src/effect_layers.rs index 5d50eeb203..3ef6bf00ea 100644 --- a/node-graph/libraries/graphic-types/src/effect_layers.rs +++ b/node-graph/libraries/graphic-types/src/effect_layers.rs @@ -22,6 +22,8 @@ pub enum PiecePlace { IntoContent { over: bool }, /// The part of an interior piece blending with what shows through the content's fill, in a layer of its mode beneath the content's, or with `over`, over it. Through { over: bool }, + /// What lies beneath the content, filtered and cut to its silhouette, at the bottom of the content's own layer. + Backdrop, } /// One coverage of an effect that draws as a piece of its own, named like the map of it. @@ -115,10 +117,16 @@ impl EffectLayers { .chain([(LayerPart::Content, blend_mode)]) .collect(); - // A shadow not knocked out in the content's layer, flattened or layered, would hide a part placed beneath that layer + // A blurred backdrop, or a shadow not knocked out (flattened or layered), in the content's layer would hide a part placed beneath that layer + let backdrop: Vec = pieces_from(0, operations.len()) + .into_iter() + .filter(|(piece, _)| piece.place == PiecePlace::Backdrop) + .map(|(piece, _)| LayerPart::Piece(piece)) + .collect(); let shows_through = |piece: &EffectPiece| piece.place == PiecePlace::Beneath && !piece.knocks_out; let mut content_run = parts.iter().rev().skip(1).take_while(|(_, mode)| *mode == BlendMode::Normal); - let covered_beneath = content_run.any(|(part, _)| matches!(part, LayerPart::Piece(piece) if shows_through(piece))) || unmerged.iter().any(|(piece, _)| shows_through(piece)); + let covered_beneath = + !backdrop.is_empty() || content_run.any(|(part, _)| matches!(part, LayerPart::Piece(piece) if shows_through(piece))) || unmerged.iter().any(|(piece, _)| shows_through(piece)); // Interior pieces of normal content blend within its share, in its layer. Below a full fill, a blended one splits off its part through the fill into a layer beneath // the content's, or over it when its mode isn't straight along what lies beneath or a shadow covers that, as every later piece then does to keep their order. @@ -166,8 +174,8 @@ impl EffectLayers { layers.splice(content_layer..content_layer, through); } - // One normal layer at a full fill draws the same with all its effects flattened into the content's image, which takes fewer passes - if blends_into_content && matches!(layers.as_slice(), [layer] if layer.blend_mode == BlendMode::Normal) { + // One normal layer at a full fill draws the same with all its effects flattened into the content's image, which takes fewer passes, unless it blurs what lies beneath + if blends_into_content && backdrop.is_empty() && matches!(layers.as_slice(), [layer] if layer.blend_mode == BlendMode::Normal) { let content = EffectLayer { blend_mode: BlendMode::Normal, parts: vec![LayerPart::Content], @@ -179,6 +187,11 @@ impl EffectLayers { }; } + // What lies beneath, filtered, goes at the bottom of the content's own layer, which fades and blends it with the content, even from a row flattened into the content + if let Some(content_layer) = layers.iter_mut().find(|layer| layer.holds_content()) { + content_layer.parts.splice(0..0, backdrop); + } + Self { flattened, layers, trailing_masks } } @@ -201,6 +214,11 @@ impl EffectLayers { planned } + /// Whether a layered piece reads what lies beneath the content. + pub fn reads_backdrop(&self) -> bool { + (self.layers.iter().flat_map(|layer| &layer.parts)).any(|part| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::Backdrop)) + } + /// The index of the layer holding the content. pub fn content_layer(&self) -> Option { self.layers.iter().position(EffectLayer::holds_content) @@ -263,6 +281,13 @@ impl EffectLayers { } } +/// Whether any of the effects reads what lies beneath the content, like a background blur. +pub fn effects_read_backdrop(effects: &Effects) -> bool { + effects + .operations() + .any(|operation| matches!(operation, EffectOperation::BackgroundBlur { .. }) && !operation.changes_nothing()) +} + /// Whether an effect row can draw as layered pieces, rather than being carried out within the content's image. /// Blurs, adjustments, masks, and feathers process the pixels of everything before them, and blend modes CSS lacks can't blend against the backdrop in SVG or a GPU layer, /// though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves. @@ -392,6 +417,7 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM inside.into_iter().chain(outside).flatten().collect() } EffectOperation::PaintOverlay { blend_mode, .. } => vec![piece(0, Within, None, *blend_mode)], + EffectOperation::BackgroundBlur { .. } => vec![piece(0, Backdrop, None, BlendMode::Normal)], EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, .. }) => vec![piece(0, Within, Some(*color), *blend_mode)], EffectOperation::Blur { .. } | EffectOperation::MotionBlur { .. } @@ -568,6 +594,11 @@ mod tests { fn interior_pieces_go_over_the_content_where_its_layer_covers_what_lies_beneath_it() { let red = RED.with_alpha(0.75); let through_over = PiecePlace::Through { over: true }; + let background_blur = EffectOperation::BackgroundBlur { + radius: 4., + box_blur: false, + gamma: false, + }; let with_knockout = |knocks_out: bool| { let mut shadow = drop_shadow(Color::BLACK.with_alpha(0.75), BlendMode::Multiply); @@ -577,10 +608,12 @@ mod tests { shadow }; - // A shadow not knocked out beneath the content in its layer would hide even a straight piece's part beneath that layer - let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(false), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true); - assert_eq!(modes(&layers), [BlendMode::Normal, BlendMode::Screen]); - assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))]); + // A blurred backdrop, or a shadow not knocked out, beneath the content in its layer would hide even a straight piece's part beneath that layer + for beneath in [background_blur, with_knockout(false)] { + let layers = EffectLayers::plan(&Effects::from_operations([beneath.clone(), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true); + assert_eq!(modes(&layers), [BlendMode::Normal, BlendMode::Screen], "{beneath:?}"); + assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))], "{beneath:?}"); + } // A knocked-out shadow doesn't cover it there let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(true), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true); @@ -758,6 +791,30 @@ mod tests { assert_eq!(kinds(filtered), [EffectKind::Mask, EffectKind::InnerShadow, EffectKind::Blur, EffectKind::Mask]); } + #[test] + fn a_background_blur_lies_at_the_bottom_of_the_contents_layer() { + let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.); + let background_blur = EffectOperation::BackgroundBlur { + radius: 4., + box_blur: false, + gamma: false, + }; + let blur = EffectOperation::Blur { + radius_mask: Default::default(), + radius: 2., + box_blur: false, + gamma: false, + }; + + // Even beside a blended shadow, and flattened by a later blur, it fades and blends with the content + let effects = Effects::from_operations([drop_shadow(blue, BlendMode::Multiply), background_blur, blur]); + let layers = EffectLayers::plan(&effects, BlendMode::Screen, 1., true); + assert!(layers.reads_backdrop()); + let content_layer = layers.content_layer().unwrap(); + assert_eq!(layers.layers[content_layer].blend_mode, BlendMode::Screen); + assert_eq!(parts(&layers)[content_layer], [Some((1, 0, PiecePlace::Backdrop)), None]); + } + #[test] fn knocked_out_pieces_hide_behind_however_the_content_covers_them() { let same_layer = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::Normal)]), BlendMode::Normal, 0.5, true); diff --git a/node-graph/libraries/graphic-types/src/effects.rs b/node-graph/libraries/graphic-types/src/effects.rs index 90cc531a9d..4c90eabf7a 100644 --- a/node-graph/libraries/graphic-types/src/effects.rs +++ b/node-graph/libraries/graphic-types/src/effects.rs @@ -91,6 +91,8 @@ pub enum EffectKind { Pixelate, /// Prints each color channel of the content as dots on its own turned screen, as a press prints ink. ColorHalftone, + /// Blurs what lies beneath the content within its silhouette, as if seen through frosted glass. + BackgroundBlur, // The adjustments, which change each color of the content on its own, as their nodes of the same names do Desaturate, GammaCorrection, @@ -148,6 +150,7 @@ impl std::fmt::Display for EffectKind { Self::Displace => "Displace", Self::Pixelate => "Pixelate", Self::ColorHalftone => "Color Halftone", + Self::BackgroundBlur => "Background Blur", Self::Desaturate => "Desaturate", Self::GammaCorrection => "Gamma Correction", Self::MakeOpaque => "Make Opaque", @@ -452,7 +455,7 @@ impl Effects { self.effects().skip(rows.start).take(rows.len()).map(Effect::operation) } - /// How far past the content the effects together can paint, in the effect space of a run of them. + /// How far past the content the effects together can paint, or a background blur among them reads what lies beneath, in the effect space of a run of them. /// It leaves out what [`Effects::reach_around`] adds from the content's bounds and what it paints past its frame, for the effects relative to its extent. pub fn reach(&self) -> f64 { self.operations().map(|operation| operation.painted_reach()).sum() @@ -1228,6 +1231,15 @@ pub enum EffectOperation { /// Percent of the spacing between dots that each screen's dots lie past the `offset` along both of its axes. phase: f64, }, + /// Blurs the backdrop beneath the content within the content's silhouette, beneath the content and its effects. + BackgroundBlur { + /// The standard deviation of the Gaussian, or the half width of the box. + radius: f64, + /// Whether to average a box of pixels rather than weighting them by a Gaussian. + box_blur: bool, + /// Whether to blend the colors with their gamma encoding rather than in linear light. + gamma: bool, + }, Adjustment(Adjustment), } @@ -1285,6 +1297,7 @@ impl EffectOperation { Self::Displace { .. } => EffectKind::Displace, Self::Pixelate { .. } => EffectKind::Pixelate, Self::ColorHalftone { .. } => EffectKind::ColorHalftone, + Self::BackgroundBlur { .. } => EffectKind::BackgroundBlur, Self::Adjustment(adjustment) => adjustment.kind(), } } @@ -1315,7 +1328,7 @@ impl EffectOperation { /// Whether this operation leaves the content as it is, like a blur of no radius or a shadow of no opacity. pub fn changes_nothing(&self) -> bool { match self { - Self::Blur { radius, .. } => *radius <= 0., + Self::Blur { radius, .. } | Self::BackgroundBlur { radius, .. } => *radius <= 0., Self::DropShadow { color, .. } | Self::InnerShadow { color, .. } | Self::Satin { color, .. } => color.a() <= 0., Self::OuterGlow { color, noise, .. } | Self::InnerGlow { color, noise, .. } => GlowFill::of(color).is_none_or(|fill| fill.is_invisible(*noise)), Self::Outline { paint, weight, contour_gradient, .. } => *weight <= 0. || OutlineFill::of(paint, *contour_gradient).is_none_or(|fill| fill.is_invisible()), @@ -1375,6 +1388,16 @@ impl EffectOperation { matches!(self, Self::Blur { radius_mask, .. } if !radius_mask.draws_nothing()) } + /// Whether this operation paints nothing past the content, whatever it reads there, like an inner shadow finding the edges it casts from. + pub fn paints_only_within_content(&self) -> bool { + match self { + Self::InnerShadow { .. } | Self::InnerGlow { .. } | Self::Satin { .. } | Self::Mask { .. } | Self::Feather { .. } | Self::BackgroundBlur { .. } => true, + Self::Outline { align, .. } => *align == StrokeAlign::Inside, + Self::BevelAndEmboss { style, .. } => *style == BevelStyle::InnerBevel, + _ => false, + } + } + /// Whether this operation reads the pixels around each one of the image the effects before it leave, like a blur or a warp, rather than casting from the content's shape or changing each pixel alone. pub fn reads_pixels_around(&self) -> bool { match self { @@ -1383,7 +1406,7 @@ impl EffectOperation { true } Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true, - // Cast from the content's shape, reading a mask's own image or a feather's map, or changing each pixel alone + // Cast from the content's shape, reading a mask's or the backdrop's own image or a feather's map, or changing each pixel alone Self::DropShadow { .. } | Self::InnerShadow { .. } | Self::OuterGlow { .. } @@ -1392,7 +1415,7 @@ impl EffectOperation { | Self::Outline { .. } | Self::BevelAndEmboss { .. } | Self::Feather { .. } => false, - Self::PaintOverlay { .. } | Self::Mask { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false, + Self::PaintOverlay { .. } | Self::Mask { .. } | Self::BackgroundBlur { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false, } } @@ -1429,8 +1452,9 @@ impl EffectOperation { pub fn reach(&self) -> f64 { match self { // A box reaches its half width, and the pixel past it for a fractional one, while a Gaussian fades out over three standard deviations - Self::Blur { radius, box_blur: true, .. } => radius.max(0.) + 1., - Self::Blur { radius, .. } => 3. * radius.max(0.), + Self::Blur { radius, box_blur: true, .. } | Self::BackgroundBlur { radius, box_blur: true, .. } => radius.max(0.) + 1., + // A background blur reads as far past the content as its Gaussian reaches + Self::Blur { radius, .. } | Self::BackgroundBlur { radius, .. } => 3. * radius.max(0.), // An inner shadow paints within the content but reads this far out to find the edges it casts from. // Shadows and glows end within their size, past which a precise glow fades over one more unit. Self::DropShadow { distance, size, .. } | Self::InnerShadow { distance, size, .. } => distance.abs() + size.max(0.) + 1., @@ -1516,7 +1540,7 @@ impl EffectOperation { }; match &mut self { - Self::Blur { radius, .. } => finite(radius), + Self::Blur { radius, .. } | Self::BackgroundBlur { radius, .. } => finite(radius), Self::DropShadow { angle, distance, spread, size, .. } | Self::InnerShadow { angle, distance, choke: spread, size, .. @@ -1801,6 +1825,11 @@ impl EffectOperation { offset: DVec2::ZERO, phase: 0., }, + EffectKind::BackgroundBlur => Self::BackgroundBlur { + radius: 0., + box_blur: false, + gamma: false, + }, EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }), EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }), EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque { strength: 0. }), @@ -1853,6 +1882,11 @@ impl EffectOperation { visitor.parameter("box_blur", box_blur, false); visitor.parameter("gamma", gamma, false); } + Self::BackgroundBlur { radius, box_blur, gamma } => { + visitor.parameter("radius", radius, 10.); + visitor.parameter("box_blur", box_blur, false); + visitor.parameter("gamma", gamma, false); + } Self::DropShadow { color, blend_mode, @@ -2193,6 +2227,23 @@ mod tests { use super::*; use vector_types::{Gradient, GradientStop}; + #[test] + fn box_blurs_reach_their_half_width_and_a_pixel_while_gaussians_reach_three_radii() { + let blur = |box_blur| EffectOperation::Blur { + radius_mask: Graphic::default(), + radius: 6., + box_blur, + gamma: false, + }; + let background_blur = |box_blur| EffectOperation::BackgroundBlur { radius: 6., box_blur, gamma: false }; + + // Whether it blurs the content or what lies beneath it, a blur reaches as far as its kernel reads + for (box_blur, reach) in [(true, 7.), (false, 18.)] { + assert_eq!(blur(box_blur).reach(), reach, "box: {box_blur}"); + assert_eq!(background_blur(box_blur).reach(), reach, "box: {box_blur}"); + } + } + #[test] fn rows_round_trip_their_operations_eliding_defaults() { let operations = [ @@ -2780,6 +2831,16 @@ mod tests { assert_eq!(runs, vec![0..3, 3..4]); } + #[test] + fn effects_painting_only_within_the_content_paint_nothing_past_it() { + // An inner shadow reads past the content to find the edges it casts from, but paints only within it + let (inner_shadow, drop_shadow) = (EffectOperation::default_for(EffectKind::InnerShadow), EffectOperation::default_for(EffectKind::DropShadow)); + let painted = |effects: Effects| effects.reach_around_by(DAffine2::IDENTITY, [DVec2::ZERO; 2], 0., |operation| !operation.paints_only_within_content()); + assert!(Effects::from_operations([inner_shadow.clone()]).reach() > 0.); + assert_eq!(painted(Effects::from_operations([inner_shadow.clone()])), DVec2::ZERO); + assert_eq!(painted(Effects::from_operations([inner_shadow, drop_shadow.clone()])), DVec2::splat(drop_shadow.reach())); + } + #[test] fn adjustment_rows_elide_their_defaults_and_name_grouped_parameters() { use EffectKind::*; diff --git a/node-graph/libraries/graphic-types/src/resampling.rs b/node-graph/libraries/graphic-types/src/resampling.rs index f7835e3407..128cc1bdd0 100644 --- a/node-graph/libraries/graphic-types/src/resampling.rs +++ b/node-graph/libraries/graphic-types/src/resampling.rs @@ -1745,6 +1745,7 @@ impl EffectOperation { | Self::HighPass { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } + | Self::BackgroundBlur { .. } | Self::Adjustment(_) => false, } } diff --git a/node-graph/libraries/raster-kernels/src/raster_effects.rs b/node-graph/libraries/raster-kernels/src/raster_effects.rs index 0a2416b904..643474d971 100644 --- a/node-graph/libraries/raster-kernels/src/raster_effects.rs +++ b/node-graph/libraries/raster-kernels/src/raster_effects.rs @@ -511,6 +511,8 @@ fn evaluate(raster: &Raster, transform: DAffine2, effects: &Effects, fill: }; place_within(&mut pieces, piece(0), &mut full, &mut filled, painted, blend_mode); } + // An image of its own has nothing beneath it to blur + EffectOperation::BackgroundBlur { .. } => {} // A solid paint overlay paints within the content alone, like any other paint overlay EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, opacity }) => { let painted = premultiplied_gamma_channels(color.with_alpha(color.a() * (opacity / 100.) as f32)); @@ -955,7 +957,7 @@ fn composite_layers( PiecePlace::Within => SharePart::Whole, PiecePlace::IntoContent { over: false } => SharePart::IntoContent, PiecePlace::IntoContent { over: true } => SharePart::IntoContentBeneathPartOver { opacity: OPACITY, fade }, - PiecePlace::Beneath | PiecePlace::Through { .. } => continue, + PiecePlace::Beneath | PiecePlace::Through { .. } | PiecePlace::Backdrop => continue, }; content = composite_in_share(&content, tinted, full_content, piece.blend_mode, part); } @@ -977,7 +979,8 @@ fn composite_layers( PiecePlace::Beneath => tinted.clone(), PiecePlace::Within if !holds_content => tinted.zip(full_content, |tinted, content| tinted.map(|channel| channel * content[3])), PiecePlace::Through { .. } => tinted.zip(&through_shares(full_content, &content, OPACITY, fade), |tinted, share| tinted.map(|channel| channel * share)), - PiecePlace::Within | PiecePlace::IntoContent { .. } => continue, + // What lies beneath, for a backdrop the image doesn't have + PiecePlace::Within | PiecePlace::IntoContent { .. } | PiecePlace::Backdrop => continue, }; stack = Some(stack_over(stack, upper)); } diff --git a/node-graph/libraries/rendering/Cargo.toml b/node-graph/libraries/rendering/Cargo.toml index 76b41fa30b..d6ca72c110 100644 --- a/node-graph/libraries/rendering/Cargo.toml +++ b/node-graph/libraries/rendering/Cargo.toml @@ -34,6 +34,7 @@ log = { workspace = true } num-traits = { workspace = true } usvg = { workspace = true } kurbo = { workspace = true } +linesweeper = { workspace = true } vector-types = { workspace = true } graphic-types = { workspace = true } raster-kernels = { workspace = true } diff --git a/node-graph/libraries/rendering/src/deferred_image.rs b/node-graph/libraries/rendering/src/deferred_image.rs index e163bbdcc1..011584caf5 100644 --- a/node-graph/libraries/rendering/src/deferred_image.rs +++ b/node-graph/libraries/rendering/src/deferred_image.rs @@ -1,6 +1,6 @@ //! What SVG can't express, which the GPU renders as images for an SVG to take, once the SVG is drawn. //! An effect whose coverage SVG filters can't work out, like the shadows and glows shaped for PSD interop, goes in its filter as a map of that coverage, while the content keeps its own markup. -//! Content with an effect no filter can carry out at all is drawn as an image of it in place of its markup. +//! Content with an effect no filter can carry out, and a backdrop whose copy in markup would nest, are drawn as images in place of markup. //! Placeholders stand in for each until it's resolved, leaving an SVG that never is short of those effects. use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, render_raster_cpu_image_svg}; @@ -8,12 +8,16 @@ use crate::vello_scene_builder::{MAX_EFFECTS_AREA_PER_VIEWPORT_AREA, VelloSceneB use core_types::Color; use core_types::blending::BlendMode; use core_types::color::SRGBA8; +use core_types::list::List; use core_types::math::quad::Quad; use core_types::transform::Footprint; use glam::{DAffine2, DVec2, UVec2}; use graphic_types::Graphic; use graphic_types::effects::EffectCapture; use graphic_types::raster_types::{CPU, Raster}; +use kurbo::{Affine, BezPath}; +use std::sync::Arc; +use vello_gpu::peniko::Fill; /// The most pixels across or down a map or image may have. pub const MAX_DEFERRED_IMAGE_PIXELS: u32 = 8192; @@ -183,13 +187,12 @@ pub fn substitute_effect_map(svg: &mut String, placement: &EffectMapPlacement, m svg.replace_range(span, &image); } -/// One item of content an SVG draws as an image the GPU renders of it, since its effects hold one SVG filters can't carry out. +/// Content an SVG draws as an image the GPU renders of it, since SVG can't carry it out as markup. #[derive(Clone)] pub struct DeferredImage { /// Names the markers around the content's own markup in the SVG, which the image replaces. pub id: u64, - /// The item with its effects, but without its opacity and blend mode, which the image takes instead. - pub content: Graphic, + pub content: DeferredContent, pub render_params: RenderParams, /// Maps the user space the markers sit in into the document. pub user_to_document: DAffine2, @@ -201,6 +204,67 @@ pub struct DeferredImage { pub blend_mode: BlendMode, } +/// What the GPU renders an image of for an SVG. +#[derive(Clone)] +pub enum DeferredContent { + /// An item with effects SVG filters can't carry out, but without its opacity and blend mode, which the image takes instead. + Item(Graphic), + /// What lies beneath content reading its backdrop, drawn in order, for which the markers stand around no markup. + /// The outline of the backdrop root's `clip`, a path in the document filled by the nonzero rule, cuts it as it's drawn, as it cuts what a copy of it would hold. + Beneath { clip: Option, drawn: Vec }, +} + +/// Content an SVG draws, which the GPU draws again into images of what lies beneath content drawn after it. +#[derive(Clone)] +pub struct DrawnContent { + items: Arc, + /// How many of the items are drawn, since content drawn among them lies over only those before it. + pub(crate) count: usize, + /// Maps the user space the items are drawn in into the document. + user_to_document: DAffine2, + render_params: RenderParams, +} + +impl DrawnContent { + /// The `items` drawn in a user space that `user_to_document` maps into the document, none of them drawn yet. + pub(crate) fn new(items: Arc, user_to_document: DAffine2, render_params: &RenderParams) -> Self { + Self { + items, + count: 0, + user_to_document, + render_params: render_params.clone(), + } + } +} + +/// A list of graphical content, or one item of it, whose first items the GPU can draw. +pub(crate) trait DrawnItems: Send + Sync { + /// Draws the first `count` items into a scene of the document, from the user space that `transform` maps into it. + fn draw_first(&self, count: usize, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams); +} + +impl DrawnItems for List +where + List: Render, +{ + fn draw_first(&self, count: usize, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) { + if count >= self.len() { + return self.render_to_vello(scene, transform, render_params); + } + + let first: List = (0..count).filter_map(|index| self.clone_item(index)).collect(); + first.render_to_vello(scene, transform, render_params); + } +} + +impl DrawnItems for Graphic { + fn draw_first(&self, count: usize, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) { + if count > 0 { + self.render_to_vello(scene, transform, render_params); + } + } +} + /// How an SVG draws the image the GPU rendered of an item of deferred content. #[derive(Clone, Debug, PartialEq)] pub struct DeferredImagePlacement { @@ -230,6 +294,11 @@ pub(crate) fn image_markers(id: u64) -> (String, String) { (format!(""), format!("")) } +/// Whether the `markup` holds markers of markup standing in for an item of deferred content. +pub(crate) fn holds_image_markers(markup: &str) -> bool { + markup.contains("")); + let layers_start = render.svg.len(); + + // Each layer transforms from the last run's effect space into the user space let transform = spaces.as_ref().and_then(|spaces| spaces.last()).copied().unwrap_or_default(); let matrix = format_transform_matrix(transform); - let mut content_through_runs = |render: &mut SvgRender| render_svg_filter_groups(render, &inner, spaces.as_deref(), &mut masked_content); - let content_id = (layers.len() > 1 && !repeats_content).then(|| format!("effects-content-{}", generate_uuid())); - let mut emitted = false; - for layer in layers { + // The content's markup through the runs before the last for the other layers to copy, and through the GPU's earlier runs to cut what lies beneath + let keeps_markup = stand_in.is_some() || backdrop.is_some(); + let (mut content_markup, mut cut_markup): (Option, Option) = (None, None); + let mut content = Some(content); + let mut draw_content = |render: &mut SvgRender| { + let Some(content) = content.take() else { return }; + let mut content = Some(content); + let group = render.open_groups.groups.len() - 1; + let cut_depth = backdrop.is_some().then_some(backdrop_cut_depth); + cut_markup = render_svg_filter_groups(render, &inner, spaces.as_deref(), cut_depth, &mut |render| { + let Some(content) = content.take() else { return }; + match &leading_mask { + Some(mask) => render.parent_tag("g", |attributes| attributes.push("mask", mask.clone()), content), + None => content(render), + } + }); + if keeps_markup { + let start = render.open_groups.groups[group].content_start; + content_markup = Some(render.svg[start..].iter().map(SvgSegment::as_str).collect()); + } + }; + + let mut draw_layer = |render: &mut SvgRender, layer: &SvgLayer, compositing: bool| { + // The group fading the content's finished layer with what lies beneath takes the layer's transform and trailing mask + let in_faded_layer = !compositing && layer.holds_content && layer_fade_mask.is_some(); + let layer_transform = if in_faded_layer { DAffine2::IDENTITY } else { transform }; + render.parent_tag( "g", |attributes| { - if !matrix.is_empty() { + let (fades, blends) = (compositing && opacity < 1., compositing && layer.blend_mode != BlendMode::default()); + if !matrix.is_empty() && !in_faded_layer { attributes.push(ATTR_TRANSFORM, matrix.clone()); } if let Some(filter) = layer.filters.last() { attributes.push("filter", filter.clone()); } - if let Some(mask) = &trailing_mask { + let trailing_mask = trailing_mask.as_ref().filter(|_| !in_faded_layer); + if let Some(mask) = trailing_mask { attributes.push("mask", mask.clone()); } - if opacity < 1. { + // With nothing else to isolate it, the content still blends within its own group, as the GPU renders it offscreen + if reads_backdrop && layer.holds_content && layer.filters.is_empty() && trailing_mask.is_none() && !fades && !blends { + attributes.push("style", "isolation: isolate"); + } + if fades { attributes.push("opacity", opacity.to_string()); } - if layer.blend_mode != BlendMode::default() { + if blends { attributes.push("style", layer.blend_mode.render()); } }, |render| { let outside_transform = render.transform; - render.transform = outside_transform * transform; + render.transform = outside_transform * layer_transform; let earlier_filters = &layer.filters[..layer.filters.len().saturating_sub(1)]; - render_svg_nested_filters(render, earlier_filters, &mut |render| match (&content_id, layer.holds_content) { - (Some(id), true) => render.parent_tag("g", |attributes| attributes.push("id", id.clone()), &mut content_through_runs), - (Some(id), false) => render.leaf_tag("use", |attributes| attributes.push("href", format!("#{id}"))), - (None, _) if repeats_content || !emitted => { - emitted = true; - content_through_runs(render); - } - (None, _) => {} + render_svg_nested_filters(render, earlier_filters, &mut |render| match (&content_id, &stand_in, layer.holds_content) { + (Some(id), _, true) => render.parent_tag("g", |attributes| attributes.push("id", id.clone()), &mut draw_content), + (_, Some(stand_in), false) => render.leaf_node(stand_in.clone()), + _ => draw_content(render), }); // Browsers cull and cut a filtered group by its children's geometry, so an unpainted rectangle spans the filter's region @@ -972,17 +1145,100 @@ fn render_svg_through_filters(render: &mut SvgRender, effects: Option render.parent_tag( + "g", + |attributes| { + if opacity < 1. { + attributes.push("opacity", opacity.to_string()); + } + if layer.blend_mode != BlendMode::default() { + attributes.push("style", layer.blend_mode.render()); + } + }, + |render| { + // Its markup lies in the last run's effect space, like the layer's content + let masked = (backdrop_masks.iter()).fold(backdrop.markup.clone(), |markup, mask| format!(r#"{markup}"#)); + match &layer_fade_mask { + Some(mask) => render.parent_tag( + "g", + |attributes| { + if !matrix.is_empty() { + attributes.push(ATTR_TRANSFORM, matrix.clone()); + } + attributes.push("mask", mask.clone()); + }, + |render| { + let outside_transform = render.transform; + render.transform = outside_transform * transform; + render.leaf_node(SvgSegment::Backdrop(masked)); + draw_layer(render, layer, false); + render.transform = outside_transform; + }, + ), + None => { + let markup = if matrix.is_empty() { masked } else { format!(r#"{masked}"#) }; + render.leaf_node(SvgSegment::Backdrop(markup)); + draw_layer(render, layer, false); + } + } + }, + ), + None => draw_layer(render, layer, true), + } + } + + let Some(markup) = content_markup else { return }; + let draws_canvases = markup.contains("data-canvas-placeholder") || (draws_to_canvases && deferred_image::holds_image_markers(&markup)); + if let (Some(id), Some(stand_in)) = (&content_id, &stand_in) { + let copy = if draws_canvases { markup.clone() } else { format!(r##""##) }; + + // Content drawn inside may have wrapped what lies beneath it at outer levels, which only moves the stand-ins later + for segment in render.svg[layers_start..].iter_mut().filter(|segment| segment.as_str() == stand_in) { + *segment = copy.clone().into(); + } + } + + if let Some(backdrop) = backdrop { + let markup = match draws_canvases { + true => { + let [min, max] = backdrop.content_bounds; + let rect = format!(r#""#, min.x, min.y, max.x - min.x, max.y - min.y); + match &leading_mask { + Some(mask) => format!(r#"{rect}"#), + None => rect, + } + } + false => cut_markup.unwrap_or(markup), + }; + write!(render.svg_defs, "{}{markup}", backdrop.mask_tag).unwrap(); } } /// Wraps `content` in the group of the last of the `filters` (innermost first, and none for a run SVG's own masks carry out), around the groups of those before it, /// each transforming into its run's effect space in `spaces`. Inside the innermost group, the content returns to the user space it's drawn in. -fn render_svg_filter_groups(render: &mut SvgRender, filters: &[Vec], spaces: Option<&[DAffine2]>, content: &mut dyn FnMut(&mut SvgRender)) { +/// Returns the markup within the groups of the first `captured_depth` filters, if asked for, which lies in the effect space of the run after them. +fn render_svg_filter_groups(render: &mut SvgRender, filters: &[Vec], spaces: Option<&[DAffine2]>, captured_depth: Option, content: &mut dyn FnMut(&mut SvgRender)) -> Option { + // The markup drawn at this depth is all that the group open around it holds + let group = render.open_groups.groups.len().saturating_sub(1); + let captured = |render: &SvgRender| -> Option { + if captured_depth != Some(filters.len()) { + return None; + } + let start = render.open_groups.groups.get(group)?.content_start; + Some(render.svg[start..].iter().map(SvgSegment::as_str).collect()) + }; + let Some((filter, inner_filters)) = filters.split_last() else { - return match spaces.and_then(|spaces| spaces.first()) { + match spaces.and_then(|spaces| spaces.first()) { Some(innermost_space) => render_svg_transformed(render, innermost_space.inverse(), content), None => content(render), - }; + } + return captured(render); }; // The group transforms from its run's effect space into the space of the run outside it @@ -992,6 +1248,7 @@ fn render_svg_filter_groups(render: &mut SvgRender, filters: &[Vec], spa None => spaces[index], }); + let mut inner_captured = None; render.parent_tag( "g", |attributes| { @@ -1007,10 +1264,13 @@ fn render_svg_filter_groups(render: &mut SvgRender, filters: &[Vec], spa let outside_transform = render.transform; render.transform = outside_transform * transform.unwrap_or_default(); let earlier_filters = &filter[..filter.len().saturating_sub(1)]; - render_svg_nested_filters(render, earlier_filters, &mut |render| render_svg_filter_groups(render, inner_filters, spaces, content)); + render_svg_nested_filters(render, earlier_filters, &mut |render| { + inner_captured = render_svg_filter_groups(render, inner_filters, spaces, captured_depth, content); + }); render.transform = outside_transform; }, ); + captured(render).or(inner_captured) } /// Wraps `content` in a group for each of the `filters` (innermost first), so each carries out its filter on the result of those inside it. @@ -1065,14 +1325,19 @@ struct DeferredMarkup { bounds: [DVec2; 2], } +impl SvgRender { + /// Whether images the GPU renders can replace the markup drawn now, unlike in masks and paints, nested markup no image can replace, or in deferred content, whose image holds it already. + pub(crate) fn images_replace_markup(&self, render_params: &RenderParams) -> bool { + !self.drawing_deferred_markup && !render_params.for_mask && !render_params.inside_pattern && !render_params.thumbnail + } +} + /// Opens markup standing in for an image the GPU renders of an item, if SVG filters can't carry out all its effects, which [`finish_deferred_markup`] then closes. /// `bounds` gives the content's extent in the current user space, and `overhang` how far it already paints past its frame there, as a group's nested effects do. fn start_deferred_markup(render: &mut SvgRender, render_params: &RenderParams, compositing: &ItemCompositing, bounds: impl FnOnce() -> RenderBoundingBox, overhang: f64) -> Option { - // Masks and paints are nested markup no image can replace, and content inside deferred content is in its image already. // TODO: Paints (patterns) whose effects need the GPU's maps then draw wrongly or not at all, unlike Vello. Embed a GPU render of such a paint, // filled in by `svg_readback.rs` like its images, maps, and planned generators (see the values and renders plan's boundary work). - let replaceable = !render.drawing_deferred_markup && !render_params.for_mask && !render_params.inside_pattern && !render_params.thumbnail; - if !replaceable || compositing.svg_expresses_effects() || !render.transform.matrix2.determinant().is_normal() { + if !render.images_replace_markup(render_params) || compositing.svg_expresses_effects() || !render.transform.matrix2.determinant().is_normal() { return None; } let RenderBoundingBox::Rectangle([min, max]) = bounds() else { return None }; @@ -1106,7 +1371,7 @@ fn finish_deferred_markup( render.deferred_images.push(DeferredImage { id, - content: content(), + content: DeferredContent::Item(content()), render_params: render_params.clone(), user_to_document: render.transform, bounds, @@ -1829,6 +2094,8 @@ fn write_svg_effects_filter_on_lattice( full = faded(&full); continue; } + // What lies beneath is copied outside the filter, which can't read it + EffectOperation::BackgroundBlur { .. } => continue, EffectOperation::Adjustment(ref adjustment) => { if !(shows_content || cuts_within) { continue; @@ -1949,6 +2216,7 @@ fn write_svg_effects_filter_on_lattice( primitives.push("feComposite", &format!(r#"in="{tinted}" in2="{share}" operator="in""#), "") } (PiecePlace::Beneath, _) | (PiecePlace::IntoContent { .. }, None) => tinted.clone(), + (PiecePlace::Backdrop, _) => continue, }; stack = Some(match stack { Some(stack) => primitives.composite_beneath(&upper, &stack), @@ -2091,9 +2359,11 @@ pub struct SvgRender { /// The content with effects SVG filters can't carry out, for the GPU to render images of in place of the markup standing in for it. pub deferred_images: Vec, /// Whether markup standing in for deferred content is being drawn, inside which nothing more is deferred since the content's image covers it. - drawing_deferred_markup: bool, + pub(crate) drawing_deferred_markup: bool, /// How far the filters of the groups around the content being drawn read past it, in document pixels, which the maps and images inside cover past the view. pub(crate) ancestors_reach: f64, + /// The groups open so far, which content reading what lies beneath it copies its backdrop from. + pub(crate) open_groups: OpenGroups, indent: usize, } @@ -2108,11 +2378,19 @@ impl SvgRender { deferred_images: Vec::new(), drawing_deferred_markup: false, ancestors_reach: 0., + open_groups: OpenGroups::default(), indent: 0, } } pub fn indent(&mut self) { + // The first markup inside a group is drawn in its content's user space + if let Some(group) = self.open_groups.groups.last_mut() + && group.user_to_document.is_none() + { + group.user_to_document = Some(self.transform); + } + self.svg.push("\n".into()); self.svg.push("\t".repeat(self.indent).into()); } @@ -2167,15 +2445,22 @@ impl SvgRender { pub fn parent_tag(&mut self, name: impl Into, attributes: impl FnOnce(&mut SvgRenderAttrs), inner: impl FnOnce(&mut Self)) { let name = name.into(); self.indent(); + let tag_start = self.svg.len(); self.svg.push("<".into()); self.svg.push(name.clone()); // Wraps `self` in a newtype (1-tuple) which is then mutated by the `attributes` closure + self.open_groups.opening_isolates = false; + self.open_groups.opening_clip_path = None; attributes(&mut SvgRenderAttrs(self)); self.svg.push(">".into()); let length = self.svg.len(); + let isolates = std::mem::take(&mut self.open_groups.opening_isolates); + let clip_path = self.open_groups.opening_clip_path.take(); + self.open_groups.groups.push(OpenGroup::new(tag_start, length, isolates, clip_path)); self.indent += 1; inner(self); self.indent -= 1; + self.open_groups.groups.pop(); if self.svg.len() != length { self.indent(); self.svg.push(" for SvgRender { deferred_images: value.deferred_images.clone(), drawing_deferred_markup: false, ancestors_reach: 0., + open_groups: OpenGroups::default(), indent: 0, } } @@ -2812,6 +3098,26 @@ fn masker_region(masker: &Graphic, transform: DAffine2) -> Option<[DVec2; 2]> { Some([min - reach, max + reach]) } +/// The shapes in the document a clipping `base` reducible to a clip path clips by the union of, which `base_to_document` places there, each filled by the nonzero rule. +/// They're the paths SVG draws of each vector: its contours together, and each face it fills where its segments branch. +fn clip_base_shapes(base: &Graphic, base_to_document: DAffine2) -> Vec { + let mut shapes = Vec::new(); + let mut add = |item: ItemRef<'_, Vector>| { + let placement = Affine::new((base_to_document * item.attribute_cloned_or_default::(ATTR_TRANSFORM)).to_cols_array()); + shapes.push(item.contours().iter().flat_map(|contour| (placement * contour).into_iter()).collect()); + if item.fills_faces() { + shapes.extend(item.faces().iter().map(|face| placement * face)); + } + }; + + match base { + Graphic::Vector(item) => add(ItemRef::Item(item)), + Graphic::VectorList(list) => (0..list.len()).for_each(|index| add(ItemRef::ListItem(list, index))), + _ => {} + } + shapes +} + /// Emits one item of graphic content as SVG, wrapped in a group carrying the item's transform, opacity, and blend mode. /// `mask_state` carries the sibling clipping run between a list's items; a lone item has no siblings, so both mask inputs stay inert. fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_state: &mut Option<(u64, MaskType)>, render: &mut SvgRender, render_params: &RenderParams) { @@ -2839,6 +3145,7 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st let mut svg = SvgRender::new(); svg.transform = render.transform * base_transform; svg.ancestors_reach = render.ancestors_reach; + svg.open_groups.clip = true; base.render_svg(&mut svg, &render_params.for_clipper()); // The def is resolved in this list's space, so the masker's own transform has to be baked into it @@ -2850,6 +3157,9 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st render.svg_defs.push_str(&svg.svg_defs); render.effect_maps.extend(svg.effect_maps); mask_type.write_to_defs(&mut render.svg_defs, uuid, masker, masker_region(&base, base_transform)); + if mask_type == MaskType::Clip { + render.record_clip_shapes(&format!("url(#mask-{uuid})"), || clip_base_shapes(&base, svg.transform), render_params); + } *mask_state = Some((uuid, mask_type)); } else if let Some((uuid, mask_type)) = *mask_state { @@ -2915,7 +3225,7 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st let filters = compositing.svg_filters(render, render_params, effects_bounds, |keeps| Graphic::Graphic(Box::new(effects_content(item, element.clone(), keeps)))); let filtered = filters.is_some(); - render_svg_through_filters(render, filters, compositing.opacity, render_params.to_canvas(), |render| { + render_svg_through_filters(render, filters, compositing.opacity, |render| { render.parent_tag( "g", |attributes| { @@ -3019,7 +3329,13 @@ fn render_graphic_item_to_vello<'a>( _ => None, }; - let layer = if needs_layer && let Some(rect) = layer_rect { + // Content reading what lies beneath it would find nothing inside a layer (its own, or a clipping mask's), so a group holding some renders offscreen instead, where what it drew so far lies beneath + let isolated = needs_layer || mask_element_and_transform.is_some(); + let offscreen = isolated && render_params.render_mode != RenderMode::Outline && nested_effects_read_backdrop(element); + let layer = if needs_layer + && !offscreen + && let Some(rect) = layer_rect + { scene.push_layer( peniko::Fill::NonZero, peniko::BlendMode::new(blend_mode, peniko::Compose::SrcOver), @@ -3037,9 +3353,27 @@ fn render_graphic_item_to_vello<'a>( bounds => bounds, }; let draw_content = |scene: &mut VelloSceneBuilder| { - compositing.draw_with_effects(scene, parent_transform, render_params, effects_bounds, frame, nested_reach.max_element(), |scene| { - element.render_to_vello(scene, transform, render_params) - }); + let mut draw = |scene: &mut VelloSceneBuilder| { + compositing.draw_with_effects(scene, parent_transform, render_params, effects_bounds, frame, nested_reach.max_element(), |scene| { + element.render_to_vello(scene, transform, render_params) + }); + }; + match (offscreen, bounds) { + (false, _) => draw(scene), + (true, RenderBoundingBox::None) => {} + (true, _) => scene.draw_effects( + &Effects::default(), + 1., + compositing.opacity, + blend_mode_attr, + true, + layer_rect, + DAffine2::IDENTITY, + None, + &mut |_, _| {}, + &mut draw, + ), + } }; if next_clips && mask_element_and_transform.is_none() { @@ -3092,9 +3426,10 @@ fn collect_graphic_item_metadata(item: ItemRef<'_, Graphic>, metadata: &mut Rend footprint.transform *= item_transform; if let Some(layer) = item.layer() { - let nested = nested_effects_reach(element, footprint.transform, |_| true); + let painted: fn(&EffectOperation) -> bool = |operation| !operation.paints_only_within_content(); + let nested = nested_effects_reach(element, footprint.transform, painted); let own = (item.attribute::(ATTR_EFFECTS)).map_or(DVec2::ZERO, |effects| { - effects_reach_around(effects, footprint.transform, || drawn_bounding_box(element, footprint.transform), nested.max_element(), |_| true) + effects_reach_around(effects, footprint.transform, || drawn_bounding_box(element, footprint.transform), nested.max_element(), painted) }); let reach = (own + nested).max_element(); if reach > 0. { @@ -3189,8 +3524,28 @@ fn add_graphic_item_outline_targets(item: ItemRef<'_, Graphic>, outlines: &mut V outlines.extend(new_outlines); } +/// Draws each of the `list`'s items with `draw`, recording them as they're drawn for images of what lies beneath content drawn after them. +fn render_list_items_svg(list: &List, render: &mut SvgRender, render_params: &RenderParams, mut draw: impl FnMut(usize, &mut SvgRender)) +where + List: Render, +{ + let record = render.record_drawn(|| list.clone(), render.transform, render_params); + + for index in 0..list.len() { + draw(index, render); + render.drew_items(record, index + 1); + } +} + impl Render for Graphic { fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) { + // A lone item is recorded for images of what lies beneath content drawn after it, as a list records its own items + let lone_item = matches!( + self, + Graphic::Graphic(_) | Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Generator(_) | Graphic::Text(_) + ); + let record = if lone_item { render.record_drawn(|| self.clone(), render.transform, render_params) } else { None }; + match self { Graphic::None(_) | Graphic::NoneList(_) => (), Graphic::Graphic(item) => render_graphic_item_svg(ItemRef::Item(item), false, &mut None, render, render_params), @@ -3211,6 +3566,8 @@ impl Render for Graphic { Graphic::TextList(list) => list.render_svg(render, render_params), Graphic::StrokeList(_) => (), } + + render.drew_items(record, 1); } fn render_to_vello(&self, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) { @@ -3438,6 +3795,8 @@ fn read_artboard_attributes(list: &List, index: usize) -> (DVec2, DVec impl Render for List { fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) { + let record = render.record_drawn(|| self.clone(), render.transform, render_params); + for index in 0..self.len() { let Some(content) = self.element(index).map(Artboard::as_graphic_list) else { continue }; let (location, dimensions, background, clip) = read_artboard_attributes(self, index); @@ -3448,6 +3807,7 @@ impl Render for List { let height = dimensions.y.abs(); // Background, which goes inside a clipping artboard's group since a clip path isolates what blends inside it from anything outside + let outer_transform = render.transform; let background_rect = |render: &mut SvgRender, offset: DVec2| { render.leaf_tag("rect", |attributes| { attributes.push("fill", format!("#{}", SRGBA8::from(background).to_rgb_hex())); @@ -3459,6 +3819,11 @@ impl Render for List { attributes.push("width", width.to_string()); attributes.push("height", height.to_string()); }); + + // Recorded as the artboard without its content, until the whole artboard is once it's drawn + let background_only = || List::new_from_item(Item::from_parts(Artboard::new(List::new()), self.clone_item_attributes(index))); + let background = render.record_drawn(background_only, outer_transform, render_params); + render.drew_items(background, 1); }; if !clip { background_rect(render, DVec2::ZERO); @@ -3486,24 +3851,29 @@ impl Render for List { y - location.y, ) .unwrap(); + let shapes = || vec![Affine::new(outer_transform.to_cols_array()) * kurbo::Rect::new(x, y, x + width, y + height).to_path(0.1)]; + attributes.0.record_clip_shapes(&selector, shapes, render_params); attributes.push("clip-path", selector); } }, // Artwork content |render| { + // Everything inside is in the group's translated user space, the background included + let parent_transform = render.transform; + render.transform = parent_transform * DAffine2::from_translation(location); + if clip { background_rect(render, location); } let mut render_params = render_params.clone(); render_params.artboard_background = Some(background); - - let parent_transform = render.transform; - render.transform = parent_transform * DAffine2::from_translation(location); content.render_svg(render, &render_params); render.transform = parent_transform; }, ); + + render.drew_items(record, index + 1); } } @@ -3580,10 +3950,10 @@ impl Render for List { fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) { let mut mask_state = None; - for index in 0..self.len() { + render_list_items_svg(self, render, render_params, |index, render| { let next_clips = index + 1 < self.len() && self.element(index + 1).unwrap().had_clip_enabled(); render_graphic_item_svg(ItemRef::ListItem(self, index), next_clips, &mut mask_state, render, render_params); - } + }); } fn render_to_vello(&self, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) { @@ -3688,7 +4058,7 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, filtered: let needs_separate_alignment_fill = can_draw_aligned_stroke && !can_use_paint_order; let override_paint_order = can_draw_aligned_stroke && can_use_paint_order; - let use_face_fill = vector.use_face_fill(paths); + let use_face_fill = item.fills_faces(); if needs_separate_alignment_fill && !wants_stroke_below { emit_svg_fill_path( @@ -3882,10 +4252,15 @@ fn render_vector_item_svg(item: ItemRef<'_, Vector>, next_clips: bool, clip_mask let mut masker_svg = SvgRender::new(); masker_svg.transform = render.transform; + masker_svg.open_groups.clip = true; masker.render_svg(&mut masker_svg, &render_params.for_clipper()); render.svg_defs.push_str(&masker_svg.svg_defs); render.effect_maps.extend(masker_svg.effect_maps); mask_type.write_to_defs(&mut render.svg_defs, uuid, masker_svg.svg.to_svg_string(), masker_region(&masker, DAffine2::IDENTITY)); + if mask_type == MaskType::Clip { + let masker_to_document = render.transform; + render.record_clip_shapes(&format!("url(#mask-{uuid})"), || clip_base_shapes(&masker, masker_to_document), render_params); + } *clip_mask_state = Some((uuid, mask_type)); } else if let Some((uuid, mask_type)) = *clip_mask_state { @@ -3940,7 +4315,7 @@ fn render_vector_item_svg(item: ItemRef<'_, Vector>, next_clips: bool, clip_mask let filtered = filters.is_some(); let blend_mode: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); - render_svg_through_filters(render, filters, compositing.opacity, render_params.to_canvas(), |render| { + render_svg_through_filters(render, filters, compositing.opacity, |render| { // The item's own filters read its paints around each pixel, so a pattern paint's images and maps cover past the view as far as they read let own_reach = if filtered { compositing.effects.map_or(0., |(effects, _)| effects.read_reach(render.transform * compositing.content_transform)) @@ -4504,11 +4879,11 @@ impl Render for List { fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) { let mut clip_mask_state: Option<(u64, MaskType)> = None; - for index in 0..self.len() { + render_list_items_svg(self, render, render_params, |index, render| { // A clip-flagged item is masked by its nearest preceding unflagged sibling, which a consecutive run shares let next_clips = index + 1 < self.len() && self.attribute_cloned_or_default::(ATTR_CLIPPING_MASK, index + 1); render_vector_item_svg(ItemRef::ListItem(self, index), next_clips, &mut clip_mask_state, render, render_params); - } + }); } fn render_to_vello(&self, scene: &mut VelloSceneBuilder, parent_transform: DAffine2, render_params: &RenderParams) { @@ -4711,7 +5086,7 @@ fn render_raster_cpu_item_svg(item: ItemRef<'_, Raster>, render: &mut SvgRe None => (compositing.opacity_without_effects(), blend_mode_attr), }; - render_svg_through_filters(render, filters, compositing.opacity, render_params.to_canvas(), |render| { + render_svg_through_filters(render, filters, compositing.opacity, |render| { render_raster_cpu_image_svg(image, transform, opacity, blend_mode, render, render_params) }); @@ -4894,7 +5269,7 @@ fn render_generator_item_svg(item: ItemRef<'_, Generator>, render: &mut SvgRende let bounds = (image_transform * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box(); let deferred = start_deferred_markup(render, render_params, &compositing, || RenderBoundingBox::Rectangle(bounds), 0.); - let filters = compositing.svg_filters_within(render, render_params, bounds, |keeps| { + let filters = compositing.svg_filters_within(render, render_params, bounds, false, |keeps| { let mut content = effects_content(item, generator, keeps); content.set_attribute(ATTR_EFFECTS, compositing.effects.map(|(effects, _)| effects.clone()).unwrap_or_default()); Graphic::Generator(content) @@ -4905,7 +5280,7 @@ fn render_generator_item_svg(item: ItemRef<'_, Generator>, render: &mut SvgRende Some(_) => (1., BlendMode::default()), None => (compositing.opacity_without_effects(), blend_mode_attr), }; - render_svg_through_filters(render, filters, compositing.opacity, render_params.to_canvas(), |render| { + render_svg_through_filters(render, filters, compositing.opacity, |render| { render_raster_cpu_image_svg(&image, image_transform, opacity, blend_mode, render, render_params) }); @@ -4989,9 +5364,9 @@ fn render_generator_item_to_vello(item: ItemRef<'_, Generator>, scene: &mut Vell impl Render for List { fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) { - for index in 0..self.len() { - render_generator_item_svg(ItemRef::ListItem(self, index), render, render_params); - } + render_list_items_svg(self, render, render_params, |index, render| { + render_generator_item_svg(ItemRef::ListItem(self, index), render, render_params) + }); } fn render_to_vello(&self, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) { @@ -5038,9 +5413,9 @@ fn add_unit_square_click_target(transform: DAffine2, click_targets: &mut Vec> { fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) { - for index in 0..self.len() { - render_raster_cpu_item_svg(ItemRef::ListItem(self, index), render, render_params); - } + render_list_items_svg(self, render, render_params, |index, render| { + render_raster_cpu_item_svg(ItemRef::ListItem(self, index), render, render_params) + }); } fn render_to_vello(&self, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) { @@ -5156,9 +5531,9 @@ impl Render for List { // For Vello, the scene records a viewport fill that covers whatever area each render draws. impl Render for List { fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) { - for index in 0..self.len() { - render_color_item_svg(ItemRef::ListItem(self, index), render, render_params); - } + render_list_items_svg(self, render, render_params, |index, render| { + render_color_item_svg(ItemRef::ListItem(self, index), render, render_params) + }); } fn render_to_vello(&self, scene: &mut VelloSceneBuilder, parent_transform: DAffine2, render_params: &RenderParams) { @@ -5181,11 +5556,11 @@ fn render_color_item_svg(item: ItemRef<'_, Color>, render: &mut SvgRender, rende let blend_mode: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); let bounds = || RenderBoundingBox::Rectangle(extent); let deferred = start_deferred_markup(render, render_params, &compositing, bounds, 0.); - let filters = compositing.svg_filters_within(render, render_params, extent, |keeps| Graphic::Color(effects_content(item, color, keeps))); + let filters = compositing.svg_filters_within(render, render_params, extent, false, |keeps| Graphic::Color(effects_content(item, color, keeps))); // Without filters, as in an effect space that collapses, the color takes its opacity and blend mode as if its masks left it without edges let filtered = filters.is_some(); - render_svg_through_filters(render, filters, compositing.opacity, render_params.to_canvas(), |render| match filtered { + render_svg_through_filters(render, filters, compositing.opacity, |render| match filtered { true => emit_endless_color(render, color, 1., BlendMode::Normal, None), false => render_edgeless_color_svg(item, render, &compositing, color, render_params), }); @@ -5229,9 +5604,7 @@ fn render_edgeless_color_svg(item: ItemRef<'_, Color>, render: &mut SvgRender, c }); if let Some((filters, adjustments)) = field_filters { let color = adjusted_color(color, &adjustments); - return render_svg_through_filters(render, Some(filters), compositing.opacity, render_params.to_canvas(), |render| { - emit_endless_color(render, color, 1., BlendMode::Normal, None) - }); + return render_svg_through_filters(render, Some(filters), compositing.opacity, |render| emit_endless_color(render, color, 1., BlendMode::Normal, None)); } // SVG filters change nothing else visible about an endless color, so its adjustments are carried out on the color itself @@ -5349,7 +5722,7 @@ fn endless_field_filters( let filters = compositing .with_remaining_effects(&remaining) - .svg_filters_within(render, render_params, area, |keeps| content(remaining.clone(), keeps, &adjustments))?; + .svg_filters_within(render, render_params, area, false, |keeps| content(remaining.clone(), keeps, &adjustments))?; Some((filters, adjustments)) } @@ -5503,9 +5876,9 @@ impl Render for List { fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) { let thumbnail_rect = gradient_thumbnail_rect(render_params); - for index in 0..self.len() { - render_gradient_item_svg_with_thumbnail_rect(ItemRef::ListItem(self, index), thumbnail_rect, render, render_params); - } + render_list_items_svg(self, render, render_params, |index, render| { + render_gradient_item_svg_with_thumbnail_rect(ItemRef::ListItem(self, index), thumbnail_rect, render, render_params) + }); } fn render_to_vello(&self, scene: &mut VelloSceneBuilder, parent_transform: DAffine2, render_params: &RenderParams) { @@ -5545,11 +5918,11 @@ fn render_gradient_item_svg_with_thumbnail_rect(item: ItemRef<'_, Gradient>, thu let blend_mode: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); let bounds = || RenderBoundingBox::Rectangle(extent); let deferred = start_deferred_markup(render, render_params, &compositing, bounds, 0.); - let filters = compositing.svg_filters_within(render, render_params, extent, |keeps| Graphic::Gradient(effects_content(item, source_gradient.clone(), keeps))); + let filters = compositing.svg_filters_within(render, render_params, extent, false, |keeps| Graphic::Gradient(effects_content(item, source_gradient.clone(), keeps))); // Without filters, as in an effect space that collapses, the gradient takes its opacity and blend mode as if its masks left it without edges let filtered = filters.is_some(); - render_svg_through_filters(render, filters, compositing.opacity, render_params.to_canvas(), |render| match filtered { + render_svg_through_filters(render, filters, compositing.opacity, |render| match filtered { true => render_gradient_shape_svg(item, source_gradient, settings, None, 1., BlendMode::Normal, render, render_params), false => render_edgeless_gradient_svg(item, source_gradient, settings, None, &compositing, render, render_params), }); @@ -5593,7 +5966,7 @@ fn render_edgeless_gradient_svg( Some((adjusted, settings)) => (Cow::Owned(adjusted), settings), None => (Cow::Borrowed(source_gradient), settings), }; - return render_svg_through_filters(render, Some(filters), compositing.opacity, render_params.to_canvas(), |render| { + return render_svg_through_filters(render, Some(filters), compositing.opacity, |render| { render_gradient_shape_svg(item, &gradient, settings, thumbnail_rect, 1., BlendMode::Normal, render, render_params) }); } @@ -6221,7 +6594,7 @@ fn render_text_item_svg(item: ItemRef<'_, String>, render: &mut SvgRender, rende let filtered = filters.is_some(); // Wrap all glyph elements in a with the item's transform/opacity/blend-mode, which a filter's wrapping group takes instead - render_svg_through_filters(render, filters, compositing.opacity, render_params.to_canvas(), |render| { + render_svg_through_filters(render, filters, compositing.opacity, |render| { render.parent_tag( "g", |attributes| { @@ -6392,9 +6765,7 @@ fn add_text_item_click_targets(item: ItemRef<'_, String>, click_targets: &mut Ve impl Render for List { fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) { - for index in 0..self.len() { - render_text_item_svg(ItemRef::ListItem(self, index), render, render_params); - } + render_list_items_svg(self, render, render_params, |index, render| render_text_item_svg(ItemRef::ListItem(self, index), render, render_params)); } fn render_to_vello(&self, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) { @@ -6418,6 +6789,8 @@ impl Render for List { pub enum SvgSegment { Slice(&'static str), String(String), + /// Markup showing what lies beneath content reading it, which copies of what lies beneath can leave out. + Backdrop(String), } impl From for SvgSegment { @@ -6432,6 +6805,15 @@ impl From<&'static str> for SvgSegment { } } +impl SvgSegment { + pub fn as_str(&self) -> &str { + match self { + Self::Slice(text) => text, + Self::String(text) | Self::Backdrop(text) => text, + } + } +} + pub trait RenderSvgSegmentList { fn to_svg_string(&self) -> String; } @@ -6440,10 +6822,7 @@ impl RenderSvgSegmentList for Vec { fn to_svg_string(&self) -> String { let mut result = String::new(); for segment in self.iter() { - result.push_str(match segment { - SvgSegment::Slice(x) => x, - SvgSegment::String(x) => x, - }); + result.push_str(segment.as_str()); } result } @@ -6460,7 +6839,14 @@ impl SvgRenderAttrs<'_> { self.0.svg.push("\"".into()); } pub fn push(&mut self, name: impl Into, value: impl Into) { - self.push_complex(name, move |renderer| renderer.svg.push(value.into())); + let (name, value) = (name.into(), value.into()); + if svg_backdrop::isolates(name.as_str(), value.as_str()) { + self.0.open_groups.opening_isolates = true; + } + if name.as_str() == "clip-path" { + self.0.open_groups.opening_clip_path = Some(value.as_str().to_string()); + } + self.push_complex(name, move |renderer| renderer.svg.push(value)); } pub fn push_val(&mut self, value: impl Into) { self.0.svg.push(value.into()); @@ -6956,6 +7342,7 @@ mod tests { _: f32, _: DAffine2, _: Option, + _: Option<(&wgpu::Texture, kurbo::Affine)>, _: Option, _: &mut dyn FnMut(usize, &mut VelloSceneBuilder), _: &mut dyn FnMut(&mut VelloSceneBuilder), @@ -7013,9 +7400,17 @@ mod tests { assert!(content_id.starts_with("effects-content-") && layered.contains(&format!(r##"` copy leaves out, so its markup is copied into each layer + let mut image = Item::new_from_element(Raster::new_cpu(graphic_types::raster_types::Image::new(2, 2, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(10.))); + graphic_types::stamp_effect(&mut image, graphic_types::Effect::new(&red_shadow)); + let mut render = SvgRender::new(); + List::new_from_item(image).render_svg(&mut render, &RenderParams::default()); + let image = render.svg.to_svg_string(); + assert!(!image.contains(", + _: Option<(&wgpu::Texture, kurbo::Affine)>, _: Option, _: &mut dyn FnMut(usize, &mut VelloSceneBuilder), _: &mut dyn FnMut(&mut VelloSceneBuilder), @@ -7271,6 +7667,7 @@ mod tests { _: f32, _: DAffine2, _: Option, + _: Option<(&wgpu::Texture, kurbo::Affine)>, _: Option, _: &mut dyn FnMut(usize, &mut VelloSceneBuilder), _: &mut dyn FnMut(&mut VelloSceneBuilder), @@ -7379,6 +7776,7 @@ mod tests { _: f32, _: DAffine2, frame: Option, + _: Option<(&wgpu::Texture, kurbo::Affine)>, _: Option, _: &mut dyn FnMut(usize, &mut VelloSceneBuilder), _: &mut dyn FnMut(&mut VelloSceneBuilder), @@ -7458,13 +7856,17 @@ mod tests { #[test] fn lists_paint_as_far_as_the_effects_nested_anywhere_inside_them_paint() { - use graphic_types::EffectOperation; + use graphic_types::{EffectKind, EffectOperation}; - // A shadow on a square inside a group paints past the group + // A shadow on a square inside a group paints past the group, while an inner shadow paints only within its content let shadow = drop_shadow(135., 20., 5.); let in_group = |effects: &[EffectOperation]| List::new_from_element(Graphic::VectorList(orange_square(effects, 1., 1.))); let square_grown_by = |reach: f64| RenderBoundingBox::Rectangle([DVec2::splat(-reach), DVec2::splat(10. + reach)]); assert_eq!(graphic_list_painted_bounds(&in_group(std::slice::from_ref(&shadow)), true), square_grown_by(shadow.reach())); + assert_eq!( + graphic_list_painted_bounds(&in_group(&[EffectOperation::default_for(EffectKind::InnerShadow)]), true), + square_grown_by(0.) + ); // An SVG with no GPU leaves the shadow out, so it frames the square alone, but it draws a Minimum's grown coverage past the square on its own assert_eq!(graphic_list_painted_bounds(&in_group(std::slice::from_ref(&shadow)), false), square_grown_by(0.)); @@ -7548,10 +7950,15 @@ mod tests { feather: 20., invert: false, }; + let background_blur = graphic_types::EffectOperation::BackgroundBlur { + radius: 30., + box_blur: false, + gamma: false, + }; - // A shadow's map is read by the blur after it and by the blur of the group around the item, but not by the mask's feather, which reads another image + // A shadow's map is read by the blur after it and by the blur of the group around the item, but not by the mask's feather or the background blur, which read other images let mut group = Item::new_from_element(Graphic::VectorList(orange_square(&[drop_shadow(180., 30., 10.), blur.clone(), feathered_mask], 1., 1.))); - group.set_attribute(ATTR_EFFECTS, Effects::from_operations([blur])); + group.set_attribute(ATTR_EFFECTS, Effects::from_operations([blur, background_blur])); let mut render = SvgRender::new(); List::new_from_item(group).render_svg( &mut render, @@ -8009,6 +8416,48 @@ mod tests { assert_eq!(render_canvas_images().keys().collect::>(), first.keys().collect::>()); } + #[test] + fn svg_background_blurs_copy_what_lies_beneath_into_a_blurred_group_cut_to_the_content() { + use graphic_types::raster_types::Image; + use graphic_types::{Effect, EffectOperation, stamp_effect}; + + let image = |transform: DAffine2| Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::WHITE))).with_attribute(ATTR_TRANSFORM, transform); + let mut glass = image(DAffine2::from_translation(DVec2::splat(5.)) * DAffine2::from_scale(DVec2::splat(10.))); + stamp_effect( + &mut glass, + Effect::new(&EffectOperation::BackgroundBlur { + radius: 2., + box_blur: false, + gamma: false, + }), + ); + let mut list = List::new_from_item(image(DAffine2::from_scale(DVec2::splat(20.)))); + list.push(glass); + + let mut render = SvgRender::new(); + list.render_svg( + &mut render, + &RenderParams { + for_export: true, + ..Default::default() + }, + ); + let svg = render.svg.to_svg_string(); + + // The image drawn first is wrapped in a group the glass copies, blurred, beneath its own unfiltered markup, and cut to it by a mask holding that markup + let backdrop_start = svg.find(r#""#), + "{}", + render.svg_defs + ); + let mask = render.svg_defs.split(" Item> { + use graphic_types::raster_types::Image; + use graphic_types::{Effect, EffectOperation, stamp_effect}; + + let mut image = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::WHITE))).with_attribute(ATTR_TRANSFORM, transform); + if glass { + let blur = EffectOperation::BackgroundBlur { + radius: 2., + box_blur: false, + gamma: false, + }; + stamp_effect(&mut image, Effect::new(&blur)); + } + image + } + + #[test] + fn svg_masks_fading_a_background_blur_with_the_content_carry_out_the_effects_of_their_own_graphics() { + use graphic_types::{Effect, EffectOperation, MaskMode, stamp_effect}; + + // A white raster covering the glass, feathered by an effect of its own stamped where it's drawn + let placement = DAffine2::from_translation(DVec2::splat(5.)) * DAffine2::from_scale(DVec2::splat(10.)); + let mut feathered = white_image(placement, false); + stamp_effect(&mut feathered, Effect::new(&EffectOperation::Feather { distance: 2. })); + feathered.set_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY); + let mask = EffectOperation::Mask { + mask: Graphic::RasterCPU(Box::new(feathered)), + mode: MaskMode::Alpha, + density: 100., + feather: 0., + invert: false, + }; + let zero_blur = EffectOperation::Blur { + radius_mask: Graphic::default(), + radius: 0., + box_blur: false, + gamma: false, + }; + + // Upright with a row changing nothing after the mask, so only the GPU's plan counts it as trailing, and stretched since stamping, measuring in a space of its own + let stretched = DAffine2::from_translation(DVec2::new(10., 5.)) * DAffine2::from_scale(DVec2::new(20., 10.)); + for (case, operations, placed_since, fading_group) in [ + ("upright", vec![mask.clone(), zero_blur], None, r#"(ATTR_EFFECTS).is_some_and(feathers), "{case}"); + + let faded = element_markup(&svg, fading_group).unwrap_or_else(|| panic!("{case}: no group fades the copy with the content in {svg}")); + let mask_id = faded.split(r#"mask="url(#"#).nth(1).and_then(|rest| rest.split(')').next()).unwrap_or_default(); + let fading_mask = element_markup(&render.svg_defs, &format!(r#"", map.id)), "{case}: {fading_mask}"); + } + } + + /// The markup of the first element with an opening tag starting with `opening`, through its closing tag, so it holds just that element and those inside it. + fn element_markup<'a>(markup: &'a str, opening: &str) -> Option<&'a str> { + let start = markup.find(opening)?; + let name = opening.strip_prefix('<')?.split([' ', '/', '>']).next()?; + let (open, close) = (format!("<{name}"), format!("")); + + // Its closing tag is the one returning the nesting of tags of its name to none + let (mut depth, mut index) = (0, start); + while let Some(offset) = markup[index..].find('<') { + let tag_start = index + offset; + index = tag_start + markup[tag_start..].find('>')? + 1; + let tag = &markup[tag_start..index]; + + if tag == close { + depth -= 1; + if depth == 0 { + return Some(&markup[start..index]); + } + } else if tag.strip_prefix(&open).is_some_and(|rest| rest.starts_with([' ', '>'])) && !tag.ends_with("/>") { + depth += 1; + } + } + None + } + + #[test] + fn svg_background_blurs_in_a_clipping_artboard_copy_in_its_own_space_and_clip() { + let mut images = List::new_from_item(white_image(DAffine2::from_scale(DVec2::splat(20.)), false)); + images.push(white_image(DAffine2::from_translation(DVec2::splat(5.)) * DAffine2::from_scale(DVec2::splat(10.)), true)); + let mut artboards = List::new_from_element(Artboard::new(List::new_from_element(Graphic::RasterCPUList(images)))); + artboards.set_attribute(ATTR_LOCATION, 0, DVec2::new(100., 50.)); + artboards.set_attribute(ATTR_DIMENSIONS, 0, DVec2::splat(40.)); + artboards.set_attribute(ATTR_CLIP, 0, true); + + let mut render = SvgRender::new(); + artboards.render_svg( + &mut render, + &RenderParams { + for_export: true, + ..Default::default() + }, + ); + let svg = render.svg.to_svg_string(); + + // The copies of the artboard's background and of the image in the group inside it lie in its translated space, clipped by it as the originals are + let clipped = svg.split(r#"").next()).expect("the copies are clipped"); + assert!(copies.matches(r##" = [Item::new_from_element(Graphic::RasterCPUList(images)), clipped].into_iter().collect(); + + let mut render = SvgRender::new(); + list.render_svg( + &mut render, + &RenderParams { + for_export: true, + ..Default::default() + }, + ); + + // The glass copies the image beneath it where the group is drawn, but not in the clip + let svg = render.svg.to_svg_string(); + assert_eq!(svg.matches(r##" List> { + let mut images = List::new_from_item(white_image(DAffine2::from_scale(DVec2::splat(20.)), false)); + for index in 0..panes { + images.push(white_image(DAffine2::from_translation(DVec2::splat(index as f64)) * DAffine2::from_scale(DVec2::splat(10.)), true)); + } + images + } + + /// The SVG render of `graphic` for an export. + fn exported(graphic: &impl Render) -> SvgRender { + let mut render = SvgRender::new(); + let render_params = RenderParams { + for_export: true, + ..Default::default() + }; + graphic.render_svg(&mut render, &render_params); + render + } + + /// How many items of each content drawn beneath it the image of what lies beneath content holds, in order. + fn drawn_beneath(image: &DeferredImage) -> Vec { + match &image.content { + DeferredContent::Beneath { drawn, .. } => drawn.iter().map(|drawn| drawn.count).collect(), + DeferredContent::Item(_) => panic!("expected an image of what lies beneath"), + } + } + + /// The outline in the document cutting what an image of what lies beneath content holds, if any does. + fn clip_outline_beneath(image: &DeferredImage) -> Option<&BezPath> { + match &image.content { + DeferredContent::Beneath { clip, .. } => clip.as_ref(), + DeferredContent::Item(_) => panic!("expected an image of what lies beneath"), + } + } + + /// The bounds in the document of the outline cutting what an image of what lies beneath content holds, if any does. + fn clip_beneath(image: &DeferredImage) -> Option<[DVec2; 2]> { + let bounds = clip_outline_beneath(image)?.bounding_box(); + Some([DVec2::new(bounds.x0, bounds.y0), DVec2::new(bounds.x1, bounds.y1)]) + } + + /// Whether the outline cutting what an image of what lies beneath content holds covers the `point`, filled by the nonzero rule. + fn clip_beneath_covers(image: &DeferredImage, point: kurbo::Point) -> bool { + clip_outline_beneath(image).is_some_and(|outline| svg_backdrop::closed_subpaths(outline).winding(point) != 0) + } + + /// The attributes of the innermost group open around the markers of the deferred `image` in the `svg`. + fn group_around_image<'a>(svg: &'a str, image: &DeferredImage) -> &'a str { + let (opening, _) = deferred_image::image_markers(image.id); + let position = svg.find(&opening).unwrap_or_else(|| panic!("no markers of the image in {svg}")); + svg[..position].rsplit(" = [group, Item::new_from_element(Graphic::RasterCPUList(List::new_from_item(glass)))].into_iter().collect(); + + let render = exported(&list); + let svg = render.svg.to_svg_string(); + + // The glass inside copies what the group drew beneath it, so the glass over the group, whose backdrop holds that copy, blurs an image of the group + assert_eq!(svg.matches(r##") -> DeferredImage { + let group = Item::new_from_element(Graphic::RasterCPUList(stacked_glass(2))).with_attribute(ATTR_CLIPPING_MASK, true); + let list: List = [Item::new_from_element(Graphic::VectorList(base)), Item::new_from_element(Graphic::Graphic(Box::new(group)))] + .into_iter() + .collect(); + + let render = exported(&list); + let [image] = &render.deferred_images[..] else { + panic!("expected one image, got {}", render.deferred_images.len()) + }; + image.clone() + } + + /// A vector of linear `paths` through the `points` they index, each path a run of segments, closed by ending where it starts. + fn vector_of_paths(points: &[(f64, f64)], paths: &[&[u32]]) -> Item { + use core_types::list::{ATTR_CURVE_TYPE, ATTR_ID}; + use graphic_types::vector_types::vector::{CurveType, PointId, SegmentId}; + + let mut vector = Vector::default(); + let mut point_id = PointId::ZERO; + for (index, &(x, y)) in points.iter().enumerate() { + vector.0.push(Item::new_from_element(DVec2::new(x, y))); + vector.0.set_attribute(ATTR_ID, index, point_id.next_id()); + } + + let mut path_list = List::new(); + let mut segment_id = SegmentId::ZERO; + for references in paths { + let mut path = Path::from_references(references.iter().copied()); + for span in 0..references.len() - 1 { + path.0.set_attribute(ATTR_ID, span, segment_id.next_id()); + } + path_list.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, CurveType::Linear)); + } + Item::new_from_element(vector).with_attribute(ATTR_PATHS, path_list) + } + + #[test] + fn svg_background_blur_images_inside_a_branching_clipping_mask_are_cut_by_the_faces_it_fills() { + // A diamond in a 10 unit square, its twelve walls separate segments branching at every point, so SVG fills its five faces + let corners_and_midpoints = [(0., 0.), (10., 0.), (10., 10.), (0., 10.), (5., 0.), (10., 5.), (5., 10.), (0., 5.)]; + let walls: [&[u32]; 12] = [&[0, 4], &[1, 4], &[1, 5], &[2, 5], &[2, 6], &[3, 6], &[3, 7], &[0, 7], &[4, 5], &[5, 6], &[6, 7], &[4, 7]]; + let mesh = vector_of_paths(&corners_and_midpoints, &walls).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(3.))); + assert!(ItemRef::Item(&mesh).fills_faces()); + let image = image_beneath_clipped_glass(List::new_from_item(mesh.clone())); + + // The shapes cover what the faces cover, the whole square, rather than nothing as the wall segments enclose, sampled off every wall + let faces = ItemRef::Item(&mesh).faces(); + let placement = Affine::translate((3., 3.)); + for index in 0..56 * 56 { + let point = kurbo::Point::new((index % 56) as f64 * 0.25 + 0.1, (index / 56) as f64 * 0.25 + 0.2); + let in_faces = faces.iter().any(|face| (placement * face).winding(point) != 0); + assert_eq!(clip_beneath_covers(&image, point), in_faces, "at {point:?}"); + assert_eq!(in_faces, (3. ..13.).contains(&point.x) && (3. ..13.).contains(&point.y), "at {point:?}"); + } + } + + #[test] + fn svg_background_blur_images_inside_a_clipping_mask_keep_every_shape_it_fills_whatever_their_windings() { + // Two triangles from the origin, crossing as one loop through their shared corners, a spur making the vector branch, and a rectangle inside the lower lobe + let points = [(0., 0.), (10., 10.), (0., 10.), (6., 0.), (0., -2.), (2., 0.5), (4., 0.5), (4., 1.5), (2., 1.5)]; + let vector = vector_of_paths(&points, &[&[0, 1, 2], &[0, 3, 2], &[0, 4], &[5, 6, 7, 8, 5]]); + assert!(ItemRef::Item(&vector).fills_faces()); + let image = image_beneath_clipped_glass(List::new_from_item(vector.clone())); + + // Within the rectangle, the faces' windings cancel, so one path joining them would leave it out, though SVG fills each face apart and covers it + let middle = kurbo::Point::new(3., 1.); + let faces = ItemRef::Item(&vector).faces(); + assert_eq!(faces.iter().map(|face| face.winding(middle)).sum::(), 0, "the faces cancel within the rectangle"); + assert!(faces.iter().any(|face| face.winding(middle) != 0), "a face covers the rectangle"); + + // The outline unites the shapes, covering the rectangle, both lobes where the triangles cross, and the triangles' contours, but nothing past them + for (x, y) in [(3., 1.), (5., 0.5), (3., 8.), (1., 5.)] { + assert!(clip_beneath_covers(&image, kurbo::Point::new(x, y)), "({x}, {y}) is covered"); + } + for (x, y) in [(8., 3.), (9., 1.), (-1., 5.)] { + assert!(!clip_beneath_covers(&image, kurbo::Point::new(x, y)), "({x}, {y}) is past every shape"); + } + } + + #[test] + fn svg_background_blur_images_inside_a_clipping_mask_of_coincident_shapes_are_cut_by_one_of_them() { + // Two coincident stripes half a unit wide, which unite into one + let stripe = || Vector::item_from_bezpath(&kurbo::Rect::new(3., 3., 3.5, 11.).to_path(0.1)); + let image = image_beneath_clipped_glass([stripe(), stripe()].into_iter().collect()); + + let outline = clip_outline_beneath(&image).expect("the stripes cut the image"); + assert!((outline.area().abs() - 4.).abs() < 1e-6, "the outline spans one stripe's area, not {}", outline.area()); + assert!(clip_beneath_covers(&image, kurbo::Point::new(3.25, 7.))); + } + + #[test] + fn svg_background_blurs_where_no_image_can_replace_markup_leave_the_copies_beneath_out_of_theirs() { + const PANES: usize = 20; + let mut render = SvgRender::new(); + let thumbnail = RenderParams { + thumbnail: true, + ..Default::default() + }; + stacked_glass(PANES).render_svg(&mut render, &thumbnail); + let svg = render.svg.to_svg_string(); + + // Nothing replaces a thumbnail's markup with images, so only the lowest pane references a copy, and every pane shows what lies beneath it blurred + assert!(render.deferred_images.is_empty(), "{svg}"); + assert_eq!(svg.matches(r##" = (svg.match_indices(r#"').map_or("", |(_, inside)| inside); + assert!( + inside.contains("` copy would leave out the canvas standing in for the image beneath, so its markup is repeated, once more for the copy + assert!(!svg.contains(""#).expect("the group isolates its content"); + + // So the glass inside copies only the image the group drew before it, which is wrapped inside the group + let copied: Vec<&str> = svg.split(r##""#)).expect("the copied content is wrapped"); + assert!(wrapped(copied[0]) < isolated && isolated < wrapped(copied[1]), "{svg}"); + } + + /// For each filter in the `defs`, how many Gaussian blurs it holds and how many a browser runs, since it redoes a primitive's result for every primitive reading it. + fn gaussian_blurs_in_filters(defs: &str) -> Vec<(usize, usize)> { + let filters = defs.split("").next().unwrap_or_default()); + filters + .map(|filter| { + // Each primitive at the filter's top level: whether it's a Gaussian blur, its result, and the results it and its children read + let mut primitives: Vec<(bool, String, Vec)> = Vec::new(); + let mut depth = 0_i32; + for tag in filter.split('<').skip(1).map(|tag| tag.split('>').next().unwrap_or_default()) { + if tag.starts_with('/') { + depth -= 1; + continue; + } + let attribute = |name: &str| tag.split(&format!(r#" {name}=""#)).nth(1).and_then(|rest| rest.split('"').next()).map(str::to_string); + let reads = ["in", "in2"].into_iter().filter_map(attribute); + match (depth, primitives.last_mut()) { + (0, _) => primitives.push((tag.starts_with("feGaussianBlur"), attribute("result").unwrap_or_default(), reads.collect())), + (_, Some((_, _, read))) => read.extend(reads), + _ => {} + } + if !tag.ends_with('/') && !tag.starts_with('!') { + depth += 1; + } + } + + // A result runs its own blur and those of everything it reads, each time it's read + let mut blurs_run: HashMap = HashMap::new(); + for (gaussian, result, reads) in &primitives { + let read = reads.iter().map(|read| blurs_run.get(read).copied().unwrap_or_default()).sum::(); + blurs_run.insert(result.clone(), *gaussian as usize + read); + } + let held = primitives.iter().filter(|(gaussian, _, _)| *gaussian).count(); + (held, primitives.last().and_then(|(_, result, _)| blurs_run.get(result).copied()).unwrap_or_default()) + }) + .collect() + } + + #[test] + fn svg_background_blurs_before_chained_masked_radius_blurs_copy_what_lies_beneath_without_multiplying_their_work() { + use graphic_types::{Effect, EffectOperation, MaskMode, stamp_effect}; + + // Glass with a mask after its background blur, then three masked radius blurs + let mask = EffectOperation::Mask { + mask: Graphic::RasterCPU(Box::new(white_image(DAffine2::from_scale(DVec2::splat(10.)), false))), + mode: MaskMode::Alpha, + density: 100., + feather: 0., + invert: false, + }; + let masked_radius_blur = EffectOperation::Blur { + radius_mask: Graphic::from(Color::WHITE), + radius: 8., + box_blur: false, + gamma: false, + }; + let mut glass = white_image(DAffine2::from_translation(DVec2::splat(5.)) * DAffine2::from_scale(DVec2::splat(10.)), true); + stamp_effect(&mut glass, Effect::new(&mask)); + (0..3).for_each(|_| stamp_effect(&mut glass, Effect::new(&masked_radius_blur))); + + // Each masked radius blur starts a filter of its own, reading a fresh source + let effects = glass.attribute::(ATTR_EFFECTS).expect("the glass has effects"); + assert_eq!(svg_runs(effects).into_iter().map(|(_, rows)| rows).collect::>(), [0..2, 2..3, 3..4, 4..5]); + + let mut images = List::new_from_item(white_image(DAffine2::from_scale(DVec2::splat(20.)), false)); + images.push(glass); + let mut render = SvgRender::new(); + images.render_svg( + &mut render, + &RenderParams { + for_export: true, + ..Default::default() + }, + ); + let svg = render.svg.to_svg_string(); + + // So a browser runs each Gaussian blur once, rather than once for each level of every blur before it + let blurs = gaussian_blurs_in_filters(&render.svg_defs); + assert_eq!(blurs.iter().filter(|(held, _)| *held > 1).count(), 3, "{blurs:?}"); + assert!(blurs.iter().all(|(held, run)| run == held), "{blurs:?}"); + + // The last filter still draws what lies beneath, cut to the glass before its effects and by its mask, as the GPU cuts it by the run's starting content and masks + assert!(svg.contains(r##"").next()); + assert!(cut.is_some_and(|cut| cut.contains("` copy would leave out, so each layer holds the markup standing in for it + let in_viewport = svg(&RenderParams::default()); + assert!(!in_viewport.contains("` copy draws + let export = svg(&RenderParams { + for_export: true, + ..Default::default() + }); + assert!(export.contains(r##" bool { + true + } + + fn render_effects( + &mut self, + size: glam::UVec2, + view: kurbo::Affine, + _: &Effects, + _: &EffectLayers, + _: f32, + _: f32, + _: DAffine2, + _: Option, + _: Option<(&wgpu::Texture, kurbo::Affine)>, + _: Option, + _: &mut dyn FnMut(usize, &mut VelloSceneBuilder), + draw: &mut dyn FnMut(&mut VelloSceneBuilder), + ) -> Vec<(wgpu::Texture, BlendMode)> { + let mut scene = VelloSceneBuilder::new(size.x as u16, size.y as u16, view, 4096).with_effects_renderer(self); + draw(&mut scene); + Vec::new() + } + + fn render_backdrop(&mut self, _: &vello_gpu::Scene, _: &[SceneImage], _: u32) -> Option { + self.0 += 1; + None + } + } + let backdrops_rendered = |item: Item| { + let mut renderer = CountsBackdrops(0); + let mut scene = VelloSceneBuilder::new(64, 64, kurbo::Affine::IDENTITY, 4096).with_effects_renderer(&mut renderer); + List::new_from_item(item).render_to_vello(&mut scene, DAffine2::IDENTITY, &RenderParams::default()); + drop(scene); + renderer.0 + }; + + // Glass alone asks for what lies beneath it + let blur = EffectOperation::BackgroundBlur { + radius: 2., + box_blur: false, + gamma: false, + }; + let glass = orange_square_item(std::slice::from_ref(&blur), 0., 1.); + assert_eq!(backdrops_rendered(glass.clone()), 1); + + // Scaled before a shadow is stamped, the blur's run is drawn into the content of the shadow's, where nothing lies beneath it to render + let mut scaled = glass; + scaled.set_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(2.))); + stamp_effect(&mut scaled, Effect::new(&drop_shadow(180., 3., 0.))); + assert_eq!(backdrops_rendered(scaled), 0); + } + #[test] fn content_with_effects_svg_cannot_express_defers_to_an_image() { use graphic_types::raster_types::Image; @@ -8088,7 +9446,7 @@ mod tests { assert!(svg[start..end].contains("(ATTR_OPACITY).is_none())); + assert!(matches!(&deferred.content, DeferredContent::Item(Graphic::RasterCPU(content)) if content.attribute::(ATTR_OPACITY).is_none())); // In a view of the document's first 100 units, the image spans the part of the reach in it, replacing the markup let layout = deferred.layout(DAffine2::IDENTITY, DVec2::splat(100.), 8192).unwrap(); diff --git a/node-graph/libraries/rendering/src/renderer/masks.rs b/node-graph/libraries/rendering/src/renderer/masks.rs index da10bac608..0f5d7865f6 100644 --- a/node-graph/libraries/rendering/src/renderer/masks.rs +++ b/node-graph/libraries/rendering/src/renderer/masks.rs @@ -98,7 +98,7 @@ pub(super) fn placed(mask: &Graphic, placement: DAffine2) -> Graphic { /// Writes into `svg_defs` the masks for the effects in each of the `ranges`, given the markup of the graphics the effects draw with in order, and the content's `bounds` in the user space, which is the effects' own. /// Returns the reference to each range's mask, which shows the content as much as all its masks together do. -pub(super) fn write_native_masks(svg_defs: &mut String, effects: &Effects, ranges: [Range; 2], paints: &[String], bounds: [DVec2; 2]) -> [Option; 2] { +pub(super) fn write_native_masks(svg_defs: &mut String, effects: &Effects, ranges: [Range; N], paints: &[String], bounds: [DVec2; 2]) -> [Option; N] { let length_scale = DVec2::ONE; let region = svg_effects_region(effects, bounds, length_scale); diff --git a/node-graph/libraries/rendering/src/svg_backdrop.rs b/node-graph/libraries/rendering/src/svg_backdrop.rs new file mode 100644 index 0000000000..b712ce95f9 --- /dev/null +++ b/node-graph/libraries/rendering/src/svg_backdrop.rs @@ -0,0 +1,406 @@ +//! What lies beneath content in an SVG, which filters can't read, copied for content that reads it, like a background blur. +//! Per the W3C's Backdrop Root, the backdrop is everything drawn before the content since the innermost group that isolates it, or since the start of the render. + +use crate::deferred_image::{self, DeferredContent, DeferredImage, DrawnContent, DrawnItems}; +use crate::renderer::{RenderParams, SvgRender, SvgSegment, format_transform_matrix}; +use core_types::blending::BlendMode; +use core_types::math::quad::Quad; +use core_types::uuid::generate_uuid; +use glam::{DAffine2, DVec2}; +use graphic_types::effects::spans_along_axes; +use graphic_types::{EffectOperation, Effects}; +use kurbo::{BezPath, PathEl, Shape}; +use linesweeper::topology::Topology; +use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH; +use std::collections::HashMap; +use std::fmt::Write; +use std::sync::Arc; + +/// A group an SVG render has open, where the content drawn so far lies beneath what's drawn next inside it. +#[derive(Clone)] +pub(crate) struct OpenGroup { + /// Where the group's opening tag starts among the render's segments. + pub tag_start: usize, + /// Where the group's content starts among the render's segments. + pub content_start: usize, + /// Whether the group isolates what's drawn inside it from what lies beneath it, as opacity, a filter, a mask, a clip path, or a blend mode does. + pub isolates: bool, + /// The group's `clip-path` attribute, which a copy of its content takes too. + pub clip_path: Option, + /// Maps the user space of the group's content into the document, once its content begins. + pub user_to_document: Option, + /// Whether a copy of what lies beneath, or an image of it, is drawn inside the group so far. + pub holds_backdrop: bool, + /// The content drawn directly inside the group so far, for the GPU to draw again in an image of what lies beneath content drawn after it. + pub drawn: Vec, +} + +impl OpenGroup { + pub fn new(tag_start: usize, content_start: usize, isolates: bool, clip_path: Option) -> Self { + Self { + tag_start, + content_start, + isolates, + clip_path, + user_to_document: None, + holds_backdrop: false, + drawn: Vec::new(), + } + } +} + +/// The groups an SVG render has open, from the render's own start inward to the innermost. +#[derive(Clone)] +pub(crate) struct OpenGroups { + pub groups: Vec, + /// Whether the attributes of the tag being opened isolate its content. + pub opening_isolates: bool, + /// The `clip-path` attribute of the tag being opened. + pub opening_clip_path: Option, + /// Whether the render draws a clipping base's clip. + pub clip: bool, + /// The shapes of the clip paths in the render's defs, paths in the document each filled by the nonzero rule, by the `clip-path` attribute referencing each. + /// Images of what lies beneath inside one are cut to the union of its shapes. + pub clip_shapes: HashMap>, +} + +impl Default for OpenGroups { + fn default() -> Self { + Self { + groups: vec![OpenGroup::new(0, 0, true, None)], + opening_isolates: false, + opening_clip_path: None, + clip: false, + clip_shapes: HashMap::new(), + } + } +} + +/// Whether an attribute makes the element carrying it an isolated group, which the content inside it blends within. +pub(crate) fn isolates(name: &str, value: &str) -> bool { + match name { + "opacity" | "filter" | "mask" | "clip-path" => true, + "style" => value.contains("mix-blend-mode") || value.contains("isolation"), + _ => false, + } +} + +impl SvgRender { + /// Records the `items` drawn next, from the user space `user_to_document` maps into the document, in the innermost open group, returning where for [`Self::drew_items`]. + /// Nothing is recorded where no image can replace markup, since no image of what lies beneath could. + pub(crate) fn record_drawn(&mut self, items: impl FnOnce() -> T, user_to_document: DAffine2, render_params: &RenderParams) -> Option { + if !self.images_replace_markup(render_params) { + return None; + } + + let group = self.open_groups.groups.last_mut()?; + group.drawn.push(DrawnContent::new(Arc::new(items()), user_to_document, render_params)); + Some(group.drawn.len() - 1) + } + + /// Notes that the first `count` of the items recorded at `record` are drawn, in place of anything recorded after them while they were drawn. + pub(crate) fn drew_items(&mut self, record: Option, count: usize) { + let (Some(record), Some(group)) = (record, self.open_groups.groups.last_mut()) else { return }; + + group.drawn.truncate(record + 1); + if let Some(drawn) = group.drawn.get_mut(record) { + drawn.count = count; + } + } + + /// Records the `shapes` of the clip path a `clip-path` attribute of the `reference` cuts by (see [`OpenGroups::clip_shapes`]), for images of what lies beneath inside it. + pub(crate) fn record_clip_shapes(&mut self, reference: &str, shapes: impl FnOnce() -> Vec, render_params: &RenderParams) { + if self.images_replace_markup(render_params) { + self.open_groups.clip_shapes.insert(reference.to_string(), shapes()); + } + } + + /// The outline of the clip path a `clip-path` attribute of the `reference` cuts by, its shapes united into one path filled by the nonzero rule, + /// or `None` if its shapes aren't recorded or can't be united. + fn clip_outline(&mut self, reference: &str) -> Option { + let shapes = self.open_groups.clip_shapes.get(reference)?; + if let [shape] = shapes.as_slice() { + return Some(shape.clone()); + } + + // United once, the outline is kept in place of the shapes, which are forgotten if they can't be + let outline = united_outline(shapes); + match &outline { + Some(outline) => _ = self.open_groups.clip_shapes.insert(reference.to_string(), vec![outline.clone()]), + None => _ = self.open_groups.clip_shapes.remove(reference), + } + outline + } + + /// Markup showing what lies beneath the content drawn next, within the `region` of the current user space it reads, or `None` if nothing does. + /// It copies the markup drawn since the backdrop root, or where that holds a copy already, stands for an image the GPU renders of it or else leaves held copies out. + pub(crate) fn backdrop_copy(&mut self, render_params: &RenderParams, region: [DVec2; 2], read_reach: f64) -> Option { + if self.drawing_deferred_markup || !self.transform.matrix2.determinant().is_normal() { + return None; + } + let root = self.open_groups.groups.iter().rposition(|group| group.isolates)?; + + // A clip's own stack lies over nothing, as in the GPU's layer for it, though a group isolated within it still reads what it drew + if root == 0 && self.open_groups.clip { + return None; + } + + // The backdrop root's own clip cuts every level's copy as it cuts the originals, from a group around them in the space of its content + let root_group = &self.open_groups.groups[root]; + let holds_backdrop = root_group.holds_backdrop; + let clip = root_group.clip_path.clone().zip(root_group.user_to_document); + let copies_to_document = clip.as_ref().map_or(self.transform, |(_, root_to_document)| *root_to_document); + + // An image needs the outline of the root's clip, if it has one, to cut what it holds by + let image_clip = match holds_backdrop && self.images_replace_markup(render_params) { + true => match &clip { + Some((reference, _)) => self.clip_outline(reference).map(Some), + None => Some(None), + }, + false => None, + }; + + // Elsewhere, copies leave out the blurred copies earlier content holds, so they never nest, losing only the blur of a blur where it overlaps + let copies = match (holds_backdrop, image_clip) { + (false, _) => self.backdrop_markup_copies(root, copies_to_document, render_params.to_canvas(), false), + (true, Some(clip)) => self.backdrop_image(root, copies_to_document, clip, region, read_reach, render_params), + (true, None) => self.backdrop_markup_copies(root, copies_to_document, true, true), + }?; + + // Every open group now holds it + for group in &mut self.open_groups.groups { + group.holds_backdrop = true; + } + + let Some((clip_path, root_to_document)) = clip else { return Some(copies) }; + + let matrix = format_transform_matrix(self.transform.inverse() * root_to_document); + let transform = if matrix.is_empty() { String::new() } else { format!(r#" transform="{matrix}""#) }; + Some(format!(r#"{copies}"#)) + } + + /// Copies of the content drawn at each level of the groups open since the backdrop `root`, in the space `copies_to_document` maps into the document, or `None` if there's none. + /// Each is wrapped in a group with an ID for `` copies, or with `repeats_markup`, copied as markup, keeping the viewport's canvases, + /// and without the markup showing what lies beneath earlier content if `leaves_out_backdrops`. O(segments drawn since the root). + fn backdrop_markup_copies(&mut self, root: usize, copies_to_document: DAffine2, repeats_markup: bool, leaves_out_backdrops: bool) -> Option { + let current = self.open_groups.groups.len() - 1; + let kept = |segment: &&SvgSegment| !(leaves_out_backdrops && matches!(segment, SvgSegment::Backdrop(_))); + + // From the innermost level out, so wrapping one level's content leaves the outer levels' positions as they are + let mut copies = Vec::new(); + for level in (root..=current).rev() { + let group = &self.open_groups.groups[level]; + let start = group.content_start; + let end = self.open_groups.groups.get(level + 1).map_or(self.svg.len(), |inner| inner.tag_start); + let drawn = self.svg[start..end].iter().filter(kept).any(|segment| segment.as_str().contains('<')); + let Some(user_to_document) = group.user_to_document.filter(|_| drawn) else { continue }; + + let matrix = format_transform_matrix(copies_to_document.inverse() * user_to_document); + let attributes = if matrix.is_empty() { String::new() } else { format!(r#" transform="{matrix}""#) }; + + if repeats_markup { + let markup: String = self.svg[start..end].iter().filter(kept).map(SvgSegment::as_str).collect(); + copies.push(format!("{markup}")); + continue; + } + + let id = format!("backdrop-{}", generate_uuid()); + self.svg.insert(end, "".into()); + self.svg.insert(start, format!(r#""#).into()); + for inner in &mut self.open_groups.groups[level + 1..] { + inner.tag_start += 2; + inner.content_start += 2; + } + copies.push(format!(r##""##)); + } + if copies.is_empty() { + return None; + } + + copies.reverse(); + Some(copies.concat()) + } + + /// The markers standing for an image the GPU renders of the content drawn since the backdrop `root`, cut by the outline of its `clip`, placed in the space `copies_to_document` maps into the document, + /// or `None` if there's none. It covers the `region` of the current user space and how far past the view the reading reaches, `read_reach` in the document. + fn backdrop_image(&mut self, root: usize, copies_to_document: DAffine2, clip: Option, region: [DVec2; 2], read_reach: f64, render_params: &RenderParams) -> Option { + let drawn: Vec = self.open_groups.groups[root..].iter().flat_map(|group| &group.drawn).filter(|drawn| drawn.count > 0).cloned().collect(); + if drawn.is_empty() { + return None; + } + + let id = generate_uuid(); + let bounds = (copies_to_document.inverse() * self.transform * Quad::from_box(region)).bounding_box(); + self.deferred_images.push(DeferredImage { + id, + content: DeferredContent::Beneath { clip, drawn }, + render_params: render_params.clone(), + user_to_document: copies_to_document, + bounds, + margin: self.ancestors_reach + read_reach, + opacity: 1., + blend_mode: BlendMode::Normal, + }); + + let (opening, closing) = deferred_image::image_markers(id); + Some(format!("{opening}{closing}")) + } +} + +/// The outline of the union of the `shapes`, each filled by the nonzero rule, as one path filled by that rule, or `None` if their coordinates aren't finite or a sweep fails. +/// Each shape's winding is resolved alone first, so the final sweep counts one winding rather than one per shape at every edge. +fn united_outline(shapes: &[BezPath]) -> Option { + const EPSILON: f64 = 1e-5; + + // A fill closes each subpath, which the sweep takes only explicitly + let closed: Vec = shapes.iter().map(closed_subpaths).collect(); + if !closed.iter().all(BezPath::is_finite) { + return None; + } + let Some(bounds) = closed.iter().map(Shape::bounding_box).reduce(|first, second| first.union(second)) else { + return Some(BezPath::new()); + }; + + // Far from the origin, the tolerance grows with the coordinates' magnitude, since the sweep can't resolve less + let magnitude = bounds.min_x().min(bounds.min_y()).abs().max(bounds.max_x().max(bounds.max_y()).abs()); + let epsilon = EPSILON.max(magnitude * f64::EPSILON * 64.); + + // Each shape alone is outlined first by what it fills, wound once around, so no shape's winding can cancel another's where they then unite + let mut outlines = BezPath::new(); + for shape in &closed { + outlines.extend(swept_outline(shape, epsilon, |&winding| winding != 0)?); + } + swept_outline(&outlines, epsilon, |&winding| winding > 0) +} + +/// The outline of where the `inside` test accepts the winding number of the closed `path`, wound once around what it holds, or `None` if the sweep fails. +fn swept_outline(path: &BezPath, epsilon: f64, inside: impl Fn(&i32) -> bool) -> Option { + let topology = Topology::::from_path(path, epsilon).ok()?; + Some(topology.contours(inside).contours().flat_map(|contour| contour.path.elements().iter().copied()).collect()) +} + +/// The `shape` with each of its subpaths closed, as a fill closes them. +pub(crate) fn closed_subpaths(shape: &BezPath) -> BezPath { + let mut closed = BezPath::new(); + for &element in shape.elements() { + if matches!(element, PathEl::MoveTo(_)) && !matches!(closed.elements().last(), None | Some(PathEl::ClosePath)) { + closed.close_path(); + } + closed.push(element); + } + if !matches!(closed.elements().last(), None | Some(PathEl::ClosePath)) { + closed.close_path(); + } + closed +} + +/// What lies beneath content with background blurs, in SVG. +pub(crate) struct SvgBackdrop { + /// Each copy of what lies beneath, blurred by one background blur, stacked in order within a group the mask cuts to the content. + pub markup: String, + /// The opening tag of the mask cutting it to the content's silhouette, which the content's own markup goes in once it's drawn. + pub mask_tag: String, + /// The content's extent, which cuts it instead where the content draws through canvases, since a mask draws no ``. + pub content_bounds: [DVec2; 2], +} + +/// What lies beneath content with background blurs, or `None` with nothing beneath it, given the content's `bounds` in the effects' `space`. +/// That space is placed in the current user space, or is the user space itself for `None`, and the markup lies in it. +/// The filters go in the render's defs (see [`SvgRender::backdrop_copy`] for what they blur). +/// A length in that space spans `pixels_per_length` screen pixels, across which a blur too slight to show is left out. +pub(crate) fn backdrop_markup(render: &mut SvgRender, effects: &Effects, bounds: [DVec2; 2], space: Option, pixels_per_length: f64, render_params: &RenderParams) -> Option { + let blurs: Vec<(f64, bool, bool)> = (effects.operations()) + .filter(|operation| !operation.changes_nothing()) + .filter_map(|operation| match operation { + EffectOperation::BackgroundBlur { radius, box_blur, gamma } => Some((radius, box_blur, gamma)), + _ => None, + }) + .collect(); + if blurs.is_empty() { + return None; + } + + // SVG has no box blur, so a box becomes the Gaussian of the same variance, which reads past the box's own reach + let sigma = |radius: f64, box_blur: bool| if box_blur { (radius * (radius + 1.) / 3.).sqrt() } else { radius }; + let box_overreach: f64 = blurs + .iter() + .filter(|(_, box_blur, _)| *box_blur) + .map(|&(radius, ..)| (3. * sigma(radius, true) - radius - 1.).max(0.)) + .sum(); + + // The blurs read as far past the content as the effects reach + let reach = effects.reach() + box_overreach; + let (min, max) = (bounds[0] - reach, bounds[1] + reach); + let region = format!(r#"x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, max.x - min.x, max.y - min.y); + + let space_to_user = space.unwrap_or_default(); + let read_region = (space_to_user * Quad::from_box([min, max])).bounding_box(); + let read_reach = reach * spans_along_axes((render.transform * space_to_user).matrix2).max_element(); + let copy = render.backdrop_copy(render_params, read_region, read_reach)?; + let copy = match space.map(|space| format_transform_matrix(space.inverse())) { + Some(matrix) if !matrix.is_empty() => format!(r#"{copy}"#), + _ => copy, + }; + + let mut blurred = String::new(); + for (radius, box_blur, gamma) in blurs { + if radius * pixels_per_length.max(1.) < NEGLIGIBLE_LENGTH { + blurred.push_str(©); + continue; + } + + let sigma = sigma(radius, box_blur); + let space = if gamma { "sRGB" } else { "linearRGB" }; + let filter_id = format!("background-blur-{}", generate_uuid()); + write!( + render.svg_defs, + r#""# + ) + .unwrap(); + write!(blurred, r#"{copy}"#).unwrap(); + } + + let mask_id = format!("backdrop-mask-{}", generate_uuid()); + Some(SvgBackdrop { + markup: format!(r#"{blurred}"#), + mask_tag: format!(r#""#), + content_bounds: bounds, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clip_shapes_with_coordinates_past_finite_ones_unite_into_no_outline() { + let square = kurbo::Rect::new(0., 0., 10., 10.).to_path(0.1); + let mut broken = BezPath::new(); + broken.move_to((0., 0.)); + broken.line_to((f64::NAN, 5.)); + broken.line_to((5., f64::INFINITY)); + + // Images inside such a clip path give way to copies leaving held ones out, rather than drawing an outline that's wrong + assert!(united_outline(&[square.clone(), broken]).is_none()); + assert!(united_outline(&[square.clone(), square]).is_some_and(|outline| (outline.area().abs() - 100.).abs() < 1e-6)); + } + + #[test] + fn thousands_of_overlapping_clip_shapes_wound_either_way_unite_quickly_into_what_they_cover() { + // A 100 by 50 grid of squares a unit and a half wide, a unit apart so neighbors overlap, every other one wound the other way + let squares: Vec = (0..5_000) + .map(|index| { + let corner = kurbo::Point::new((index % 100) as f64, (index / 100) as f64); + let square = kurbo::Rect::from_origin_size(corner, (1.5, 1.5)).to_path(0.1); + if index % 2 == 0 { square } else { square.reverse_subpaths() } + }) + .collect(); + + // They unite into the rectangle they cover, none cancelling a neighbor wound against it + let start = std::time::Instant::now(); + let outline = united_outline(&squares).expect("the squares unite"); + let elapsed = start.elapsed(); + assert!((outline.area().abs() - 100.5 * 50.5).abs() < 1e-6, "the union spans {}", outline.area().abs()); + assert!(elapsed < std::time::Duration::from_secs(10), "uniting took {elapsed:?}"); + } +} diff --git a/node-graph/libraries/rendering/src/vello_scene_builder.rs b/node-graph/libraries/rendering/src/vello_scene_builder.rs index c15273ac5a..894c994dcb 100644 --- a/node-graph/libraries/rendering/src/vello_scene_builder.rs +++ b/node-graph/libraries/rendering/src/vello_scene_builder.rs @@ -47,6 +47,16 @@ pub struct VelloSceneBuilder<'a> { effects_renderer: Option<&'a mut dyn EffectsRenderer>, /// The coverage the next effects group drawn outputs in place of its result, for an SVG map of it. effect_capture: Option, + /// How many placed drawings are open, each a backdrop root of its own, like a thumbnail of an atlas. + placed_depth: u32, + /// How many pixels past the scene's edges the content reading what lies beneath it reads, which a render of the scene grown by as much holds. + backdrop_apron: u32, + /// Each content drawn so far reading what lies beneath it, as its bounds in the scene and how many pixels past them it reads along each axis, for later content reading through it. + backdrop_readers: Vec<(Rect, DVec2)>, + /// The widest apron a render of the scene grown for content reading past its edges can have, up to which such content stops the drawing, or 0 to draw everything. + largest_apron: u32, + /// Whether the scene still draws, rather than only measuring the apron after content reading past its edges stopped it. + drawing: bool, } /// Renders the content of a scene's effects groups offscreen and carries out their effects, while the scene is drawn. @@ -58,6 +68,7 @@ pub trait EffectsRenderer: Send { /// returning one for each of the `layers` that `effects` carried out on it draw, with the mode it blends by. /// `effect_to_pixels` places the effects' space on the texture's pixels, `fill` fades the content but not the shadows and glows cast from it, and `opacity` fades the layers. /// The `frame`, in the texture's pixels, is what effects relative to the content's extent take as their own. + /// `backdrop` is what lies beneath, for the effects that read it, with the placement of the textures' pixels in it. /// With a `capture`, the only texture instead holds that effect's coverage, as black with it in alpha. #[expect(clippy::too_many_arguments)] fn render_effects( @@ -70,10 +81,17 @@ pub trait EffectsRenderer: Send { opacity: f32, effect_to_pixels: DAffine2, frame: Option, + backdrop: Option<(&wgpu::Texture, Affine)>, capture: Option, draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder), draw: &mut dyn FnMut(&mut VelloSceneBuilder), ) -> Vec<(wgpu::Texture, core_types::blending::BlendMode)>; + + /// Renders a `scene` drawn so far, with the `images` it draws, into a premultiplied texture of its size, as the backdrop of what's drawn next. + /// `None` if it fails to render. + fn render_backdrop(&mut self, _scene: &vello_gpu::Scene, _images: &[SceneImage], _max_texture_size: u32) -> Option { + None + } } /// The pixels behind an image the scene draws. @@ -127,7 +145,12 @@ impl GeneratorTile { #[derive(Debug)] enum Pushed { Layer, - Clip, + /// With the path it clips to, given in the scene's space, so it can be pushed again in a scene continuing this one. + Clip { + path: BezPath, + transform: Affine, + fill_rule: Fill, + }, } impl std::fmt::Debug for VelloSceneBuilder<'_> { @@ -157,6 +180,11 @@ impl<'a> VelloSceneBuilder<'a> { pushed: Vec::new(), effects_renderer: None, effect_capture: None, + placed_depth: 0, + backdrop_apron: 0, + backdrop_readers: Vec::new(), + largest_apron: 0, + drawing: true, } } @@ -166,6 +194,18 @@ impl<'a> VelloSceneBuilder<'a> { self } + /// Stops drawing at the first content reading what lies beneath it past the scene's edges by at most `largest_apron` pixels, which a render grown by as much draws instead. + /// The scene then only measures how far past its edges the rest reads, for that render's apron. + pub fn stopping_for_an_apron_up_to(mut self, largest_apron: u32) -> Self { + self.largest_apron = largest_apron; + self + } + + /// Whether the scene drew all its content, rather than stopping at content reading past its edges. + pub fn drew_everything(&self) -> bool { + self.drawing + } + /// Has the next effects group drawn output the coverage `capture` names in place of its result, leaving the groups drawn within it as they are. pub fn capture_next_effects(&mut self, capture: EffectCapture) { self.effect_capture = Some(capture); @@ -188,6 +228,11 @@ impl<'a> VelloSceneBuilder<'a> { self.max_texture_size } + /// How many pixels past the scene's edges the content drawn so far that reads what lies beneath it reads, which the scene doesn't hold. + pub fn backdrop_apron(&self) -> u32 { + self.backdrop_apron + } + /// The finished Vello GPU scene and the images its external textures stand for, closing whatever layers and clips were left open. pub fn finish(mut self) -> (vello_gpu::Scene, Vec) { if !self.pushed.is_empty() { @@ -206,10 +251,13 @@ impl<'a> VelloSceneBuilder<'a> { } /// Draws what `draw` draws placed by `placement` within the view, as content with its own document space for its effects' lengths, like each thumbnail of an atlas. + /// It's a backdrop root of its own with nothing beneath it to read, as a run of effects drawn into another run's content is. pub fn draw_placed(&mut self, placement: Affine, draw: impl FnOnce(&mut Self)) { let outer_view = self.view; self.view = outer_view * placement; + self.placed_depth += 1; draw(self); + self.placed_depth -= 1; self.view = outer_view; } @@ -228,6 +276,9 @@ impl<'a> VelloSceneBuilder<'a> { /// Like [`Self::fill`] for a path, which it draws without copying. pub fn fill_path<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into>, brush_transform: Option, path: &BezPath) { + if !self.drawing { + return; + } let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return }; self.scene.set_transform(self.view * transform); self.scene.set_fill_rule(fill_rule); @@ -238,6 +289,9 @@ impl<'a> VelloSceneBuilder<'a> { /// Strokes a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`. pub fn stroke<'b>(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into>, brush_transform: Option, shape: &impl Shape) { + if !self.drawing { + return; + } let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return }; self.scene.set_transform(self.view * transform); self.scene.set_stroke(stroke.clone()); @@ -248,6 +302,9 @@ impl<'a> VelloSceneBuilder<'a> { /// Fills the whole scene, which is how content without bounds (like a color or gradient layer) paints, with the brush placed by `brush_transform` in the space of the drawn content. pub fn fill_viewport<'b>(&mut self, brush: impl Into>, brush_transform: Option) { + if !self.drawing { + return; + } let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return }; self.scene.set_transform(Affine::IDENTITY); self.scene.set_paint(paint); @@ -257,38 +314,99 @@ impl<'a> VelloSceneBuilder<'a> { /// Begins an isolated layer clipped to `clip`, given in the space of `transform`. Must be balanced by [`Self::pop_layer`]. pub fn push_layer(&mut self, fill_rule: Fill, blend_mode: impl Into, alpha: f32, transform: Affine, clip: &impl Shape) { - self.scene.set_transform(self.view * transform); - self.scene.set_fill_rule(fill_rule); - self.scene - .push_layer(Some(&finite_path(&clip.to_path(SHAPE_TOLERANCE))), Some(blend_mode.into()), Some(alpha), None, None); + if self.drawing { + self.scene.set_transform(self.view * transform); + self.scene.set_fill_rule(fill_rule); + self.scene + .push_layer(Some(&finite_path(&clip.to_path(SHAPE_TOLERANCE))), Some(blend_mode.into()), Some(alpha), None, None); + } self.pushed.push(Pushed::Layer); } /// Begins an isolated layer covering the whole scene, for content without bounds. Must be balanced by [`Self::pop_layer`]. pub fn push_viewport_layer(&mut self, blend_mode: impl Into, alpha: f32) { - self.scene.push_layer(None, Some(blend_mode.into()), Some(alpha), None, None); + if self.drawing { + self.scene.push_layer(None, Some(blend_mode.into()), Some(alpha), None, None); + } self.pushed.push(Pushed::Layer); } /// Clips the content that follows to `clip`, given in the space of `transform`, without isolating it. Must be balanced by [`Self::pop_layer`]. pub fn push_clip_layer(&mut self, fill_rule: Fill, transform: Affine, clip: &impl Shape) { - self.scene.set_transform(self.view * transform); - self.scene.set_fill_rule(fill_rule); - self.scene.push_clip_path(&finite_path(&clip.to_path(SHAPE_TOLERANCE))); - self.pushed.push(Pushed::Clip); + // The path is kept to begin the clip again after a render of the scene so far, copied only if it had to be made finite + let path = clip.to_path(SHAPE_TOLERANCE); + let finite = match finite_path(&path) { + Cow::Owned(finite) => Some(finite), + Cow::Borrowed(_) => None, + }; + let (path, transform) = (finite.unwrap_or(path), self.view * transform); + if self.drawing { + self.scene.set_transform(transform); + self.scene.set_fill_rule(fill_rule); + self.scene.push_clip_path(&path); + } + self.pushed.push(Pushed::Clip { path, transform, fill_rule }); } /// Ends the most recent layer or clip. pub fn pop_layer(&mut self) { match self.pushed.pop() { - Some(Pushed::Layer) => self.scene.pop_layer(), - Some(Pushed::Clip) => self.scene.pop_clip(), + Some(Pushed::Layer) if self.drawing => self.scene.pop_layer(), + Some(Pushed::Clip { .. }) if self.drawing => self.scene.pop_clip(), + Some(_) => {} None => log::error!("A scene ends a layer or clip it never began"), } } + /// What's drawn so far, which lies beneath what's drawn next, in a premultiplied texture the size of the scene. + /// The scene is rendered so far and continues from an image of that render. `None` where content has nothing beneath it to read, or once the scene stopped drawing. + pub fn backdrop(&mut self) -> Option { + if !self.drawing || !self.backdrop_readable() { + return None; + } + let renderer = self.effects_renderer.as_deref_mut()?; + + // The clips end for the render, then begin again in the scene continuing it + self.pushed.iter().for_each(|_| self.scene.pop_clip()); + let rendered = renderer.render_backdrop(&self.scene, &self.images, self.max_texture_size); + if rendered.is_some() { + self.scene.reset(); + self.images.clear(); + self.image_ids.clear(); + } + let backdrop = rendered.inspect(|backdrop| { + self.images.push(SceneImage::Rendered(backdrop.clone())); + let area = Rect::new(0., 0., backdrop.width() as f64, backdrop.height() as f64); + self.scene.set_transform(Affine::IDENTITY); + self.scene.set_paint(PaintType::Image(Image { + image: ImageSource::external_texture(TextureId(0), TextureRegion::Full, true), + sampler: peniko::ImageSampler::new(), + })); + self.scene.set_paint_transform(Affine::IDENTITY); + self.scene.fill_rect(&area); + }); + for pushed in &self.pushed { + if let Pushed::Clip { path, transform, fill_rule } = pushed { + self.scene.set_transform(*transform); + self.scene.set_fill_rule(*fill_rule); + self.scene.push_clip_path(path); + } + } + + backdrop + } + + /// Whether content drawn now has what lies beneath it to read, which it hasn't within an isolated layer, where what lies beneath is only the part inside the layer, + /// within a placed drawing, where the content lies over nothing of its own, or without a renderer. + fn backdrop_readable(&self) -> bool { + self.placed_depth == 0 && !self.pushed.iter().any(|pushed| matches!(pushed, Pushed::Layer)) && self.effects_renderer.is_some() + } + /// Draws an image's rectangle of pixels, from the origin to its width and height, placed by `transform`. pub fn draw_image(&mut self, image: &peniko::ImageBrush, transform: Affine) { + if !self.drawing { + return; + } let Some((source, texture_to_image, texture_size)) = self.image_source(SceneImage::Pixels(image.image.clone())) else { return; }; @@ -297,6 +415,9 @@ impl<'a> VelloSceneBuilder<'a> { /// Draws a CPU raster's rectangle of pixels with `adjustments` carried out on them, from the origin to its width and height, placed by `transform`. pub fn draw_raster(&mut self, raster: Raster, adjustments: Vec, sampler: peniko::ImageSampler, transform: Affine) { + if !self.drawing { + return; + } let Some((source, texture_to_image, texture_size)) = self.image_source(SceneImage::Raster { raster, adjustments }) else { return; }; @@ -305,6 +426,9 @@ impl<'a> VelloSceneBuilder<'a> { /// Draws a GPU texture's rectangle of pixels, from the origin to its width and height, placed by `transform`. pub fn draw_texture(&mut self, texture: Texture, sampler: peniko::ImageSampler, transform: Affine) { + if !self.drawing { + return; + } let Some((source, texture_to_image, texture_size)) = self.image_source(SceneImage::Texture(texture)) else { return; }; @@ -317,7 +441,7 @@ impl<'a> VelloSceneBuilder<'a> { let local_to_device = self.view * transform; let [a, b, c, d, _, _] = local_to_device.as_coeffs(); let determinant = a * d - b * c; - if !determinant.is_normal() { + if !self.drawing || !determinant.is_normal() { return; } @@ -409,9 +533,12 @@ impl<'a> VelloSceneBuilder<'a> { let layers = EffectLayers::plan(effects, blend_mode, fill, layered); // The texture follows the viewport's axes if the effect space only turns and evenly scales, or else its own axes, scaled evenly to keep every direction's detail. - // A box blur or a minimum or maximum, whose square neighborhoods aren't round, turns with its space only along that space's axes. + // A box blur (of the content or what lies beneath it) or a minimum or maximum, whose square neighborhoods aren't round, turns with its space only along that space's axes. let has_square_kernel = effects.operations().any(|operation| { - let square = matches!(operation, EffectOperation::Blur { box_blur: true, .. } | EffectOperation::MinimumMaximum { .. }); + let square = matches!( + operation, + EffectOperation::Blur { box_blur: true, .. } | EffectOperation::BackgroundBlur { box_blur: true, .. } | EffectOperation::MinimumMaximum { .. } + ); square && !operation.changes_nothing() }); let follows_viewport = is_similarity(effect_to_device.matrix2) && (!has_square_kernel || is_axis_aligned(effect_to_device.matrix2)); @@ -483,16 +610,61 @@ impl<'a> VelloSceneBuilder<'a> { let size = UVec2::new(size_along(region.width()), size_along(region.height())); let origin = region.origin().to_vec2(); + // What lies beneath, for the effects that read it, where each of the effects texture's pixels lands in it. + // Content without bounds reads nothing, as in SVG, and content reading past the scene's edges asks for the scene to be rendered grown by as much. + let reads_backdrop = layers.reads_backdrop() && capture.is_none() && bounds.is_some() && self.backdrop_readable(); + if reads_backdrop { + // A box reaches as far along each axis of the view as its square turned into it does, and a Gaussian as far every way as its widest stretch + let readers = (effects.operations()).filter(|operation| matches!(operation, graphic_types::EffectOperation::BackgroundBlur { .. }) && !operation.changes_nothing()); + let linear = effect_to_device.matrix2; + let backdrop_reach: DVec2 = readers + .map(|operation| match operation { + graphic_types::EffectOperation::BackgroundBlur { box_blur: true, .. } => operation.reach() * (linear.abs() * DVec2::ONE), + _ => DVec2::splat(operation.reach() * largest_stretch(linear)), + }) + .sum(); + + // The content in view reads what lies beneath only within its backdrop readers' reach, however far past the view the region extends + let region_in_device = Affine::new(frame_to_device.to_cols_array()).transform_rect_bbox(region); + let mut read_region = region_in_device.intersect(viewport.inflate(backdrop_reach.x, backdrop_reach.y)); + + // Content farther from the view than its backdrop reach needs no apron of its own, though later content reading through it may + if read_region.width() > 0. && read_region.height() > 0. { + // Where it reads earlier content reading what lies beneath, it reads what that content read too, from the latest back. O(readers drawn so far). + for &(earlier_bounds, earlier_reach) in self.backdrop_readers.iter().rev() { + let overlap = earlier_bounds.intersect(read_region); + if overlap.width() > 0. && overlap.height() > 0. { + read_region = read_region.union(overlap.inflate(earlier_reach.x, earlier_reach.y)); + } + } + + let past_edges = (-read_region.x0).max(-read_region.y0).max(read_region.x1 - viewport.x1).max(read_region.y1 - viewport.y1); + self.backdrop_apron = self.backdrop_apron.max(past_edges.max(0.).ceil() as u32); + } + self.backdrop_readers.extend(bounds.map(|bounds| (self.view.transform_rect_bbox(bounds), backdrop_reach))); + } + + // Content reading past the edges by no more than a grown render holds stops the drawing, leaving all of it to that render + if (1..=self.largest_apron).contains(&self.backdrop_apron) { + self.drawing = false; + } + if !self.drawing { + return; + } + let backdrop = reads_backdrop.then(|| self.backdrop()).flatten(); + + let texture_to_device = Affine::new(frame_to_device.to_cols_array()) * Affine::translate(origin) * Affine::scale(1. / resolution); + let frame_to_pixels = Affine::scale(resolution) * Affine::translate(-origin); let content_view = frame_to_pixels * document_to_frame; let effect_to_pixels = DAffine2::from_cols_array(&content_view.as_coeffs()) * effect_space; let effect_frame = effect_frame.map(|frame| frame.placed(DAffine2::from_cols_array(&frame_to_pixels.as_coeffs()))); let Some(renderer) = self.effects_renderer.as_deref_mut() else { return }; - let results = renderer.render_effects(size, content_view, effects, &layers, fill, opacity, effect_to_pixels, effect_frame, capture, draw_paint, draw); + let backdrop = backdrop.as_ref().map(|backdrop| (backdrop, texture_to_device)); + let results = renderer.render_effects(size, content_view, effects, &layers, fill, opacity, effect_to_pixels, effect_frame, backdrop, capture, draw_paint, draw); // Draw each layer where the content was, blended onto what lies beneath, except a captured coverage, which is drawn as it is let area = Rect::new(0., 0., size.x as f64, size.y as f64); - let texture_to_device = Affine::new(frame_to_device.to_cols_array()) * Affine::translate(origin) * Affine::scale(1. / resolution); for (texture, blend_mode) in results { let isolated = capture.is_none() && (opacity < 1. || blend_mode != core_types::blending::BlendMode::Normal); if isolated { diff --git a/node-graph/libraries/wgpu-executor/src/vello_effects.rs b/node-graph/libraries/wgpu-executor/src/vello_effects.rs index 9470661514..9b1a0158e9 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_effects.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_effects.rs @@ -15,6 +15,7 @@ use raster_kernels::effect_kernels::{BlurKernel, MAX_DIRECT_BOX_RADIUS, NEGLIGIB use raster_kernels::resample_kernels::MotionBlurShear; use std::collections::HashMap; use std::sync::{Mutex, PoisonError}; +use vello_gpu::kurbo::Affine; use wgpu::util::DeviceExt; mod filters; @@ -69,6 +70,20 @@ impl Default for Parameters { } } +impl Parameters { + /// The parameters placing a pass's pixels in the scene's backdrop by `placement`, laid out as the shader's `backdrop_point` reads them. + fn placed_in_backdrop(placement: Affine) -> Self { + let [a, b, c, d, x, y] = placement.as_coeffs().map(|coefficient| coefficient as f32); + + Self { + step: [a, b], + offset: [c, d], + values: [x, y, 0., 0.], + ..Default::default() + } + } +} + /// The kernel's taps for a texture halved `levels` times, each the distance and weight of a symmetric pair of taps that sample between two texels. fn kernel_taps(kernel: BlurKernel, levels: u32) -> Vec<[f32; 4]> { let weights = kernel.weights(levels); @@ -249,6 +264,7 @@ impl EffectPasses { /// `effect_to_pixels` places the effects' space on the texture's pixels, `fill` fades the content but not the shadows and glows cast from it, and `opacity` fades the layers. /// The `frame`, in the texture's pixels, is the content's extent, which displacements take as their own. /// `paints` holds the effects' drawn paints in order, each rendered over the same pixels as the content. + /// `backdrop` is what lies beneath, for the effects that read it, with the placement of the content texture's pixels in it. /// With a `capture`, the only result is instead that effect's coverage, as black with it in alpha, or the share [`EffectCapture::THROUGH_MASK`] names. #[expect(clippy::too_many_arguments)] pub(crate) fn apply( @@ -264,6 +280,7 @@ impl EffectPasses { effect_to_pixels: DAffine2, frame: Option, paints: &[wgpu::Texture], + backdrop: Option<(&wgpu::Texture, Affine)>, capture: Option, ) -> Vec<(wgpu::Texture, BlendMode)> { let mut recorder = PassRecorder { @@ -287,6 +304,8 @@ impl EffectPasses { let mut pieces: HashMap = HashMap::new(); // How much the trailing masks together show of each finished layer let mut layer_fade: Option = None; + // How strongly all the masks together show the content, which they show what lies beneath it by too + let mut masks_strength: Option = None; // A captured coverage ends the passes in place of the effects' result, once the content's layer is finished if its knockout or share depends on that let mut captured: Option = None; @@ -715,6 +734,29 @@ impl EffectPasses { } recorder.textures.release(height); } + // What lies beneath, blurred, is always a piece at the bottom of the content's own layer + EffectOperation::BackgroundBlur { radius, box_blur, gamma } => { + let Some((backdrop, placement)) = backdrop else { continue }; + let parameters = Parameters::placed_in_backdrop(placement); + let mut seen = recorder.run("sample_backdrop", WORKING_FORMAT, recorder.size, backdrop, None, None, parameters); + + let radius = radius * length_scale; + if box_blur && radius > MAX_DIRECT_BOX_RADIUS { + // Past the widest box blurred directly, a box sums running sums at the full radius everywhere, exact as the content's box blur is + let every_pixel = Parameters { color: [1.; 4], ..Default::default() }; + let full_radius = recorder.run("flood", COVERAGE_FORMAT, recorder.size, &seen, None, None, every_pixel); + let mut blurred = None; + recorder.masked_box_blur(&seen, &mut blurred, &mut None, &full_radius, DVec2::splat(radius), !gamma, true); + recorder.textures.release(full_radius); + if let Some(blurred) = blurred { + recorder.textures.release(std::mem::replace(&mut seen, blurred)); + } + } else if radius >= NEGLIGIBLE_LENGTH { + let kernel = if box_blur { BlurKernel::Box { radius } } else { BlurKernel::Gaussian { sigma: radius } }; + seen = recorder.blur(seen, kernel, !gamma); + } + pieces.insert(piece(0), seen); + } EffectOperation::PaintOverlay { blend_mode, opacity, .. } => { let Some(paint) = paints.next() else { continue }; let painted = recorder.scale(paint, (opacity / 100.) as f32); @@ -736,12 +778,24 @@ impl EffectPasses { let strength = recorder.mask_strength(mask, mode, density, mask_feather_sigma(feather) * length_scale, invert); capture_plane(&mut recorder, 0, &strength, false); + // Trailing masks fade every finished layer, what lies beneath in the content's own layer included, so only the others fade it here if layers.trailing_masks.contains(&index) { layer_fade = Some(recorder.faded_together(layer_fade.take(), strength)); } else { recorder.merge_beneath(content, &mut full, &mut filled, beneath.take()); recorder.fade_by(content, &mut full, &mut filled, &strength); - recorder.textures.release(strength); + masks_strength = match (backdrop.is_some(), masks_strength.take()) { + (false, _) => { + recorder.textures.release(strength); + None + } + (true, None) => Some(strength), + (true, Some(previous)) => { + let combined = recorder.run("apply_mask", COVERAGE_FORMAT, recorder.size, &previous, Some(&strength), None, Parameters::default()); + [previous, strength].into_iter().for_each(|texture| recorder.textures.release(texture)); + Some(combined) + } + }; } } EffectOperation::Feather { distance } => { @@ -953,7 +1007,7 @@ impl EffectPasses { } } if let Some(captured) = captured.take_if(|_| !capture_needs_content_layer) { - let textures = [full, filled, beneath, layer_fade].into_iter().flatten().chain(pieces.into_values()); + let textures = [full, filled, beneath, layer_fade, masks_strength].into_iter().flatten().chain(pieces.into_values()); textures.for_each(|texture| recorder.textures.release(texture)); queue.submit([recorder.encoder.finish()]); return vec![(captured, BlendMode::Normal)]; @@ -962,7 +1016,7 @@ impl EffectPasses { // A coverage the passes never reached, like that of a band too thin to draw at this resolution, covers nothing if capture.is_some_and(|capture| capture != EffectCapture::THROUGH_MASK) && captured.is_none() { let empty = recorder.scale(full.as_ref().unwrap_or(content), 0.); - let textures = [full, filled, beneath, layer_fade].into_iter().flatten().chain(pieces.into_values()); + let textures = [full, filled, beneath, layer_fade, masks_strength].into_iter().flatten().chain(pieces.into_values()); textures.for_each(|texture| recorder.textures.release(texture)); queue.submit([recorder.encoder.finish()]); return vec![(empty, BlendMode::Normal)]; @@ -995,7 +1049,7 @@ impl EffectPasses { PiecePlace::Within => 0., PiecePlace::IntoContent { over: false } => 1., PiecePlace::IntoContent { over: true } => 2., - PiecePlace::Beneath | PiecePlace::Through { .. } => continue, + PiecePlace::Beneath | PiecePlace::Through { .. } | PiecePlace::Backdrop => continue, }; let Some(tinted) = pieces.get(&piece.capture) else { continue }; let parameters = Parameters { @@ -1031,7 +1085,10 @@ impl EffectPasses { // A coverage too small to draw, like an outline's band at a far zoom, covers nothing _ => recorder.run("flood", WORKING_FORMAT, recorder.size, full_content, None, None, Parameters::default()), }; - let textures = [full, Some(content_image), beneath, content_with_fade, layer_fade].into_iter().flatten().chain(pieces.into_values()); + let textures = [full, Some(content_image), beneath, content_with_fade, layer_fade, masks_strength] + .into_iter() + .flatten() + .chain(pieces.into_values()); textures.for_each(|texture| recorder.textures.release(texture)); queue.submit([recorder.encoder.finish()]); return vec![(output, BlendMode::Normal)]; @@ -1057,6 +1114,7 @@ impl EffectPasses { for (index, layer) in layers.layers.iter().enumerate() { let holds_content = Some(index) == content_layer; let mut stack = if holds_content { beneath.take() } else { None }; + let mut backdrop_stack: Option = None; for part in &layer.parts { let LayerPart::Piece(part_piece) = part else { continue }; @@ -1083,6 +1141,12 @@ impl EffectPasses { }; recorder.run("through_mask", WORKING_FORMAT, recorder.size, tinted, Some(content_image), Some(fading_content), parameters) }), + PiecePlace::Backdrop => { + if let Some(tinted) = pieces.remove(&part_piece.capture) { + backdrop_stack = Some(recorder.stack_over(backdrop_stack, tinted)); + } + continue; + } PiecePlace::Within | PiecePlace::IntoContent { .. } => continue, }; if let Some(upper) = upper { @@ -1090,13 +1154,26 @@ impl EffectPasses { } } + // What lies beneath, filtered and cut to the content's own silhouette before its effects and by its masks, goes beneath everything else in the layer + let backdrop_stack = backdrop_stack.map(|backdrop_stack| { + let cut = recorder.run("mask_within", WORKING_FORMAT, recorder.size, &backdrop_stack, None, Some(content), Parameters::default()); + recorder.textures.release(backdrop_stack); + let Some(strength) = &masks_strength else { return cut }; + + let masked = recorder.run("apply_mask", WORKING_FORMAT, recorder.size, &cut, Some(strength), None, Parameters::default()); + recorder.textures.release(cut); + masked + }); let image = match (holds_content, read_after) { (true, true) => content_image.as_ref().map(|image| recorder.scale(image, 1.)), (true, false) => content_image.take(), (false, _) => None, }; - let Some(mut result) = image.map(|image| recorder.stack_over(stack.take(), image)).or(stack) else { - continue; + let result = image.map(|image| recorder.stack_over(stack.take(), image)).or(stack); + let mut result = match (result, backdrop_stack) { + (Some(result), backdrop_stack) => recorder.stack_over(backdrop_stack, result), + (None, Some(backdrop_stack)) => backdrop_stack, + (None, None) => continue, }; if let Some(fade) = &layer_fade { let faded = recorder.run("apply_mask", WORKING_FORMAT, recorder.size, &result, Some(fade), None, Parameters::default()); @@ -1105,7 +1182,10 @@ impl EffectPasses { results.push((result, layer.blend_mode)); } - let textures = [full, content_image, beneath, content_with_fade, layer_fade].into_iter().flatten().chain(pieces.into_values()); + let textures = [full, content_image, beneath, content_with_fade, layer_fade, masks_strength] + .into_iter() + .flatten() + .chain(pieces.into_values()); textures.for_each(|texture| recorder.textures.release(texture)); queue.submit([recorder.encoder.finish()]); results @@ -2021,7 +2101,7 @@ mod tests { let apply = |textures: &mut EffectTextures, effects: &Effects| { textures.drawn_passes.clear(); let layers = EffectLayers::plan(effects, BlendMode::Normal, 1., false); - let results = passes.apply(&context.device, &queue, textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None); + let results = passes.apply(&context.device, &queue, textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None); results.into_iter().for_each(|(result, _)| textures.release(result)); }; let draw = |textures: &mut EffectTextures| { @@ -2043,7 +2123,7 @@ mod tests { textures.drawn_passes.clear(); let effects = Effects::from_operations(operations); let layers = EffectLayers::plan(&effects, BlendMode::Normal, fill, false); - let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None); + let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None); results.into_iter().for_each(|(result, _)| textures.release(result)); textures.drawn_passes.clone() }; @@ -2087,7 +2167,7 @@ mod tests { let mut drawn = |layered: bool| { textures.drawn_passes.clear(); let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., layered); - let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None); + let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None); results.into_iter().for_each(|(result, _)| textures.release(result)); textures.drawn_passes.clone() }; @@ -2109,7 +2189,7 @@ mod tests { let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm); let queue = context.queue.lock(); let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false); - let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None); + let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None); results.into_iter().for_each(|(result, _)| textures.release(result)); let drawn = |label: &str| textures.drawn_passes.iter().filter(|&&drawn| drawn == label).count(); diff --git a/node-graph/libraries/wgpu-executor/src/vello_effects.wgsl b/node-graph/libraries/wgpu-executor/src/vello_effects.wgsl index 48bf28a1db..f3e56dde59 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_effects.wgsl +++ b/node-graph/libraries/wgpu-executor/src/vello_effects.wgsl @@ -3,9 +3,9 @@ struct Parameters { // Converts a target pixel's position into the normalized coordinates the inputs are sampled at target_to_uv: vec2, - // One step along the axis a kernel runs, in normalized coordinates + // One step along the axis a kernel runs, in normalized coordinates, or values described where a pass reads them step: vec2, - // How far a silhouette is cast, in normalized coordinates + // How far a silhouette is cast, in normalized coordinates, or values described where a pass reads them offset: vec2, // A pass's scalar setting, like a scale factor, fill, opacity, or knockout cover, described where it reads it amount: f32, @@ -680,6 +680,17 @@ fn flood(@builtin(position) position: vec4) -> @location(0) vec4 { return parameters.color; } +// Where a pixel at `position` lands in the scene's backdrop, in its pixels, placed by the linear map with the columns `step` and `offset`, then moved by `values.xy` +fn backdrop_point(position: vec2) -> vec2 { + return parameters.values.xy + mat2x2(parameters.step, parameters.offset) * position; +} + +// What lies beneath the content, sampled from the scene's backdrop (`source`) where each pixel lands +@fragment +fn sample_backdrop(@builtin(position) position: vec4) -> @location(0) vec4 { + return textureSampleLevel(source, linear_sampler, backdrop_point(position.xy) / vec2(textureDimensions(source)), 0.); +} + // A tinted image cut to the full-strength `content`, for a piece within the content drawn in a layer of its own @fragment fn mask_within(@builtin(position) position: vec4) -> @location(0) vec4 { diff --git a/node-graph/libraries/wgpu-executor/src/vello_render.rs b/node-graph/libraries/wgpu-executor/src/vello_render.rs index 2cd323a7ca..b5028b7046 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_render.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_render.rs @@ -162,7 +162,7 @@ impl VelloRenderer { queue, }; let (scene, images) = scene.finish(); - if let Err(error) = context.submit(&scene, images, max_texture_size, target, TargetAlpha::Straight) { + if let Err(error) = context.submit(&scene, images, max_texture_size, target, TargetAlpha::Straight, true) { log::error!("Vello GPU failed to render: {error}"); clear(device, queue, target); } @@ -254,24 +254,86 @@ impl RenderContext<'_> { /// Renders the scene `draw` draws into `target`, a texture of `size`, in a single Vello GPU render. fn render_once(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha) -> Result<(), RenderError> { - let (width, height) = (size.x as u16, size.y as u16); let max_texture_size = self.device.limits().max_texture_dimension_2d; + let max_size = max_texture_size.min(u16::MAX as u32); + let (mut scene, mut images, apron) = self.draw_scene(draw, view, size, max_texture_size, largest_apron(size, max_size)); - // Draw the scene for this render's size and placement, which renders its effects groups as they're drawn - let mut scene = self.canvas.spare_scenes.pop().unwrap_or_else(|| vello_gpu::Scene::new(width, height)); - scene.reset_and_resize(width, height); - let mut builder = VelloSceneBuilder::from_vello(scene, view, max_texture_size).with_effects_renderer(self); - draw(&mut builder); - let (scene, images) = builder.finish(); + // Content reading what lies beneath it past the scene's edges stops its drawing for one grown by as much, of which the target takes the middle + if let Some(apron) = apron + && let Some(grown_size) = grown_render_size(size, apron, max_size) + { + self.discard_scene(scene, images); + let grown_view = Affine::translate((apron as f64, apron as f64)) * view; + let (scene, images, _) = self.draw_scene(draw, grown_view, grown_size, max_texture_size, 0); - let rendered = self.submit(&scene, images, max_texture_size, target, target_alpha); + let grown_target = create_texture( + self.device, + "vello_gpu_grown_target", + grown_size, + target.format(), + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC, + ); + let rendered = self.submit(&scene, images, max_texture_size, &grown_target, target_alpha, true); + self.canvas.spare_scenes.push(scene); + + let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_grown_copy") }); + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { + origin: wgpu::Origin3d { x: apron, y: apron, z: 0 }, + ..grown_target.as_image_copy() + }, + target.as_image_copy(), + wgpu::Extent3d { + width: size.x, + height: size.y, + depth_or_array_layers: 1, + }, + ); + self.queue.submit([encoder.finish()]); + return rendered; + } + + // Later content reading farther past the edges than a grown render holds leaves the scene to draw again, reading only what it holds + if apron.is_some() { + self.discard_scene(scene, images); + (scene, images, _) = self.draw_scene(draw, view, size, max_texture_size, 0); + } + + let rendered = self.submit(&scene, images, max_texture_size, target, target_alpha, true); // Once the render that draws it is submitted, the scene is free to reuse self.canvas.spare_scenes.push(scene); rendered } + /// Draws the scene `draw` draws for a render of `size` placed by `view`, which renders its effects groups as they're drawn. + /// It stops at the first content reading what lies beneath it past its edges by at most `largest_apron` pixels, then returns how far past them all of it reads. + fn draw_scene(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, max_texture_size: u32, largest_apron: u32) -> (vello_gpu::Scene, Vec, Option) { + let (width, height) = (size.x as u16, size.y as u16); + let mut scene = self.canvas.spare_scenes.pop().unwrap_or_else(|| vello_gpu::Scene::new(width, height)); + scene.reset_and_resize(width, height); + + let mut builder = VelloSceneBuilder::from_vello(scene, view, max_texture_size) + .with_effects_renderer(self) + .stopping_for_an_apron_up_to(largest_apron); + draw(&mut builder); + let apron = (!builder.drew_everything()).then(|| builder.backdrop_apron()); + let (scene, images) = builder.finish(); + (scene, images, apron) + } + + /// Sets aside a drawn scene without rendering it, freeing the effects results it draws for reuse. + fn discard_scene(&mut self, scene: vello_gpu::Scene, images: Vec) { + for image in images { + if let SceneImage::Rendered(texture) = image { + self.canvas.effect_textures.release(texture); + } + } + self.canvas.spare_scenes.push(scene); + } + /// Renders a drawn scene, with the images it draws, into `target`, a texture of the scene's size, in a single Vello GPU render. - fn submit(&mut self, scene: &vello_gpu::Scene, images: Vec, max_texture_size: u32, target: &wgpu::Texture, target_alpha: TargetAlpha) -> Result<(), RenderError> { + /// The effects results it draws are freed for reuse after it, even if it fails when `release_failed`. + fn submit(&mut self, scene: &vello_gpu::Scene, images: Vec, max_texture_size: u32, target: &wgpu::Texture, target_alpha: TargetAlpha, release_failed: bool) -> Result<(), RenderError> { let device = self.device; let (width, height) = (scene.width(), scene.height()); let size = UVec2::new(width as u32, height as u32); @@ -350,10 +412,12 @@ impl RenderContext<'_> { queue.submit([encoder.finish()]); drop((gpu, queue)); - // Once the render that draws them is submitted, its effects results are free to reuse - for image in images { - if let SceneImage::Rendered(texture) = image { - self.canvas.effect_textures.release(texture); + // Once the render that draws them is submitted, its effects results are free to reuse, unless a failed render leaves them still to draw + if rendered.is_ok() || release_failed { + for image in images { + if let SceneImage::Rendered(texture) = image { + self.canvas.effect_textures.release(texture); + } } } @@ -376,6 +440,7 @@ impl EffectsRenderer for RenderContext<'_> { opacity: f32, effect_to_pixels: DAffine2, frame: Option, + backdrop: Option<(&wgpu::Texture, Affine)>, capture: Option, draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder), draw: &mut dyn FnMut(&mut VelloSceneBuilder), @@ -408,6 +473,7 @@ impl EffectsRenderer for RenderContext<'_> { effect_to_pixels, frame, &paint_textures, + backdrop, capture, ); effect_textures.release(content_texture); @@ -415,6 +481,31 @@ impl EffectsRenderer for RenderContext<'_> { results } + + fn render_backdrop(&mut self, scene: &vello_gpu::Scene, images: &[SceneImage], max_texture_size: u32) -> Option { + let size = UVec2::new(scene.width() as u32, scene.height() as u32); + let backdrop = self.canvas.effect_textures.acquire(self.device, size, self.renderer.precise_format); + + // A failed render leaves the scene to go on drawing what it drew, so the results it draws stay in use + match self.submit(scene, images.to_vec(), max_texture_size, &backdrop, TargetAlpha::Premultiplied, false) { + Ok(()) => Some(backdrop), + Err(error) => { + log::error!("Vello GPU failed to render what lies beneath content reading it: {error}"); + self.canvas.effect_textures.release(backdrop); + None + } + } + } +} + +/// The widest apron of pixels past each edge that a render of `size` can grow by and still fit a texture of `max_size`. +fn largest_apron(size: UVec2, max_size: u32) -> u32 { + max_size.saturating_sub(size.max_element()) / 2 +} + +/// The size of a render of `size` grown by an `apron` of pixels past each edge, or `None` without one or if it's too large for a texture of `max_size`. +fn grown_render_size(size: UVec2, apron: u32, max_size: u32) -> Option { + (apron > 0 && apron <= largest_apron(size, max_size)).then(|| size + UVec2::splat(2 * apron)) } /// Leaves `target` transparent. diff --git a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs index 22e01b3d51..05bbba7b7e 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs @@ -1607,7 +1607,7 @@ fn gpu_effect_texels(effects: &graphic_types::Effects, texels: &[[half::f16; 4]] let mut textures = crate::vello_effects::EffectTextures::default(); let layers = graphic_types::effect_layers::EffectLayers::plan(effects, BlendMode::Normal, 1., false); - let results = effect_passes.apply(device, &queue, &mut textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &paints, None); + let results = effect_passes.apply(device, &queue, &mut textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &paints, None, None); let (result, _) = results.into_iter().next()?; drop(queue); @@ -1788,6 +1788,1146 @@ fn later_shadows_stack_over_earlier_ones_beneath_the_content() { assert_eq!(pixel(&pixels, size, 93, 93)[3], 0, "no shadow of a shadow"); } +#[test] +fn background_blurs_blur_what_lies_beneath_within_the_content() { + use graphic_types::{EffectOperation, Effects}; + + let size = UVec2::new(128, 128); + let square = Rect::new(32., 32., 96., 96.); + let blur = Effects::from_operations([EffectOperation::BackgroundBlur { + radius: 6., + box_blur: false, + gamma: false, + }]); + + // Red to the left of x = 64 and blue to the right, beneath a square of no fill straddling the border, inside a clip of all but the bottom rows, which the restart keeps clipping + let draw = |scene: &mut VelloSceneBuilder| { + scene.push_clip_layer(Fill::NonZero, Affine::IDENTITY, &Rect::new(0., 0., 128., 120.)); + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(255, 0, 0), None, &Rect::new(0., 0., 64., 128.)); + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(0, 0, 255), None, &Rect::new(64., 0., 128., 128.)); + scene.draw_effects(&blur, 0., 1., BlendMode::Normal, true, Some(square), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| { + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square) + }); + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(0, 255, 0), None, &Rect::new(0., 100., 128., 128.)); + scene.pop_layer(); + }; + let Some(pixels) = render(size, draw) else { return }; + + let [red, _, blue, alpha] = pixel(&pixels, size, 64, 64); + assert!(red > 100 && blue > 100 && alpha == 255, "the border blurs within the content: {:?}", pixel(&pixels, size, 64, 64)); + assert_eq!(pixel(&pixels, size, 40, 64), [255, 0, 0, 255], "far from the border, the blur leaves red"); + assert_eq!(pixel(&pixels, size, 63, 20), [255, 0, 0, 255], "outside the content, the border stays sharp"); + assert_eq!(pixel(&pixels, size, 64, 20), [0, 0, 255, 255], "on both sides"); + assert_eq!(pixel(&pixels, size, 20, 110), [0, 255, 0, 255], "what's drawn after it is clipped as before"); + assert_eq!(pixel(&pixels, size, 20, 124)[3], 0, "past the clip"); +} + +#[test] +fn background_blurs_show_what_lies_beneath_them_in_any_effect_space() { + use glam::{DMat2, DVec2}; + use graphic_types::{EffectOperation, Effects}; + + let size = UVec2::new(128, 128); + let square = Rect::new(32., 32., 96., 96.); + let background_blur = EffectOperation::BackgroundBlur { + radius: 1., + box_blur: false, + gamma: false, + }; + let box_blur = EffectOperation::Blur { + radius_mask: Default::default(), + radius: 1., + box_blur: true, + gamma: false, + }; + + // Glass stretched or sheared since its blur was stamped, and turned glass with a box blur, each rendered along its effect space's axes + let stretched = DAffine2::from_scale(DVec2::new(2., 1.)); + let sheared = DAffine2::from_mat2(DMat2::from_cols(DVec2::X, DVec2::new(0.5, 1.))); + let turned = DAffine2::from_angle(30_f64.to_radians()); + let cases = [ + ("stretched", stretched, vec![background_blur.clone()]), + ("sheared", sheared, vec![background_blur.clone()]), + ("turned", turned, vec![background_blur, box_blur]), + ]; + + // A color in each quarter of the render, beneath a square of no fill covering part of each + let (green, white) = (Color::from_rgb8(0, 255, 0), Color::from_rgb8(255, 255, 255)); + let quarters = [(0., 0., RED), (64., 0., green), (0., 64., BLUE), (64., 64., white)]; + + for (name, effect_space, operations) in cases { + let effects = Effects::from_operations(operations); + let draw = |scene: &mut VelloSceneBuilder| { + for (x, y, color) in quarters { + scene.fill(Fill::NonZero, Affine::IDENTITY, color, None, &Rect::new(x, y, x + 64., y + 64.)); + } + scene.draw_effects(&effects, 0., 1., BlendMode::Normal, true, Some(square), effect_space, None, &mut |_, _| {}, &mut |scene| { + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square) + }); + }; + let Some(pixels) = render(size, draw) else { return }; + + // Each quarter shows through the glass where it lies, near the borders between them and near the glass's corners + let shown = [ + (54, 54, [255, 0, 0]), + (74, 54, [0, 255, 0]), + (54, 74, [0, 0, 255]), + (74, 74, [255, 255, 255]), + (38, 38, [255, 0, 0]), + (90, 38, [0, 255, 0]), + (38, 90, [0, 0, 255]), + (90, 90, [255, 255, 255]), + ]; + for (x, y, expected) in shown { + let [red, green, blue, alpha] = pixel(&pixels, size, x, y); + let close = [red, green, blue].iter().zip(expected).all(|(&channel, expected)| channel.abs_diff(expected) <= 2); + assert!(close && alpha == 255, "{name} glass at ({x}, {y}): {:?} against {expected:?}", pixel(&pixels, size, x, y)); + } + } +} + +#[test] +fn masks_cut_what_background_blurs_blur_as_they_cut_the_content() { + use core_types::list::{Item, List}; + use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM}; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, EffectOperation, Graphic, MaskMode, stamp_effect}; + use rendering::{Render, RenderParams}; + + // Red to the left of x = 64 and blue to the right, then glass of no fill straddling the border, masked to its top half + let image = |color: core_types::Color, min: DVec2, size: DVec2| { + Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size)) + }; + let top_half = image(core_types::Color::WHITE, DVec2::ZERO, DVec2::new(1., 0.5)); + let operations = [ + EffectOperation::BackgroundBlur { + radius: 6., + box_blur: false, + gamma: false, + }, + EffectOperation::Mask { + mask: Graphic::RasterCPU(Box::new(top_half)), + mode: MaskMode::Alpha, + density: 100., + feather: 0., + invert: false, + }, + ]; + let mut glass = image(core_types::Color::WHITE, DVec2::splat(32.), DVec2::splat(64.)).with_attribute(ATTR_OPACITY_FILL, 0_f64); + operations.iter().for_each(|operation| stamp_effect(&mut glass, Effect::new(operation))); + let mut images = List::new_from_item(image(core_types::Color::RED, DVec2::ZERO, DVec2::new(64., 128.))); + images.push(image(core_types::Color::BLUE, DVec2::new(64., 0.), DVec2::new(64., 128.))); + images.push(glass); + let graphic = Graphic::RasterCPUList(images); + + let size = UVec2::new(128, 128); + let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + + let [red, _, blue, _] = pixel(&pixels, size, 64, 40); + assert!(red > 100 && blue > 100, "the border blurs within the shown glass: {:?}", pixel(&pixels, size, 64, 40)); + assert_eq!(pixel(&pixels, size, 64, 88), [0, 0, 255, 255], "where the mask hides the glass, the border stays sharp"); + assert_eq!(pixel(&pixels, size, 63, 88), [255, 0, 0, 255], "on both sides"); +} + +#[test] +fn masks_trailing_background_blurs_fade_the_copy_with_the_content_as_one_layer_on_the_gpu_and_in_svg() { + use core_types::ATTR_TRANSFORM; + use core_types::list::{Item, List}; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, EffectOperation, Graphic, MaskMode, stamp_effect}; + use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender}; + + // Black to the left of x = 64 and white to the right, then opaque white glass over the border, faded by half by a black luminance mask at half density + let image = |color: core_types::Color, min: DVec2, size: DVec2| { + Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size)) + }; + let operations = [ + EffectOperation::BackgroundBlur { + radius: 8., + box_blur: false, + gamma: true, + }, + EffectOperation::Mask { + mask: Graphic::RasterCPU(Box::new(image(core_types::Color::BLACK, DVec2::ZERO, DVec2::ONE))), + mode: MaskMode::Luminance, + density: 50., + feather: 0., + invert: false, + }, + ]; + let mut glass = image(core_types::Color::WHITE, DVec2::splat(32.), DVec2::splat(64.)); + operations.iter().for_each(|operation| stamp_effect(&mut glass, Effect::new(operation))); + let mut images = List::new_from_item(image(core_types::Color::BLACK, DVec2::ZERO, DVec2::new(64., 128.))); + images.push(image(core_types::Color::WHITE, DVec2::new(64., 0.), DVec2::new(64., 128.))); + images.push(glass); + let graphic = Graphic::RasterCPUList(images); + + // SVG applies the mask once, to a group around the blurred copy and the content, so the copy doesn't show through the faded content + let mut svg = SvgRender::new(); + let export = RenderParams { + for_export: true, + ..Default::default() + }; + graphic.render_svg(&mut svg, &export); + let markup = svg.svg.to_svg_string(); + assert_eq!(markup.matches(r#"mask="url(#mask-"#).count(), 1, "{markup}"); + let faded = element_markup(&markup, r#"(markup: &'a str, opening: &str) -> Option<&'a str> { + let start = markup.find(opening)?; + let name = opening.strip_prefix('<')?.split([' ', '/', '>']).next()?; + let (open, close) = (format!("<{name}"), format!("")); + + // Its closing tag is the one returning the nesting of tags of its name to none + let (mut depth, mut index) = (0, start); + while let Some(offset) = markup[index..].find('<') { + let tag_start = index + offset; + index = tag_start + markup[tag_start..].find('>')? + 1; + let tag = &markup[tag_start..index]; + + if tag == close { + depth -= 1; + if depth == 0 { + return Some(&markup[start..index]); + } + } else if tag.strip_prefix(&open).is_some_and(|rest| rest.starts_with([' ', '>'])) && !tag.ends_with("/>") { + depth += 1; + } + } + None +} + +#[test] +fn background_blurs_inside_a_faded_group_blur_what_the_group_drew_beneath_them() { + use core_types::list::{Item, List}; + use core_types::{ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM}; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect}; + use rendering::{Render, RenderParams}; + + // Red to the left of x = 64 and blue to the right, then glass of no fill straddling the border, in a group at half opacity + let image = |color: core_types::Color, min: DVec2, size: DVec2| { + Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size)) + }; + let mut images = List::new_from_item(image(core_types::Color::RED, DVec2::ZERO, DVec2::new(64., 128.))); + images.push(image(core_types::Color::BLUE, DVec2::new(64., 0.), DVec2::new(64., 128.))); + let blur = EffectOperation::BackgroundBlur { + radius: 6., + box_blur: false, + gamma: false, + }; + let mut glass = image(core_types::Color::WHITE, DVec2::splat(32.), DVec2::splat(64.)).with_attribute(ATTR_OPACITY_FILL, 0_f64); + stamp_effect(&mut glass, Effect::new(&blur)); + images.push(glass); + let group = Graphic::Graphic(Box::new(Item::new_from_element(Graphic::RasterCPUList(images)).with_attribute(ATTR_OPACITY, 0.5_f64))); + + let size = UVec2::new(128, 128); + let Some(pixels) = render(size, |scene| group.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + + // The group renders offscreen, where its glass finds what it drew so far beneath it, all faded by half + let [red, _, blue, alpha] = pixel(&pixels, size, 64, 64); + assert!( + red > 100 && blue > 100 && alpha.abs_diff(128) <= 2, + "the border blurs within the glass: {:?}", + pixel(&pixels, size, 64, 64) + ); + let [red, _, blue, _] = pixel(&pixels, size, 64, 20); + assert!(red == 0 && blue > 200, "outside the glass, the border stays sharp: {:?}", pixel(&pixels, size, 64, 20)); +} + +#[test] +fn svgs_blur_an_image_the_gpu_renders_of_what_lies_beneath_glass_over_other_glass() { + use core_types::list::{Item, List}; + use core_types::transform::Footprint; + use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color as GraphicColor}; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect}; + use rendering::deferred_image::DeferredContent; + use rendering::{Render, RenderParams, SvgRender}; + + let Some(executor) = executor() else { return }; + + // Red to the left of x = 64 and blue to the right, then a pane of glass of no fill over the border, and a larger pane over that + let image = |color: GraphicColor, min: DVec2, size: DVec2| { + Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size)) + }; + let glass = |min: DVec2, size: DVec2| { + let mut glass = image(GraphicColor::WHITE, min, size).with_attribute(ATTR_OPACITY_FILL, 0_f64); + let blur = EffectOperation::BackgroundBlur { + radius: 6., + box_blur: false, + gamma: false, + }; + stamp_effect(&mut glass, Effect::new(&blur)); + glass + }; + let mut beneath = List::new_from_item(image(GraphicColor::RED, DVec2::ZERO, DVec2::new(64., 128.))); + beneath.push(image(GraphicColor::BLUE, DVec2::new(64., 0.), DVec2::new(64., 128.))); + beneath.push(glass(DVec2::new(32., 16.), DVec2::new(64., 32.))); + let mut images = beneath.clone(); + images.push(glass(DVec2::new(16., 8.), DVec2::new(96., 64.))); + + // SVG blurs an image of what lies beneath the upper pane, the lower pane included, rather than a copy holding the lower pane's copy + let mut svg = SvgRender::new(); + let export = RenderParams { + for_export: true, + ..Default::default() + }; + Graphic::RasterCPUList(images).render_svg(&mut svg, &export); + let [deferred] = &svg.deferred_images[..] else { + panic!("expected one image, got {}", svg.deferred_images.len()) + }; + assert!(matches!(deferred.content, DeferredContent::Beneath { .. })); + + let size = UVec2::splat(128); + let footprint = Footprint { + transform: DAffine2::IDENTITY, + resolution: size, + ..Default::default() + }; + let (placement, image_size, image_pixels) = { + let _turn = take_turn(); + let rendered = executor.render_deferred_svg_images(&svg.deferred_images, footprint); + let [(placement, texture)] = &rendered[..] else { + panic!("expected one image, got {}", rendered.len()) + }; + (placement.clone(), UVec2::new(texture.width(), texture.height()), executor.read_texture_pixels(texture).unwrap()) + }; + let image_pixel = |x: u32, y: u32| { + let unit = placement.transform.inverse().transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)); + let texel = (unit * image_size.as_dvec2()).floor().as_uvec2(); + let start = ((texel.y * image_size.x + texel.x) * 4) as usize; + <[u8; 4]>::try_from(&image_pixels[start..start + 4]).unwrap() + }; + + // The image matches the GPU's own render of what lies beneath: the border blurred within the lower pane and sharp beside it + let beneath = Graphic::RasterCPUList(beneath); + let Some(pixels) = render(size, |scene| beneath.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + let [red, _, blue, _] = image_pixel(64, 32); + assert!(red > 100 && blue > 100, "the border blurs within the lower pane: {:?}", image_pixel(64, 32)); + assert_eq!([image_pixel(63, 60), image_pixel(64, 60)], [[255, 0, 0, 255], [0, 0, 255, 255]], "beside it, the border stays sharp"); + for (x, y) in [(64, 32), (40, 32), (88, 32), (60, 20), (68, 44), (20, 12), (108, 68)] { + let (expected, actual) = (pixel(&pixels, size, x, y), image_pixel(x, y)); + assert!(expected.iter().zip(actual).all(|(&a, b)| a.abs_diff(b) <= 2), "at ({x}, {y}): {actual:?} against {expected:?}"); + } +} + +#[test] +fn svgs_blur_images_of_what_lies_beneath_glass_cut_by_its_clipping_artboard_before_the_glass_beneath_blurs_it() { + use core_types::list::{ATTR_CLIP, ATTR_DIMENSIONS, ATTR_LOCATION, Item, List}; + use core_types::transform::Footprint; + use core_types::{ATTR_BACKGROUND, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color as GraphicColor}; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Artboard, Effect, EffectOperation, Graphic, stamp_effect}; + use rendering::{Render, RenderParams, SvgRender}; + + let Some(executor) = executor() else { return }; + + // A white clipping artboard holding red just past its left edge, then two overlapping panes of glass of no fill just inside it + let image = |color: GraphicColor, min: DVec2, size: DVec2| { + Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size)) + }; + let glass = |min: DVec2, size: DVec2| { + let mut glass = image(GraphicColor::WHITE, min, size).with_attribute(ATTR_OPACITY_FILL, 0_f64); + let blur = EffectOperation::BackgroundBlur { + radius: 6., + box_blur: false, + gamma: false, + }; + stamp_effect(&mut glass, Effect::new(&blur)); + glass + }; + let artboards = |panes: usize| { + let mut content = List::new_from_item(image(GraphicColor::RED, DVec2::new(-24., 8.), DVec2::new(20., 48.))); + content.push(glass(DVec2::new(2., 16.), DVec2::new(40., 32.))); + if panes > 1 { + content.push(glass(DVec2::new(4., 12.), DVec2::new(48., 40.))); + } + let mut artboards = List::new_from_element(Artboard::new(List::new_from_element(Graphic::RasterCPUList(content)))); + artboards.set_attribute(ATTR_LOCATION, 0, DVec2::new(32., 0.)); + artboards.set_attribute(ATTR_DIMENSIONS, 0, DVec2::new(96., 64.)); + artboards.set_attribute(ATTR_BACKGROUND, 0, GraphicColor::WHITE); + artboards.set_attribute(ATTR_CLIP, 0, true); + artboards + }; + + let mut svg = SvgRender::new(); + let export = RenderParams { + for_export: true, + ..Default::default() + }; + artboards(2).render_svg(&mut svg, &export); + let size = UVec2::new(128, 64); + let footprint = Footprint { + transform: DAffine2::IDENTITY, + resolution: size, + ..Default::default() + }; + let (placement, image_size, image_pixels) = { + let _turn = take_turn(); + let rendered = executor.render_deferred_svg_images(&svg.deferred_images, footprint); + let [(placement, texture)] = &rendered[..] else { + panic!("expected one image, got {}", rendered.len()) + }; + (placement.clone(), UVec2::new(texture.width(), texture.height()), executor.read_texture_pixels(texture).unwrap()) + }; + let image_pixel = |x: u32, y: u32| { + let user = placement.user_to_document.inverse().transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)); + let texel = (placement.transform.inverse().transform_point2(user) * image_size.as_dvec2()).floor().as_uvec2(); + let start = ((texel.y * image_size.x + texel.x) * 4) as usize; + <[u8; 4]>::try_from(&image_pixels[start..start + 4]).unwrap() + }; + + // The image of what lies beneath the upper pane matches the GPU's own render, where the lower pane blurs only the white the artboard clips to + let beneath = artboards(1); + let Some(pixels) = render(size, |scene| beneath.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + for (x, y) in [(33, 32), (35, 24), (38, 40), (60, 32)] { + let (expected, actual) = (pixel(&pixels, size, x, y), image_pixel(x, y)); + let [red, green, blue, _] = actual; + assert!(green.abs_diff(red) <= 2 && blue.abs_diff(red) <= 2, "no red reaches in at ({x}, {y}): {actual:?}"); + assert!(expected.iter().zip(actual).all(|(&a, b)| a.abs_diff(b) <= 2), "at ({x}, {y}): {actual:?} against {expected:?}"); + } +} + +#[test] +fn svgs_blur_images_of_what_lies_beneath_glass_cut_by_the_faces_a_branching_clipping_mask_fills() { + use core_types::list::{ATTR_CURVE_TYPE, ATTR_ID, ATTR_PATHS, Item, List}; + use core_types::transform::Footprint; + use core_types::{ATTR_CLIPPING_MASK, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color as GraphicColor}; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::vector_types::vector::{CurveType, Path, PointId, SegmentId}; + use graphic_types::{Effect, EffectOperation, Graphic, Vector, stamp_effect}; + use rendering::{Render, RenderParams, SvgRender}; + + let Some(executor) = executor() else { return }; + + // A diamond in a 64 unit square, its walls separate segments branching at every point, so it fills its five faces rather than its contours + let corners_and_midpoints = [(0., 0.), (64., 0.), (64., 64.), (0., 64.), (32., 0.), (64., 32.), (32., 64.), (0., 32.)]; + let walls = [(0, 4), (1, 4), (1, 5), (2, 5), (2, 6), (3, 6), (3, 7), (0, 7), (4, 5), (5, 6), (6, 7), (4, 7)]; + let mut mesh = Vector::default(); + let mut point_id = PointId::ZERO; + for (index, (x, y)) in corners_and_midpoints.into_iter().enumerate() { + mesh.0.push(Item::new_from_element(DVec2::new(x, y))); + mesh.0.set_attribute(ATTR_ID, index, point_id.next_id()); + } + let mut paths = List::new(); + let mut segment_id = SegmentId::ZERO; + for (start, end) in walls { + let mut path = Path::from_references([start, end]); + path.0.set_attribute(ATTR_ID, 0, segment_id.next_id()); + paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, CurveType::Linear)); + } + let base = Item::new_from_element(mesh) + .with_attribute(ATTR_PATHS, paths) + .with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(32.))); + + // The mesh clipping a group of red filling the render and two overlapping panes of glass of no fill inside the square + let image = |color: GraphicColor, min: DVec2, size: DVec2| { + Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size)) + }; + let glass = |min: DVec2, size: DVec2| { + let mut glass = image(GraphicColor::WHITE, min, size).with_attribute(ATTR_OPACITY_FILL, 0_f64); + let blur = EffectOperation::BackgroundBlur { + radius: 6., + box_blur: false, + gamma: false, + }; + stamp_effect(&mut glass, Effect::new(&blur)); + glass + }; + let mut clipped = List::new_from_item(image(GraphicColor::RED, DVec2::ZERO, DVec2::splat(128.))); + clipped.push(glass(DVec2::new(44., 52.), DVec2::new(40., 24.))); + clipped.push(glass(DVec2::new(40., 48.), DVec2::new(48., 32.))); + let group = Item::new_from_element(Graphic::RasterCPUList(clipped)).with_attribute(ATTR_CLIPPING_MASK, true); + let graphic = Graphic::GraphicList( + [ + Item::new_from_element(Graphic::VectorList(List::new_from_item(base))), + Item::new_from_element(Graphic::Graphic(Box::new(group))), + ] + .into_iter() + .collect(), + ); + + let mut svg = SvgRender::new(); + let export = RenderParams { + for_export: true, + ..Default::default() + }; + graphic.render_svg(&mut svg, &export); + let footprint = Footprint { + transform: DAffine2::IDENTITY, + resolution: UVec2::splat(128), + ..Default::default() + }; + let (placement, image_size, image_pixels) = { + let _turn = take_turn(); + let rendered = executor.render_deferred_svg_images(&svg.deferred_images, footprint); + let [(placement, texture)] = &rendered[..] else { + panic!("expected one image, got {}", rendered.len()) + }; + (placement.clone(), UVec2::new(texture.width(), texture.height()), executor.read_texture_pixels(texture).unwrap()) + }; + let image_pixel = |x: u32, y: u32| { + let user = placement.user_to_document.inverse().transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)); + let texel = (placement.transform.inverse().transform_point2(user) * image_size.as_dvec2()).floor().as_uvec2(); + let start = ((texel.y * image_size.x + texel.x) * 4) as usize; + <[u8; 4]>::try_from(&image_pixels[start..start + 4]).unwrap() + }; + + // The image of what lies beneath the upper pane holds the red within every face and across the walls between them, and nothing past the square + for (x, y) in [(64, 64), (36, 36), (92, 36), (36, 92), (92, 92), (64, 40), (88, 64), (47, 48), (79, 48), (48, 79), (79, 79)] { + assert_eq!(image_pixel(x, y), [255, 0, 0, 255], "within the faces at ({x}, {y})"); + } + for (x, y) in [(26, 64), (64, 31), (101, 64)] { + assert_eq!(image_pixel(x, y)[3], 0, "past the square at ({x}, {y})"); + } +} + +#[test] +fn svgs_blur_images_of_what_lies_beneath_glass_cut_by_the_union_of_shapes_a_clipping_mask_fills_whatever_their_windings() { + use core_types::list::{ATTR_CURVE_TYPE, ATTR_ID, ATTR_PATHS, Item, List}; + use core_types::transform::Footprint; + use core_types::{ATTR_CLIPPING_MASK, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color as GraphicColor}; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::vector_types::vector::{CurveType, Path, PointId, SegmentId}; + use graphic_types::{Effect, EffectOperation, Graphic, Vector, stamp_effect}; + use rendering::{Render, RenderParams, SvgRender}; + + let Some(executor) = executor() else { return }; + + // Two triangles from the origin, crossing as one loop through their shared corners, a spur making the vector branch, and a rectangle inside the lower lobe. + // Its faces' windings cancel within the rectangle, which SVG still fills, filling each face apart. + let points = [(0., 0.), (10., 10.), (0., 10.), (6., 0.), (0., -2.), (2., 0.5), (4., 0.5), (4., 1.5), (2., 1.5)]; + let paths: [&[u32]; 4] = [&[0, 1, 2], &[0, 3, 2], &[0, 4], &[5, 6, 7, 8, 5]]; + let mut vector = Vector::default(); + let mut point_id = PointId::ZERO; + for (index, (x, y)) in points.into_iter().enumerate() { + vector.0.push(Item::new_from_element(DVec2::new(x, y))); + vector.0.set_attribute(ATTR_ID, index, point_id.next_id()); + } + let mut path_list = List::new(); + let mut segment_id = SegmentId::ZERO; + for references in paths { + let mut path = Path::from_references(references.iter().copied()); + for span in 0..references.len() - 1 { + path.0.set_attribute(ATTR_ID, span, segment_id.next_id()); + } + path_list.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, CurveType::Linear)); + } + let placement = DAffine2::from_translation(DVec2::new(24., 32.)) * DAffine2::from_scale(DVec2::splat(8.)); + let base = Item::new_from_element(vector).with_attribute(ATTR_PATHS, path_list).with_attribute(ATTR_TRANSFORM, placement); + + // It clips a group of red left of x = 60 and blue right of it, glass of no fill over the rectangle and that border, and larger glass over all of it + let image = |color: GraphicColor, min: DVec2, size: DVec2| { + Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size)) + }; + let glass = |min: DVec2, size: DVec2| { + let mut glass = image(GraphicColor::WHITE, min, size).with_attribute(ATTR_OPACITY_FILL, 0_f64); + let blur = EffectOperation::BackgroundBlur { + radius: 6., + box_blur: false, + gamma: false, + }; + stamp_effect(&mut glass, Effect::new(&blur)); + glass + }; + let mut clipped = List::new_from_item(image(GraphicColor::RED, DVec2::ZERO, DVec2::new(60., 128.))); + clipped.push(image(GraphicColor::BLUE, DVec2::new(60., 0.), DVec2::new(68., 128.))); + clipped.push(glass(DVec2::new(40., 32.), DVec2::new(32., 16.))); + clipped.push(glass(DVec2::new(16., 16.), DVec2::new(96., 96.))); + let group = Item::new_from_element(Graphic::RasterCPUList(clipped)).with_attribute(ATTR_CLIPPING_MASK, true); + let graphic = Graphic::GraphicList( + [ + Item::new_from_element(Graphic::VectorList(List::new_from_item(base))), + Item::new_from_element(Graphic::Graphic(Box::new(group))), + ] + .into_iter() + .collect(), + ); + + let mut svg = SvgRender::new(); + let export = RenderParams { + for_export: true, + ..Default::default() + }; + graphic.render_svg(&mut svg, &export); + let footprint = Footprint { + transform: DAffine2::IDENTITY, + resolution: UVec2::splat(128), + ..Default::default() + }; + let (image_placement, image_size, image_pixels) = { + let _turn = take_turn(); + let rendered = executor.render_deferred_svg_images(&svg.deferred_images, footprint); + let [(image_placement, texture)] = &rendered[..] else { + panic!("expected one image, got {}", rendered.len()) + }; + (image_placement.clone(), UVec2::new(texture.width(), texture.height()), executor.read_texture_pixels(texture).unwrap()) + }; + let image_pixel = |shape_point: (f64, f64)| { + let point = placement.transform_point2(DVec2::new(shape_point.0, shape_point.1)); + let user = image_placement.user_to_document.inverse().transform_point2(point); + let texel = (image_placement.transform.inverse().transform_point2(user) * image_size.as_dvec2()).floor().as_uvec2(); + let start = ((texel.y * image_size.x + texel.x) * 4) as usize; + <[u8; 4]>::try_from(&image_pixels[start..start + 4]).unwrap() + }; + + // The image of what lies beneath the upper pane covers the rectangle, both lobes, and the triangles' contours, and nothing past them + for shape_point in [(3., 1.), (5., 0.5), (3., 8.), (1., 5.)] { + assert_eq!(image_pixel(shape_point)[3], 255, "covered at {shape_point:?}: {:?}", image_pixel(shape_point)); + } + for shape_point in [(8., 3.), (9., 1.), (-1., 5.)] { + assert_eq!(image_pixel(shape_point)[3], 0, "past every shape at {shape_point:?}: {:?}", image_pixel(shape_point)); + } + + // The lower pane still read what lies beneath it there, blurring the border between red and blue + let [red, _, blue, _] = image_pixel((4.5, 1.)); + assert!(red > 60 && blue > 60, "the border blurs within the lower pane: {:?}", image_pixel((4.5, 1.))); +} + +/// The alphas at x = 39, 40, and 41 of the image an SVG blurs of what lies beneath the uppermost of four panes of glass beside a stripe from x = 40 to 40.5, +/// in a group of red the `bases` clip, or `None` without a GPU. The three panes beneath each read what lies beneath them as the image renders. +fn alphas_across_a_thin_clip_beneath_glass(bases: core_types::list::List) -> Option<[u8; 3]> { + use core_types::list::{Item, List}; + use core_types::transform::Footprint; + use core_types::{ATTR_CLIPPING_MASK, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color as GraphicColor}; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect}; + use rendering::{Render, RenderParams, SvgRender}; + + let executor = executor()?; + + let image = |color: GraphicColor, min: DVec2, size: DVec2| { + Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size)) + }; + let mut clipped = List::new_from_item(image(GraphicColor::RED, DVec2::ZERO, DVec2::splat(128.))); + for _ in 0..4 { + let mut glass = image(GraphicColor::WHITE, DVec2::new(44., 24.), DVec2::new(16., 80.)).with_attribute(ATTR_OPACITY_FILL, 0_f64); + let blur = EffectOperation::BackgroundBlur { + radius: 2., + box_blur: false, + gamma: false, + }; + stamp_effect(&mut glass, Effect::new(&blur)); + clipped.push(glass); + } + let group = Item::new_from_element(Graphic::RasterCPUList(clipped)).with_attribute(ATTR_CLIPPING_MASK, true); + let graphic = Graphic::GraphicList( + [Item::new_from_element(Graphic::VectorList(bases)), Item::new_from_element(Graphic::Graphic(Box::new(group)))] + .into_iter() + .collect(), + ); + + let mut svg = SvgRender::new(); + let export = RenderParams { + for_export: true, + ..Default::default() + }; + graphic.render_svg(&mut svg, &export); + let footprint = Footprint { + transform: DAffine2::IDENTITY, + resolution: UVec2::splat(128), + ..Default::default() + }; + let _turn = take_turn(); + let rendered = executor.render_deferred_svg_images(&svg.deferred_images, footprint); + let [.., (placement, texture)] = &rendered[..] else { panic!("expected an image") }; + assert_eq!(rendered.len(), 3, "each pane above the lowest blurs an image of what lies beneath it"); + let (image_size, image_pixels) = (UVec2::new(texture.width(), texture.height()), executor.read_texture_pixels(texture).unwrap()); + let alpha = |x: u32| { + let user = placement.user_to_document.inverse().transform_point2(DVec2::new(x as f64 + 0.5, 64.5)); + let texel = (placement.transform.inverse().transform_point2(user) * image_size.as_dvec2()).floor().as_uvec2(); + image_pixels[((texel.y * image_size.x + texel.x) * 4 + 3) as usize] + }; + Some([alpha(39), alpha(40), alpha(41)]) +} + +/// A stripe half a pixel wide, from x = 40 to 40.5. +fn thin_stripe() -> core_types::list::Item { + use vello_gpu::kurbo::Shape; + + graphic_types::Vector::item_from_bezpath(&Rect::new(40., 16., 40.5, 112.).to_path(0.1)) +} + +#[test] +fn svgs_blur_images_of_what_lies_beneath_glass_keeping_a_thin_clip_partly_covered_through_every_read() { + use vello_gpu::kurbo::Shape; + + // The stripe with a square elsewhere, which unite into one outline + let square = graphic_types::Vector::item_from_bezpath(&Rect::new(80., 40., 100., 60.).to_path(0.1)); + let Some(alphas) = alphas_across_a_thin_clip_beneath_glass([thin_stripe(), square].into_iter().collect()) else { + return; + }; + + // The stripe covers half its pixel however many times the panes beneath read what lies beneath them + let [left, middle, right] = alphas; + assert!(left == 0 && middle.abs_diff(128) <= 2 && right == 0, "{alphas:?}"); +} + +#[test] +fn svgs_blur_images_of_what_lies_beneath_glass_cut_by_coincident_thin_clipping_shapes_as_by_one() { + let Some(alphas) = alphas_across_a_thin_clip_beneath_glass([thin_stripe(), thin_stripe()].into_iter().collect()) else { + return; + }; + + // Two coincident stripes cover half the pixel, as one does, rather than adding up to all of it + let [left, middle, right] = alphas; + assert!(left == 0 && middle.abs_diff(128) <= 2 && right == 0, "{alphas:?}"); +} + +#[test] +fn background_blurs_in_a_clip_read_what_lies_beneath_them_only_inside_an_offscreen_render() { + use core_types::list::{ATTR_EFFECTS, Item, List}; + use core_types::{ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_TRANSFORM, Color as GraphicColor}; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, EffectOperation, Effects, Graphic, MaskMode, linked_to_content, stamp_effect}; + use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender}; + + let image = |color: GraphicColor, min: DVec2, size: DVec2| { + Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size)) + }; + let blur = |radius: f64| EffectOperation::Blur { + radius_mask: Default::default(), + radius, + box_blur: false, + gamma: false, + }; + + // A white image, then white glass overhanging its right edge, softened by a blur that keeps its background blur in a clip, or the same without the background blur + let images = |with_background_blur: bool| { + let mut overhanging = image(GraphicColor::WHITE, DVec2::new(24., 16.), DVec2::new(20., 32.)); + if with_background_blur { + let background_blur = EffectOperation::BackgroundBlur { + radius: 4., + box_blur: false, + gamma: false, + }; + stamp_effect(&mut overhanging, Effect::new(&background_blur)); + } + stamp_effect(&mut overhanging, Effect::new(&blur(4.))); + + let mut images = List::new_from_item(image(GraphicColor::WHITE, DVec2::splat(8.), DVec2::new(24., 48.))); + images.push(overhanging); + Graphic::RasterCPUList(images) + }; + + // The images as the clipping base itself, then nested in a render of their own inside it: of a group with an effect kept in the clip, of a faded group, and of a mask's graphic + let bases = |with_background_blur: bool| { + let masked_placement = DAffine2::from_scale(DVec2::splat(64.)); + let mut masked = image(GraphicColor::WHITE, DVec2::ZERO, DVec2::splat(64.)); + let mask = EffectOperation::Mask { + mask: linked_to_content(images(with_background_blur), masked_placement), + mode: MaskMode::Alpha, + density: 100., + feather: 0., + invert: false, + }; + stamp_effect(&mut masked, Effect::new(&mask)); + let faded = Item::new_from_element(images(with_background_blur)).with_attribute(ATTR_OPACITY, 0.5_f64); + + [ + ("directly", Item::new_from_element(images(with_background_blur))), + ( + "in a group with a blur", + Item::new_from_element(images(with_background_blur)).with_attribute(ATTR_EFFECTS, Effects::from_operations([blur(1.)])), + ), + ("in a faded group", Item::new_from_element(Graphic::GraphicList(List::new_from_item(faded)))), + ("in a mask's graphic", Item::new_from_element(Graphic::RasterCPU(Box::new(masked)))), + ] + }; + + // The base is hidden by its opacity, which its clip doesn't take, so a red square clipped to it shows only as much as the clip covers + let clipped_scene = |base: Item| { + let red = image(GraphicColor::RED, DVec2::ZERO, DVec2::splat(64.)).with_attribute(ATTR_CLIPPING_MASK, true); + let clipped = Item::new_from_element(Graphic::RasterCPU(Box::new(red))); + Graphic::GraphicList([base.with_attribute(ATTR_OPACITY, 0_f64), clipped].into_iter().collect()) + }; + + let size = UVec2::splat(64); + for ((case, base), (_, base_without_background_blur)) in bases(true).into_iter().zip(bases(false)) { + let nested = case != "directly"; + + // In SVG, the glass copies what lies beneath it where the base is drawn, and in the clip only where it's nested + let mut svg = SvgRender::new(); + let export = RenderParams { + for_export: true, + ..Default::default() + }; + clipped_scene(base.clone()).render_svg(&mut svg, &export); + let copies = format!("{}{}", svg.svg_defs, svg.svg.to_svg_string()).matches(r##"| { + let graphic = clipped_scene(base); + render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())).map(|pixels| pixel(&pixels, size, 32, 16)[3]) + }; + let (Some(with_background_blur), Some(without_background_blur)) = (clip_coverage(base), clip_coverage(base_without_background_blur)) else { + continue; + }; + let message = format!("with the glass {case}, the GPU's clip covers {with_background_blur} with its background blur and {without_background_blur} without it"); + match nested { + true => assert!(with_background_blur >= without_background_blur + 10, "{message}"), + false => assert!(with_background_blur.abs_diff(without_background_blur) <= 1, "{message}"), + } + } +} + +#[test] +fn background_blurs_read_past_the_edges_of_the_render() { + use graphic_types::{EffectOperation, Effects}; + + let blur = Effects::from_operations([EffectOperation::BackgroundBlur { + radius: 8., + box_blur: false, + gamma: false, + }]); + + // Stripes beneath a square crossing the right edge of the narrower render, which reads the stripes past that edge + let draw = |scene: &mut VelloSceneBuilder| { + for stripe in 0..16 { + let color = if stripe % 2 == 0 { Color::from_rgb8(255, 0, 0) } else { Color::from_rgb8(0, 0, 255) }; + scene.fill(Fill::NonZero, Affine::IDENTITY, color, None, &Rect::new(stripe as f64 * 8., 0., stripe as f64 * 8. + 8., 64.)); + } + let square = Rect::new(16., 16., 112., 48.); + scene.draw_effects(&blur, 0., 1., BlendMode::Normal, true, Some(square), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| { + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square) + }); + }; + let (narrow, wide) = (UVec2::new(64, 64), UVec2::new(128, 64)); + let (Some(narrow_pixels), Some(wide_pixels)) = (render(narrow, draw), render(wide, draw)) else { + return; + }; + + // The narrower render's edge matches the wider render's same pixels + for x in 56..64 { + let (narrow_pixel, wide_pixel) = (pixel(&narrow_pixels, narrow, x, 32), pixel(&wide_pixels, wide, x, 32)); + assert!(narrow_pixel.iter().zip(wide_pixel).all(|(&a, b)| a.abs_diff(b) <= 2), "at {x}: {narrow_pixel:?} against {wide_pixel:?}"); + } +} + +#[test] +fn background_blurs_reading_past_the_edges_of_the_render_carry_out_their_effects_once() { + use graphic_types::{EffectOperation, Effects}; + + let blur = Effects::from_operations([EffectOperation::BackgroundBlur { + radius: 8., + box_blur: false, + gamma: false, + }]); + let glass = Rect::new(64., 48., 160., 80.); + + // How many times a render of `size` draws the glass, and the effect passes it draws + let effects_drawn = |size: UVec2| { + let executor = executor()?; + let _turn = take_turn(); + let take_drawn_passes = || std::mem::take(&mut executor.inner.document_canvas.lock().unwrap_or_else(std::sync::PoisonError::into_inner).effect_textures.drawn_passes); + take_drawn_passes(); + + let mut glass_drawn = 0; + let mut draw = |scene: &mut VelloSceneBuilder| { + scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(0., 0., 112., 128.)); + scene.fill(Fill::NonZero, Affine::IDENTITY, BLUE, None, &Rect::new(112., 0., 256., 128.)); + scene.draw_effects(&blur, 0., 1., BlendMode::Normal, true, Some(glass), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| { + glass_drawn += 1; + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &glass) + }); + }; + executor.render_vello(size, DAffine2::IDENTITY, &mut draw).unwrap_or_else(|error| panic!("Render failed: {error}")); + Some((glass_drawn, take_drawn_passes())) + }; + + // Glass crossing the right edge of the narrower render, and lying with its whole reach inside the wider one + let (Some(narrow), Some(wide)) = (effects_drawn(UVec2::new(128, 128)), effects_drawn(UVec2::new(256, 128))) else { + return; + }; + + // The narrower render carries out the blur once, in a render grown to read past its edge, as the wider one does at its own size + assert_eq!(wide.0, 1); + assert!(!wide.1.is_empty()); + assert_eq!(narrow, wide); +} + +#[test] +fn background_blurs_beside_effects_reading_their_whole_frame_read_only_their_own_reach_past_the_render() { + use glam::DVec2; + use graphic_types::{EffectOperation, Effects}; + + // Glass reaching far left of the render, with a twirl that reads across the whole of an ellipse within its frame + let glass = Rect::new(-300., 0., 64., 64.); + let frame = DAffine2::from_translation(DVec2::new(-300., 0.)) * DAffine2::from_scale(DVec2::new(364., 64.)); + let effects = Effects::from_operations([ + EffectOperation::BackgroundBlur { + radius: 2., + box_blur: false, + gamma: false, + }, + EffectOperation::Twirl { + angle: 90., + transform: frame * DAffine2::from_translation(DVec2::splat(0.5)), + }, + ]); + + let mut widths = Vec::new(); + let draw = |scene: &mut VelloSceneBuilder| { + widths.push(scene.width()); + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(255, 0, 0), None, &Rect::new(-400., 0., 64., 64.)); + scene.draw_effects( + &effects, + 0., + 1., + BlendMode::Normal, + true, + Some(glass), + DAffine2::IDENTITY, + Some((frame, 0.)), + &mut |_, _| {}, + &mut |scene| scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &glass), + ); + }; + if render(UVec2::new(64, 64), draw).is_none() { + return; + } + + // The blur reads three times its radius past the render, so a render grown to read what lies there needs no more + assert!(widths.iter().all(|&width| width <= 64 + 2 * 6), "{widths:?}"); +} + +#[test] +fn background_blurs_out_of_reach_of_the_render_leave_it_at_its_own_size() { + use glam::DVec2; + use graphic_types::{EffectOperation, Effects}; + + let background_blur = |box_blur| EffectOperation::BackgroundBlur { radius: 2., box_blur, gamma: false }; + let shadow = drop_shadow(core_types::Color::BLACK, DVec2::new(-100., 0.), 0., 0.); + + // Glass farther past the right edge than its blur reaches, kept in the region by a turned frame's bounding box or by a shadow reaching farther + let cases = [ + ("turned", DAffine2::from_angle(45_f64.to_radians()), vec![background_blur(true)], Rect::new(170., 59., 180., 69.)), + ("beside a shadow", DAffine2::IDENTITY, vec![background_blur(false), shadow], Rect::new(308., 16., 408., 48.)), + ]; + + for (name, effect_space, operations, glass) in cases { + let effects = Effects::from_operations(operations); + let mut widths = Vec::new(); + let draw = |scene: &mut VelloSceneBuilder| { + widths.push(scene.width()); + scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(0., 0., 512., 128.)); + scene.draw_effects(&effects, 0., 1., BlendMode::Normal, true, Some(glass), effect_space, None, &mut |_, _| {}, &mut |scene| { + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &glass) + }); + }; + if render(UVec2::new(128, 128), draw).is_none() { + return; + } + + // No pixel in view reads what lies beneath the glass, so the scene is drawn once, at its own size + assert_eq!(widths, [128], "{name}"); + } +} + +#[test] +fn background_blurs_over_other_background_blurs_read_through_them_past_the_edges_of_the_render() { + use graphic_types::{EffectOperation, Effects}; + + let blur = Effects::from_operations([EffectOperation::BackgroundBlur { + radius: 8., + box_blur: false, + gamma: false, + }]); + + // Red to the left of x = 88 and blue to the right, beneath three panes of glass crossing the right edge of the narrower render. + // Each pane reads the blurs of the panes beneath it, which read past its own reach in turn. + let draw = |scene: &mut VelloSceneBuilder| { + scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(-200., 0., 88., 64.)); + scene.fill(Fill::NonZero, Affine::IDENTITY, BLUE, None, &Rect::new(88., 0., 400., 64.)); + let glass = Rect::new(16., 16., 240., 48.); + for _ in 0..3 { + scene.draw_effects(&blur, 0., 1., BlendMode::Normal, true, Some(glass), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| { + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &glass) + }); + } + }; + let (narrow, wide) = (UVec2::new(64, 64), UVec2::new(256, 64)); + let (Some(narrow_pixels), Some(wide_pixels)) = (render(narrow, draw), render(wide, draw)) else { + return; + }; + + // The narrower render's edge matches the wider render's same pixels, where the blue reaches through the panes + assert!(pixel(&wide_pixels, wide, 63, 32)[2] > 10, "{:?}", pixel(&wide_pixels, wide, 63, 32)); + for x in 56..64 { + let (narrow_pixel, wide_pixel) = (pixel(&narrow_pixels, narrow, x, 32), pixel(&wide_pixels, wide, x, 32)); + assert!(narrow_pixel.iter().zip(wide_pixel).all(|(&a, b)| a.abs_diff(b) <= 2), "at {x}: {narrow_pixel:?} against {wide_pixel:?}"); + } +} + +#[test] +fn background_blurs_reading_farther_past_the_render_than_a_texture_holds_render_it_at_its_own_size() { + use graphic_types::{EffectOperation, Effects}; + + // A radius reaching so far past the render that twice its reach overflows the pixels a size can count + let blur = Effects::from_operations([EffectOperation::BackgroundBlur { + radius: 715_827_883., + box_blur: false, + gamma: false, + }]); + + let mut widths = Vec::new(); + let draw = |scene: &mut VelloSceneBuilder| { + widths.push(scene.width()); + scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(0., 0., 64., 64.)); + let glass = Rect::new(32., 16., 96., 48.); + scene.draw_effects(&blur, 0., 1., BlendMode::Normal, true, Some(glass), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| { + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &glass) + }); + }; + let size = UVec2::new(64, 64); + let Some(pixels) = render(size, draw) else { return }; + + // The scene is drawn once, at its own size, and what lies outside the glass is drawn as it is + assert_eq!(widths, [64]); + assert_eq!(pixel(&pixels, size, 16, 32), [255, 0, 0, 255]); +} + +#[test] +fn renders_grow_by_their_apron_only_while_they_fit_a_texture() { + let size = UVec2::new(64, 32); + assert_eq!(super::grown_render_size(size, 0, 16_384), None); + assert_eq!(super::grown_render_size(size, 8, 16_384), Some(UVec2::new(80, 48))); + assert_eq!(super::grown_render_size(size, 8160, 16_384), Some(UVec2::new(16_384, 16_352))); + assert_eq!(super::grown_render_size(size, 8161, 16_384), None); + + // Aprons too wide to count twice, or to add to the size, don't fit either + assert_eq!(super::grown_render_size(size, 2_147_483_649, 16_384), None); + assert_eq!(super::grown_render_size(size, u32::MAX / 2, 16_384), None); +} + +#[test] +fn background_box_blurs_turn_their_square_with_their_effect_space() { + use graphic_types::{EffectOperation, Effects}; + + let size = UVec2::new(128, 128); + let glass = Rect::new(16., 16., 112., 112.); + let blur = Effects::from_operations([EffectOperation::BackgroundBlur { + radius: 6., + box_blur: true, + gamma: false, + }]); + + // Red to the left of x = 64 and blue to the right, beneath glass of no fill with its effect space turned, and no other box blur beside it + let render_turned = |degrees: f64| { + render(size, |scene| { + scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(0., 0., 64., 128.)); + scene.fill(Fill::NonZero, Affine::IDENTITY, BLUE, None, &Rect::new(64., 0., 128., 128.)); + let effect_space = DAffine2::from_angle(degrees.to_radians()); + scene.draw_effects(&blur, 0., 1., BlendMode::Normal, true, Some(glass), effect_space, None, &mut |_, _| {}, &mut |scene| { + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &glass) + }); + }) + }; + let (Some(upright), Some(turned)) = (render_turned(0.), render_turned(45.)) else { return }; + + // Seven pixels from the border, an upright square's half width of 6 stops short of it, while a square turned 45° reaches across it with its corner + assert_eq!(pixel(&upright, size, 57, 64), [255, 0, 0, 255]); + let [red, _, blue, alpha] = pixel(&turned, size, 57, 64); + assert!(red > 200 && blue > 20 && alpha == 255, "{:?}", pixel(&turned, size, 57, 64)); +} + +#[test] +fn background_box_blurs_reach_only_their_half_width_at_any_radius() { + use graphic_types::{EffectOperation, Effects}; + + let size = UVec2::new(256, 32); + let glass = Rect::new(0., 0., 256., 32.); + + // Red to the left of x = 128 and blue to the right, beneath glass covering the render, blurred directly and, past 24 pixels, by running sums + for radius in [6_u32, 40] { + let blur = Effects::from_operations([EffectOperation::BackgroundBlur { + radius: radius as f64, + box_blur: true, + gamma: false, + }]); + let Some(pixels) = render(size, |scene| { + scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(0., 0., 128., 32.)); + scene.fill(Fill::NonZero, Affine::IDENTITY, BLUE, None, &Rect::new(128., 0., 256., 32.)); + scene.draw_effects(&blur, 0., 1., BlendMode::Normal, true, Some(glass), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| { + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &glass) + }); + }) else { + return; + }; + + // Two pixels past its half width from the border, the box reads only red, and two pixels within it, some blue + assert_eq!(pixel(&pixels, size, 128 - radius - 2, 16), [255, 0, 0, 255], "radius {radius}"); + assert!(pixel(&pixels, size, 128 - radius + 2, 16)[2] > 0, "radius {radius}: {:?}", pixel(&pixels, size, 128 - radius + 2, 16)); + } +} + +#[test] +fn background_box_blurs_turned_by_their_effect_space_read_their_turned_square_past_the_edges_of_the_render() { + use graphic_types::{EffectOperation, Effects}; + + let blur = Effects::from_operations([EffectOperation::BackgroundBlur { + radius: 40., + box_blur: true, + gamma: false, + }]); + let effect_space = DAffine2::from_angle(45_f64.to_radians()); + + // Red to the left of x = 174 and blue to the right, beneath glass crossing the right edge of the narrower render. + // Its box turned 45° reaches the blue from that edge with a corner about 57 pixels out, farther than the 41 it reaches unturned. + let draw = |scene: &mut VelloSceneBuilder| { + scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(-200., -200., 174., 400.)); + scene.fill(Fill::NonZero, Affine::IDENTITY, BLUE, None, &Rect::new(174., -200., 600., 400.)); + let glass = Rect::new(0., 0., 256., 128.); + scene.draw_effects(&blur, 0., 1., BlendMode::Normal, true, Some(glass), effect_space, None, &mut |_, _| {}, &mut |scene| { + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &glass) + }); + }; + let (narrow, wide) = (UVec2::new(128, 128), UVec2::new(384, 128)); + let (Some(narrow_pixels), Some(wide_pixels)) = (render(narrow, draw), render(wide, draw)) else { + return; + }; + + // The narrower render's edge matches the wider render's same pixels, where the blue reaches into the turned square's corner + assert!(pixel(&wide_pixels, wide, 127, 64)[2] > 10, "{:?}", pixel(&wide_pixels, wide, 127, 64)); + for x in 120..128 { + let (narrow_pixel, wide_pixel) = (pixel(&narrow_pixels, narrow, x, 64), pixel(&wide_pixels, wide, x, 64)); + assert!(narrow_pixel.iter().zip(wide_pixel).all(|(&a, b)| a.abs_diff(b) <= 2), "at {x}: {narrow_pixel:?} against {wide_pixel:?}"); + } +} + #[test] fn effects_blend_by_their_modes_onto_what_lies_beneath() { use core_types::Color as GraphicColor; @@ -2053,21 +3193,28 @@ fn the_part_through_the_fill_shows_over_what_lies_beneath_the_content_in_its_lay let size = UVec2::new(64, 64); let (backdrop, content, glow) = ([0.2, 0.3, 0.9], [1., 0.5, 0.], [1., 1., 0.75]); + let background_blur = EffectOperation::BackgroundBlur { + radius: 4., + box_blur: false, + gamma: false, + }; let mut shadow = drop_shadow(core_types::Color::BLACK.with_alpha(0.75), DVec2::ZERO, 0., 0.); if let EffectOperation::DropShadow { knockout, .. } = &mut shadow { *knockout = false; } - // Content at 30% fill over a shadow it doesn't knock out, with a screen glow over the content - let effects = vec![shadow, color_overlay(glow, BlendMode::Screen, 0.75)]; - let Some(pixels) = render_square_over_backdrop(effects, 0.3, 1., BlendMode::Normal, Some(opaque(backdrop)), opaque(content), 16., 48., size) else { - return; - }; + // Glass at 30% fill over the blurred backdrop (uniform here), and content over a shadow it doesn't knock out, each with a screen glow over the content + for (beneath, shown_beneath) in [(background_blur, backdrop), (shadow, mix_channels(backdrop, [0.; 3], 0.75))] { + let effects = vec![beneath.clone(), color_overlay(glow, BlendMode::Screen, 0.75)]; + let Some(pixels) = render_square_over_backdrop(effects, 0.3, 1., BlendMode::Normal, Some(opaque(backdrop)), opaque(content), 16., 48., size) else { + return; + }; - let expected = interior_over(mix_channels(backdrop, [0.; 3], 0.75), content, 0.3, &[(BlendMode::Screen, glow, 0.75)]); - let actual = pixel(&pixels, size, 32, 32); - let close = actual.iter().zip(expected).all(|(&actual, expected)| (actual as f32 - expected * 255.).abs() <= 3.); - assert!(close, "{actual:?} against {:?}", expected.map(|channel| channel * 255.)); + let expected = interior_over(shown_beneath, content, 0.3, &[(BlendMode::Screen, glow, 0.75)]); + let actual = pixel(&pixels, size, 32, 32); + let close = actual.iter().zip(expected).all(|(&actual, expected)| (actual as f32 - expected * 255.).abs() <= 3.); + assert!(close, "over {beneath:?}: {actual:?} against {:?}", expected.map(|channel| channel * 255.)); + } } #[test] @@ -3115,7 +4262,7 @@ fn gpu_adjusted_texels(run: &[graphic_types::Adjustment], texels: &[[half::f16; let effects = Effects::from_operations(run.iter().cloned().map(EffectOperation::Adjustment)); let mut textures = crate::vello_effects::EffectTextures::default(); let layers = graphic_types::effect_layers::EffectLayers::plan(&effects, core_types::blending::BlendMode::Normal, fill, false); - let results = effect_passes.apply(device, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None); + let results = effect_passes.apply(device, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None); let (adjusted, _) = results.into_iter().next().expect("the adjustments draw one layer"); drop(queue); diff --git a/node-graph/nodes/blending/src/backdrop.rs b/node-graph/nodes/blending/src/backdrop.rs new file mode 100644 index 0000000000..4e74d152f3 --- /dev/null +++ b/node-graph/nodes/blending/src/backdrop.rs @@ -0,0 +1,38 @@ +use core_types::list::Item; +use core_types::{Color, Ctx}; +use graphic_types::raster_types::{CPU, GPU, Raster}; +use graphic_types::{Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect}; +use vector_types::Gradient; + +/// Blurs what lies beneath the input graphics within their shape, like frosted glass seen through them. +/// +/// The content draws over the blur, hiding it where opaque. Lowering the content's fill reveals the blur at full strength, while a translucent paint shows it only as strongly as the paint covers. +#[node_macro::node(category("Raster: Effect"))] +fn background_blur( + _: impl Ctx, + /// The content to see the blurred backdrop through. + #[implementations(Graphic, Vector, Raster, Raster, Color, Gradient, String, Generator)] + content: Item, + /// How far the blur spreads each point of what lies beneath. + #[unit(" px")] + #[range] + #[hard(0..)] + #[soft(..100)] + #[default(10.)] + radius: Item, + /// Use a box kernel instead of a circular Gaussian kernel, which averages evenly and leaves boxy artifacts. + box_blur: Item, + /// Opt to incorrectly blend the colors in gamma space for compatibility with the results from other software. + gamma: Item, +) -> Item { + let mut content = content; + stamp_effect( + &mut content, + Effect::new(&EffectOperation::BackgroundBlur { + radius: radius.into_element(), + box_blur: box_blur.into_element(), + gamma: gamma.into_element(), + }), + ); + content +} diff --git a/node-graph/nodes/blending/src/lib.rs b/node-graph/nodes/blending/src/lib.rs index a1c8e1ca6e..80e473a099 100644 --- a/node-graph/nodes/blending/src/lib.rs +++ b/node-graph/nodes/blending/src/lib.rs @@ -1,3 +1,4 @@ +pub mod backdrop; pub mod distortions; pub mod effects; pub mod filters;