From c10d62d0271ed5e0bdf84ebba5a56c98fc34241c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 10:19:29 -0800 Subject: [PATCH] Performance: paths keep their control-point box, so a hover reads no anchors Hit walks measure every path's culling box with PathData::control_bounds, which read every anchor of the path on every call. Since anchors are kept in shared chunks, that read follows two more pointers per path and goes through the chunked iterator, so each node of a hover or cursor walk cost about twice what it did before the chunks. Each subpath's anchor list now keeps the box round its points and handles once it is measured (Anchors::control_bounds), and every change to the list clears it. A copy of the list keeps the box too. control_bounds unions the subpaths' boxes, with the same result as before. - anchors.rs: control_bounds reads the anchors once until they change, counted by measured_control_anchors; each change to the list clears it. - Tests count the anchors read: a list reads them once across calls and copies, again after each kind of change, and a hover past 100 squares reads none after the first. --- crates/doc/src/hit/tests.rs | 23 ++++++++ crates/geom/src/anchors.rs | 111 +++++++++++++++++++++++++++++++++++- crates/geom/src/path.rs | 7 +-- 3 files changed, 134 insertions(+), 7 deletions(-) diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 7ac945e4ee..ff31058da6 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -3569,3 +3569,26 @@ fn a_shaper_groups_original_shapes_in_symbol_art_are_not_picked() { assert_eq!(symbol_part_at(&d, n, Point::new(130.0, 50.0), opt), None, "over the erased original shape"); assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "over the shown face"); } + +/// The pointer resting over empty canvas past many paths reads their anchors for their culling +/// boxes on the first hover only: the next hovers use the boxes the paths keep. +#[test] +fn hovers_past_many_paths_read_their_anchors_once() { + use vectorcraft_geom::anchors::measured_control_anchors; + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + for i in 0..100 { + let n = square(&mut d, (i % 10) as f64 * 60.0, (i / 10) as f64 * 60.0); + d.insert(Some(l), 0, n).unwrap(); + } + let empty = Point::new(900.0, 900.0); + let before = measured_control_anchors(); + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + let first = measured_control_anchors() - before; + assert!(first >= 400, "the first hover reads every square's anchors: {first}"); + for _ in 0..3 { + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + } + assert_eq!(measured_control_anchors() - before, first, "later hovers read no anchor"); + assert!(hit_at(&d, 25.0, 25.0, HitOptions::default()).is_some(), "a square is still hit"); +} diff --git a/crates/geom/src/anchors.rs b/crates/geom/src/anchors.rs index 57b8081686..3b9f4aa9bd 100644 --- a/crates/geom/src/anchors.rs +++ b/crates/geom/src/anchors.rs @@ -8,12 +8,16 @@ //! in and rebuilds the table, which has one entry per chunk. //! //! The list reads and writes as one flat sequence of anchors, as a `Vec` does. +//! +//! The list also keeps the box round its anchors' points and handles ([`Anchors::control_bounds`]) +//! once it has been measured, until the list changes. use std::borrow::Cow; use std::fmt; use std::ops::{Index, IndexMut, RangeBounds}; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; +use kurbo::Rect; use serde::{Deserialize, Serialize}; use crate::path::Anchor; @@ -40,12 +44,49 @@ pub struct Anchors { ends: Vec, /// The number of anchors. len: usize, + /// The box round every anchor's point and handles, once measured; emptied by every change. + control: OnceLock, +} + +thread_local! { + /// [`measured_control_anchors`] of this thread. + static MEASURED_CONTROL_ANCHORS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many anchors [`Anchors::control_bounds`] has read on this thread. +pub fn measured_control_anchors() -> u64 { + MEASURED_CONTROL_ANCHORS.get() } impl Anchors { /// An empty list. pub const fn new() -> Self { - Self { chunks: Vec::new(), ends: Vec::new(), len: 0 } + Self { chunks: Vec::new(), ends: Vec::new(), len: 0, control: OnceLock::new() } + } + + /// The box round every anchor's point and handles, or `None` when the list is empty. The list + /// reads its anchors for it once, and again only after it has changed. + pub fn control_bounds(&self) -> Option { + if self.len == 0 { + return None; + } + Some(*self.control.get_or_init(|| { + MEASURED_CONTROL_ANCHORS.set(MEASURED_CONTROL_ANCHORS.get().saturating_add(self.len as u64)); + let mut r: Option = None; + for c in &self.chunks { + for a in c.iter() { + for p in [a.p, a.h_in, a.h_out] { + r = Some(r.map_or(Rect::from_points(p, p), |r| r.union_pt(p))); + } + } + } + r.unwrap_or_default() + })) + } + + /// Forget the measured [`Self::control_bounds`]: every change calls it. + fn changed(&mut self) { + self.control.take(); } /// The number of anchors. @@ -85,6 +126,7 @@ impl Anchors { if i >= self.len { return None; } + self.changed(); let (c, o) = self.locate(i); Arc::make_mut(self.chunks.get_mut(c)?).get_mut(o) } @@ -101,11 +143,13 @@ impl Anchors { /// The first anchor to change. pub fn first_mut(&mut self) -> Option<&mut Anchor> { + self.changed(); Arc::make_mut(self.chunks.first_mut()?).first_mut() } /// The last anchor to change. pub fn last_mut(&mut self) -> Option<&mut Anchor> { + self.changed(); Arc::make_mut(self.chunks.last_mut()?).last_mut() } @@ -118,6 +162,7 @@ impl Anchors { /// The anchors in order, to change. Each chunk is copied, when another list shares it, as the /// iterator reaches it. pub fn iter_mut(&mut self) -> IterMut<'_> { + self.changed(); let chunk: fn(&mut Arc>) -> std::slice::IterMut<'_, Anchor> = |c| Arc::make_mut(c).iter_mut(); self.chunks.iter_mut().flat_map(chunk) } @@ -177,6 +222,7 @@ impl Anchors { /// Rebuild `ends` and `len` after the chunks changed, dropping empty chunks. fn reindex(&mut self) { + self.changed(); self.chunks.retain(|c| !c.is_empty()); self.len = self.chunks.iter().map(|c| c.len()).sum(); let n = self.chunks.len(); @@ -193,6 +239,7 @@ impl Anchors { /// Add `a` at the end. pub fn push(&mut self, a: Anchor) { + self.changed(); match self.chunks.last_mut() { Some(last) if last.len() < CHUNK => Arc::make_mut(last).push(a), _ => { @@ -210,6 +257,7 @@ impl Anchors { /// Remove the last anchor. pub fn pop(&mut self) -> Option { + self.changed(); let last = self.chunks.last_mut()?; let a = Arc::make_mut(last).pop(); if last.is_empty() { @@ -489,6 +537,7 @@ impl Index for Anchors { impl IndexMut for Anchors { /// Anchor `i` to change ([`Anchors::get_mut`]). Panics past the end, as indexing a slice does. fn index_mut(&mut self, i: usize) -> &mut Anchor { + self.changed(); let (c, o) = self.locate(i); &mut Arc::make_mut(&mut self.chunks[c])[o] } @@ -501,7 +550,7 @@ impl From> for Anchors { } let len = v.len(); let chunks = if len <= CHUNK { vec![Arc::new(v)] } else { v.chunks(CHUNK).map(|c| Arc::new(c.to_vec())).collect() }; - Self { chunks, ends: Vec::new(), len } + Self { chunks, ends: Vec::new(), len, control: OnceLock::new() } } } @@ -725,6 +774,8 @@ mod tests { } } assert_eq!(a.len(), v.len(), "step {step}"); + // The box kept from the step before is measured again after the edit. + assert_eq!(a.control_bounds(), Anchors::from(v.clone()).control_bounds(), "step {step}"); if step % 50 == 0 { assert_eq!(a, v, "step {step}"); for i in 0..v.len() { @@ -737,6 +788,60 @@ mod tests { assert_eq!(a.get(v.len()), None); } + /// The box of every anchor of `v` with its handles, measured anchor by anchor. + fn box_of(v: &[Anchor]) -> Option { + let mut it = v.iter().flat_map(|a| [a.p, a.h_in, a.h_out]); + let first = it.next()?; + Some(it.fold(Rect::from_points(first, first), |r, p| r.union_pt(p))) + } + + #[test] + fn control_bounds_read_the_anchors_once_until_they_change() { + let n = 1000; + let mut a = Anchors::from(line(n)); + let read = measured_control_anchors; + let before = read(); + assert_eq!(a.control_bounds(), box_of(&line(n))); + assert_eq!(read() - before, n as u64, "the first call reads every anchor"); + let copy = a.clone(); + for _ in 0..5 { + assert_eq!(a.control_bounds(), box_of(&line(n))); + assert_eq!(copy.control_bounds(), box_of(&line(n))); + } + assert_eq!(read() - before, n as u64, "later calls, and a copy's, read no anchor"); + // Every change measures again, and only the list that changed. + let far = Point::new(-50.0, 900.0); + type Edit = fn(&mut Anchors, Point); + let edits: [(&str, Edit); 11] = [ + ("get_mut", |a, p| a.get_mut(3).into_iter().for_each(|x| x.h_out = p)), + ("index_mut", |a, p| a[4].h_in = p), + ("first_mut", |a, p| a.first_mut().into_iter().for_each(|x| x.p = p)), + ("last_mut", |a, p| a.last_mut().into_iter().for_each(|x| x.p = p)), + ("iter_mut", |a, p| a.iter_mut().take(1).for_each(|x| x.p = p)), + ("push", |a, p| a.push(Anchor::corner(p))), + ("insert", |a, p| a.insert(1, Anchor::corner(p))), + ("pop", |a, _| { + let _ = a.pop(); + }), + ("remove", |a, _| { + let _ = a.try_remove(0); + }), + ("truncate", |a, _| a.truncate(10)), + ("reverse", |a, _| a.reverse()), + ]; + for (k, (what, edit)) in edits.iter().enumerate() { + let p = Point::new(far.x - k as f64, far.y + k as f64); + assert!(a.control_bounds().is_some()); + edit(&mut a, p); + let r = read(); + assert_eq!(a.control_bounds(), box_of(&a.to_vec()), "after {what}"); + assert_eq!(read() - r, a.len() as u64, "after {what}: measured again"); + } + assert_eq!(copy.control_bounds(), box_of(&line(n)), "the copy keeps its box"); + a.clear(); + assert_eq!(a.control_bounds(), None); + } + #[test] fn iterators_skip_and_count_as_a_slice_does() { let v = line(1000); diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 5264414cb3..c5e857f017 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -745,11 +745,10 @@ impl PathData { } bbox } - /// Bounds including control handles (used for quick culling). + /// Bounds including control handles (used for quick culling). Each subpath keeps its own box + /// ([`Anchors::control_bounds`]) until its anchors change. pub fn control_bounds(&self) -> Option { - let mut it = self.subpaths.iter().flat_map(|s| s.anchors.iter()).flat_map(|a| [a.p, a.h_in, a.h_out]); - let first = it.next()?; - Some(it.fold(Rect::from_points(first, first), |r, p| r.union_pt(p))) + self.subpaths.iter().filter_map(|s| s.anchors.control_bounds()).reduce(|a, b| a.union(b)) } pub fn transform(&mut self, a: Affine) { for sp in &mut self.subpaths {