diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index a7d2850a1e..1280e7d998 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -11,6 +11,8 @@ workspace = true [features] # `vectorcraft_doc::blend::spines_built` for other crates' tests (dev-dependencies only). spine-count = [] +# `vectorcraft_doc::symbols_read` for other crates' tests (dev-dependencies only). +symbol-read-count = [] [dependencies] vectorcraft-geom = { workspace = true } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index f590a46497..180c2d95aa 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -75,6 +75,9 @@ pub mod style_libs; pub mod swatches; mod symbols; pub use symbols::SymbolBoxes; +#[cfg(any(test, feature = "symbol-read-count"))] +#[doc(hidden)] +pub use symbols::symbols_read; pub mod text; pub mod trace; pub mod twist; diff --git a/crates/doc/src/symbols.rs b/crates/doc/src/symbols.rs index a3c864118a..5aba1a8885 100644 --- a/crates/doc/src/symbols.rs +++ b/crates/doc/src/symbols.rs @@ -134,7 +134,7 @@ impl Document { /// Each symbol name of this document → the index of the first symbol of that name (the one a /// name finds). pub(crate) fn symbol_names(&self) -> SymbolNames { - #[cfg(test)] + #[cfg(any(test, feature = "symbol-read-count"))] SYMBOLS_READ.with(|c| c.set(c.get() + self.symbols.len())); let mut names = HashMap::with_capacity(self.symbols.len()); for (i, s) in self.symbols.iter().enumerate() { @@ -144,18 +144,37 @@ impl Document { } } -#[cfg(test)] +#[cfg(any(test, feature = "symbol-read-count"))] thread_local! { /// How many symbols [`Document::symbol_names`] has read on this thread. pub(crate) static SYMBOLS_READ: Cell = const { Cell::new(0) }; } +/// How many symbols [`Document::symbol_names`] has read on this thread, for other crates' tests +/// that count how often the symbol list is read to find symbols by name (the `symbol-read-count` +/// feature, dev-dependencies only). +#[cfg(any(test, feature = "symbol-read-count"))] +#[doc(hidden)] +pub fn symbols_read() -> usize { + SYMBOLS_READ.with(Cell::get) +} + impl<'a> SymbolBoxes<'a> { /// The document whose symbols these are. pub fn document(&self) -> &'a Document { self.doc } + /// New boxes for the same document, none measured yet and with none of the options set, that + /// find symbols by name through the same index as these boxes ([`Self::symbol`]). Measuring + /// objects one at a time in boxes of their own made this way measures them as boxes made by + /// [`Document::symbol_boxes`] do, without reading the symbol list again. + pub fn unmeasured(&self) -> SymbolBoxes<'a> { + let doc: &'a Document = self.doc; + let names = self.names.get_or_init(|| Arc::new(doc.symbol_names())); + doc.symbol_boxes().with_names(names) + } + /// Makes these boxes find symbols by `names` ([`Document::symbol_names`]), made from the /// document's symbols while they had the names and order they have now. pub(crate) fn with_names(self, names: &Arc) -> Self { @@ -749,6 +768,35 @@ mod tests { assert_eq!(read() - before, d.symbols.len()); } + #[test] + fn unmeasured_boxes_share_the_index_and_nothing_measured() { + // 2,000 symbols, then a 9-slice frame held, scaled, by "Holder", whose instances spend + // the boxes' budget of placed objects. + let mut d = Document::new(200.0, 200.0); + for i in 0..2000 { + let r = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0); + symbol(&mut d, &format!("Filler {i}"), vec![r]); + } + let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0); + symbol(&mut d, "Panel", vec![frame]); + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + let wide = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0)); + symbol(&mut d, "Holder", vec![wide]); + let holder = instance(&mut d, "Holder", Affine::scale_non_uniform(1.5, 1.5)); + let fresh = holder.visual_bounds_with(&d.symbol_boxes().quick()); + let read = || SYMBOLS_READ.with(Cell::get); + let s = d.symbol_boxes().quick(); + assert_eq!(holder.visual_bounds_with(&s), fresh); + assert!(s.sliced_placed.get() > 0); + let before = read(); + let u = s.unmeasured(); + assert_eq!(read(), before, "the index is shared"); + assert!(u.measured.borrow().is_empty() && u.sliced.borrow().is_empty() && u.reaches.borrow().is_empty()); + assert_eq!((u.sliced_placed.get(), u.holders.get(), u.quick.get()), (0, 0, false)); + assert_eq!(holder.visual_bounds_with(&u.quick()), fresh); + assert_eq!(read(), before); + } + #[test] fn measuring_9_slice_instances_reads_the_symbol_list_once() { // 2,000 symbols, then a frame with guides and a symbol with guides holding the frame diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index cd91a0bfbb..7e09d01aaa 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -96,6 +96,8 @@ proptest = { workspace = true } vectorcraft-text = { workspace = true, features = ["test-fonts"] } # How many times an open reads a PDF. vectorcraft-pdf = { workspace = true, features = ["read-count"] } +# How many times the symbol list is read to find symbols by name. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } wat = { workspace = true } # Zstandard streams for the Illustrator editing data fuzz tests. ruzstd = { workspace = true } diff --git a/crates/engine/src/cmd/fileio/export.rs b/crates/engine/src/cmd/fileio/export.rs index 9f767c7347..2fb2b63357 100644 --- a/crates/engine/src/cmd/fileio/export.rs +++ b/crates/engine/src/cmd/fileio/export.rs @@ -211,17 +211,11 @@ fn selected_part(n: &Arc, keep: &HashSet, holders: &HashSet Document { - fn kept( - n: &Arc, - painted_boxes: &SymbolBoxes, - symbols: &SymbolBoxes, - rect: vectorcraft_geom::Rect, - renderer: &mut vectorcraft_render::Renderer, - ) -> Option> { + fn kept(n: &Arc, symbols: &SymbolBoxes, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Option> { if matches!(n.kind, NodeKind::Layer { clip: false, .. }) { let mut layer = Node::clone(n); let children = layer.children_mut()?; - *children = children.iter().filter_map(|c| kept(c, painted_boxes, symbols, rect, renderer)).collect(); + *children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect(); return Some(Arc::new(layer)); } // A group that doesn't clip keeps only its members over the artboard, so art gathered in one @@ -230,20 +224,21 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: & if matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.appearance.effects.is_empty() { let mut group = Node::clone(n); let children = group.children_mut()?; - *children = children.iter().filter_map(|c| kept(c, painted_boxes, symbols, rect, renderer)).collect(); + *children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect(); return (!children.is_empty()).then(|| Arc::new(group)); } let over = |b: vectorcraft_geom::Rect| b.x0 <= rect.x1 && rect.x0 <= b.x1 && b.y0 <= rect.y1 && rect.y0 <= b.y1; let mut holds_instance = false; n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. })); - let painted = || holds_instance && vectorcraft_render::painted_bounds_with(painted_boxes, n).is_some_and(over); + // Measured in boxes of its own, which find symbols through the same index. + let painted = || holds_instance && vectorcraft_render::painted_bounds_with(&symbols.unmeasured(), n).is_some_and(over); let reach = vectorcraft_brush::reach_within(n); let brushed = |b: vectorcraft_geom::Rect| over(if reach > 0.0 { b.inflate(reach, reach) } else { b }); (n.visual_bounds_with(symbols).is_none_or(brushed) || renderer.effect_bounds(symbols, n).is_some_and(brushed) || painted()).then(|| n.clone()) } - let (painted_boxes, symbols) = (doc.symbol_boxes(), doc.symbol_boxes().with_brush_art()); + let symbols = doc.symbol_boxes().with_brush_art(); let mut d = doc.clone(); - d.layers = doc.layers.iter().filter_map(|l| kept(l, &painted_boxes, &symbols, rect, renderer)).collect(); + d.layers = doc.layers.iter().filter_map(|l| kept(l, &symbols, rect, renderer)).collect(); d } diff --git a/crates/engine/src/cmd/fileio/tests_svgenc.rs b/crates/engine/src/cmd/fileio/tests_svgenc.rs index 7884c1e86b..944f373474 100644 --- a/crates/engine/src/cmd/fileio/tests_svgenc.rs +++ b/crates/engine/src/cmd/fileio/tests_svgenc.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use serde_json::json; -use vectorcraft_doc::Document; +use vectorcraft_doc::{Document, Node, NodeKind}; use super::*; @@ -212,6 +212,44 @@ fn a_chosen_artboard_s_svg_keeps_nested_brush_art_but_not_unpainted_or_clipped_a assert!(kept.node(compounds[1]).is_some(), "a compound path that is brushed itself"); } +/// The art over an artboard, among 300 instances with drop shadows and 2,000 symbols, is found +/// reading the symbol list once, and keeps the instances over it. +#[test] +fn art_over_an_artboard_reads_the_symbol_list_once() { + let mut d = Document::new(100.0, 100.0); + let square = |d: &mut Document, side: f64| { + let r = vectorcraft_geom::Rect::new(-side, -side, side, side); + let ap = + vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0); + Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), ap)) + }; + for i in 0..2000 { + let art = square(&mut d, 0.5); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art }); + } + let art = square(&mut d, 2.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art }); + let layer = d.layers[0].id; + // Twenty rows of 15: the first ten over the artboard, the rest below it. + let ids: Vec<_> = (0..300) + .map(|i| { + let xf = vectorcraft_geom::Affine::translate((f64::from(i % 15) * 6.0 + 5.0, f64::from(i / 15) * 10.0 + 5.0)); + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + d.insert(Some(layer), usize::MAX, n).unwrap() + }) + .collect(); + let before = vectorcraft_doc::symbols_read(); + let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new()); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); + assert_eq!(ids.iter().filter(|id| kept.node(**id).is_some()).count(), 150); +} + /// #3544: an SVG of one artboard on its own (an `artboard` or `range`, Export for Screens, an asset) /// has the artboard's (or asset's) name as ``; Save's SVG and Export for Screens' Full /// Document keep the document's. diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index e960fd41e7..63055e1ba0 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -535,7 +535,8 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas: /// The walk of [`printed_type`]. struct Printed<'a> { d: &'a Document, - /// `d`'s symbols, found by name and measured once for the walk. + /// `d`'s symbols, found by name. Each object is measured in boxes of its own made from these + /// ([`vectorcraft_doc::SymbolBoxes::unmeasured`]). boxes: vectorcraft_doc::SymbolBoxes<'a>, /// Whether the walk is among the objects of the document, not in art drawn for one. own: bool, @@ -634,7 +635,7 @@ impl<'a> Printed<'a> { let clipped = match (clip, areas) { (false, _) => None, (true, Some(a)) => Some(self.clip(n, a)), - (true, None) => vectorcraft_render::painted_bounds_with(&self.boxes, n).map(|c| vec![c]), + (true, None) => vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n).map(|c| vec![c]), }; for c in children { self.node(c, clipped.as_deref().or(areas)); @@ -668,13 +669,13 @@ impl<'a> Printed<'a> { /// Whether what `n` paints, its effects applied, meets one of `areas`. fn meets(&self, n: &Node, areas: &[Rect]) -> bool { - vectorcraft_render::painted_bounds_with(&self.boxes, n) + vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n) .is_some_and(|b| areas.iter().any(|r| b.intersect(*r).area() > 0.0 || r.contains_rect(b))) } /// The parts of `areas` inside the bounds of clip group `n` (its clipping path's). fn clip(&self, n: &Node, areas: &[Rect]) -> Vec<Rect> { - let Some(c) = vectorcraft_render::painted_bounds_with(&self.boxes, n) else { return areas.to_vec() }; + let Some(c) = vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n) else { return areas.to_vec() }; areas.iter().filter(|r| c.intersect(**r).area() > 0.0 || r.contains_rect(c)).map(|r| r.intersect(c)).collect() } } @@ -2387,4 +2388,40 @@ mod dirty_tests { s.execute("edit.undo", &json!({})).unwrap(); assert!(!s.doc().unwrap().is_dirty(), "back to the saved state"); } + + /// The walk Print and the exports make over 300 instances with drop shadows, among 2,000 + /// symbols, reads the symbol list once to find their symbols. + #[test] + fn printed_type_reads_the_symbol_list_once() { + let mut d = Document::new(200.0, 200.0); + for i in 0..2000 { + let art = Node::path( + d.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), + vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 0.0), + ); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) }); + } + let art = Node::path( + d.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), + vectorcraft_doc::Appearance::basic(Paint::solid(vectorcraft_color::Color::BLACK), Paint::None, 0.0), + ); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(art) }); + let l = d.layers[0].id; + for i in 0..300 { + let xf = vectorcraft_geom::Affine::translate((f64::from(i % 20) * 10.0, f64::from(i / 20) * 10.0)); + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + d.insert(Some(l), usize::MAX, n).unwrap(); + } + let before = vectorcraft_doc::symbols_read(); + printed_type(&d, &d.layers, &[Rect::new(0.0, 0.0, 100.0, 100.0)]); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); + } } diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 8e90f83312..2a073ab62a 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -830,9 +830,8 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec<Node>, p let clip = look .clipping_mask .then(|| { - let symbols = doc.symbol_boxes(); let outlines = nodes.iter().filter_map(|n| { - let (bp, rule) = vectorcraft_render::drawn_outline_with(&symbols, n)?; + let (bp, rule) = vectorcraft_render::drawn_outline(doc, n)?; let mut p = Node::path(n.id, PathData::from_bezpath(&bp), Appearance::default()); if let NodeKind::Path { rule: r, .. } = &mut p.kind { *r = rule; diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index 817d334fb8..69bcf84f7f 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -54,6 +54,8 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] } serde_json = { workspace = true } # `draw_text`, to write test files with live text as other writers do. krilla = { workspace = true, features = ["simple-text"] } +# How many times the symbol list is read to find symbols by name. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } # An independent raster oracle for gradient placement in PDF forms. These are test-only macOS # bindings; the exporter stays portable Rust and does not depend on an OS PDF renderer. diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 434b321ff5..91c037ad84 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -256,6 +256,27 @@ fn instances_are_written_with_the_first_symbol_of_their_name() { assert!(fills.contains(&[255, 0, 0, 255]) && !fills.contains(&[0, 0, 255, 255]), "{fills:?}"); } +/// An export of 300 instances with drop shadows, among 2,000 symbols, reads the symbol list once +/// to find their symbols. +#[test] +fn an_export_reads_the_symbol_list_once() { + let mut d = marks("Other"); + for i in 0..300 { + let xf = Affine::translate((f64::from(i % 20) * 5.0, f64::from(i / 20) * 5.0)) * Affine::scale(0.2); + let mut n = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + add(&mut d, n); + } + let before = vectorcraft_doc::symbols_read(); + export(&d, &PdfOptions::default()).expect("export"); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); +} + #[test] fn an_instance_whose_brush_art_reaches_the_page_is_written() { // The symbol's art: a line from (0, 40) to (0, 60) with a 1 pt stroke painted by a 20 pt round diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 61569cc79e..9a4c095650 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -51,3 +51,5 @@ craft-tiff = { workspace = true } craft-psd = { workspace = true } proptest = { workspace = true } serde_json = { workspace = true } +# How many times the symbol list is read to find symbols by name. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } diff --git a/crates/render/src/addons/halftone.rs b/crates/render/src/addons/halftone.rs index 9b1cfe7091..a113e8fab8 100644 --- a/crates/render/src/addons/halftone.rs +++ b/crates/render/src/addons/halftone.rs @@ -57,7 +57,7 @@ pub fn sample(doc: &Document, nodes: Vec<Node>, region: Rect, scale: f64, mono: /// take too many cells: `n` then draws as it is. pub fn art(doc: &Document, n: &Node) -> Option<Node> { let ht = Halftone::of(n)?; - let found = Renderer::new().live_found(doc, &Arc::new(n.clone())); + let found = Renderer::new().live_found(&doc.symbol_boxes(), &Arc::new(n.clone())); let mut cache = CACHE.lock().unwrap_or_else(PoisonError::into_inner); if let Some(at) = cache.iter().position(|(node, was, _)| was.0 == found.0 && node == n) { let kept = cache.remove(at); diff --git a/crates/render/src/bounds.rs b/crates/render/src/bounds.rs index 06fd0af082..57ff859954 100644 --- a/crates/render/src/bounds.rs +++ b/crates/render/src/bounds.rs @@ -76,13 +76,7 @@ pub fn rasterize_stage(doc: &Document, n: &Node) -> Option<(Node, vectorcraft_ge /// The outline, with `n`'s geometry effects applied, that the canvas clips `n`'s Rasterize with /// Create Clipping Mask to. Object › Rasterize's clipping mask follows it. pub fn drawn_outline(doc: &Document, n: &Node) -> Option<(BezPath, FillRule)> { - drawn_outline_with(&doc.symbol_boxes(), n) -} - -/// [`drawn_outline`] with the symbols of instances found in `symbols` (made with -/// [`Document::symbol_boxes`]). -pub fn drawn_outline_with(symbols: &SymbolBoxes, n: &Node) -> Option<(BezPath, FillRule)> { - fx::drawn_outline(symbols, n) + fx::drawn_outline(&doc.symbol_boxes(), n) } /// The outlines a drag draws for `nodes` with Real-time Drawing off: one for each object in them, diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index f40a6ce905..d6a03d6d0f 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -542,7 +542,6 @@ impl Renderer { /// colors shaded through the color settings ([`reads_outside`]), is kept only while what it /// reads from outside `a` stays the same ([`Self::live_found`]). pub(super) fn fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>, cache: bool) -> Arc<Node> { - let doc = symbols.document(); let key = Arc::as_ptr(a) as usize; let mut kept = None; if cache @@ -554,7 +553,7 @@ impl Renderer { Some(was) => kept = Some((art.clone(), was.0)), } } - let found = (kept.is_some() || (cache && (evaluates_live(a) || reads_outside(a)))).then(|| self.live_found(doc, a)); + let found = (kept.is_some() || (cache && (evaluates_live(a) || reads_outside(a)))).then(|| self.live_found(symbols, a)); if let Some((art, was)) = kept && found.as_ref().is_some_and(|f| f.0 == was) { @@ -570,7 +569,7 @@ impl Renderer { Some((art, was)) => { let now = match &found { Some(f) => Some(f.0), - None => self.outside_key(doc, a), + None => self.outside_key(symbols, a), }; if was == now { art } else { self.make_fx_art(symbols, a) } } @@ -588,17 +587,16 @@ impl Renderer { /// drawn. What is measured but never drawn (culled, off the view) is let go, and isn't kept in /// place of what is drawn. pub(crate) fn measured_fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Arc<Node> { - let doc = symbols.document(); let key = Arc::as_ptr(a) as usize; if let Some((node, art, found)) = self.fx_arts.get(&key, self.stamp) && Arc::ptr_eq(node, a) { let (art, was) = (art.clone(), found.as_ref().map(|f| f.0)); - if was.is_none_or(|was| self.live_found(doc, a).0 == was) { + if was.is_none_or(|was| self.live_found(symbols, a).0 == was) { return art; } } - let now = self.outside_key(doc, a); + let now = self.outside_key(symbols, a); if let Some((node, art, was)) = self.measured.get(&key) && Arc::ptr_eq(node, a) && *was == now @@ -638,8 +636,8 @@ impl Renderer { /// The key of what `a`'s art reads from outside it ([`Self::live_found`]), `None` when it reads /// nothing. - fn outside_key(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Option<u64> { - (evaluates_live(a) || reads_outside(a)).then(|| self.live_found(doc, a).0) + fn outside_key(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Option<u64> { + (evaluates_live(a) || reads_outside(a)).then(|| self.live_found(symbols, a).0) } /// The art [`Self::fx_art`] draws for `a`, made now. diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 02142f118b..4671aa2096 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -278,9 +278,7 @@ mod renderer; mod text_geom; mod threads; -pub use bounds::{ - drawn_bounds, drawn_outline, drawn_outline_with, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage, -}; +pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage}; pub use frame::FrameStats; use frame::{ ClipEntry, ClipPaintEntry, Frame, FxArtEntry, GeomEntry, PlacedEntry, PlacedKey, PtrHasher, PtrMap, SliceEntry, StrokeEntry, StrokeKey, diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index 3777c98948..71cfd6fc94 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -21,7 +21,7 @@ use std::sync::{Arc, Weak}; use vectorcraft_doc::live::{GradientMesh, MeshQuad}; use vectorcraft_doc::placed_document::ReadDocument; -use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_doc::{Document, Node, NodeKind, SymbolBoxes}; use vectorcraft_geom::{Affine, BezPath, Point, Vec2}; use vello_cpu::RenderContext; use vello_cpu::peniko; @@ -109,10 +109,11 @@ pub fn expand_live(n: &Node) -> Vec<Node> { /// their address). Art is hashed by the addresses of its `Arc`s, which copies of the document /// share: a copy of the document has the same key. It also returns weak references to the reads /// found, and what the walk found ([`Walked`]) when it found no placed file and no such image. -fn resources_key(doc: &Document, cms: usize, names: u64, n: &Node) -> (u64, Vec<Weak<ReadDocument>>, Option<Walked>) { +/// Symbols are found by name in `symbols`. +fn resources_key(symbols: &SymbolBoxes, cms: usize, names: u64, n: &Node) -> (u64, Vec<Weak<ReadDocument>>, Option<Walked>) { let mut h = DefaultHasher::new(); let mut shown = Shown::default(); - hash_resources(doc, n, &mut shown, &mut h); + hash_resources(symbols, n, &mut shown, &mut h); let walked = Walked { hash: h.finish(), text: shown.text, plugins: shown.plugins }; (walked.key(cms, names), shown.reads, (!shown.placed && !shown.pixels).then_some(walked)) } @@ -175,8 +176,9 @@ struct Shown { /// own fills or strokes follow them ([`crate::effects::follows_image_pixels`]). It walks `n` and /// then, one at a time from a list, the opacity-mask, pattern and symbol art it finds, each pattern /// and each symbol's art once ([`first_seen`]). `shown` records the type, placed files, reads, -/// such images and plug-in effects found. -fn hash_resources<'a>(doc: &'a Document, n: &'a Node, shown: &mut Shown, h: &mut DefaultHasher) { +/// such images and plug-in effects found. Symbols are found by name in `symbols`. +fn hash_resources<'a>(symbols: &SymbolBoxes<'a>, n: &'a Node, shown: &mut Shown, h: &mut DefaultHasher) { + let doc = symbols.document(); let mut todo = vec![]; let mut next = Some(n); while let Some(art) = next { @@ -198,7 +200,7 @@ fn hash_resources<'a>(doc: &'a Document, n: &'a Node, shown: &mut Shown, h: &mut } match &c.kind { NodeKind::SymbolInstance { symbol, .. } => { - if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) { + if let Some(s) = symbols.symbol(symbol) { (Arc::as_ptr(&s.art) as usize).hash(h); if first_seen(&mut shown.seen, Arc::as_ptr(&s.art) as usize) { todo.push(&s.art); @@ -453,14 +455,14 @@ fn spread_to_edges(px: &mut [vello_cpu::color::PremulRgba8], filled: Vec<bool>, } impl Renderer { - /// The [`resources_key`] of `n` in `doc`, with the frame's [`DocInputs`] ([`Found`]): `n` is a - /// live node, or an object with effects whose art ([`Renderer::fx_art`]) can be made from - /// evaluated live objects, type, symbol art or colors shaded through the color settings. The - /// key is made from the [`Walk`] kept for `n` while `doc`'s symbols and patterns are those it - /// read; `n` is walked again when they changed, and in every frame when the walk found a - /// placed file or an image whose own fills or strokes follow its pixels. - pub(crate) fn live_found(&mut self, doc: &Document, n: &Arc<Node>) -> Found { - let inputs = self.doc_inputs(doc); + /// The [`resources_key`] of `n` in the document of `symbols`, with the frame's [`DocInputs`] + /// ([`Found`]): `n` is a live node, or an object with effects whose art ([`Renderer::fx_art`]) + /// can be made from evaluated live objects, type, symbol art or colors shaded through the color + /// settings. The key is made from the [`Walk`] kept for `n` while the document's symbols and + /// patterns are those it read; `n` is walked again when they changed, and in every frame when + /// the walk found a placed file or an image whose own fills or strokes follow its pixels. + pub(crate) fn live_found(&mut self, symbols: &SymbolBoxes, n: &Arc<Node>) -> Found { + let inputs = self.doc_inputs(symbols.document()); let at = Arc::as_ptr(n) as usize; if let Some((node, walked, read)) = self.live.walks.get(&at, self.stamp) && std::ptr::eq(node.as_ptr(), Arc::as_ptr(n)) @@ -472,7 +474,7 @@ impl Renderer { { self.live.walked += 1; } - let (key, reads, walked) = resources_key(doc, inputs.cms, inputs.names, n); + let (key, reads, walked) = resources_key(symbols, inputs.cms, inputs.names, n); if let Some(walked) = walked { // The bytes count the key and the entry, and the node's allocation that the weak // reference keeps. @@ -482,11 +484,12 @@ impl Renderer { (key, inputs, reads) } - fn live_expanded(&mut self, doc: &Document, a: &Arc<Node>, cache: bool) -> Expanded { + fn live_expanded(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>, cache: bool) -> Expanded { + let doc = symbols.document(); let key = Arc::as_ptr(a) as usize; // An evaluation the cache does not keep is made without the key, so the copy that // `draw_live_node` makes is not walked. - let resources = cache.then(|| self.live_found(doc, a)); + let resources = cache.then(|| self.live_found(symbols, a)); if let Some(resources) = &resources && let Some(e) = self.live.expanded.get(&key, self.stamp) && Arc::ptr_eq(&e.0, a) @@ -541,7 +544,7 @@ impl Renderer { let knockout = !f.opts.outline && matches!(a.kind, NodeKind::Blend { .. }) && a.knockout.resolve(self.knockout) - && vectorcraft_doc::live::steps_knockout_shows(&self.live_expanded(f.doc, a, true)); + && vectorcraft_doc::live::steps_knockout_shows(&self.live_expanded(f.symbols, a, true)); let enclosing = std::mem::replace(&mut self.knockout, knockout); if !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_color::BlendMode::Normal || a.isolate || knockout) { let blends = self.blends_through(a); @@ -566,7 +569,7 @@ impl Renderer { | NodeKind::Intertwine { .. } | NodeKind::Group { .. } | NodeKind::Layer { .. } => { - let items = self.live_expanded(f.doc, a, cache); + let items = self.live_expanded(f.symbols, a, cache); // An evaluation the cache did not keep is made again in the next frame. let kept = cache && self.live.expanded.get(&(Arc::as_ptr(a) as usize), self.stamp).is_some_and(|e| Arc::ptr_eq(&e.1, &items)); let outer = self.made_again; @@ -809,7 +812,12 @@ mod tests { let envelope = Node::new(d.alloc_id(), envelope); let key = |d: &Document| { std::thread::scope(|s| { - std::thread::Builder::new().stack_size(256 << 10).spawn_scoped(s, || resources_key(d, 0, 0, &envelope).0).unwrap().join().unwrap() + std::thread::Builder::new() + .stack_size(256 << 10) + .spawn_scoped(s, || resources_key(&d.symbol_boxes(), 0, 0, &envelope).0) + .unwrap() + .join() + .unwrap() }) }; let before = key(&d); @@ -841,8 +849,8 @@ mod tests { frame: Box::new(Affine::IDENTITY), }; let envelope = Node::new(d.alloc_id(), envelope); - let before = resources_key(&d, 0, 0, &envelope).0; + let before = resources_key(&d.symbol_boxes(), 0, 0, &envelope).0; d.symbols[2].art = y.clone(); - assert_ne!(resources_key(&d, 0, 0, &envelope).0, before, "the art of every instance is hashed"); + assert_ne!(resources_key(&d.symbol_boxes(), 0, 0, &envelope).0, before, "the art of every instance is hashed"); } } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 2163b58ef8..3c73980b81 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -349,6 +349,40 @@ fn instances_draw_the_first_symbol_of_their_name() { assert!(img.pixels == render(&marks("Other")).pixels, "the pixels differ"); } +/// A frame that draws 300 instances with drop shadows, among 2,000 symbols, and an envelope around +/// instances reads the symbol list once to find their symbols. +#[test] +fn a_frame_reads_the_symbol_list_once() { + let mut d = marks("Other"); + let l = d.layers[0].id; + for i in 0..300 { + let xf = Affine::translate((f64::from(i % 20) * 5.0, f64::from(i / 20) * 5.0)) * Affine::scale(0.2); + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + d.insert(Some(l), usize::MAX, n).unwrap(); + } + let content = Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((50.0, 50.0)) })); + let kind = vectorcraft_doc::live::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; + let envelope = NodeKind::Envelope { + content: vec![content], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: Default::default(), + frame: Box::new(Affine::IDENTITY), + }; + let envelope = Node::new(d.alloc_id(), envelope); + d.insert(Some(l), usize::MAX, envelope).unwrap(); + let before = vectorcraft_doc::symbols_read(); + render(&d); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); +} + /// Symbols 0 to 29 each hold two instances of the next, sheared two ways, so that the 2^30 /// instances drawn from the first are all placed differently. Symbol 30 holds a square with a drop /// shadow. An instance of symbol 0 lies far left of the view. With `effect`, every instance has diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 3ebda15d43..486916fd3e 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -46,3 +46,5 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] } craft-svg = { workspace = true, features = ["tree-render", "tree-text"] } vectorcraft-testkit = { workspace = true } proptest = { workspace = true } +# How many times the symbol list is read to find symbols by name. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index f941f0fccd..6427d048bd 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -2,8 +2,8 @@ use super::output::{sanitize_id, valid_xml_value, xml_attr_escape, xml_attr_vali use super::paint::{StrokePlan, has_raster, pixel_gradient}; use super::text::OUTLINE_TOLERANCE; use super::{ - Affine, AppearanceItem, BezPath, BlendMode, FillRule, HashMap, Node, NodeKind, Paint, PathData, Props, Rect, StrokeAlign, StrokeLayer, Writer, - Written, WrittenShape, blend_css, css, fmt_num, stroke, xml_escape, + Affine, AppearanceItem, BezPath, BlendMode, Document, FillRule, HashMap, Node, NodeKind, Paint, PathData, Props, Rect, StrokeAlign, StrokeLayer, + Writer, Written, WrittenShape, blend_css, css, fmt_num, stroke, xml_escape, }; /// A symbol's `<symbol>` def and the instance transforms that can `<use>` it. @@ -51,16 +51,16 @@ fn export_shape_bounds(n: &Node) -> Option<Rect> { impl Reuse { const NONE: Self = Self { moves: false, turns: false, scales: false }; - /// What a def of symbol art `art` stands for, the symbols it holds instances of found in - /// `symbols`. - pub(crate) fn of(symbols: &vectorcraft_doc::SymbolBoxes, art: &Node) -> Self { + /// What a def of symbol art `art` stands for, in `doc`. `find` finds the symbol of each + /// instance in it by name. + pub(crate) fn of<'d>(doc: &'d Document, find: &dyn Fn(&str) -> Option<&'d vectorcraft_doc::Symbol>, art: &Node) -> Self { let mut r = Self { moves: true, turns: true, scales: true }; - r.scan(symbols, art, 0); + r.scan(doc, find, art, 0); r } /// Narrow down to what `n` (inside symbols nested `depth` deep) allows. - fn scan(&mut self, symbols: &vectorcraft_doc::SymbolBoxes, n: &Node, depth: u32) { + fn scan<'d>(&mut self, doc: &'d Document, find: &dyn Fn(&str) -> Option<&'d vectorcraft_doc::Symbol>, n: &Node, depth: u32) { let pattern = |p: &Paint| matches!(p, Paint::Pattern { .. }); let text_patterns = matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| pattern(&r.style.fill) || pattern(&r.style.stroke))); let unlinked_mask = n.extras().mask.as_ref().is_some_and(|m| !m.linked); @@ -93,20 +93,20 @@ impl Reuse { NodeKind::SymbolInstance { symbol, .. } => { // A scale reaching an instance of a symbol with 9-slice guides changes how its // cells are sized. - if symbols.document().symbol_nine_slice(symbol).is_some() { + if doc.symbol_nine_slice(symbol).is_some() { self.scales = false; } - if let Some(s) = symbols.symbol(symbol) { - self.scan(symbols, &s.art, depth + 1); + if let Some(s) = find(symbol) { + self.scan(doc, find, &s.art, depth + 1); } } _ => {} } if let Some(m) = &n.extras().mask { - self.scan(symbols, &m.art, depth); + self.scan(doc, find, &m.art, depth); } for c in n.children().into_iter().flatten() { - self.scan(symbols, c, depth); + self.scan(doc, find, c, depth); } } @@ -519,7 +519,7 @@ impl Writer<'_> { /// its geometry, so the region also covers the geometry's box, placed, grown by the strokes' /// and effects' reach unscaled. fn region_attrs(&mut self, nodes: &[&Node]) -> String { - let symbols = self.region_boxes.take().unwrap_or_else(|| self.doc.symbol_boxes()); + let symbols = self.region_boxes.take().unwrap_or_else(|| self.symbol_lookup.unmeasured()); let mut art_reach = std::mem::take(&mut self.art_reach); let region = self.region_of(&symbols, &mut art_reach, nodes); self.region_boxes = Some(symbols); @@ -529,7 +529,7 @@ impl Writer<'_> { /// The box of what each of `nodes` paints, as [`Self::paint_box`] measures it. fn paint_boxes(&mut self, nodes: &[&Node]) -> Vec<Option<Option<Rect>>> { - let symbols = self.region_boxes.take().unwrap_or_else(|| self.doc.symbol_boxes()); + let symbols = self.region_boxes.take().unwrap_or_else(|| self.symbol_lookup.unmeasured()); let mut art_reach = std::mem::take(&mut self.art_reach); let boxes = nodes.iter().map(|n| self.paint_box(&symbols, &mut art_reach, n)).collect(); self.region_boxes = Some(symbols); @@ -1114,7 +1114,8 @@ impl Writer<'_> { return None; } if !self.symbols.contains_key(&sym.name) { - let reuse = Reuse::of(&self.symbol_lookup, &sym.art); + let lookup = &self.symbol_lookup; + let reuse = Reuse::of(self.doc, &|name| lookup.symbol(name), &sym.art); self.symbols.insert(sym.name.clone(), SymbolDef { id: None, reuse, nodes: 0 }); } let def = self.symbols.get(&sym.name)?; diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index 234783d029..57e0a6caf4 100644 --- a/crates/svg/src/export/paint.rs +++ b/crates/svg/src/export/paint.rs @@ -680,7 +680,7 @@ impl Writer<'_> { } return 0; } - let bounds = n.visual_bounds_with(&self.doc.symbol_boxes()); + let bounds = n.visual_bounds_with(&self.symbol_lookup.unmeasured()); // An Outer Glow's silhouette grows by a quarter of a pixel of the document's raster grid first. let grow = 18.0 / self.doc.raster_ppi(); let reach: f64 = @@ -705,7 +705,7 @@ impl Writer<'_> { // object's geometry turned into it, grown by what its strokes and other paint add // around it in the document: a square that far to each side, as it measures in // user space along each axis (a miter corner reaches that far along both). - let symbols = self.doc.symbol_boxes(); + let symbols = self.symbol_lookup.unmeasured(); let visual = input.visual_bounds_with(&symbols).unwrap_or_default(); let user_box = if sf.moves_only() { visual - sf.origin() diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 6348b6e141..aaeac31a11 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -202,7 +202,7 @@ pub(crate) fn import_finding( hidden: found.hidden, uses: found.uses, symbols: HashMap::new(), - symbol_names: HashSet::new(), + symbol_names: HashMap::new(), symbol_suffixes: HashMap::new(), pattern_suffixes: HashMap::new(), blends: fx::blends(&xml, &scan.markers), @@ -360,8 +360,8 @@ struct Importer { uses: HashMap<String, String>, /// The symbols made so far, by `<symbol>` id. symbols: HashMap<String, SymbolMade>, - /// The names of the symbols made so far. - symbol_names: HashSet<String>, + /// The names of the symbols made so far, each with its index in the document's symbols. + symbol_names: HashMap<String, usize>, /// Where the suffixes of each symbol and pattern name base go on from (`unique_name`). symbol_suffixes: HashMap<String, usize>, pattern_suffixes: HashMap<String, usize>, diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 42f3565efe..c1dd856559 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -207,9 +207,11 @@ impl Importer { None => { let base = self.name_of(&sym).to_string(); let names = &self.symbol_names; - let name = unique_name(&base, &mut self.symbol_suffixes, |n| names.contains(n)); - self.symbol_names.insert(name.clone()); - let reuse = Reuse::of(&self.doc.symbol_boxes(), &art); + let name = unique_name(&base, &mut self.symbol_suffixes, |n| names.contains_key(n)); + let doc = &self.doc; + let find = |n: &str| names.get(n).and_then(|&i| doc.symbols.get(i)).filter(|s| s.name == n); + let reuse = Reuse::of(doc, &find, &art); + self.symbol_names.insert(name.clone(), self.doc.symbols.len()); let made = SymbolMade { name: name.clone(), art: without_ids(&art), reuse }; self.doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.clone(), art: Arc::new(art) }); self.symbols.insert(sym, made); @@ -862,7 +864,7 @@ mod tests { hidden: HashSet::new(), uses: HashMap::new(), symbols: HashMap::new(), - symbol_names: HashSet::new(), + symbol_names: HashMap::new(), symbol_suffixes: HashMap::new(), pattern_suffixes: HashMap::new(), blends: HashMap::new(), diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index fd84b58a22..1d1b4cc712 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -105,6 +105,28 @@ fn instances_are_written_with_the_first_symbol_of_their_name() { assert!(svg.contains("#ff0000") && !svg.contains("#0000ff"), "{svg}"); } +/// An export of 300 instances with drop shadows, among 2,000 symbols, reads the symbol list once +/// to find their symbols. +#[test] +fn an_export_reads_the_symbol_list_once() { + let mut d = marks("Other"); + for i in 0..300 { + let xf = Affine::translate((f64::from(i % 20) * 10.0, f64::from(i / 20) * 8.0)) * Affine::scale(0.2); + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, n).unwrap(); + } + let before = vectorcraft_doc::symbols_read(); + export(&d, &ExportOptions::default()); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); +} + /// A scaled instance of a symbol with 9-slice guides is written as the canvas draws it, with no /// `<use>`: at 200 × 150 its 10 × 10 corner square stays 10 × 10 and its center square becomes /// 30 × 20. An instance at the natural size still uses the def.