mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 21:27:00 +00:00
Merge pull request #8169 from dotCooCoo/fix/symbol-lookup-index
Symbols: render and SVG/PDF export find each instance's symbol in one index
This commit is contained in:
@@ -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 }
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
@@ -312,7 +312,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() {
|
||||
@@ -322,7 +322,7 @@ 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<usize> = const { Cell::new(0) };
|
||||
@@ -330,12 +330,31 @@ thread_local! {
|
||||
static ART_BOXES_MEASURED: Cell<usize> = 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<SymbolNames>) -> Self {
|
||||
@@ -343,19 +362,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<Node>> {
|
||||
/// 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<Node>> {
|
||||
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
|
||||
@@ -904,6 +928,57 @@ 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 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
|
||||
|
||||
@@ -98,6 +98,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 }
|
||||
|
||||
@@ -211,17 +211,11 @@ fn selected_part(n: &Arc<Node>, keep: &HashSet<NodeId>, holders: &HashSet<NodeId
|
||||
/// its own art, not a whole document of artboards. `renderer` measures the 3D art, and keeps it for
|
||||
/// the next artboard of the same document.
|
||||
pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Document {
|
||||
fn kept(
|
||||
n: &Arc<Node>,
|
||||
doc: &Document,
|
||||
symbols: &SymbolBoxes,
|
||||
rect: vectorcraft_geom::Rect,
|
||||
renderer: &mut vectorcraft_render::Renderer,
|
||||
) -> Option<Arc<Node>> {
|
||||
fn kept(n: &Arc<Node>, symbols: &SymbolBoxes, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Option<Arc<Node>> {
|
||||
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, 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, doc, 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(doc, 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 symbols = 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, &symbols, rect, renderer)).collect();
|
||||
d
|
||||
}
|
||||
|
||||
|
||||
@@ -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 `<title>`; Save's SVG and Export for Screens' Full
|
||||
/// Document keep the document's.
|
||||
|
||||
@@ -247,10 +247,11 @@ impl Resources {
|
||||
fn expand(&mut self, d: &Document) {
|
||||
let mut symbols: Vec<String> = self.symbols.iter().cloned().collect();
|
||||
let mut patterns: Vec<String> = 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<UsedFont> {
|
||||
/// 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<Node>], areas: &[Rect]) -> (BTreeSet<UsedFont>, BTreeSet<NodeId>) {
|
||||
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<Node>], 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<Node>], areas: Option<&[Rect]>) -> Option<String> {
|
||||
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,9 @@ 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. 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,
|
||||
fonts: BTreeSet<UsedFont>,
|
||||
@@ -544,7 +548,13 @@ struct Printed<'a> {
|
||||
patterns: BTreeSet<String>,
|
||||
}
|
||||
|
||||
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 +635,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.unmeasured(), n).map(|c| vec![c]),
|
||||
};
|
||||
for c in children {
|
||||
self.node(c, clipped.as_deref().or(areas));
|
||||
@@ -641,9 +651,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 +669,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.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(self.d, 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()
|
||||
}
|
||||
}
|
||||
@@ -2378,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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -118,7 +118,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
|
||||
@@ -452,7 +452,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
|
||||
@@ -968,8 +968,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],
|
||||
@@ -983,9 +985,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.
|
||||
@@ -1046,8 +1049,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| {
|
||||
@@ -1080,8 +1082,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))
|
||||
}
|
||||
|
||||
@@ -1177,7 +1178,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);
|
||||
@@ -1205,11 +1207,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.
|
||||
@@ -1247,6 +1250,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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -223,6 +223,60 @@ 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:?}");
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<Rect> {
|
||||
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<Rect> {
|
||||
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,7 @@ pub fn rasterize_stage(doc: &Document, n: &Node) -> Option<(Node, Vec<vectorcraf
|
||||
/// 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)
|
||||
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,
|
||||
|
||||
@@ -397,9 +397,7 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
// 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());
|
||||
@@ -466,7 +464,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;
|
||||
@@ -501,13 +499,15 @@ pub(crate) fn painted_reach(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
/// 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 {
|
||||
@@ -545,7 +545,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);
|
||||
}
|
||||
@@ -570,7 +570,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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -690,9 +690,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());
|
||||
|
||||
@@ -481,7 +481,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<Node>, 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
|
||||
@@ -493,7 +493,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;
|
||||
@@ -545,9 +545,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;
|
||||
@@ -562,7 +562,7 @@ 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<Node>, cache: bool) -> Arc<Node> {
|
||||
pub(super) fn fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>, cache: bool) -> Arc<Node> {
|
||||
let key = Arc::as_ptr(a) as usize;
|
||||
let mut kept = None;
|
||||
if cache
|
||||
@@ -574,7 +574,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)
|
||||
{
|
||||
@@ -590,11 +590,11 @@ 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(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);
|
||||
@@ -607,24 +607,24 @@ 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<Node>) -> Arc<Node> {
|
||||
pub(crate) fn measured_fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Arc<Node> {
|
||||
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
|
||||
{
|
||||
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));
|
||||
@@ -657,18 +657,17 @@ 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.
|
||||
fn make_fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Arc<Node> {
|
||||
fn make_fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Arc<Node> {
|
||||
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);
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
|
||||
@@ -285,7 +285,7 @@ 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_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,
|
||||
|
||||
+30
-22
@@ -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);
|
||||
@@ -462,14 +464,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))
|
||||
@@ -481,7 +483,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.
|
||||
@@ -491,11 +493,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)
|
||||
@@ -550,7 +553,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);
|
||||
@@ -575,7 +578,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;
|
||||
@@ -818,7 +821,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);
|
||||
@@ -850,8 +858,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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 `<use>`).
|
||||
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);
|
||||
|
||||
@@ -314,6 +314,76 @@ 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");
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -47,3 +47,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"] }
|
||||
|
||||
@@ -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<String, SymbolDef>,
|
||||
/// 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,
|
||||
|
||||
@@ -51,15 +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.
|
||||
pub(crate) fn of(doc: &Document, 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(doc, art, 0);
|
||||
r.scan(doc, find, 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<'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);
|
||||
@@ -95,17 +96,17 @@ impl Reuse {
|
||||
if doc.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) = find(symbol) {
|
||||
self.scan(doc, find, &s.art, depth + 1);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(m) = &n.extras().mask {
|
||||
self.scan(doc, &m.art, depth);
|
||||
self.scan(doc, find, &m.art, depth);
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
self.scan(doc, c, depth);
|
||||
self.scan(doc, find, 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() });
|
||||
}
|
||||
@@ -518,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);
|
||||
@@ -528,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);
|
||||
@@ -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,8 @@ impl Writer<'_> {
|
||||
return None;
|
||||
}
|
||||
if !self.symbols.contains_key(&sym.name) {
|
||||
let reuse = Reuse::of(self.doc, &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)?;
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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>,
|
||||
|
||||
@@ -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, &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(),
|
||||
|
||||
@@ -69,6 +69,64 @@ 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}");
|
||||
}
|
||||
|
||||
/// 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.
|
||||
|
||||
Reference in New Issue
Block a user