From 9a588078419876ffa2ec576ecc13678718a74812 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:44:27 -0800 Subject: [PATCH 1/2] Performance: a move finds the selected objects' places in fewer walks of the tree With 10,000 objects selected, object.move walked the document's tree five times and looked each object up by id three times. It now walks the tree three times and looks each object up once. - The selected roots (for the menus, for Move, Rotate, Scale and the other transforms, for Copy and Cut, and inside an isolated group) are put in paint order and reduced to their top-level objects from one walk instead of two. - A transform finds the objects' places once for Transform Patterns and for the edit, instead of once for each. - After a transform, the check for a pixel-aligned compound path reads the parent at the object's place instead of looking the object and its parent up by id. --- crates/engine/src/cmd/edit.rs | 30 +++++++++++++++++++---- crates/engine/src/cmd/edit/tests.rs | 30 +++++++++++++++++++++++ crates/engine/src/cmd/object/pixelgrid.rs | 12 +++++++++ crates/engine/src/cmd/object/transform.rs | 18 +++++++++----- crates/engine/src/tests/large_edits.rs | 18 ++++++++++++++ 5 files changed, 97 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 4fc1b83c29..70d7547313 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -967,7 +967,8 @@ pub(crate) fn selection_roots(st: &crate::DocState) -> Vec { } #[cfg(test)] ROOTS_FOUND.set(ROOTS_FOUND.get() + 1); - let roots = roots_of(&st.doc, st.selection.in_paint_order(&st.doc)); + let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects); + let roots = roots_placed(&st.doc, ids, &paths, |_, _| false); *kept = Some((Arc::downgrade(&st.doc), st.selection.objects.clone(), roots.clone())); roots }) @@ -1015,7 +1016,19 @@ pub(crate) fn no_symbol_part(s: &Session) -> std::result::Result<(), String> { pub(crate) fn selected_roots_to_transform(s: &Session) -> Result> { refuse_symbol_part(s)?; let st = s.doc()?; - Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_, _| true)) + let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects); + Ok(roots_placed(&st.doc, ids, &paths, |_, _| true)) +} + +/// The objects of `objects` that are in `doc`, in paint order as +/// [`vectorcraft_doc::Selection::in_paint_order`] gives them, with their places in the tree. One +/// walk finds the places for both the order and [`roots_placed`] ([`roots_within`] after +/// `in_paint_order` walks the tree twice). +fn placed_in_paint_order(doc: &Document, objects: &[NodeId]) -> (Vec, HashMap>) { + let paths = doc.index_paths(objects.iter().copied()); + let mut ids: Vec = objects.iter().copied().filter(|id| paths.contains_key(id)).collect(); + ids.sort_by(|a, b| paths.get(a).cmp(&paths.get(b))); + (ids, paths) } /// [`selected_roots`] for the selected objects inside the isolated object `root` @@ -1027,8 +1040,9 @@ pub(crate) fn selected_roots_to_transform(s: &Session) -> Result> { pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result> { refuse_symbol_part(s)?; let st = s.doc()?; - let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect(); - Ok(roots_within(&st.doc, ids, |compound, _| members || compound == root)) + let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects); + let ids = ids.into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect(); + Ok(roots_placed(&st.doc, ids, &paths, |compound, _| members || compound == root)) } /// The top-level objects among `ids` (in paint order): compound-path members stand for their @@ -1042,6 +1056,11 @@ pub(crate) fn roots_of(doc: &Document, ids: Vec) -> Vec { fn roots_within(doc: &Document, ids: Vec, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec { // Every id's place in the tree, found in one walk (a lookup per id is a walk per id). let paths = doc.index_paths(ids.iter().copied()); + roots_placed(doc, ids, &paths, keep_member) +} + +/// [`roots_within`] with `paths`, the places of `ids` in `doc`'s tree, found already. +fn roots_placed(doc: &Document, ids: Vec, paths: &HashMap>, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec { // A compound-path member acts as its compound (compounds are one object). let mut sel: Vec<(NodeId, Option>)> = ids .into_iter() @@ -1105,7 +1124,8 @@ fn copy_cut_targets(s: &Session) -> Result<(bool, Vec)> { st.doc.node(compound).and_then(|n| n.children()).is_some_and(|members| !members.is_empty() && members.iter().all(|m| whole(m))) }) }; - let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |compound, _member| in_isolated_compound || !all_members_whole(compound)); + let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects); + let roots = roots_placed(&st.doc, ids, &paths, |compound, _member| in_isolated_compound || !all_members_whole(compound)); Ok((direct, roots)) } diff --git a/crates/engine/src/cmd/edit/tests.rs b/crates/engine/src/cmd/edit/tests.rs index 7ac2d9c162..7e0471f0f5 100644 --- a/crates/engine/src/cmd/edit/tests.rs +++ b/crates/engine/src/cmd/edit/tests.rs @@ -348,6 +348,36 @@ fn direct_selection_cut_timing() { } } +/// Finding the selected roots (for the menus, for Move and its siblings, for Copy and Cut, and +/// inside an isolated group) walks the tree once for the paint order and the roots together, in +/// paint order whatever order the objects were selected in. +#[test] +fn finding_the_selected_roots_walks_the_tree_once() { + let mut s = session(2_000, square); + let all = crate::tests_large_edits::layer(&s, 0); + let reversed: Vec = all.iter().rev().map(|id| id.0).collect(); + s.execute("select.set", &json!({"ids": reversed})).unwrap(); + type Find = fn(&Session) -> Vec; + let finds: [(&str, Find); 3] = [ + ("the selected roots", |s| selected_roots(s).unwrap()), + ("the roots to transform", |s| selected_roots_to_transform(s).unwrap()), + ("Copy's targets", |s| copy_cut_targets(s).unwrap().1), + ]; + for (what, find) in finds { + let walks = tree_walks(); + assert!(find(&s) == all, "{what} in paint order"); + assert_eq!(tree_walks() - walks, 1, "finding {what} walked the tree {} times", tree_walks() - walks); + } + s.execute("object.group", &json!({})).unwrap(); + let group = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id; + s.execute("select.set", &json!({"ids": reversed})).unwrap(); + // The first call also builds the lookup cache that the isolation check reads. + assert!(selected_roots_inside(&s, group, false).unwrap() == all, "the roots inside the group in paint order"); + let walks = tree_walks(); + assert!(selected_roots_inside(&s, group, false).unwrap() == all); + assert_eq!(tree_walks() - walks, 1, "finding the roots inside the group walked the tree {} times", tree_walks() - walks); +} + /// The selected roots are found once for a document version and its selected objects, however many enabled checks /// read them, and found again after the selection changes, after an edit, and for another selection. #[test] diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 81909da76f..220ed30099 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -142,6 +142,18 @@ pub(crate) fn keep_compound_aligned(d: &mut Document, id: NodeId, sc: Scaling) { } } +/// [`keep_compound_aligned`] for the object at `path` in `d`'s tree, found already: the compound +/// path is read at the parent's place, without looking either object up by id. +pub(crate) fn keep_compound_aligned_at(d: &mut Document, path: &[usize], sc: Scaling) { + let Some((_, up)) = path.split_last() else { return }; + if up.is_empty() || !d.node_at(up).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.extras().pixel_aligned) { + return; + } + if let Some(n) = d.node_mut_at(up) { + snap_object(n, sc); + } +} + /// After any edit ([`Session::edit`]): snap each pixel-aligned object that the edit changed or added /// (its node in `doc` is not the one in `before`), with the pixel-aligned art of its linked opacity /// mask, to the pixel grid. Objects the edit did not touch are not visited. diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 1a15e44aa3..3f471a00fe 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -66,10 +66,15 @@ pub(super) fn scaling_options(s: &Session, p: &Value) -> Scaling { /// param, else General › Transform Pattern Tiles)? Noted in the journal when they or the art of /// their linked opacity masks use a pattern, so a replay moves their tiles alike whatever the preference is then. pub(crate) fn transform_patterns(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result { + let paths = s.doc()?.doc.index_paths(ids.iter().copied()); + transform_patterns_at(s, p, ids, &paths) +} + +/// [`transform_patterns`] with `paths`, the places of `ids` in the document's tree, found already. +fn transform_patterns_at(s: &mut Session, p: &Value, ids: &[NodeId], paths: &std::collections::HashMap>) -> Result { let on = bool_or(p, "patterns", s.prefs.transform_pattern_tiles); let d = &s.doc()?.doc; let mut uses = false; - let paths = d.index_paths(ids.iter().copied()); for n in ids.iter().filter_map(|id| paths.get(id)).filter_map(|p| d.node_at(p)) { uses |= uses_pattern_with_masks(n); } @@ -152,7 +157,9 @@ fn apply_transform_moving_guides( let areas = bool_or(p, "typeAreas", false); let objects = transforms_objects(p); let mut sc = if Scaling::factor(xf).is_some() { scaling(s, p) } else { Scaling::default() }; - sc.patterns = transform_patterns(s, p, &ids)?; + // The places of `ids`, found in one walk for Transform Patterns and for the edit below. + let paths = s.doc()?.doc.index_paths(ids.iter().copied()); + sc.patterns = transform_patterns_at(s, p, &ids, &paths)?; let c = xf.as_coeffs(); let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9; let delta = guides.unwrap_or(Vec2::new(c[4], c[5])); @@ -174,8 +181,6 @@ fn apply_transform_moving_guides( // An edit normally preserves the tree positions already found here. Settling an active // typing session can change the document before the edit closure runs, so look up again then. let reindex = copy || (!s.previewing && crate::cmd::typing_in_progress(s)); - let d = &s.doc()?.doc; - let paths = d.index_paths(ids.iter().copied()); let none = paths.is_empty() && !has_guides; // A move of direct-selected anchors may re-map the handles beside them (`interpolate`). let mut interpolate = None; @@ -230,8 +235,9 @@ fn apply_transform_moving_guides( } } if objects { - for id in &targets { - super::pixelgrid::keep_compound_aligned(d, *id, sc); + // The transforms above leave every object at its place, so `paths` still holds them. + for p in targets.iter().filter_map(|id| paths.get(id)) { + super::pixelgrid::keep_compound_aligned_at(d, p, sc); } // Moving all of the tile art moves the tile as far. if let Some(before) = tile_art { diff --git a/crates/engine/src/tests/large_edits.rs b/crates/engine/src/tests/large_edits.rs index 0394fb18fa..2806cdd925 100644 --- a/crates/engine/src/tests/large_edits.rs +++ b/crates/engine/src/tests/large_edits.rs @@ -253,6 +253,24 @@ fn transform_each_with_copy_of_50000_objects_takes_few_tree_walks() { undo_gives_back(&mut s, &before); } +/// A move of 10,000 selected objects walks the tree once for the paint order and the top-level +/// objects, once for Transform Patterns and the edit, and once for the selection's check after the +/// edit. It reads each object's compound path at the object's place, so the only lookups by id are +/// the range check's, one per object. +#[test] +fn moving_10000_selected_objects_walks_the_tree_three_times() { + let n = 10_000; + let mut s = session(n, square); + let ids = layer(&s, 0); + let (walks, lookups) = (vectorcraft_doc::tree_walks(), vectorcraft_doc::path_lookups()); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + let (walks, lookups) = (vectorcraft_doc::tree_walks() - walks, vectorcraft_doc::path_lookups() - lookups); + assert_eq!(walks, 3, "walked the tree {walks} times"); + assert!(lookups <= n as u64, "{lookups} lookups by id for {n} objects"); + assert_eq!(bounds(&s, ids[n - 1]), square_at(n - 1) + vectorcraft_geom::Vec2::new(3.0, 0.0)); + assert!(selected(&s, &ids)); +} + #[test] fn offset_path_of_50000_objects_takes_few_tree_walks() { let s = session(50_000, square); From 04ced9bee734f216ee55ac13316932b5e501184c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 03:33:26 -0800 Subject: [PATCH 2/2] Performance: the check of a moved selection reads the objects at their places After a move, the check that a view can move the selection's marks instead of building them again looked each moved object up by id three times: the object, its parent's id and the parent. With 10,000 objects selected that was 30,000 lookups after the edit. The check now keeps each object's place from the transform and reads the object and its parent there, so the move looks each object up once, as before. --- crates/engine/src/cmd/object/transform.rs | 26 ++++++++++++----------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index c3ce0107f0..4212588f1b 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -200,7 +200,7 @@ fn apply_transform_moving_guides( // A move of whole objects, not of copies (which `reindex` covers): the document before it, // and the moved objects as the transform left them, for [`moved_by`] to check after the edit. let from = (objects && !areas && !reindex && c[..4] == [1.0, 0.0, 0.0, 1.0]).then(|| s.doc().map(|st| st.doc.clone())).transpose()?; - let mut held: Vec<(NodeId, Arc)> = vec![]; + let mut held: Vec<(Vec, Arc)> = vec![]; let targets = s.edit(label, |d, sel| { let mut targets = match &kept { // The document becomes the snapshot with the kept copies, untransformed, and the @@ -240,7 +240,7 @@ fn apply_transform_moving_guides( } // Holding them makes any later change to them copy them first, which `moved_by` sees. if from.is_some() { - held = targets.iter().filter_map(|id| Some((*id, node_arc(d, paths.get(id)?)?))).collect(); + held = targets.iter().filter_map(|id| paths.get(id)).filter_map(|p| Some((p.clone(), node_arc(d, p)?))).collect(); } if objects { // The transforms above leave every object at its place, so `paths` still holds them. @@ -294,20 +294,22 @@ fn node_arc(d: &Document, path: &[usize]) -> Option> { } /// The [`crate::Moved`] of a move by `by` that took `from` to the document of `st`, given the moved -/// objects as the transform left them (`held`). `None` unless every moved object is still that -/// node, none is a member of a blend (whose spine follows its members), and every object the -/// selection shows, the key object and the key anchor's object included, is a moved object or -/// inside one. A pass after the transform that changes a moved object, such as the one that snaps -/// moved pixel-aligned objects to the pixel grid again ([`super::pixelgrid::refresh`]), copies it -/// first, so it is no longer that node. -fn moved_by(from: &Arc, st: &crate::DocState, held: &[(NodeId, Arc)], by: Vec2) -> Option { +/// objects as the transform left them (`held`, each with its index path). `None` unless every moved +/// object is still that node at its path, none is a member of a blend (whose spine follows its +/// members), and every object the selection shows, the key object and the key anchor's object +/// included, is a moved object or inside one. A pass after the transform that changes a moved +/// object, such as the one that snaps moved pixel-aligned objects to the pixel grid again +/// ([`super::pixelgrid::refresh`]), copies it first, so it is no longer that node. The checks read +/// the nodes at their paths and look nothing up by id. +fn moved_by(from: &Arc, st: &crate::DocState, held: &[(Vec, Arc)], by: Vec2) -> Option { let d = &st.doc; - let unchanged = |(id, n): &(NodeId, Arc)| d.node(*id).is_some_and(|now| std::ptr::eq(now, Arc::as_ptr(n))); + let unchanged = |(p, n): &(Vec, Arc)| d.node_at(p).is_some_and(|now| std::ptr::eq(now, Arc::as_ptr(n))); if held.is_empty() || !held.iter().all(unchanged) { return None; } - let in_blend = |id: NodeId| d.parent_of(id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Blend { .. })); - if held.iter().any(|(id, _)| in_blend(*id)) { + // The node at each path is the moved object, so its parent is the node one level up. + let in_blend = |p: &[usize]| p.split_last().and_then(|(_, up)| d.node_at(up)).is_some_and(|parent| matches!(parent.kind, NodeKind::Blend { .. })); + if held.iter().any(|(p, _)| in_blend(p)) { return None; } let mut moved = std::collections::HashSet::new();