Select: Select Behind in isolation looks up the objects it found in a set

Each round of the repeated hit test that Select Behind uses in isolation
mode and in Edit Contents skipped the objects already found by searching
the found list, which made one Cmd/Ctrl-click cubic in the number of
objects under the point. A set beside the ordered list answers the same
lookups, so the objects and their order do not change.

A test compares the set lookup with the list lookup on random documents
for every object isolated in turn, and an ignored timing test measures
both on 200 and 1,000 stacked objects.
This commit is contained in:
dotCooCoo
2026-11-17 11:44:23 -08:00
parent 36b5a5920c
commit 0da5bf3a0b
2 changed files with 215 additions and 3 deletions
+5 -3
View File
@@ -607,9 +607,11 @@ fn objects_at_repeated(doc: &Document, p: Point, opt: HitOptions, scope: Option<
/// [`objects_at_repeated`] after `tops`, the topmost objects under `p` already found.
fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> {
// Each round leaves out the objects found so far (and everything inside them).
while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) {
if tops.contains(&top) {
// Each round leaves out the objects found so far (and everything inside them). `found` holds
// the same ids as `tops`, which keeps their order.
let mut found: HashSet<NodeId> = tops.iter().copied().collect();
while let Some(top) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true).map(|h| h.top_object(scope)) {
if !found.insert(top) {
break;
}
tops.push(top);
+210
View File
@@ -1823,6 +1823,216 @@ fn objects_at_matches_repeated_hits_on_random_documents() {
}
}
/// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the
/// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times.
fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> {
while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) {
if tops.contains(&top) {
break;
}
tops.push(top);
}
tops
}
/// A layer holding a group of `count` overlapping 50 × 50 squares, member `i` at x = 5 × (`i` mod
/// 10), with a square at x = 0 below the group and above it, and one at x = 100 above it: the
/// document, the group and its members, topmost first.
fn isolated_stack(count: u32) -> (Document, NodeId, Vec<NodeId>) {
let mut d = Document::new(200.0, 200.0);
let l = d.layers[0].id;
let square = |d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art());
let below = square(&mut d, 0.0);
d.insert(Some(l), usize::MAX, below).unwrap();
let members: Vec<Node> = (0..count).map(|i| square(&mut d, f64::from(i % 10) * 5.0)).collect();
let mut ids: Vec<NodeId> = members.iter().map(|n| n.id).collect();
let g = d.alloc_id();
d.insert(Some(l), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap();
for x in [0.0, 100.0] {
let above = square(&mut d, x);
d.insert(Some(l), usize::MAX, above).unwrap();
}
ids.reverse();
(d, g, ids)
}
/// Select Behind in an isolated group of 40 overlapping squares, with art around the group above
/// and below them: each member once, front to back, over 41 rounds of hit tests, and nothing where
/// only the art around the group lies.
#[test]
fn select_behind_in_isolation_lists_a_large_stack_once() {
let (d, g, ids) = isolated_stack(40);
let at = |x: f64, scope| objects_at(&d, Point::new(x, 25.0), HitOptions::default(), scope);
assert_eq!(at(47.5, Some(g)), ids);
assert_eq!(at(47.5, Some(g)).iter().collect::<HashSet<_>>().len(), 40, "no object twice");
assert_eq!(at(47.5, None).len(), 3, "not isolated: the square above, the group and the square below");
// At x = 17.5 only the members at x = 0 to 20 are hit (the one at 20 on its stroke, within
// the tolerance): `ids[k]` is member 39 - k.
let left: Vec<NodeId> = ids.iter().enumerate().filter(|(k, _)| (39 - k) % 10 <= 4).map(|(_, id)| *id).collect();
assert_eq!(left.len(), 20);
assert_eq!(at(17.5, Some(g)), left);
assert!(at(125.0, Some(g)).is_empty(), "only the square around the group");
assert_eq!(at(125.0, None).len(), 1);
let isolated = HitOptions { scope: Some(g), ..HitOptions::default() };
let p = Point::new(47.5, 25.0);
assert_eq!(objects_at_repeated_after(&d, p, isolated, Some(g), ids[..15].to_vec()), ids, "the objects passed in stay first");
let (d, g, clip, art) = masked_square(false);
let isolated = HitOptions { scope: Some(g), ..SELECTING };
for p in [Point::new(140.0, 90.0), Point::new(170.0, 90.0), Point::new(100.0, 90.0)] {
let want = objects_at_repeated_after_by_list(&d, p, isolated, Some(g), vec![]);
assert_eq!(objects_at(&d, p, SELECTING, Some(g)), want, "clip group isolated, {p:?}");
}
assert_eq!(objects_at(&d, Point::new(170.0, 90.0), SELECTING, Some(g)), vec![art], "the art its mask hides");
assert!(objects_at(&d, Point::new(140.0, 90.0), SELECTING, Some(g)).contains(&clip), "the mask on its outline");
}
/// Documents built at random (nested groups, clipping groups, envelopes in Edit Contents, hidden
/// and locked objects), each object in turn isolated, and each list started with some of the
/// objects already found: the set lookup returns what the ordered-list lookup returns, field for
/// field.
#[test]
fn select_behind_in_isolation_matches_the_list_lookup_on_random_documents() {
let mut seed = 0x2545_f491_u32;
let mut next = move |n: u32| {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
seed % n
};
fn fill(d: &mut Document, parent: NodeId, depth: u32, next: &mut impl FnMut(u32) -> u32) {
for _ in 0..2 + next(5) {
let id = d.alloc_id();
let rect = |next: &mut dyn FnMut(u32) -> u32| {
let (x, y) = (f64::from(next(60)), f64::from(next(60)));
Rect::new(x, y, x + 10.0 + f64::from(next(50)), y + 10.0 + f64::from(next(50)))
};
let mut n = match next(if depth < 3 { 9 } else { 4 }) {
4 | 5 => Node::group(id, Vec::new()),
6 => {
let mut g = Node::group(id, Vec::new());
g.set_clips(true);
g
}
7 => {
let content =
(0..2).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(rect(next)), Appearance::default_art()))).collect();
Node::new(
id,
NodeKind::Envelope {
content,
kind: Box::new(crate::live::EnvelopeKind::Warp {
style: "arc".to_string(),
bend: 0.0,
h: 0.0,
v: 0.0,
horizontal: true,
version: 0,
}),
fidelity: 100.0,
editing: next(2) == 0,
options: Default::default(),
frame: Box::new(vectorcraft_geom::Affine::IDENTITY),
},
)
}
_ => Node::path(id, shapes::rectangle(rect(next)), if next(4) == 0 { Appearance::default() } else { Appearance::default_art() }),
};
n.visible = next(8) != 0;
n.locked = next(8) == 0;
let group = matches!(n.kind, NodeKind::Group { .. });
d.insert(Some(parent), usize::MAX, n).unwrap();
if group {
fill(d, id, depth + 1, next);
}
}
}
let mut compared = 0;
for round in 0..60 {
let mut d = Document::new(120.0, 120.0);
let layer = d.layers[0].id;
fill(&mut d, layer, 0, &mut next);
let mut scopes = vec![None];
d.walk(|n| {
if n.id != layer {
scopes.push(Some(n.id));
}
});
for _ in 0..6 {
let p = Point::new(f64::from(next(120)), f64::from(next(120)));
let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() };
for &scope in &scopes {
let opt = HitOptions { scope, ..opt };
let want = objects_at_repeated_after_by_list(&d, p, opt, scope, vec![]);
let context = format!("round {round}, {p:?}, {opt:?}");
assert_eq!(objects_at_repeated_after(&d, p, opt, scope, vec![]), want, "{context}");
if scope.is_some() {
assert_eq!(objects_at(&d, p, opt, scope), want, "{context}");
}
for found in 1..want.len() {
let start = want[..found].to_vec();
assert_eq!(objects_at_repeated_after(&d, p, opt, scope, start.clone()), want, "{context}, {found} found");
assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, scope, start), want, "{context}, {found} found");
}
compared += usize::from(!want.is_empty());
}
}
}
assert!(compared > 500, "only {compared} non-empty lists compared");
}
/// Times Select Behind in an isolated group of 200 and of 1,000 overlapping squares, the set lookup
/// against the ordered-list lookup, alternating the two in one process:
/// `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture select_behind_isolation_timing`.
#[test]
#[ignore = "a timing, not a check"]
fn select_behind_isolation_timing() {
/// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere.
fn clock(start: std::time::Instant) -> u128 {
let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok();
cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos())
}
type Lookup = fn(&Document, Point, HitOptions, Option<NodeId>, Vec<NodeId>) -> Vec<NodeId>;
let start = std::time::Instant::now();
println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" });
let p = Point::new(47.5, 25.0);
for count in [200, 1_000] {
let (d, g, ids) = isolated_stack(count);
let opt = HitOptions { scope: Some(g), ..HitOptions::default() };
assert_eq!(objects_at_repeated_after(&d, p, opt, Some(g), vec![]), ids);
assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, Some(g), vec![]), ids);
// The time per call of `f`: batches of calls double until one takes at least 100 ms.
let per_call = |f: Lookup| {
let mut calls = 1u32;
loop {
let t = clock(start);
for _ in 0..calls {
std::hint::black_box(f(&d, std::hint::black_box(p), opt, Some(g), vec![]));
}
let spent = clock(start) - t;
if spent >= 100_000_000 || calls >= 1 << 20 {
return (spent as f64 / f64::from(calls), calls);
}
calls *= 2;
}
};
let (mut old, mut new) = (vec![], vec![]);
for _ in 0..7 {
old.push(per_call(objects_at_repeated_after_by_list));
new.push(per_call(objects_at_repeated_after));
}
old.sort_by(|a, b| a.0.total_cmp(&b.0));
new.sort_by(|a, b| a.0.total_cmp(&b.0));
let (o, n) = (old[3], new[3]);
println!(
"{count} objects: list lookup {:.2} ms per call ({} calls), set lookup {:.2} ms per call ({} calls), median of 7 runs",
o.0 / 1e6,
o.1,
n.0 / 1e6,
n.1
);
}
}
/// Select Behind finds a symbol instance by its symbol's art, as a click does: art from
/// (100, 60) to (140, 80), outside the 20 × 20 square around the origin, drawn where it lies by
/// one instance and 100 pt lower by an instance in a group.