mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 08:26:28 +00:00
Merge pull request #8230 from dotCooCoo/perf/direction-handles-select-set
Select: Object > Direction Handles selects the paths with one set call
This commit is contained in:
@@ -0,0 +1,145 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example direction_handles_bench` prints the time
|
||||
//! Select › Object › Direction Handles takes to select every path of documents of 2,000, 10,000 and
|
||||
//! 20,000 rectangles, spread over two layers with one group. For each size it times, on the same
|
||||
//! paths and anchors, the selection built one path at a time (a clear, then an add per path) and
|
||||
//! the selection built with one `Selection::set` call, checks that the two are equal, and then
|
||||
//! times the whole `select.object.directionHandles` command.
|
||||
//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere
|
||||
//! it is wall time, and the first line says which. `ITERS` sets the runs per row (default 7); each
|
||||
//! row is the median in ms. A run of the two selection rows repeats the selection 1,000,000 / paths
|
||||
//! times and gives the time of one.
|
||||
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::{Document, NodeId, Selection};
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_testkit::fixtures::DocBuilder;
|
||||
|
||||
type Items = Vec<(NodeId, BTreeSet<(usize, usize)>)>;
|
||||
|
||||
fn iters() -> usize {
|
||||
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7)
|
||||
}
|
||||
|
||||
/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read.
|
||||
fn cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise.
|
||||
fn ms(f: impl FnOnce()) -> f64 {
|
||||
let (cpu, wall) = (cpu_ns(), Instant::now());
|
||||
f();
|
||||
match (cpu, cpu_ns()) {
|
||||
(Some(a), Some(b)) => (b - a) as f64 / 1e6,
|
||||
_ => wall.elapsed().as_secs_f64() * 1000.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn median(mut v: Vec<f64>) -> f64 {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
}
|
||||
|
||||
/// `n` 10 pt squares: a tenth of them in one group and the rest loose, half on each of two layers.
|
||||
fn document(n: usize) -> Document {
|
||||
let mut b = DocBuilder::new(4000.0, 4000.0);
|
||||
let square = |b: &mut DocBuilder, i: usize| {
|
||||
let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0);
|
||||
b.rect_node(Rect::new(x, y, x + 10.0, y + 10.0), Color::rgb(0.2, 0.4, 0.6))
|
||||
};
|
||||
let grouped = n / 10;
|
||||
let kids = (0..grouped).map(|i| square(&mut b, i)).collect();
|
||||
b.group(kids, false);
|
||||
for i in grouped..n {
|
||||
if i == n / 2 {
|
||||
b.layer("Layer 2");
|
||||
}
|
||||
let node = square(&mut b, i);
|
||||
b.add(node);
|
||||
}
|
||||
b.build()
|
||||
}
|
||||
|
||||
/// Selects `items` one path at a time: a clear, then an add and an anchor insert per path.
|
||||
fn one_by_one(sel: &mut Selection, items: Items) {
|
||||
sel.clear();
|
||||
for (id, refs) in items {
|
||||
sel.add(id);
|
||||
sel.anchors.insert(id, refs);
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects `items` with one `Selection::set` call and one extend of the anchors.
|
||||
fn with_set(sel: &mut Selection, items: Items) {
|
||||
sel.set(items.iter().map(|(id, _)| *id));
|
||||
sel.anchors.extend(items);
|
||||
}
|
||||
|
||||
fn row(name: &str, ms: f64) {
|
||||
println!(" {name:<44} {ms:>10.3} ms");
|
||||
}
|
||||
|
||||
fn bench(n: usize) {
|
||||
println!("{n} paths");
|
||||
let mut s = Session::new();
|
||||
s.add_document(document(n), None);
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let start = s.doc().unwrap().selection.clone();
|
||||
s.execute("select.object.directionHandles", &json!({})).unwrap();
|
||||
let command = s.doc().unwrap().selection.clone();
|
||||
// The paths and anchors the command selects, in its order.
|
||||
let items: Items = command.objects.iter().map(|id| (*id, command.anchors[id].clone())).collect();
|
||||
assert_eq!(items.len(), n);
|
||||
|
||||
// Each run selects `reps` times, on copies made before the clock starts, and gives the time of one.
|
||||
let reps = (1_000_000 / n).max(1);
|
||||
let time = |f: fn(&mut Selection, Items)| -> (f64, Selection) {
|
||||
let mut last = Selection::default();
|
||||
let runs = (0..iters())
|
||||
.map(|_| {
|
||||
let mut work: Vec<(Selection, Items)> = (0..reps).map(|_| (start.clone(), items.clone())).collect();
|
||||
let t = ms(|| {
|
||||
for (sel, it) in &mut work {
|
||||
f(sel, black_box(std::mem::take(it)));
|
||||
}
|
||||
});
|
||||
last = work.pop().unwrap().0;
|
||||
t / reps as f64
|
||||
})
|
||||
.collect();
|
||||
(median(runs), last)
|
||||
};
|
||||
let (old, a) = time(one_by_one);
|
||||
let (new, b) = time(with_set);
|
||||
assert_eq!(a, b, "both ways give the same selection");
|
||||
let mut want = start.clone();
|
||||
with_set(&mut want, items.clone());
|
||||
assert_eq!(want.objects, command.objects);
|
||||
assert_eq!(want.anchors, command.anchors);
|
||||
row("selection, one add per path", old);
|
||||
row("selection, one set call", new);
|
||||
println!(" {:<44} {:>10.1}x", "ratio", old / new);
|
||||
|
||||
let runs = (0..iters())
|
||||
.map(|_| {
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
ms(|| drop(black_box(s.execute("select.object.directionHandles", &json!({})).unwrap())))
|
||||
})
|
||||
.collect();
|
||||
row("select.object.directionHandles, whole command", median(runs));
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" });
|
||||
for n in [2_000, 10_000, 20_000] {
|
||||
bench(n);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection, TextKind};
|
||||
use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection, Selection, TextKind};
|
||||
use vectorcraft_geom::Vec2;
|
||||
|
||||
use super::edit::selected_roots;
|
||||
@@ -495,16 +495,17 @@ fn direction_handles(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let total: usize = items.iter().map(|x| x.1.len()).sum();
|
||||
s.select(|_, sel| {
|
||||
sel.clear();
|
||||
for (id, refs) in items {
|
||||
sel.add(id);
|
||||
sel.anchors.insert(id, refs);
|
||||
}
|
||||
})?;
|
||||
s.select(|_, sel| select_anchors(sel, items))?;
|
||||
Ok(json!({ "anchors": total }))
|
||||
}
|
||||
|
||||
/// Replaces `sel` with the paths of `items` in order, each once, and direct-selects the anchors
|
||||
/// listed with each path. A path listed twice keeps its first place and its last anchor set.
|
||||
fn select_anchors(sel: &mut Selection, items: Vec<(NodeId, BTreeSet<(usize, usize)>)>) {
|
||||
sel.set(items.iter().map(|(id, _)| *id));
|
||||
sel.anchors.extend(items);
|
||||
}
|
||||
|
||||
fn save_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "select.save";
|
||||
let st = s.doc()?;
|
||||
@@ -1026,3 +1027,6 @@ fn close_all(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(json!({ "closed": n }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
//! The selection that Select ▸ Object ▸ Direction Handles builds.
|
||||
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::{NodeId, Selection, SymbolPart};
|
||||
|
||||
use super::select_anchors;
|
||||
|
||||
type Items = Vec<(NodeId, BTreeSet<(usize, usize)>)>;
|
||||
|
||||
/// Selects `items` one path at a time: a clear, then an add and an anchor insert per path.
|
||||
fn one_by_one(sel: &mut Selection, items: Items) {
|
||||
sel.clear();
|
||||
for (id, refs) in items {
|
||||
sel.add(id);
|
||||
sel.anchors.insert(id, refs);
|
||||
}
|
||||
}
|
||||
|
||||
/// A selection with every field set, as one left by earlier selecting.
|
||||
fn busy() -> Selection {
|
||||
let mut sel = Selection::default();
|
||||
sel.set([NodeId(90), NodeId(91)]);
|
||||
sel.anchors.insert(NodeId(90), BTreeSet::from([(0, 0)]));
|
||||
sel.segments.insert(NodeId(91), BTreeSet::from([(0, 1)]));
|
||||
sel.key = Some(NodeId(91));
|
||||
sel.target = Some(NodeId(92));
|
||||
sel.slices = vec![NodeId(93)];
|
||||
sel.guides = vec![NodeId(94)];
|
||||
sel.key_guide = Some(NodeId(94));
|
||||
sel.key_anchor = Some((NodeId(90), (0, 0)));
|
||||
sel.symbol_part = Some(SymbolPart { instance: NodeId(95), path: vec![0, 1] });
|
||||
sel.on_path_member = Some(NodeId(96));
|
||||
sel.new_art = Arc::new(HashSet::from([NodeId(97)]));
|
||||
sel
|
||||
}
|
||||
|
||||
fn refs(n: usize) -> BTreeSet<(usize, usize)> {
|
||||
(0..n).map(|i| (0, i)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_anchors_gives_the_selection_one_by_one_selecting_gives() {
|
||||
let cases: Vec<Items> = vec![
|
||||
vec![],
|
||||
vec![(NodeId(1), refs(4))],
|
||||
(1..=500).map(|i| (NodeId(i), refs(4))).collect(),
|
||||
// A path listed again keeps its first place and its last anchors.
|
||||
vec![(NodeId(3), refs(1)), (NodeId(1), refs(4)), (NodeId(3), refs(2)), (NodeId(2), BTreeSet::new()), (NodeId(1), refs(3))],
|
||||
];
|
||||
for items in cases {
|
||||
for start in [Selection::default(), busy()] {
|
||||
let (mut want, mut got) = (start.clone(), start);
|
||||
one_by_one(&mut want, items.clone());
|
||||
select_anchors(&mut got, items.clone());
|
||||
assert_eq!(got, want, "{items:?}");
|
||||
}
|
||||
}
|
||||
let mut got = busy();
|
||||
select_anchors(&mut got, vec![(NodeId(3), refs(1)), (NodeId(1), refs(4)), (NodeId(3), refs(2))]);
|
||||
assert_eq!(got.objects, vec![NodeId(3), NodeId(1)]);
|
||||
assert_eq!(got.anchors[&NodeId(3)], refs(2));
|
||||
assert!(got.segments.is_empty() && got.slices.is_empty() && got.guides.is_empty());
|
||||
assert_eq!((got.key, got.target, got.key_guide, got.key_anchor, got.on_path_member), (None, None, None, None, None));
|
||||
assert!(got.symbol_part.is_none());
|
||||
assert_eq!(*got.new_art, HashSet::from([NodeId(97)]), "selecting leaves the new-art list alone");
|
||||
}
|
||||
@@ -3160,6 +3160,27 @@ fn direction_handles_leave_out_hidden_and_locked_paths() {
|
||||
assert_eq!(selected(&s), vec![a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direction_handles_select_many_paths_in_groups_and_layers_in_paint_order() {
|
||||
let mut s = session();
|
||||
let mut paths: Vec<NodeId> = (0..60).map(|i| rect(&mut s, (i % 20) as f64 * 12.0, (i / 20) as f64 * 12.0, 10.0, 10.0)).collect();
|
||||
sel(&mut s, &paths[10..40]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
paths.extend((0..60).map(|i| rect(&mut s, (i % 20) as f64 * 12.0, 100.0 + (i / 20) as f64 * 12.0, 10.0, 10.0)));
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("select.object.directionHandles", &json!({})).unwrap()["anchors"], 4 * paths.len());
|
||||
let st = s.doc().unwrap();
|
||||
let mut want = vectorcraft_doc::Selection::default();
|
||||
for id in st.doc.paint_order(paths.iter().copied()) {
|
||||
want.add(id);
|
||||
want.anchors.insert(id, (0..4).map(|i| (0, i)).collect());
|
||||
}
|
||||
want.new_art = st.selection.new_art.clone();
|
||||
assert_eq!(st.selection.objects.len(), paths.len());
|
||||
assert_eq!(st.selection, want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_point_and_area_text() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1199,6 +1199,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
The Magic Wand finds compound paths, the selected objects and the objects it picks through hash sets instead of searching lists, and it selects the same objects in the same order. In a release build, with every second object selected in a document of 50,000 paths (12,500 of them in 6,250 compound paths), setting that selection and Shift-clicking takes a median of 142 ms of CPU time, against 353 ms for the same steps run with test-only copies of the earlier searches, and 30 ms against 61 ms at 20,000 paths (7 alternating runs of each in one process, measured while other builds were running; `magic_wand_membership_timing`). Small documents gain little: 2.1 ms against 2.3 ms at 2,000 paths. `membership_sets_give_the_same_objects_in_the_same_order_as_searches` compares the selection in each mode with the earlier searches.
|
||||
Select ▸ Object ▸ Bristle Brush Strokes selects the objects whose topmost stroke has a bristle brush, whatever the brush is named, and leaves out objects whose brush is of another type, also when its name has "Bristle" in it.
|
||||
Select ▸ Object ▸ Not Aligned to Pixel Grid (`select.object.notAlignedToPixelGrid`) selects the paths and compound paths whose pixel-aligned property is off, whatever their coordinates, and leaves out guides, type, images, groups and the paths inside a compound path ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185); `tests::pixelalign::not_aligned_to_pixel_grid_selects_paths_without_the_property`, `not_aligned_to_pixel_grid_leaves_out_what_cant_be_selected`). It also leaves out symbol instances, area type, type on a path, gradient meshes and placed documents, and the paths on template layers, in hidden or locked sublayers and on locked artboards; it selects the paths in clip groups, blends, envelopes, repeats and Intertwine groups and paths with effects (`not_aligned_to_pixel_grid_leaves_out_images_symbol_instances_and_type`, `not_aligned_to_pixel_grid_leaves_out_template_layers_locked_sublayers_and_locked_artboards`, `not_aligned_to_pixel_grid_selects_clipping_paths_and_paths_with_effects`, `not_aligned_to_pixel_grid_selects_the_paths_of_blends_envelopes_repeats_and_intertwines`, `not_aligned_to_pixel_grid_leaves_out_meshes_placed_documents_and_guides_but_takes_live_shapes`, `not_aligned_to_pixel_grid_takes_a_compound_path_by_its_own_property`).
|
||||
Select ▸ Object ▸ Direction Handles (`select.object.directionHandles`) builds its selection with one `Selection::set` call, so the time spent building the selection grows in step with the number of paths. With 20,000 four-anchor paths, building the selection takes 1.9 ms of thread CPU time on Linux, against 69 ms when each path is added on its own, and the whole command takes 51 ms (`crates/engine/examples/direction_handles_bench.rs`; `cmd::docmenu::tests::select_anchors_gives_the_selection_one_by_one_selecting_gives`, `tests::menucmds::direction_handles_select_many_paths_in_groups_and_layers_in_paint_order`).
|
||||
Align and Distribute Spacing keep a compound path or selected group that contains the key object in place, as they keep the key object itself.
|
||||
Align to Glyph Bounds (#4231): the Align panel menu's Align to Glyph Bounds submenu has Point Text and Area Text, each checked while on (`alignGlyphBoundsPoint`, `alignGlyphBoundsArea`, off by default). With one on, Align, Distribute Objects and Distribute Spacing measure that kind of type by the ink of its glyphs instead of its em box (point type) or frame (area type), so lowercase type aligned to a rectangle's top lines up the tops of its letters; the other kind, type on a path and type in a selected group are measured as before, and Use Preview Bounds adds the characters' strokes ([Align text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/align-text.html); `tests::glyphbounds`, `panels::align::tests::align_to_glyph_bounds_toggles_point_and_area_text`). The Character and Properties panels' controls for the same setting are not done.
|
||||
Anchor Align moves the selected points to their bounds or the artboard (#1180). Repeating it, or moving by at most 1e-9 pt on both axes as whole-object Align does, leaves the document, Undo, Redo and saved state unchanged; actual moves still take one undo step. `crates/engine/src/tests.rs` covers repeated alignment, rounding-only alignment, unchanged handles, saved state, command recording and Undo/Redo.
|
||||
|
||||
Reference in New Issue
Block a user