From 52b4b039204874aafd2d3f2a1a24960da8ad962a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 07:09:32 -0800 Subject: [PATCH] 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.