From 52b4b039204874aafd2d3f2a1a24960da8ad962a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 07:09:32 -0800 Subject: [PATCH 1/2] Symbols: render and SVG/PDF export find each instance's symbol in one index MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drawing or exporting a symbol instance looked its symbol up by scanning the document's symbol list, so a document with many instances and many symbols spent most of a frame or an export on name comparisons. The renderer, the SVG and PDF writers and the export walks now find symbols through SymbolBoxes::symbol, which builds the name index once per frame, export or walk and returns the first symbol of a name as before. - Renderer: plain instances, inline graphics, instances with object effects (their art and the symbol budget) and the effect bounds. - SVG export: instance art, symbol defs and their reuse check, and the paint reach of filter regions. - PDF export: instance art, inline graphics and the brush search of knockout masks. - Export warnings and artboard crops measured what each object paints with new symbol boxes per object, which built the name index again for every instance. painted_bounds_with and drawn_outline_with take the boxes once; Object › Rasterize's clipping mask uses them too. --- crates/doc/src/symbols.rs | 39 ++++++++++++++++++++++---- crates/engine/src/cmd/fileio/export.rs | 12 ++++---- crates/engine/src/cmd/fonts.rs | 27 ++++++++++++------ crates/engine/src/cmd/menucmds.rs | 3 +- crates/pdf/src/export/nodes.rs | 33 ++++++++++++---------- crates/pdf/src/export/text.rs | 2 +- crates/pdf/src/tests.rs | 33 ++++++++++++++++++++++ crates/render/src/bounds.rs | 16 +++++++++-- crates/render/src/fx/bounds.rs | 24 ++++++++-------- crates/render/src/fx/renderer.rs | 27 +++++++++--------- crates/render/src/fx/tests.rs | 8 +++--- crates/render/src/lib.rs | 4 ++- crates/render/src/renderer/nodes.rs | 4 +-- crates/render/src/renderer/text.rs | 4 +-- crates/render/src/tests.rs | 36 ++++++++++++++++++++++++ crates/render/src/tests/objectfx.rs | 5 ++-- crates/svg/src/export.rs | 4 +++ crates/svg/src/export/nodes.rs | 31 ++++++++++---------- crates/svg/src/import/importer.rs | 2 +- crates/svg/tests/it/symbols_layers.rs | 36 ++++++++++++++++++++++++ 20 files changed, 257 insertions(+), 93 deletions(-) diff --git a/crates/doc/src/symbols.rs b/crates/doc/src/symbols.rs index 99a65ae1f7..a3c864118a 100644 --- a/crates/doc/src/symbols.rs +++ b/crates/doc/src/symbols.rs @@ -9,7 +9,7 @@ use std::sync::Arc; use vectorcraft_geom::{Affine, Rect}; use crate::symbol_nine_slice::transformed; -use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF}; +use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF, Symbol}; /// The box a symbol instance is measured by when its symbol's art has no box /// ([`SymbolBoxes::art`]), and in [`Node::geometric_bounds`]: the 20 × 20 square around the origin @@ -163,19 +163,24 @@ impl<'a> SymbolBoxes<'a> { self } - /// The art of the first symbol of the document named `name`, found in time independent of the - /// number of symbols after the first lookup. - pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc> { + /// The first symbol of the document named `name`, found in time independent of the number of + /// symbols after the first lookup. + pub fn symbol(&self, name: &str) -> Option<&'a Symbol> { let doc: &'a Document = self.doc; let names = self.names.get_or_init(|| Arc::new(doc.symbol_names())); let i = *names.get(name)?; match doc.symbols.get(i) { - Some(s) if s.name == name => Some(&s.art), + Some(s) if s.name == name => Some(s), // Names that no longer match the symbols: the first symbol of that name. - _ => doc.symbols.iter().find(|s| s.name == name).map(|s| &s.art), + _ => doc.symbols.iter().find(|s| s.name == name), } } + /// The art of the first symbol of the document named `name` ([`Self::symbol`]). + pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc> { + self.symbol(name).map(|s| &s.art) + } + /// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its /// art box alone. An instance that scales or turns stroked art then measures a little larger /// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The @@ -722,6 +727,28 @@ mod tests { assert_eq!(s.sliced_placed.get(), 13); } + #[test] + fn symbols_are_found_by_name_reading_the_list_once() { + // 2,000 symbols, then two named "Mark": a name finds the first. + 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 (first, second) = (rect(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0), 0.0), rect(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0), 0.0)); + symbol(&mut d, "Mark", vec![first]); + symbol(&mut d, "Mark", vec![second]); + let read = || SYMBOLS_READ.with(Cell::get); + let before = read(); + let s = d.symbol_boxes(); + for _ in 0..1000 { + assert!(s.symbol("Mark").is_some_and(|m| std::ptr::eq(m, &d.symbols[2000]))); + assert!(s.symbol("Filler 7").is_some_and(|m| std::ptr::eq(m, &d.symbols[7]))); + assert!(s.symbol("Nowhere").is_none()); + } + assert_eq!(read() - before, d.symbols.len()); + } + #[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/src/cmd/fileio/export.rs b/crates/engine/src/cmd/fileio/export.rs index 1e27778aac..9f767c7347 100644 --- a/crates/engine/src/cmd/fileio/export.rs +++ b/crates/engine/src/cmd/fileio/export.rs @@ -213,7 +213,7 @@ fn selected_part(n: &Arc, keep: &HashSet, holders: &HashSet Document { fn kept( n: &Arc, - doc: &Document, + painted_boxes: &SymbolBoxes, symbols: &SymbolBoxes, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer, @@ -221,7 +221,7 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: & 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, doc, symbols, rect, renderer)).collect(); + *children = children.iter().filter_map(|c| kept(c, painted_boxes, 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 +230,20 @@ 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, doc, symbols, rect, renderer)).collect(); + *children = children.iter().filter_map(|c| kept(c, painted_boxes, 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(doc, n).is_some_and(over); + let painted = || holds_instance && vectorcraft_render::painted_bounds_with(painted_boxes, 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 symbols = doc.symbol_boxes().with_brush_art(); + let (painted_boxes, symbols) = (doc.symbol_boxes(), doc.symbol_boxes().with_brush_art()); let mut d = doc.clone(); - d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect, renderer)).collect(); + d.layers = doc.layers.iter().filter_map(|l| kept(l, &painted_boxes, &symbols, rect, renderer)).collect(); d } diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 5a000c3327..e960fd41e7 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -247,10 +247,11 @@ impl Resources { fn expand(&mut self, d: &Document) { let mut symbols: Vec = self.symbols.iter().cloned().collect(); let mut patterns: Vec = self.patterns.iter().cloned().collect(); + let boxes = d.symbol_boxes(); while !symbols.is_empty() || !patterns.is_empty() { let mut more = Resources::default(); for name in symbols.drain(..) { - if let Some(sym) = d.symbols.iter().find(|sym| sym.name == name) { + if let Some(sym) = boxes.symbol(&name) { more.add(&sym.art); } } @@ -511,7 +512,7 @@ pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet { /// art of a placed document (`d` as [`Document::with_placed_art`] gives it, for that art's /// resources). pub(super) fn printed_type(d: &Document, layers: &[Arc], areas: &[Rect]) -> (BTreeSet, BTreeSet) { - let mut walk = Printed { d, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }; + let mut walk = Printed::new(d); for l in layers { walk.node(l, Some(areas)); } @@ -523,7 +524,7 @@ pub(super) fn printed_type(d: &Document, layers: &[Arc], areas: &[Rect]) - /// found as [`printed_type`] finds them for Print: visible objects of the document that aren't on /// a template layer. pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc], areas: Option<&[Rect]>) -> Option { - let mut walk = Printed { d, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }; + let mut walk = Printed::new(d); for l in layers { walk.node(l, areas); } @@ -534,6 +535,8 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc], areas: /// The walk of [`printed_type`]. struct Printed<'a> { d: &'a Document, + /// `d`'s symbols, found by name and measured once for the walk. + boxes: vectorcraft_doc::SymbolBoxes<'a>, /// Whether the walk is among the objects of the document, not in art drawn for one. own: bool, fonts: BTreeSet, @@ -544,7 +547,13 @@ struct Printed<'a> { patterns: BTreeSet, } -impl Printed<'_> { +impl<'a> Printed<'a> { + /// A walk of `d` among its own objects, nothing found yet. + fn new(d: &'a Document) -> Self { + let boxes = d.symbol_boxes(); + Self { d, boxes, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() } + } + /// Adds the fonts of `n` and its descendants that print, and the ids of those that don't fit /// while [`Printed::own`] is set: those whose bounds meet one of `areas`, or with `None` (in the /// art of a symbol, opacity mask, pattern or placed document, in brush pieces, or in a live @@ -625,7 +634,7 @@ impl Printed<'_> { let clipped = match (clip, areas) { (false, _) => None, (true, Some(a)) => Some(self.clip(n, a)), - (true, None) => vectorcraft_render::painted_bounds(self.d, n).map(|c| vec![c]), + (true, None) => vectorcraft_render::painted_bounds_with(&self.boxes, n).map(|c| vec![c]), }; for c in children { self.node(c, clipped.as_deref().or(areas)); @@ -641,9 +650,8 @@ impl Printed<'_> { /// Adds the fonts of symbol `name`'s art, the first time it is shown. fn symbol(&mut self, name: &str) { - let d = self.d; if self.symbols.insert(name.to_string()) - && let Some(s) = d.symbols.iter().find(|s| s.name == name) + && let Some(s) = self.boxes.symbol(name) { self.art(&s.art); } @@ -660,12 +668,13 @@ impl Printed<'_> { /// Whether what `n` paints, its effects applied, meets one of `areas`. fn meets(&self, n: &Node, areas: &[Rect]) -> bool { - vectorcraft_render::painted_bounds(self.d, n).is_some_and(|b| areas.iter().any(|r| b.intersect(*r).area() > 0.0 || r.contains_rect(b))) + vectorcraft_render::painted_bounds_with(&self.boxes, 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 { - let Some(c) = vectorcraft_render::painted_bounds(self.d, n) else { return areas.to_vec() }; + let Some(c) = vectorcraft_render::painted_bounds_with(&self.boxes, 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() } } diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 2a073ab62a..8e90f83312 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -830,8 +830,9 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, 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(doc, n)?; + let (bp, rule) = vectorcraft_render::drawn_outline_with(&symbols, 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/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 71b65e65d0..ffcfaf1440 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -117,7 +117,7 @@ impl Exporter<'_> { if several && !elements.iter().skip(1).all(|(c, _)| shape_is_coverage(c)) { let doc = self.doc; let brushes = self.brushes.get_or_insert_with(|| vectorcraft_brush::library(doc)); - match knockout_masks(BrushSearch::new(doc, brushes), &elements) { + match knockout_masks(BrushSearch::new(&self.symbols, brushes), &elements) { Ok(above) => { // Every mask is made before anything is drawn: when the symbol objects the // masks may hold run out, one would leave out art its element covers, and @@ -451,7 +451,7 @@ impl Exporter<'_> { // A dynamic symbol's instance shows its own appearance changes, and the instance's // fill stains its art, as on the canvas. let doc = self.doc; - if let Some(sym) = doc.symbols.iter().find(|x| &x.name == symbol) { + if let Some(sym) = self.symbols.symbol(symbol) { let changed; let art: &Node = if n.extras().symbol_overrides.is_empty() && vectorcraft_doc::symbol_overrides::stain(n).is_none() { &sym.art @@ -953,8 +953,10 @@ enum SharedArt { /// A search for the brushed strokes drawing an object draws, whose brush art can hold many more /// objects than the stroked path. -struct BrushSearch<'a> { - doc: &'a Document, +struct BrushSearch<'a, 'd> { + doc: &'d Document, + /// `doc`'s symbols, found by name. + symbols: &'a vectorcraft_doc::SymbolBoxes<'d>, /// The brushes the export draws strokes with ([`Exporter::brush_art`]); a stroke whose brush /// is not among them is drawn as a plain stroke. brushes: &'a [vectorcraft_brush::Brush], @@ -968,9 +970,10 @@ struct BrushSearch<'a> { exhausted: bool, } -impl<'a> BrushSearch<'a> { - fn new(doc: &'a Document, brushes: &'a [vectorcraft_brush::Brush]) -> Self { - Self { doc, brushes, seen: HashMap::new(), left: MAX_KNOCKOUT_MASK_OBJECTS, exhausted: false } +impl<'a, 'd> BrushSearch<'a, 'd> { + /// A search through the document of `symbols`. + fn new(symbols: &'a vectorcraft_doc::SymbolBoxes<'d>, brushes: &'a [vectorcraft_brush::Brush]) -> Self { + Self { doc: symbols.document(), symbols, brushes, seen: HashMap::new(), left: MAX_KNOCKOUT_MASK_OBJECTS, exhausted: false } } /// Takes `n` objects from [`Self::left`]; false, and the search exhausted, when fewer are left. @@ -1031,8 +1034,7 @@ impl<'a> BrushSearch<'a> { NodeKind::SymbolInstance { symbol, .. } => { // A dynamic symbol's instance draws its art with its own appearance changes: the // art is copied once for each set of changes, counted before it is copied. - let doc = self.doc; - match doc.symbols.iter().find(|s| &s.name == symbol) { + match self.symbols.symbol(symbol) { Some(s) if !n.extras().symbol_overrides.is_empty() => { let key = format!("{symbol}\u{0}{:?}", n.extras().symbol_overrides); self.shared(SharedArt::Dynamic, &key, |search| { @@ -1065,8 +1067,7 @@ impl<'a> BrushSearch<'a> { /// Whether the art of the symbol named `name` draws a brushed stroke. fn symbol(&mut self, name: &str, depth: usize) -> bool { - let doc = self.doc; - let Some(s) = doc.symbols.iter().find(|s| s.name == name) else { return false }; + let Some(s) = self.symbols.symbol(name) else { return false }; self.shared(SharedArt::Symbol, name, |search| search.node(&s.art, true, depth)) } @@ -1162,7 +1163,8 @@ mod tests { let square = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::None, 0.0)); let art = Node::group(NodeId(0), vec![Arc::new(square), Arc::new(instance())]); d.symbols.push(Symbol { dynamic: true, name: "Loop".into(), art: Arc::new(art) }); - let mut search = BrushSearch::new(&d, &[]); + let symbols = d.symbol_boxes(); + let mut search = BrushSearch::new(&symbols, &[]); assert!(!search.node(&instance(), true, 0)); assert!(!search.exhausted); assert!(MAX_KNOCKOUT_MASK_OBJECTS - search.left < 10, "{} objects", MAX_KNOCKOUT_MASK_OBJECTS - search.left); @@ -1190,11 +1192,12 @@ mod tests { .collect(); Node::group(NodeId(0), instances) }; - let mut search = BrushSearch::new(&d, &[]); + let symbols = d.symbol_boxes(); + let mut search = BrushSearch::new(&symbols, &[]); assert!(search.node(&group(true), true, 0)); assert!(search.exhausted); assert_eq!(search.left, 0); - let mut search = BrushSearch::new(&d, &[]); + let mut search = BrushSearch::new(&symbols, &[]); assert!(!search.node(&group(false), true, 0)); assert!(!search.exhausted); // The group, the 1,000 instances, and one copy of the art counted and looked through. @@ -1232,6 +1235,6 @@ mod tests { vectorcraft_doc::placed_document::prime(&placed, Arc::new(vec![]), brushed_art()); let n = Node::new(NodeId(0), NodeKind::PlacedDocument(Box::new(placed))); let brushes = vectorcraft_brush::library(&d); - assert!(BrushSearch::new(&d, &brushes).node(&n, true, 0)); + assert!(BrushSearch::new(&d.symbol_boxes(), &brushes).node(&n, true, 0)); } } diff --git a/crates/pdf/src/export/text.rs b/crates/pdf/src/export/text.rs index ea29167f1b..4350e0c7ae 100644 --- a/crates/pdf/src/export/text.rs +++ b/crates/pdf/src/export/text.rs @@ -134,7 +134,7 @@ impl Exporter<'_> { self.inline_depth += 1; for ig in &layout.inlines { let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue }; - let Some(sym) = doc.symbols.iter().find(|x| x.name == art.symbol) else { continue }; + let Some(sym) = self.symbols.symbol(&art.symbol) else { continue }; let mut node = (*sym.art).clone(); // Strokes scale with the art, as on the canvas. node.transform(t.xf * ig.xf * doc.symbol_natural_xf(&art.symbol), true); diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 2337cc8dee..434b321ff5 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -223,6 +223,39 @@ fn an_instance_whose_art_reaches_the_page_is_written() { assert!(fills.contains(&[255, 0, 0, 255]) && fills.contains(&[0, 0, 255, 255]), "{fills:?}"); } +/// 2,000 symbols, then two named "Mark" (a red square, then a blue one), with an instance of +/// "Mark" at (25, 25) and, in a knockout group above a green square, a half-opaque one at (70, 70). +/// With `second` the blue square's symbol is named that instead. +fn marks(second: &str) -> Document { + let mut d = doc(100.0, 100.0); + for i in 0..2000 { + let art = rect_node(Rect::new(0.0, 0.0, 1.0, 1.0), Color::BLACK); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) }); + } + for (name, color) in [("Mark", Color::rgb(1.0, 0.0, 0.0)), (second, Color::rgb(0.0, 0.0, 1.0))] { + let art = rect_node(Rect::new(-10.0, -10.0, 10.0, 10.0), color); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + add(&mut d, Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((25.0, 25.0)) })); + let green = rect_node(Rect::new(60.0, 60.0, 80.0, 80.0), Color::rgb(0.0, 1.0, 0.0)); + let mut above = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((70.0, 70.0)) }); + above.opacity = 0.5; + let mut group = Node::group(NodeId(0), vec![Arc::new(green), Arc::new(above)]); + group.knockout = vectorcraft_doc::Knockout::On; + add(&mut d, group); + d +} + +/// Instances among many symbols are written with the first symbol of their name, the same bytes +/// as when no other symbol has that name. +#[test] +fn instances_are_written_with_the_first_symbol_of_their_name() { + let d = marks("Mark"); + assert!(uncompressed(&d) == uncompressed(&marks("Other")), "the files differ"); + let fills: Vec<[u8; 4]> = leaves(&roundtrip(&d)).iter().filter_map(|n| Some(n.appearance.fill_paint().color()?.to_rgba8(1.0))).collect(); + assert!(fills.contains(&[255, 0, 0, 255]) && !fills.contains(&[0, 0, 255, 255]), "{fills:?}"); +} + #[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/src/bounds.rs b/crates/render/src/bounds.rs index ae7ccba77e..06fd0af082 100644 --- a/crates/render/src/bounds.rs +++ b/crates/render/src/bounds.rs @@ -6,7 +6,13 @@ use super::{BezPath, Document, FillRule, Node, NodeKind, Rect, SymbolBoxes, brus /// geometry effects, and the shadows and glows of it and its members. Symbol instances are /// measured by their art in `doc` ([`Node::visual_bounds_with`]). pub fn painted_bounds(doc: &Document, n: &Node) -> Option { - brush_fx::cull_bounds(&doc.symbol_boxes(), n) + painted_bounds_with(&doc.symbol_boxes(), n) +} + +/// [`painted_bounds`] with symbol instances measured by their art in `symbols` (made with +/// [`Document::symbol_boxes`]). +pub fn painted_bounds_with(symbols: &SymbolBoxes, n: &Node) -> Option { + brush_fx::cull_bounds(symbols, n) } /// [`painted_bounds`] of `n` without the room it leaves for brush art past the brushed strokes of @@ -70,7 +76,13 @@ 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)> { - fx::drawn_outline(doc, n) + 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) } /// 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/bounds.rs b/crates/render/src/fx/bounds.rs index aefe50a947..06c339d7d8 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -390,9 +390,7 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { // effects in a symbol's art and a live object's content paint past it. _ if has_object_fx(n) => { let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, .. } => { - symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| dynamic_art(&s.art, n)) - } + NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| dynamic_art(&s.art, n)), _ => None, }; let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref()); @@ -459,7 +457,7 @@ fn pieces_within(symbols: &SymbolBoxes, art: &Node, depth: usize, budget: &mut u NodeKind::Path { .. } | NodeKind::Compound { .. } if has_fx(art) => visual_bounds(symbols, art), NodeKind::SymbolInstance { symbol, .. } if depth < vectorcraft_doc::depth::MAX_DEPTH && has_instance_row_effects(art) => { let doc = symbols.document(); - let reshaped = doc.symbols.iter().find(|s| s.name == *symbol).and_then(|s| { + let reshaped = symbols.symbol(symbol).and_then(|s| { let count = s.art.count() as u64; if count > *budget { return None; @@ -494,13 +492,15 @@ pub(crate) fn painted_reach(symbols: &SymbolBoxes, n: &Node) -> Option { /// The outline the renderer clips `n`'s Feather, Inner Glow and Rasterize with Create Clipping /// Mask to: a path's or compound path's geometry with its object-level geometry effects applied, /// the outline of the art [`Renderer::fx_art`] makes for an object with object effects, and with -/// Crop Marks the object's own. For other objects it is [`effects::clip_outline`]. -pub(crate) fn drawn_outline(doc: &Document, n: &Node) -> Option<(BezPath, FillRule)> { +/// Crop Marks the object's own. For other objects it is [`effects::clip_outline`]. The symbols of +/// instances are found in `symbols`. +pub(crate) fn drawn_outline(symbols: &SymbolBoxes, n: &Node) -> Option<(BezPath, FillRule)> { + let doc = symbols.document(); if let Some(art) = effects::crop_marks_art(n) { - return drawn_outline(doc, art.children()?.first()?); + return drawn_outline(symbols, art.children()?.first()?); } if has_object_fx(n) { - let art = Renderer::new().fx_art(doc, &Arc::new(n.clone()), false); + let art = Renderer::new().fx_art(symbols, &Arc::new(n.clone()), false); return effects::clip_outline(&art); } match &n.kind { @@ -538,7 +538,7 @@ pub(crate) fn drawn_outlines(doc: &Document, symbols: &SymbolBoxes, n: &Node, le if is_container(n) && !makes_art && !effects::has_item_geometry(n) { object.appearance.items.clear(); } - let art = Renderer::new().fx_art(doc, &Arc::new(object), false); + let art = Renderer::new().fx_art(symbols, &Arc::new(object), false); if art.children().is_some() && !has_object_fx(&art) { return evaluated_outlines(doc, symbols, &art, left, out); } @@ -563,7 +563,7 @@ pub(crate) fn drawn_outlines(doc: &Document, symbols: &SymbolBoxes, n: &Node, le NodeKind::SymbolInstance { .. } => { push_outline(n.geometric_bounds_with(symbols).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()), left, out) } - _ => push_outline(drawn_outline(doc, n).map(|(path, _)| path), left, out), + _ => push_outline(drawn_outline(symbols, n).map(|(path, _)| path), left, out), } } @@ -683,9 +683,7 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b // symbol instance's art paint past that art. _ if has_object_fx(n) => { let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, .. } => { - symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| dynamic_art(&s.art, n)) - } + NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| dynamic_art(&s.art, n)), _ => None, }; let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref()); diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 0291d998f0..f40a6ce905 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -460,7 +460,7 @@ impl Renderer { /// What [`Self::draw_object_fx`] draws inside the object's transparency group. fn draw_object_fx_art(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc, cache: bool) { - if !self.charge_fx_instance(f.doc, a) { + if !self.charge_fx_instance(f.symbols, a) { return; } // A path whose Transform effects after its Rasterize effect hold options that reach its @@ -472,7 +472,7 @@ impl Renderer { { return self.draw_staged(ctx, f, stage, &bp, *rule); } - let art = self.fx_art(f.doc, a, cache); + let art = self.fx_art(f.symbols, a, cache); // Art the cache did not keep is made again in the next frame. let kept = cache && self.fx_arts.get(&(Arc::as_ptr(a) as usize), self.stamp).is_some_and(|e| Arc::ptr_eq(&e.1, &art)); let outer = self.made_again; @@ -524,9 +524,9 @@ impl Renderer { /// frame's symbol budget as an instance without effects is (`draw_node`): an instance whose /// effects reshape its art draws through here, and nested instances would otherwise expand /// without a limit. True for any other object. - pub(crate) fn charge_fx_instance(&mut self, doc: &vectorcraft_doc::Document, a: &Node) -> bool { + pub(crate) fn charge_fx_instance(&mut self, symbols: &SymbolBoxes, a: &Node) -> bool { let NodeKind::SymbolInstance { symbol, .. } = &a.kind else { return true }; - let count = doc.symbols.iter().find(|s| &s.name == symbol).map_or(0, |s| s.art.count() as u64); + let count = symbols.symbol(symbol).map_or(0, |s| s.art.count() as u64); let mut used = self.symbol_nodes; let room = vectorcraft_doc::charge_symbol_art(&mut used, count, || ((), count)).is_some(); self.symbol_nodes = used; @@ -541,7 +541,8 @@ impl Renderer { /// is made from live objects it evaluated ([`evaluates_live`]), or from type, symbol art or /// 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, doc: &vectorcraft_doc::Document, a: &Arc, cache: bool) -> Arc { + pub(super) fn fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc, cache: bool) -> Arc { + let doc = symbols.document(); let key = Arc::as_ptr(a) as usize; let mut kept = None; if cache @@ -571,9 +572,9 @@ impl Renderer { Some(f) => Some(f.0), None => self.outside_key(doc, a), }; - if was == now { art } else { self.make_fx_art(doc, a) } + if was == now { art } else { self.make_fx_art(symbols, a) } } - None => self.make_fx_art(doc, a), + None => self.make_fx_art(symbols, a), }; if cache { let bytes = crate::lru::node_bytes(&art); @@ -586,7 +587,8 @@ impl Renderer { /// held until the frame ends ([`Renderer::measured`]), for [`Self::fx_art`] to keep if `a` is /// 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, doc: &vectorcraft_doc::Document, a: &Arc) -> Arc { + pub(crate) fn measured_fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc) -> Arc { + 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) @@ -603,7 +605,7 @@ impl Renderer { { return art.clone(); } - let art = self.make_fx_art(doc, a); + let art = self.make_fx_art(symbols, a); // Art held for an object before (made from what it read then) gives way. if let Some(old) = self.measured.remove(&key) { self.measured_bytes = self.measured_bytes.saturating_sub(crate::lru::node_bytes(&old.1)); @@ -641,13 +643,12 @@ impl Renderer { } /// The art [`Self::fx_art`] draws for `a`, made now. - fn make_fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc) -> Arc { + fn make_fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc) -> Arc { + let doc = symbols.document(); // Whether the art is a 3D effect's ([`Self::three_d_art_bounds`]). let mut three_d = false; let symbol = match &a.kind { - NodeKind::SymbolInstance { symbol, .. } => { - doc.symbols.iter().find(|s| s.name == *symbol).map(|s| crate::brush_fx::instance_art(&s.art, a)) - } + NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| crate::brush_fx::instance_art(&s.art, a)), _ => None, }; let container = is_container(a); diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 3bbd803cc2..3c2e9ff65a 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -1066,7 +1066,7 @@ fn a_measuring_pass_sweeps_the_bounds_of_held_art_as_they_double() { } let mut r = Renderer::new(); // Held here, as the art kept to draw is. - let held: Vec<_> = d.layers[0].children().unwrap().iter().map(|n| r.measured_fx_art(&d, n)).collect(); + let held: Vec<_> = d.layers[0].children().unwrap().iter().map(|n| r.measured_fx_art(&d.symbol_boxes(), n)).collect(); assert_eq!((held.len(), r.three_d_bounds.len()), (3000, 3000)); assert!(r.three_d_sweeps <= 2, "{} sweeps", r.three_d_sweeps); } @@ -1193,7 +1193,7 @@ fn drawing_takes_measured_art_out_of_the_budget() { let mut r = Renderer::new(); r.bounds_of(&d.symbol_boxes(), &n); assert!(r.measured_bytes > 0); - r.fx_art(&d, &n, true); + r.fx_art(&d.symbol_boxes(), &n, true); assert_eq!((r.measured_bytes, r.measured.len()), (0, 0), "taken out when drawn"); let mut r = Renderer::new(); r.render(&d, 800, 100, Affine::IDENTITY, &RenderOptions::default()); @@ -1343,11 +1343,11 @@ fn art_measured_again_takes_the_place_of_the_held() { let n = d.layers[0].children().unwrap()[0].clone(); let key = Arc::as_ptr(&n) as usize; let mut r = Renderer::new(); - let art = r.measured_fx_art(&d, &n); + let art = r.measured_fx_art(&d.symbol_boxes(), &n); let bytes = r.measured_bytes; // As if it had read something else then. r.measured.insert(key, (n.clone(), art, Some(7))); - r.measured_fx_art(&d, &n); + r.measured_fx_art(&d.symbol_boxes(), &n); assert_eq!((r.measured_bytes, r.measured.len()), (bytes, 1)); } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index c49671fd8c..02142f118b 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -278,7 +278,9 @@ mod renderer; mod text_geom; mod threads; -pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, rasterize_stage}; +pub use bounds::{ + drawn_bounds, drawn_outline, drawn_outline_with, 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/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index 8e18b3a045..bd26c851cd 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -36,7 +36,7 @@ impl Renderer { // drawn otherwise, measured as below. _ if measures_three_d(a) && let Some(b) = { - let art = self.measured_fx_art(symbols.document(), a); + let art = self.measured_fx_art(symbols, a); self.three_d_art_bounds(symbols, &art) } => { @@ -578,7 +578,7 @@ impl Renderer { self.draw_image_in(ctx, f, &f.doc.shown_image(n, im), None, images::image_tint(f.doc, n, f.ink), n.extras().pixelated) } NodeKind::SymbolInstance { symbol, xf } => { - if let Some(sym) = f.doc.symbols.iter().find(|s| &s.name == symbol) { + if let Some(sym) = f.symbols.symbol(symbol) { // The instance draws when the frame has room for its art's objects; a symbol // with 9-slice guides is placed cell by cell (`Self::sliced_art`). let mut used = self.symbol_nodes; diff --git a/crates/render/src/renderer/text.rs b/crates/render/src/renderer/text.rs index 945ce5303b..01c73918e7 100644 --- a/crates/render/src/renderer/text.rs +++ b/crates/render/src/renderer/text.rs @@ -32,14 +32,14 @@ impl Renderer { return; } for r in t.runs.iter().filter_map(|r| r.inline.as_ref()) { - if !f.doc.symbols.iter().any(|s| s.name == r.symbol) && !MISSING_INLINE_LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) { + if f.symbols.symbol(&r.symbol).is_none() && !MISSING_INLINE_LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) { log::warn!("inline graphic shows symbol {:?}, which the document doesn't have: it draws nothing", r.symbol); } } self.inline_depth += 1; for ig in &g.inlines { let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue }; - let Some(sym) = f.doc.symbols.iter().find(|s| s.name == art.symbol) else { continue }; + let Some(sym) = f.symbols.symbol(&art.symbol) else { continue }; // Strokes scale with the art (it is sized to the type, as in the SVG ``). let (node, kept) = self.placed_art(&sym.art, t.xf * ig.xf * f.doc.symbol_natural_xf(&art.symbol), true, None); self.draw_placed_art(ctx, f, &node, kept); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index a25738c5ba..2163b58ef8 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -313,6 +313,42 @@ fn past_the_measured_placements_an_instance_is_culled_by_an_estimate_of_its_art_ assert!(img.pixel(3, 20)[3] > 0, "{:?}", img.pixel(3, 20)); } +/// 2,000 symbols, then two named "Mark" (a red square, then a blue one), and an instance of +/// "Mark" at (25, 25) and one with a drop shadow at (70, 70). With `second` the blue square's +/// symbol is named that instead. +fn marks(second: &str) -> Document { + let mut d = Document::new(100.0, 100.0); + for i in 0..2000 { + let art = rect_node(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), Paint::solid(Color::BLACK), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) }); + } + for (name, color) in [("Mark", Color::rgb(1.0, 0.0, 0.0)), (second, Color::rgb(0.0, 0.0, 1.0))] { + let art = rect_node(&mut d, Rect::new(-10.0, -10.0, 10.0, 10.0), Paint::solid(color), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + let l = d.layers[0].id; + let plain = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((25.0, 25.0)) }); + let mut shadowed = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((70.0, 70.0)) }); + shadowed.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 4, "y": 4, "blur": 0}), + visible: true, + }); + d.insert(Some(l), 0, plain).unwrap(); + d.insert(Some(l), 1, shadowed).unwrap(); + d +} + +/// Instances among many symbols draw the first symbol of their name, the same pixels as when no +/// other symbol has that name. +#[test] +fn instances_draw_the_first_symbol_of_their_name() { + let img = render(&marks("Mark")); + assert_eq!(img.pixel(25, 25), [255, 0, 0, 255]); + assert_eq!(img.pixel(70, 70), [255, 0, 0, 255]); + assert!(img.pixels == render(&marks("Other")).pixels, "the pixels differ"); +} + /// 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/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index 13fc9c0cbf..dcc1a9f019 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -1241,9 +1241,10 @@ fn symbol_instances_with_effects_are_charged_to_the_symbol_budget() { let inst = d.layers[0].children().unwrap()[0].clone(); let mut r = Renderer::new(); r.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES - 1; - assert!(r.charge_fx_instance(&d, &inst), "one object fits"); + let symbols = d.symbol_boxes(); + assert!(r.charge_fx_instance(&symbols, &inst), "one object fits"); assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES); - assert!(!r.charge_fx_instance(&d, &inst), "the next does not"); + assert!(!r.charge_fx_instance(&symbols, &inst), "the next does not"); assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES); } diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index e3acc9f032..ded9a037fe 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -117,6 +117,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: linked: Vec::new(), instance_xf: Affine::IDENTITY, symbols: HashMap::new(), + symbol_lookup: doc.symbol_boxes(), symbol_nest: 0, symbol_nodes: 0, inline_graphic: false, @@ -301,6 +302,9 @@ struct Writer<'a> { instance_xf: Affine, /// What each symbol's instances can share, by symbol name (see [`Writer::symbol_use`]). symbols: HashMap, + /// The document's symbols, found by name ([`vectorcraft_doc::SymbolBoxes::symbol`]) in time + /// independent of how many symbols the document holds. + symbol_lookup: vectorcraft_doc::SymbolBoxes<'a>, /// Symbols being written inside one another (instances nested deeper are left out: a symbol /// can't contain itself). symbol_nest: u32, diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index b9af2a6c06..f941f0fccd 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, Document, 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, FillRule, HashMap, Node, NodeKind, Paint, PathData, Props, Rect, StrokeAlign, StrokeLayer, Writer, + Written, WrittenShape, blend_css, css, fmt_num, stroke, xml_escape, }; /// A symbol's `` def and the instance transforms that can `` it. @@ -51,15 +51,16 @@ fn export_shape_bounds(n: &Node) -> Option { impl Reuse { const NONE: Self = Self { moves: false, turns: false, scales: false }; - /// What a def of symbol art `art` stands for. - pub(crate) fn of(doc: &Document, art: &Node) -> Self { + /// 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 { let mut r = Self { moves: true, turns: true, scales: true }; - r.scan(doc, art, 0); + r.scan(symbols, art, 0); r } /// Narrow down to what `n` (inside symbols nested `depth` deep) allows. - fn scan(&mut self, doc: &Document, n: &Node, depth: u32) { + fn scan(&mut self, symbols: &vectorcraft_doc::SymbolBoxes, 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); @@ -92,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 doc.symbol_nine_slice(symbol).is_some() { + if symbols.document().symbol_nine_slice(symbol).is_some() { self.scales = false; } - if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) { - self.scan(doc, &s.art, depth + 1); + if let Some(s) = symbols.symbol(symbol) { + self.scan(symbols, &s.art, depth + 1); } } _ => {} } if let Some(m) = &n.extras().mask { - self.scan(doc, &m.art, depth); + self.scan(symbols, &m.art, depth); } for c in n.children().into_iter().flatten() { - self.scan(doc, c, depth); + self.scan(symbols, c, depth); } } @@ -481,7 +482,7 @@ impl Writer<'_> { if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { let custom = !n.extras().symbol_overrides.is_empty(); if symbols.insert((symbol.clone(), custom.then_some(n.id))) - && let Some(s) = self.doc.symbols.iter().find(|s| s.name == *symbol) + && let Some(s) = self.symbol_lookup.symbol(symbol) { stack.push(if custom { std::sync::Arc::new(vectorcraft_brush::instance_art(&s.art, n)) } else { s.art.clone() }); } @@ -615,7 +616,7 @@ impl Writer<'_> { return Some(own + past + self.paint_reach(symbols, art_reach, &g, gb, depth + 1)?); } let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, xf } => self.doc.symbols.iter().find(|s| s.name == *symbol).map(|s| (s, xf)), + NodeKind::SymbolInstance { symbol, xf } => self.symbol_lookup.symbol(symbol).map(|s| (s, xf)), _ => None, }; if n.children().is_none_or(|c| c.is_empty()) && symbol.is_none() { @@ -1026,7 +1027,7 @@ impl Writer<'_> { let doc = self.doc; // The instances nested in an inline graphic's art are ordinary instances again. let inline = std::mem::take(&mut self.inline_graphic); - let Some(sym) = doc.symbols.iter().find(|s| s.name == *symbol) else { return }; + let Some(sym) = self.symbol_lookup.symbol(symbol) else { return }; if self.symbol_nest > MAX_SYMBOL_NEST { return; } @@ -1113,7 +1114,7 @@ impl Writer<'_> { return None; } if !self.symbols.contains_key(&sym.name) { - let reuse = Reuse::of(self.doc, &sym.art); + let reuse = Reuse::of(&self.symbol_lookup, &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/import/importer.rs b/crates/svg/src/import/importer.rs index 9badabc601..42f3565efe 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -209,7 +209,7 @@ impl Importer { 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, &art); + let reuse = Reuse::of(&self.doc.symbol_boxes(), &art); 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); diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index b30d367858..fd84b58a22 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -69,6 +69,42 @@ fn three_instances_give_one_symbol_and_three_uses() { assert!(boxes.iter().any(|b| (b.x0 - 90.0).abs() < 1e-3 && (b.y0 - 30.0).abs() < 1e-3), "{boxes:?}"); } +/// 2,000 symbols, then two named "Mark" (a red square with a black stroke, then a blue one) and +/// "Holder", holding an instance of "Mark". Instances: "Mark" moved, "Mark" stretched (written as +/// its own art) and "Holder". With `second` the blue square's symbol is named that instead. +fn marks(second: &str) -> Document { + let mut d = Document::new(200.0, 120.0); + for i in 0..2000 { + let art = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + d.symbols.push(Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) }); + } + for (name, color) in [("Mark", Color::rgb8(255, 0, 0)), (second, Color::rgb8(0, 0, 255))] { + let ap = Appearance::basic(Paint::solid(color), Paint::solid(Color::BLACK), 2.0); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), ap); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + let held = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((5.0, 5.0)) }); + let holder = Node::group(d.alloc_id(), vec![Arc::new(held)]); + d.symbols.push(Symbol { dynamic: false, name: "Holder".into(), art: Arc::new(holder) }); + instance(&mut d, "Mark", Affine::translate((25.0, 25.0))); + instance(&mut d, "Mark", Affine::translate((80.0, 60.0)) * Affine::scale_non_uniform(2.0, 1.0)); + instance(&mut d, "Holder", Affine::translate((150.0, 60.0))); + d +} + +/// Instances among many symbols are written with the first symbol of their name, the same SVG as +/// when no other symbol has that name. +#[test] +fn instances_are_written_with_the_first_symbol_of_their_name() { + let svg = export(&marks("Mark"), &ExportOptions::default()); + assert_eq!(svg, export(&marks("Other"), &ExportOptions::default())); + assert!(svg.contains("#ff0000") && !svg.contains("#0000ff"), "{svg}"); +} + /// A scaled instance of a symbol with 9-slice guides is written as the canvas draws it, with no /// ``: 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. From 1143546a0a1c8f7f66c3a3bd57dce3514d13f168 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 09:07:50 -0800 Subject: [PATCH 2/2] Symbols: keep per-object measuring in the export walks; live walks and SVG import use the index MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The export walks for type and fonts and the artboard crop shared one SymbolBoxes for every object. A SymbolBoxes also holds measuring budgets (effect reaches, 9-slice placements), so in a large document objects late in a walk could be measured by estimates where main measured them exactly. SymbolBoxes::unmeasured makes new boxes that share the name index, and each object is measured in boxes of its own again. - The live-object walk (render/src/live.rs) finds symbols through the frame's SymbolBoxes. - SVG export's filter regions measure each object in unmeasured boxes, and the region boxes share the writer's index. - SVG import keeps each imported symbol's index, so a symbol whose art holds instances no longer scans or indexes the list again. - Object › Rasterize's clipping mask is left as it is on main, with drawn_outline_with removed. - The symbol-read-count feature of vectorcraft-doc gives other crates' tests vectorcraft_doc::symbols_read. New tests check that a frame, an SVG export, a PDF export, the type walk and the artboard crop read the symbol list once among 2,000 symbols and 300 instances with drop shadows. --- crates/doc/Cargo.toml | 2 + crates/doc/src/lib.rs | 3 ++ crates/doc/src/symbols.rs | 52 +++++++++++++++++++- crates/engine/Cargo.toml | 2 + crates/engine/src/cmd/fileio/export.rs | 19 +++---- crates/engine/src/cmd/fileio/tests_svgenc.rs | 40 ++++++++++++++- crates/engine/src/cmd/fonts.rs | 45 +++++++++++++++-- crates/engine/src/cmd/menucmds.rs | 3 +- crates/pdf/Cargo.toml | 2 + crates/pdf/src/tests.rs | 21 ++++++++ crates/render/Cargo.toml | 2 + crates/render/src/addons/halftone.rs | 2 +- crates/render/src/bounds.rs | 8 +-- crates/render/src/fx/renderer.rs | 14 +++--- crates/render/src/lib.rs | 4 +- crates/render/src/live.rs | 52 +++++++++++--------- crates/render/src/tests.rs | 34 +++++++++++++ crates/svg/Cargo.toml | 2 + crates/svg/src/export/nodes.rs | 31 ++++++------ crates/svg/src/export/paint.rs | 4 +- crates/svg/src/import.rs | 6 +-- crates/svg/src/import/importer.rs | 10 ++-- crates/svg/tests/it/symbols_layers.rs | 22 +++++++++ 23 files changed, 294 insertions(+), 86 deletions(-) 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.