From a01b7a3935ae162b75c2e063fb18e1879fddbcb6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:41:09 -0800 Subject: [PATCH] Reuse web canvas pixels outside view-sensitive effect bounds --- crates/render/src/frame.rs | 38 ++++++++++++++ crates/render/src/fx/pixels.rs | 20 +++++++- crates/render/src/fx/renderer.rs | 11 ++-- crates/render/src/fx/tests.rs | 24 +++++++++ crates/render/src/group.rs | 3 ++ crates/render/src/live.rs | 4 ++ crates/render/src/pattern.rs | 1 + crates/render/src/renderer.rs | 55 +++++++++++++++++--- crates/render/src/renderer/nodes.rs | 12 +++-- crates/render/src/renderer/text.rs | 4 ++ crates/render/src/tests/typeedges.rs | 11 ++++ crates/render/src/tests/viewraster.rs | 4 ++ crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/caches.rs | 11 ++-- crates/ui-egui/src/canvas/raster.rs | 59 ++++++++++++++++++---- crates/ui-egui/src/canvas/tests.rs | 72 +++++++++++++++++++++++++++ 16 files changed, 303 insertions(+), 28 deletions(-) diff --git a/crates/render/src/frame.rs b/crates/render/src/frame.rs index 7d000aa64f..90a35458cc 100644 --- a/crates/render/src/frame.rs +++ b/crates/render/src/frame.rs @@ -167,6 +167,8 @@ pub struct FrameStats { /// group or an effect's raster. A part of the frame rendered on its own can draw that art with /// other pixels than the whole frame does. pub view_sized: usize, + bounded_view_sized: usize, + view_sized_bounds: Option, /// How many threads composed the frame from its two ink planes, in a CMYK document that shows /// transparency; 0 for other frames. pub ink_threads: usize, @@ -183,10 +185,35 @@ pub struct FrameStats { pub micros: u64, } +impl FrameStats { + /// A conservative enclosure in the frame's output pixels, when every view-sized operation has + /// a known bound. `None` leaves the choice to render the whole frame. + pub fn view_sized_bounds(&self) -> Option { + self.view_sized_bounds.filter(|_| self.bounded_view_sized == self.view_sized) + } +} + +impl super::Renderer { + /// Records an operation bounded by its own output clip. A nested effect can affect more than + /// its own clip once an ancestor filters or composites it, so only bound direct RGB output. + pub(crate) fn note_view_sized_clip(&mut self, f: &Frame, clip: Rect) { + self.stats.view_sized += 1; + if self.nested == 0 && self.offscreen_live == 0 && f.view == f.output && f.doc.color_mode == vectorcraft_doc::ColorMode::Rgb { + let bound = f.output.transform_rect_bbox(clip).inflate(1.0, 1.0); + if bound.is_finite() { + self.stats.bounded_view_sized += 1; + self.stats.view_sized_bounds = vectorcraft_geom::union_opt(self.stats.view_sized_bounds, Some(bound)); + } + } + } +} + #[derive(Clone, Copy)] pub(crate) struct Frame<'a> { /// Drawing into a multithreaded context: vello filter layers must be rendered offscreen. pub(crate) mt: bool, + /// Set the flag if the incomplete paint would need a full render. + pub(crate) patch: Option<&'a std::cell::Cell>, pub(crate) doc: &'a Document, /// `doc`'s symbol art boxes, which culling measures symbol instances by ([`SymbolBoxes::quick`]). pub(crate) symbols: &'a SymbolBoxes<'a>, @@ -208,6 +235,17 @@ pub(crate) struct Frame<'a> { } impl Frame<'_> { + pub(crate) fn reject_patch(&self) -> bool { + self.patch.is_some_and(|hit| { + hit.set(true); + true + }) + } + + pub(crate) fn patch_rejected(&self) -> bool { + self.patch.is_some_and(std::cell::Cell::get) + } + /// Text space → device pixels when type is snapped to the pixel grid (Type anti-aliasing). pub(crate) fn text_snap(&self, t: &TextObject) -> Option { (self.opts.anti_alias == AntiAlias::Type).then(|| self.view * t.xf) diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index fe6933fea3..ceead2a01e 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -11,6 +11,12 @@ use super::{ RasterFx, Rect, RenderContext, Renderer, Shape, blend_mode, effects, fill_rule, paint, peniko, }; +/// The content to filter. An inner glow's output has an enclosing clip, while a shadow can spread beyond its content. +pub(super) enum FilterReach { + Clipped(Rect), + Spreads(Rect), +} + /// A hash of the names of `doc`'s swatches and patterns, of the paints and spot flags of its global /// swatches, and of the Spot Colors option those colors depend on. pub(crate) fn paint_names(doc: &Document) -> u64 { @@ -596,15 +602,25 @@ impl Renderer { &mut self, ctx: &mut RenderContext, f: &Frame, - reach: Rect, + reach: FilterReach, blur: f64, composite: Option<(vectorcraft_doc::color::BlendMode, f32)>, draw: impl FnOnce(&mut Self, &mut RenderContext, &Frame, Option<(vectorcraft_doc::color::BlendMode, f32)>), ) { // A filter layer's coarser grid starts where its context does: at the corner of a context // drawn single-threaded, and at the frame's edge for a region cropped to the frame. + let (reach, clipped) = match reach { + FilterReach::Clipped(rect) => (rect, true), + FilterReach::Spreads(rect) => (rect, false), + }; let screen = Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height())); - self.stats.view_sized += usize::from(!f.mt || f.view.transform_rect_bbox(reach).union(screen) != screen); + if !f.mt || f.view.transform_rect_bbox(reach).union(screen) != screen { + if clipped { + self.note_view_sized_clip(f, reach); + } else { + self.stats.view_sized += 1; + } + } if !f.mt { return self.inside_layer(|r| draw(r, ctx, f, composite)); } diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index cafc8ec35b..b66a1db09e 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -1,5 +1,6 @@ use super::bounds::{cull_bounds, effected_path_carrying, node_bezpath, rasterize_stage}; use super::entries::{Content, Drawn, FX_RASTER_BUDGET, FxGeom, Inputs, ItemGeom, Kept, KeptImage, Made, Reads, Shadow, ShadowEntry}; +use super::pixels::FilterReach; use super::predicates::{evaluates_live, is_container, rasterize_bounds, reads_outside, shifted}; use super::raster::{ DRAG_PIXEL_BUDGET, MAX_RASTERIZE, PIXEL_BUDGET, ViewCrop, content_changing, doc_raster_ppi, image_size, linear_key, pan_margin, pcolor, @@ -261,7 +262,7 @@ impl Renderer { let reach = reach + Vec2::new(dx, dy); #[cfg(test)] note_silhouette(); - self.with_filters(ctx, f, reach, blur, Some((mode, opacity)), |r, c, fr, comp| { + self.with_filters(ctx, f, FilterReach::Spreads(reach), blur, Some((mode, opacity)), |r, c, fr, comp| { c.set_transform(fr.view); c.push_layer(None, comp.map(|m| blend_mode(m.0)), comp.map(|m| m.1), None, Some(filter)); let ink = darkness.map_or(fr.ink, |d| fr.ink.darkened(d)); @@ -819,6 +820,9 @@ impl Renderer { rfx: &[RasterFx], paint: &mut dyn FnMut(&mut Self, &mut RenderContext, &Frame), ) { + if !rfx.is_empty() && f.reject_patch() { + return; + } // Only the last MAX_RASTERIZE Rasterize effects are drawn. let count = rfx.iter().filter(|fx| matches!(fx, RasterFx::Rasterize(_))).count(); let capped: Vec; @@ -998,7 +1002,7 @@ impl Renderer { let RasterFx::InnerGlow { mode, opacity, blur, color, center } = fx else { continue }; let filter = shadow_filter(0.0, 0.0, *blur, pcolor(f.ink, color)); if pixels { - self.with_filters(ctx, f, g.bounding_box(), *blur, Some((*mode, *opacity)), |r, c, fr, comp| { + self.with_filters(ctx, f, FilterReach::Clipped(g.bounding_box()), *blur, Some((*mode, *opacity)), |r, c, fr, comp| { if let Some((m, o)) = comp { c.set_transform(Affine::IDENTITY); c.push_layer(None, Some(blend_mode(m)), Some(o), None, None); @@ -1032,7 +1036,7 @@ impl Renderer { }); continue; } - self.with_filters(ctx, f, g.bounding_box(), *blur, Some((*mode, *opacity)), |_, c, fr, comp| { + self.with_filters(ctx, f, FilterReach::Clipped(g.bounding_box()), *blur, Some((*mode, *opacity)), |_, c, fr, comp| { // The blend layer goes outside the clip: a clip layer is isolated, so a blend // inside it would mix with nothing instead of the content below. if let Some((m, o)) = comp { @@ -1131,6 +1135,7 @@ mod tests { let opts = RenderOptions::default(); let frame = Frame { mt: false, + patch: None, doc: &doc, symbols: &symbols, view: Affine::IDENTITY, diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 1090c937ad..4838d27354 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -1530,6 +1530,30 @@ fn moved_objects_draw_their_effect_rasters_while_interacting() { /// 1600 × 1000 view near its corner needs more than the drag's budget. The /// frame after the drag, of the same document, is what a fresh renderer draws, as is a frame /// rendered while interacting without a drag (a dialog's preview). +#[test] +fn a_plain_patch_stops_at_a_raster_effect() { + let mut doc = doc_with(Rect::new(20.0, 20.0, 80.0, 76.0), Color::BLACK, vec![("texture.texturizer", json!({}))]); + let plain = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(94.0, 3.0, 96.0, 6.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + doc.insert(Some(doc.layers[0].id), usize::MAX, plain).unwrap(); + let (width, height) = (2000, 1600); + let view = Affine::scale(20.0); + let still = RenderOptions::default(); + let mut renderer = Renderer::new(); + renderer.threads = 0; + renderer.render(&doc, width, height, view, &still); + let total_drawn = renderer.stats.drawn; + let mut scratch = Renderer::new(); + scratch.threads = 0; + let patch_view = Affine::translate((-1850.0, -50.0)) * view; + assert!(scratch.render_plain_patch(&doc, 100, 100, patch_view, &still).is_some(), "the distant patch does not draw the effect"); + assert!(scratch.render_plain_patch(&doc, width, height, view, &still).is_none(), "a patch that draws the effect needs the full render"); + assert!(scratch.stats.drawn < total_drawn, "the rejected patch does not draw the artwork after the effect"); +} + #[test] fn a_drag_renders_raster_effects_within_the_drag_budget() { let effects = vec![("stylize.dropShadow", json!({"x": 4, "y": 3, "blur": 7, "opacity": 80})), ("texture.texturizer", json!({}))]; diff --git a/crates/render/src/group.rs b/crates/render/src/group.rs index 09509f58e7..b80b903ae9 100644 --- a/crates/render/src/group.rs +++ b/crates/render/src/group.rs @@ -114,6 +114,9 @@ impl Renderer { } fn group_offscreen(&mut self, ctx: &mut RenderContext, f: &Frame, c: Composite, r: Region, draw: &mut Content) { + if f.reject_patch() { + return; + } let Composite { clip, blend, opacity, mask, isolated, .. } = c; // A group that blends with its backdrop is drawn twice (over the backdrop, and alone for // its coverage), and so is everything in it, so such groups nested in each other cost 2ⁿ. diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index cda46c8fc0..dc0ac84e2b 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -636,6 +636,10 @@ impl Renderer { if !m.is_valid() { return; } + // A cropped mesh may lose a covered neighbor that supplied a color at its fringe. + if f.reject_patch() { + return; + } if f.opts.outline { let bp = m.lines().to_bezpath(); self.hairline(ctx, f, &bp, [0, 0, 0, 255]); diff --git a/crates/render/src/pattern.rs b/crates/render/src/pattern.rs index 94b8e8576e..5f4b5d71df 100644 --- a/crates/render/src/pattern.rs +++ b/crates/render/src/pattern.rs @@ -198,6 +198,7 @@ fn rasterize( let v = view * def.instance_xf(o); let frame = Frame { mt: false, + patch: None, doc, symbols: &symbols, view: v, diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 1b9ba6db1a..3f6689134f 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -113,9 +113,32 @@ impl Renderer { /// set in one of the document's composite fonts draws in the document's definition, also when /// no session has registered it (a document that is not in front, or read from a file). pub fn render(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Rendered { + self.render_document(doc, width, height, view, opts, None) + } + + /// Render a plain RGB canvas patch using a separate renderer. Raster effects and offscreen + /// group compositing require the full render. + pub fn render_plain_patch(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Option { + if doc.color_mode != vectorcraft_doc::ColorMode::Rgb || opts.mask_view.is_some() || opts.supersample { + return None; + } + let hit = std::cell::Cell::new(false); + let image = self.render_document(doc, width, height, view, opts, Some(&hit)); + (!hit.get()).then_some(image) + } + + fn render_document( + &mut self, + doc: &Document, + width: u32, + height: u32, + view: Affine, + opts: &RenderOptions, + patch: Option<&std::cell::Cell>, + ) -> Rendered { let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); let _frame = vectorcraft_text::KeptLayoutsFrame::begin(); - self.render_as(doc, width, height, view, opts, false, 1) + self.render_as(doc, width, height, view, opts, false, 1, patch) } /// [`Self::render`], or with `inks` the ink amounts in the working CMYK space instead of @@ -123,14 +146,24 @@ impl Renderer { /// pixel of the output in pixels of this render: the supersampling factor while an export /// draws its art at several times its size, else 1 ([`Frame::output`]). #[allow(clippy::too_many_arguments)] - fn render_as(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions, inks: bool, cell: u32) -> Rendered { + fn render_as( + &mut self, + doc: &Document, + width: u32, + height: u32, + view: Affine, + opts: &RenderOptions, + inks: bool, + cell: u32, + patch: Option<&std::cell::Cell>, + ) -> Rendered { let start = now(); if opts.supersample && opts.anti_alias == AntiAlias::Art && opts.mask_view.is_none() { let (w, h) = (width.clamp(1, MAX_CONTEXT_SIDE), height.clamp(1, MAX_CONTEXT_SIDE)); if let Some(k) = supersample_factor(w, h) { let hard = RenderOptions { anti_alias: AntiAlias::None, supersample: false, ..opts.clone() }; let hairline = std::mem::replace(&mut self.hairline, f64::from(k)); - let big = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k); + let big = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k, patch); self.hairline = hairline; let pixels = downsample(&big.pixels, big.width as usize, big.height as usize, k as usize); self.stats.micros = now().saturating_sub(start); @@ -164,7 +197,7 @@ impl Renderer { let symbols = doc.symbol_boxes().quick(); let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; let plates = proof::plate_lut(opts, doc); - let frame = Frame { mt: threads > 0, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() }; + let frame = Frame { mt: threads > 0, patch, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() }; self.begin_frame(); // View Opacity Mask: the mask's coverage in greyscale instead of the artwork. if let Some(m) = opts.mask_view.and_then(|id| doc.node(id)).and_then(|n| n.extras().mask.as_deref()) { @@ -199,7 +232,7 @@ impl Renderer { self.draw_frame(&frame, w, h) }; self.end_frame(); - if !inks { + if !inks && !pixels.is_empty() { proof::post(&mut pixels, opts); } self.stats.symbol_art = symbols.art_measured(); @@ -309,11 +342,17 @@ impl Renderer { } else { self.draw_page(&mut ctx, f); } - let pm = self.finish(&mut ctx, self.raster); + let pm = if f.patch_rejected() { + self.picture = None; + None + } else { + Some(self.finish(&mut ctx, self.raster)) + }; self.contexts.push((threads, ctx)); if self.contexts.len() > 2 { self.contexts.remove(0); } + let Some(pm) = pm else { return Vec::new() }; let mut pixels = pm.data_as_u8_slice().to_vec(); if let Some(bg) = opts.background { over_background(&mut pixels, f.ink.fixed8(screen_under_art(f, bg))); @@ -370,7 +409,7 @@ impl Renderer { let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0)); let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); let _frame = vectorcraft_text::KeptLayoutsFrame::begin(); - self.render_as(doc, w, h, view, opts, true, 1).pixels + self.render_as(doc, w, h, view, opts, true, 1, None).pixels } /// Render a single node (thumbnails, previews) fitted into `size`×`size` pixels. @@ -427,7 +466,7 @@ impl Renderer { ctx.set_aliasing_threshold(opts.anti_alias.threshold()); let symbols = doc.symbol_boxes().quick(); let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; - let frame = Frame { mt: false, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None }; + let frame = Frame { mt: false, patch: None, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None }; let raster = std::mem::replace(&mut self.raster, raster_settings(opts)); self.begin_frame(); (self.knockout, self.nested, self.backdrop, self.picture) = (false, 0, None, None); diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index fd1218e0a8..654dd938ee 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -241,7 +241,7 @@ impl Renderer { } pub(crate) fn draw_arc(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc) { - if self.skipped(f, a) { + if f.patch_rejected() || self.skipped(f, a) { return; } // An image masked by one white shape painted straight into the shape, as an image in a @@ -296,6 +296,9 @@ impl Renderer { /// The coverage of opacity mask `m` per output pixel (row-major): its art rendered offscreen, /// as luminance ([`mask_value`]). pub(super) fn mask_values(&mut self, f: &Frame, m: &vectorcraft_doc::OpacityMask, w: u16, h: u16) -> Option> { + if f.reject_patch() { + return None; + } let mut mctx = f.offscreen_context(w, h); // Mask art is a picture of its own: it takes no part in a knockout group around the object, // and its luminance is that of its screen colours. @@ -393,7 +396,7 @@ impl Renderer { return; } // A cancelled export stops drawing; whoever asked for the picture drops it (see `cancel`). - if vectorcraft_doc::cancel::is_cancelled() { + if f.patch_rejected() || vectorcraft_doc::cancel::is_cancelled() { return; } if force { @@ -781,7 +784,7 @@ impl Renderer { self.dimmed(ctx, f, &mut |r, c, fr| rest.iter().for_each(|n| r.draw_arc(c, fr, n))); } } else { - for c in children { + for c in children.iter().take_while(|_| !f.patch_rejected()) { self.draw_arc(ctx, f, c); } } @@ -804,6 +807,9 @@ impl Renderer { /// over the elements below it (the art below the group when the group is non-isolated and /// drawn over a copy of it, see [`Self::group`] and [`Self::knockout_over`]). pub(crate) fn draw_knockout(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc]) { + if f.reject_patch() { + return; + } let backdrop = self.backdrop.take(); for c in Node::knockout_elements(children) { if self.skipped(f, c) { diff --git a/crates/render/src/renderer/text.rs b/crates/render/src/renderer/text.rs index 01c73918e7..9e6851043f 100644 --- a/crates/render/src/renderer/text.rs +++ b/crates/render/src/renderer/text.rs @@ -327,6 +327,10 @@ impl Renderer { /// characters'. It also returns false for type whose offscreen drawing would be more than /// [`MAX_RASTER_SIDE`] pixels a side or more than [`fx::PIXEL_BUDGET`] pixels in all. fn draw_type_edges(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node, t: &TextObject, g: &Arc, geom_kept: bool) -> bool { + // A smaller frame can fit the offscreen type that a full frame draws as Sharp. + if f.reject_patch() { + return true; + } if proof::overprints(f.opts) && t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke) { return false; } diff --git a/crates/render/src/tests/typeedges.rs b/crates/render/src/tests/typeedges.rs index 3295342ce8..80c46edcc5 100644 --- a/crates/render/src/tests/typeedges.rs +++ b/crates/render/src/tests/typeedges.rs @@ -43,6 +43,17 @@ fn partial(a: &[u8]) -> usize { a.iter().filter(|v| **v > 0 && **v < 255).count() } +#[test] +fn a_plain_patch_defers_frame_sensitive_type_edges() { + let mut renderer = Renderer::new(); + renderer.threads = 0; + let opts = RenderOptions::default(); + let sharp = page(TypeAntiAlias::Sharp, None); + let crisp = page(TypeAntiAlias::Crisp, None); + assert!(renderer.render_plain_patch(&sharp, W, H, Affine::IDENTITY, &opts).is_some()); + assert!(renderer.render_plain_patch(&crisp, W, H, Affine::IDENTITY, &opts).is_none()); +} + /// The first pixels of `drawn` (type drawn with `m`) that are not the share `edge_coverage` gives /// the same pixel of `sharp` (the type drawn with Sharp), within a step of rounding: (pixel, /// Sharp, drawn). diff --git a/crates/render/src/tests/viewraster.rs b/crates/render/src/tests/viewraster.rs index 7474772eae..0087c1a4a8 100644 --- a/crates/render/src/tests/viewraster.rs +++ b/crates/render/src/tests/viewraster.rs @@ -276,6 +276,10 @@ fn a_frame_counts_the_art_it_draws_by_its_size() { let mut r = Renderer::new(); r.render(&mesh(100.0), 2100, 2100, Affine::IDENTITY, &RenderOptions::default()); assert_eq!(r.stats.view_sized, 0, "a mesh within the mesh buffer"); + assert!( + r.render_plain_patch(&mesh(100.0), 60, 60, Affine::translate((-50.0, -50.0)), &RenderOptions::default()).is_none(), + "a patch through a mesh must fall back even when the full mesh fits" + ); r.render(&mesh(3000.0), 2100, 2100, Affine::IDENTITY, &RenderOptions::default()); assert!(r.stats.view_sized > 0, "a mesh past the mesh buffer"); } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 6db68a7371..9a91fa708f 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -114,6 +114,7 @@ impl VectorcraftApp { host, canvas: CanvasCache { renderer: vectorcraft_render::Renderer::new(), + web_patch_renderer: None, texture: None, key: None, shown: None, @@ -121,6 +122,7 @@ impl VectorcraftApp { moved: false, from_worker: false, whole_frames: false, + view_sized_bounds: None, reused: None, waits_for_still: cfg!(target_arch = "wasm32"), still: None, diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 1be3cbe933..6072b80e30 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -11,6 +11,9 @@ use super::{canvas, render_worker}; /// Cached canvas raster. pub struct CanvasCache { pub renderer: vectorcraft_render::Renderer, + /// Draws for a patch against a web frame with bounded view-sensitive art. + /// The renderer of the whole frame keeps its raster and derived-art caches across these patches. + pub web_patch_renderer: Option>, pub texture: Option, pub key: Option, /// The document the frame shown was rendered from, and the options it was rendered with, with @@ -26,10 +29,12 @@ pub struct CanvasCache { /// ([`canvas::show`]). pub from_worker: bool, /// The frame shown drew art in a way that depends on its size, or a part of it drawn again on - /// this thread would not have matched the frame around it: until the next whole frame is shown, - /// edits of the frame shown render whole, on the worker when the frame is heavy - /// ([`canvas::show`]). + /// this thread would not have matched the frame around it. Edits that reach the affected area + /// render whole, on the worker when the frame is heavy ([`canvas::show`]). pub whole_frames: bool, + /// The shown web frame can still be patched outside this enclosure in its own raster pixels. + /// Present only when all frame-size-dependent output has a known bound. + pub view_sized_bounds: Option, /// The frame shown holds pixels the worker copied from its last frame, and when it was shown /// (seconds, egui's input time): it renders whole once it has been shown for /// [`canvas::STILL_SECS`] with the view unmoved. diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 1c1d17c00d..18b47fd840 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -57,9 +57,10 @@ pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered) -> egui::Colo /// is at most 8 ms, and except when that frame drew raster effects from rasters made before their /// objects moved ([`crate::CanvasCache::moved`]) or holds pixels copied from the worker's last frame /// ([`crate::CanvasCache::reused`]): the worker's renderer keeps the rasters of the art's effects, -/// and this thread's doesn't. No frame that drew art in a way that depends on its size, or that a -/// part drawn again here since it was shown would have differed from, is drawn again in part -/// ([`crate::CanvasCache::whole_frames`]). A frame that drew nothing from moved rasters or at a +/// and this thread's doesn't. A web frame with known view-sensitive output bounds can still be +/// patched outside them, accounting for the patch's rounding. Otherwise view-sensitive art or +/// an earlier rejected patch requires a whole render ([`crate::CanvasCache::whole_frames`]). +/// A frame that drew nothing from moved rasters or at a /// drag's lower resolution can supply the unchanged pixels when a Pen press starts an interaction /// over a worker frame, even when [`CacheKey::interacting`] and [`CacheKey::dragging`] change. /// Leaving an interaction still replaces the whole frame. What changed is measured by this thread's renderer: it keeps what @@ -101,17 +102,32 @@ pub(super) fn changed_pixels( vectorcraft_render::Changed::Nothing => Some(None), vectorcraft_render::Changed::Area(area) => match vectorcraft_render::view_pixels(area, view, w, h) { None => Some(None), - Some([x0, y0, x1, y1]) if !app.canvas.whole_frames => { + Some([x0, y0, x1, y1]) => { let ((x0, x1), (y0, y1)) = (in_steps(x0, x1, w), in_steps(y0, y1, h)); + let patch = Rect::new(f64::from(x0), f64::from(y0), f64::from(x1), f64::from(y1)); + if app.canvas.whole_frames && app.canvas.view_sized_bounds.is_none_or(|bounds| !bounds.intersect(patch).is_zero_area()) { + return None; + } + // A full draw can use 3D art measured here. Do not rebuild it in the scratch renderer. + if app.canvas.view_sized_bounds.is_some() && app.canvas.renderer.measured_bytes() > 0 { + return None; + } let share = (f64::from(x1 - x0) * f64::from(y1 - y0)) / (f64::from(w) * f64::from(h)); (share <= budget.min(0.5)).then_some(Some([x0, y0, x1, y1])) } - Some(_) => None, }, vectorcraft_render::Changed::Everything => None, } } +fn web_patch_renderer(slot: &mut Option>) -> &mut vectorcraft_render::Renderer { + slot.get_or_insert_with(|| { + let mut renderer = vectorcraft_render::Renderer::new(); + renderer.threads = 0; + Box::new(renderer) + }) +} + /// `a..b` of `0..n`, grown to whole eighths of `n` and moved back into `0..n`: the parts of a /// frame rendered again come in few sizes, which keep the contexts the renderer keeps. fn in_steps(a: u32, b: u32, n: u32) -> (u32, u32) { @@ -608,6 +624,8 @@ fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate: app.canvas.moved = done.moved > 0; app.canvas.from_worker = true; app.canvas.whole_frames = done.view_sized; + app.canvas.view_sized_bounds = None; + app.canvas.web_patch_renderer = None; } /// The size and view matrix of the frame to render: the pixel region in Pixel Preview, else the whole canvas. @@ -711,11 +729,23 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4] } let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) { - let renderer = &mut app.canvas.renderer; let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * *view; - let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, opts)); + let plain_patch = app.canvas.view_sized_bounds.is_some(); + let renderer = if plain_patch { web_patch_renderer(&mut app.canvas.web_patch_renderer) } else { &mut app.canvas.renderer }; + let part = effects.view(|| { + if plain_patch { + renderer.render_plain_patch(doc, x1 - x0, y1 - y0, part_view, opts) + } else { + Some(renderer.render(doc, x1 - x0, y1 - y0, part_view, opts)) + } + }); + let Some(mut part) = part else { + app.canvas.view_sized_bounds = None; + return false; + }; if renderer.stats.view_sized > 0 || renderer.stats.previewed > 0 || app.canvas.from_worker && renderer.stats.moved > 0 { app.canvas.whole_frames = true; + app.canvas.view_sized_bounds = None; return false; } let width = part.width; @@ -723,7 +753,10 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4] let color = color_image(&part); let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR }; tex.set_partial([x0 as usize, y0 as usize], color, options); - app.canvas.moved |= app.canvas.renderer.stats.moved > 0; + app.canvas.moved |= renderer.stats.moved > 0; + if plain_patch { + app.canvas.renderer.let_go_of_measured(); + } } app.canvas.key = Some((*key).clone()); app.canvas.shown = Some(((*doc).clone(), opts.clone())); @@ -779,6 +812,9 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { // thread's renderer has none, so a frame fast on the worker would be slow here. An edit in a // part of the frame shown is drawn again here, unless that part would differ ([`draw_changed`]). let same_doc = app.canvas.key.as_ref().is_some_and(|k| k.doc == key.doc); + if !same_doc { + app.canvas.web_patch_renderer = None; + } let settling = app.canvas.moved && !key.interacting; let staying = key.interacting && app.canvas.from_worker; // A document's first frame (opened, or its tab chosen) renders on the worker too: how long it @@ -835,7 +871,12 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { app.perf.render_ms = monotonic_ms() - t0; app.canvas.last_ms = app.perf.render_ms; app.canvas.moved = app.canvas.renderer.stats.moved > 0; - app.canvas.whole_frames = app.canvas.renderer.stats.view_sized > 0 || app.canvas.renderer.stats.previewed > 0; + let stats = app.canvas.renderer.stats; + app.canvas.whole_frames = stats.view_sized > 0 || stats.previewed > 0; + app.canvas.view_sized_bounds = if app.canvas.waits_for_still && stats.previewed == 0 { stats.view_sized_bounds() } else { None }; + if app.canvas.view_sized_bounds.is_none() { + app.canvas.web_patch_renderer = None; + } app.canvas.from_worker = false; app.canvas.reused = None; } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index c9e44fd207..04e367dce5 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1030,6 +1030,78 @@ fn an_edit_over_art_drawn_for_the_frames_size() { } } +#[test] +fn web_partial_redraws_skip_unchanged_view_sensitive_art() { + keeping_color_settings(|| { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300, "colorMode": "rgb"})).unwrap(); + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.canvas.worker_started = true; + app.canvas.waits_for_still = true; + app.canvas.renderer.threads = 0; + let glow = app.run("shape.rectangle", json!({"x": 55, "y": 70, "width": 55, "height": 55})).unwrap()["id"].clone(); + app.run("effect.apply", json!({"ids": [glow], "effect": "stylize.innerGlow", "params": {"blur": 8}})).unwrap(); + let large = app.run("shape.rectangle", json!({"x": -980, "y": -700, "width": 965, "height": 1010})).unwrap()["id"].clone(); + app.run("effect.apply", json!({"ids": [large], "effect": "texture.texturizer", "params": {}})).unwrap(); + let far = app.run("shape.rectangle", json!({"x": 300, "y": 200, "width": 12, "height": 12})).unwrap()["id"].clone(); + let near = app.run("shape.rectangle", json!({"x": 60, "y": 80, "width": 12, "height": 12})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [near], "color": "#ffffff"})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + shapes(&mut app, &ctx); + if let Some(vm) = app.view_mut() { + (vm.zoom, vm.center) = (1.2, Point::new(200.0, 150.0)); + } + // Start from a full raster at the chosen view rather than waiting for the reprojected view to settle. + app.canvas.key = None; + let read = |app: &mut VectorcraftApp| { + let (_, mut delta) = frame_output(app, &ctx); + let tex = app.canvas.texture.as_ref().unwrap().id(); + delta.set.remove(&tex).and_then(|mut uploads| uploads.pop()).expect("the edit uploads canvas pixels") + }; + let first = read(&mut app); + assert!(first.pos.is_none()); + assert!(app.canvas.renderer.stats.view_sized > 0, "single-threaded filter layers depend on the frame size"); + let egui::ImageData::Color(first) = first.image; + let mut composed = (*first).clone(); + for color in ["#ff0000", "#00ff00"] { + app.run("paint.setFill", json!({"ids": [far], "color": color})).unwrap(); + let delta = read(&mut app); + let [x, y] = delta.pos.expect("an edit away from the glow uploads only a patch"); + let egui::ImageData::Color(patch) = delta.image; + for row in 0..patch.height() { + let start = (y + row) * composed.width() + x; + composed.pixels[start..start + patch.width()].copy_from_slice(&patch.pixels[row * patch.width()..(row + 1) * patch.width()]); + } + } + let key = app.canvas.key.as_ref().unwrap(); + let view = app.canvas_view().unwrap(); + let (w, h, view) = frame_view(key.pixel, (key.w, key.h), &view, key.ppp); + let (doc, still) = app.canvas.shown.as_ref().unwrap(); + let drag = vectorcraft_render::RenderOptions { interacting: true, dragging: true, ..still.clone() }; + let mut cold = vectorcraft_render::Renderer::new(); + cold.threads = 0; + cold.render(doc, w, h, view, &drag); + assert!(cold.stats.previewed > 0, "a cold renderer draws the large effect at drag resolution"); + app.canvas.renderer.render(doc, w, h, view, &drag); + assert_eq!(app.canvas.renderer.stats.previewed, 0, "distant canvas patches left the full-resolution effect available for the drag"); + + // The old glow's bounds survive successive partial renders, even though neither draws it. + app.run("paint.setFill", json!({"ids": [near], "color": "#0202ee"})).unwrap(); + let overlap = read(&mut app); + assert!(overlap.pos.is_none(), "editing inside the old glow's bounds renders the whole frame"); + app.run("paint.setFill", json!({"ids": [near], "color": "#ffffff"})).unwrap(); + let restored = read(&mut app); + assert!(restored.pos.is_none()); + let egui::ImageData::Color(restored) = restored.image; + assert_eq!(restored.size, composed.size); + assert!(restored.pixels == composed.pixels, "partial updates equal a full redraw: {}", differing(&composed.pixels, Some(&restored.pixels))); + app.run("effect.apply", json!({"ids": [far], "effect": "stylize.innerGlow", "params": {"blur": 8}})).unwrap(); + assert!(read(&mut app).pos.is_none(), "the new glow in the part also requires a whole frame"); + }); +} + /// A canvas more device pixels across than the largest texture side the display supports renders /// its art at fewer pixels a point, within that size, and draws it over the whole canvas. Pixel /// Preview's region of document pixels stays within it too.